1.准备工作
- npm
- nodejs
- 使用npm安装ganache -cil,web3,solc(用0.4.26版本)
- 源文件,如VoteSystem.sol
2.编译代码
首先打开ganache -cil客户端
然后打开根目录,打开node,命令行交互
var Web3 = require('web3')
var web3 = new Web3(new Web3.providers.HttpProvider('http://localhost:8545'))
var sourceCode = fs.readFileSync('VoteSystem.sol').toString()
var solc = require('solc')
var compiledCode = solc.compile(sourceCode)
var abi = JSON.parse(compiledCode.contracts[':Ballot'].interface)
var byteCode = compiledCode.contracts[':Ballot'].bytecode
或者直接写一个js脚本用node执行,执行前创造这样的目录

脚本如下:
const fs = require('fs-extra');
const solc = require('solc');
const path = require('path');
const compilePath = path.resolve(__dirname,'../compiled');
fs.removeSync(compilePath);
fs.ensureDirSync(compilePath);
const contractPath = path.resolve(__dirname,'../contracts','VoteSystem.sol');
const contractSource = fs.readFileSync(contractPath,'utf-8');
let compileResult = solc.compile(contractSource,1);
Object.keys(compileResult.contracts).forEach(name=>{
let contractName = name.replace(/^:/,'');
let filePath = path.resolve(__dirname,'../compiled',`${contractName}.json`);
fs.outputJsonSync(filePath,compileResult.contracts[name]);
console.log("Saving json file to",filePath);
})
3.完成智能合约的部署
3.1 部署的必要条件
- 与以太坊节点的通信连接
我们需要启动一个以太坊节点,连接到想要的网络,然后开放HTTP-RPC的API(默认8545端口)给外部调用;或者也可以用第三方提供的可用节点入口,以太坊社区有人专门为开发者提供了节点服务。目前我们直接用ganache,不需要考虑这些问题,但如果配置其它网络,这个配置就是必要的。 - 余额大于О的账户
因为以太坊上的任何交易都需要账户发起,账户中必须有足够的余额来支付手续费(Transaction Fee),如果余额为О部署会失败。当然,我们目前用的是ganache,里面默认有10个账户,每个账户100ETH,不存在这个问题,但如果要部署到其它网络(私链、测试网络、主网)就必须考虑这个问题。
3.2 安装依赖
搞清楚部署的必要条件之后,我们需要安装必要的依赖包。首先是web3.js,web3.js 的1.0.0版本尚未发布,但是相比0.2xx版本变化非常大,1.x中大量使用了 Promise,可以结合asynclawait使用,而0x版本只支持回调,因为使用asynclawait能让代码可读性更好,我们这次选择使用1.0.0版本。
npm install web3
3.3 编写合约部署脚本
const Web3 = require('web3');
const web3 = new Web3(new Web3.providers.HttpProvider('http://localhost:7545'));
const fs = require('fs-extra');
const path = require('path');
//读取ABI和bytecode
const filePath = path.resolve(__dirname,'../compiled/Ballot.json');
const {interface,bytecode} = require(filePath);
(async()=>{
let accounts = await web3.eth.getAccounts();
console.log(JSON.parse(interface))
console.time("deploy time");
let myContract = await new web3.eth.Contract(JSON.parse(interface));
let result = myContract.deploy({data:bytecode,arguments:[[web3.utils.toHex('Alice'),web3.utils.toHex('Bob')]]})
.send({from:accounts[0],gas:5000000});
console.timeEnd("deploy time");
console.log(result);
})();
本文档详细介绍了如何在本地环境利用ganache-cli、web3.js和solc编译及部署Ethereum智能合约。首先,确保安装npm、nodejs以及相关依赖。接着,编译Solidity源代码,例如VoteSystem.sol。然后,通过web3.js与ganache建立连接,部署智能合约。部署过程中涉及账户余额、gas等关键因素,并提供了部署脚本示例。
5123

被折叠的 条评论
为什么被折叠?



