我们先create-react-app
创建一个项目
然后写一个合约
lottery.sol
我们来安装一下合约的编译器
npm install solc@0.4.25 --save
然后来编译合约
compile.js
let fs = require('fs')
let solc = require('solc')
//1.读取合约
let lotteryInfo = fs.readFileSync('lottery.sol')
console.log(lotteryInfo)
//2.编译合约
let compileInfo = solc.compile(lotteryInfo.toString(),1)
console.log(compileInfo)
//3.导出abi
module.exports = compileInfo['contracts'][':Lottery']
我们安装一下web3
npm install web3 --save
然后启动巧克力ganache-cli
ganache-cli -h 127.0.0.1 -p 7545 -m "aaa bbb ccc..."
然后
部署合约
deploy.js
let {bytecode, interface} = require('./compile.js')
let Web3 = require('web3')
console.log(bytecode)
console.log(interface)
//1.实例化web3
let web3 = new Web3('http://127.0.0.1:7545')
console.log(web3.version)
//2.部署函数
let deploy = async() =>{
//1.填写abi
let contractInstance = new web3.eth.Contract(JSON.parse(interface))
//2.填写bytecode
let result = await contractInstance.deploy({
data: bytecode,
arguments: [],
}).send({
//3.send交易
from: account0,
gas: '100',
value: 0,
})
//合约地址
console.log(result.options.address)
}
deploy()
获取合约实例
loadInstance.js
let Web3 = require('web3')
let abi = [{abcabc...}]
let address = '0xabc...'
//1.实例化web3
let web3 = new Web3('http://127.0.0.1:7545')
console.log(web3.version)
//2.获取合约实例
let lotteryInstance = new web3.eth.Contract(abi, address)
module.exports = lotteryInstance
现在,在前端页面展示一下
打开App.js
import React, {Component} from 'react';
let loadInstance = require('./loadInstance.js')
class App extends Component{
state={
manager: ''
}
async componentWillMount(){
let manager = await lotteryInstance.methods.manager().call()
console.log(manager)
//给状态变量赋值
this.setState({
manager: manager
})
}
render(){
return (
<p>hello world</p>
<p>manager : {this.state.manager}</p>
);
}
}
export default App;
合约交互