本地开发环境以太坊合约交互实战
操作步骤
所有的操作都是在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-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-deploy
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
上一篇:以太坊真实测试网络合约交互实战
下一篇:如何从DeFi协议获取交易数据