本地開發環境以太坊合約互動實戰

買賣虛擬貨幣
操作步驟所有的操作都是在goland裡面使用nodejs調web3庫•編寫合約•編譯合約(web3)-用solc編譯(拿到bytecode、abi)•部署合約(web3)•找到合約例項
•呼叫合約(set,get操作)開發環境//安裝淘寶的映象npm install -g cnpm --registry=https://registry.npm.taobao.org//安裝指定版本solc cnpm install admin@chaindaily
//安裝create-react-appnpm install create-react-app -g//建立空的react專案create-react-app project//進入到project中npm run start
//安裝web3npm i web3 --saveweb3模組劃分:•web3-eth:與blockchain合約相關的模組•web3-shh:與p2p協議廣播相關•web3-bzz:與swarm儲存協議相關
•web3-utils:開發者工具相關a.部署合約時候,需要用到提供abi,即可執行後面的動作,進行部署 b.獲取合約例項的時候需要用到這個函式,指定abi,指定addressGanache用於搭建私有網路。在開發和測試環境下,Ganache提供了非常簡便的以太坊私有網路搭建方法,透過視覺化介面可以直觀地設定各種引數、瀏覽檢視賬戶和交易等資料程式碼加註解01-compile
//匯入solc編譯器var solc = require('solc')//讀取合約let fs = require('fs')let sourceCode = fs.readFileSync('./contracts/SimpleStorage.sol', 'utf-8')let output = solc.compile(sourceCode, 1)
console.log('output:', output)console.log('abi:______',output['contracts'][':SimpleStorage']['interface'])//匯出合約module.exports = output['contracts'][':SimpleStorage']02-deploylet {bytecode, interface} = require('./01-compile')
// console.log('bytecode_____',bytecode)// console.log('interface____',interface)//1.引入web3let Web3 = require('web3')//2.new一個web3例項let web3 = new Web3()
//3.設定網路web3.setProvider('http://localhost:7545')console.log('version:________', web3.version)console.log('web3-eth.curretProvider_____________', web3.currentProvider)//此地址需要使用Ganache地址const account ='0xd4DB91aCBB5Be2a42276567c7473857e14888B53'
//1.拼接合約資料interfacelet contract = new web3.eth.Contract(JSON.parse(interface))//2.拼接bytecodecontract.deploy({    data: bytecode,//合約的bytecode    arguments: ['helloworld']//給建構函式傳遞引數,使用陣列
}).send({    from:account,    gas:'3000000',    gasPrice:'1',}).then(instance =>{    console.log('address:',instance.options.address)
})03-instance//獲取合約例項,匯出去//1.引入web3let Web3 = require('web3')//2.new一個web3例項
let web3 = new Web3()//3.設定網路web3.setProvider('http://localhost:7545')let abi = [{    "constant": true,    "inputs": [],
    "name": "getValue",    "outputs": [{"name": "", "type": "string"}],    "payable": false,    "stateMutability": "view",    "type": "function"}, {
    "constant": false,    "inputs": [{"name": "_str", "type": "string"}],    "name": "setValue",    "outputs": [],    "payable": false,    "stateMutability": "nonpayable",
    "type": "function"}, {    "inputs": [{"name": "_str", "type": "string"}],    "payable": false,    "stateMutability": "nonpayable",    "type": "constructor"
}]let address = '0x7a0402FDB3de50eBEBe77F0ff72A6b7526e92447' //此處是合約地址//此處abi已經json物件,不需要進行parse動作let contractInstance = new web3.eth.Contract(abi, address)console.log('address__________', contractInstance.options.address)module.exports = contractInstance
04-interaction//1.匯入合約例項let instance = require('./03-instance')const from = '0xd4DB91aCBB5Be2a42276567c7473857e14888B53'//非同步呼叫,返回值是一個promise//2.讀取資料
//整體封裝成函式//web3和區塊鏈互動的返回值都是promise,可以直接使用asynclet test = async () => {    try {        let y1 = await instance.methods.getValue().call()        let res = await instance.methods.setValue('Hello HangTou').send({
            from: from,            value: 0,        })        console.log('res:', res)        let v2 = await instance.methods.getValue().call()        console.log('v2:', v2)
    } catch (e) {        console.log(e)    }}test()

呼叫結果

git地址 https://github.com/potaxie/web3

免責聲明:

  1. 本文版權歸原作者所有,僅代表作者本人觀點,不代表鏈報觀點或立場。
  2. 如發現文章、圖片等侵權行爲,侵權責任將由作者本人承擔。
  3. 鏈報僅提供相關項目信息,不構成任何投資建議

推荐阅读

;