ethereum部署合约
我们先来看下文档
找到 new contract
然后我们看看
new web3.eth.Contract(jsonInterface[,address][,options])
Creates a new contract instance with all its methods and events defined in its json interface object.
翻译一下
创建一个合约实例,根据json接口
1.jsonInterface abi
2.address 地址
3.options 参数
两种情况使用
1.合约部署的时候
2.合约已经部署完成,根据abi和地址获取合约实例的时候
安装web3
npm install web3
导入Web3
let Web3 = require('web3')
let web3 = new Web3()
部署
let deploy = () => {
let contractInstance = new web3.eth.Contract(interface)
contractInstance.deploy({
data: bytecode,
arguments: ["hello world"]
}).send({
from: ,
gas: ,
})
}
开启
ganache-cli -h 127.0.0.1 -p 7545 -m "scout same naive genius cannon maze differ acquire penalty habit surround ice"
//web3设置网络
web3.setProvider('http://127.0.0.1:7545')
开启ganache-cli之后,
执行node deploy.js
看下完整代码
//导入
let {bytecode, interface} = require('./compile')
//大写Web3导入的是构造函数,需要实例化
let Web3 = require('web3')
//实例化web3对象, 并且设置网络
let web3 = new Web3('http://127.0.0.1:7545')
console.log('typeof interface:', typeof interface)
//地址
let account1 = '0xd5957914c31e1d785ccc58237d065dd25c61c4d0'
//部署
let deploy = async () => {
//1. 实例化合约数据,填写ABI
// JSON.parse() : string => json
// stringfy() : json => string
let contractInstance = new web3.eth.Contract(JSON.parse(interface))
//2. 填写bytecode,构造函数参数
let res = await contractInstance.deploy({
data: bytecode,
arguments: ["hello world!"]
}).send({
//用哪个账户
from : account1,
// gas : 10000000000, //gas过大,超过区块的上限
gas : '1000000'
})
console.log('address : ', res.options.address)
}
deploy()