完成一个自动化脚本,将合约部署到区块链网络中。
一、部署的必要条件
1、与以太坊节点的通信连接
我们需要启动一个以太坊节点,连接到想要的网络,然后开放HTTP-RPC的API(默认8545端口)给外部调用;或者也可以用第三方提供的可用节点入口,以太坊社区有人专门为开发者提供了节点服务。目前我们直接用ganache,不需要考虑这些问题,但如果配置其它网络,这个配置就是必要的。
2、余额大于 0 的账户
因为以太坊上的任何交易都需要账户发起,账户中必须有足够的余额来支付手续费(Transaction Fee),如果余额为 0 部署会失败。当然,我们目前用的是ganache,里面默认有10个账户,每个账户100ETH,不存在这个问题,但如果要部署到其它网络(私链、测试网络、主网)就必须考虑这个问题。
3、安装依赖
搞清楚部署的必要条件之后,我们需要安装必要的依赖包。 首先是 web3.js,web3.js 的 1.0.0 版本相比 0.2x.x 版本变化非常大,1.x 中大量使用了 Promise,可以结合 async/await 使用,而 0.x 版本只支持回调,因为使用 async/await 能让代码可读性更好,我们这次选择使用 1.0.0 版本。
npm install web3
二、编写部署脚本
做好准备工作之后,我们开始编写合约部署脚本,在scripts目录下新建脚本文件 deploy.js:
const path = require('path');
const Web3 = require('web3');
const web3 = new Web3(new Web3.providers
.HttpProvider('http://localhost:8545'));
// 1. 拿到 abi和bytecode
const contractPath = path.resolve(__dirname,
'../compiled/Car.json');
const { interface, bytecode } = require(contractPath);
(async () => {
// 2. 获取钱包里面的账户
const accounts = await web3.eth.getAccounts();
console.log('部署合约的账户:', accounts[0]);
// 3. 创建合约实例并且部署
var result = await new
web3.eth.Contract(JSON.parse(interface))
.deploy({ data: bytecode, arguments: ['AUDI'] })
.send({ from: accounts[0], gas: '1000000' });
console.log('合约部署成功:', result);
})();
1、部署前启动测试私链
2、部署合约
三、
1、加入计时、提取地址
const Web3 = require('web3');
const web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
const path = require('path');
const filePath = path.resolve(__dirname, '../compiled/Car.json');
const {interface, bytecode} = require(filePath);
(async () =>{
let accounts = await web3.eth.getAccounts();
console.time("deploy time");
let result = await new web3.eth.Contract(JSON.parse(interface))
.deploy({data:bytecode, arguments:["BMW"]})
.send({from:accounts[0], gas:5000000});
console.timeEnd("deploy time");
console.log("contract address:", result.options.address);
})();
2、web0.2.x或0.1.x中的脚本
const Web3 = require('web3');
const web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
const path = require('path');
const filePath = path.resolve(__dirname, '../compiled/Car.json');
const {interface, bytecode} = require(filePath);
const abi = JSON.parse(interface);
const contract = web3.eth.contract(abi);
const _from = web3.eth.accounts[0];
const txObj = {data:bytecode, from:_from, gas:5000000};
let contractInstance = contract.new(txObj, (err, res)=>{
if(err)
console.log("Error:", err);
else
console.log("Result:", res);
});
四、总结
1、部署时报错
2、原因:缺少web3模块
3、解决:
npm install web3