本地開發環境nodejs、web3以太坊合約交互實戰
提供想從事區塊鏈開發的同學一篇入門實操案例,歡迎吐槽。
操作步驟
所有的操作都是在goland裏面使用nodejs調web3庫
- 編寫合約
- 編譯合約(web3)-用solc編譯(拿到bytecode、abi)
- 部署合約(web3)
- 找到合約實例
- 調用合約(set,get操作)
開發環境
//安裝淘寶的鏡像 npm install -g cnpm --registry=https://registry.npm.taobao.org //安裝指定版本solc cnpm install [email protected] //安裝create-react-app npm install create-react-app -g //創建空的react項目 create-react-app project //進入到project中 npm run start //安裝web3 npm i web3 --save
web3模塊劃分:
- web3-eth:與blockchain合約相關的模塊
- web3-shh:與p2p協議廣播相關
- web3-bzz: 與swarm存儲協議相關
- web3-utils: 開發者工具相關
a.部署合約時候,需要用到提供abi,即可執行後面的動作,進行部署 b.獲取合約實例的時候需要用到這個函數,指定abi,指定address
Ganache用於搭建私有網絡。在開發和測試環境下,Ganache提供了非常簡便的以太坊私有網絡搭建方法, 通過可視化界面可以直觀地設置各種參數、瀏覽查看賬戶和交易等數據
代碼加註解
01-deploy
//導入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-compile
let {bytecode, interface} = require('./01-compile') // console.log('bytecode_____',bytecode) // console.log('interface____',interface) //1.引入web3 let 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.拼接合約數據interface let contract = new web3.eth.Contract(JSON.parse(interface)) //2.拼接bytecode contract.deploy({ data: bytecode,//合約的bytecode arguments: ['helloworld']//給構造函數傳遞參數,使用數組 }).send({ from:account, gas:'3000000', gasPrice:'1', }).then(instance =>{ console.log('address:',instance.options.address) })
03-instance
//獲取合約實例,導出去 //1.引入web3 let 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,可以直接使用async let 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
操作步驟
所有的操作都是在goland裏面使用nodejs調web3庫
- 編寫合約
- 編譯合約(web3)-用solc編譯(拿到bytecode、abi)
- 部署合約(web3)
- 找到合約實例
- 調用合約(set,get操作)
開發環境
//安裝淘寶的鏡像 npm install -g cnpm --registry=https://registry.npm.taobao.org //安裝指定版本solc cnpm install [email protected] //安裝create-react-app npm install create-react-app -g //創建空的react項目 create-react-app project //進入到project中 npm run start //安裝web3 npm i web3 --save
web3模塊劃分:
- web3-eth:與blockchain合約相關的模塊
- web3-shh:與p2p協議廣播相關
- web3-bzz: 與swarm存儲協議相關
- web3-utils: 開發者工具相關
a.部署合約時候,需要用到提供abi,即可執行後面的動作,進行部署 b.獲取合約實例的時候需要用到這個函數,指定abi,指定address
Ganache用於搭建私有網絡。在開發和測試環境下,Ganache提供了非常簡便的以太坊私有網絡搭建方法, 通過可視化界面可以直觀地設置各種參數、瀏覽查看賬戶和交易等數據
代碼加註解
01-deploy
//導入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-compile
let {bytecode, interface} = require('./01-compile') // console.log('bytecode_____',bytecode) // console.log('interface____',interface) //1.引入web3 let 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.拼接合約數據interface let contract = new web3.eth.Contract(JSON.parse(interface)) //2.拼接bytecode contract.deploy({ data: bytecode,//合約的bytecode arguments: ['helloworld']//給構造函數傳遞參數,使用數組 }).send({ from:account, gas:'3000000', gasPrice:'1', }).then(instance =>{ console.log('address:',instance.options.address) })
03-instance
//獲取合約實例,導出去 //1.引入web3 let 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,可以直接使用async let 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小時前
- 閱讀 ( 16 )
- 學分 ( 0 )
- 分類:以太坊