写在前面
运行前
- 安装node和npm
- 下载文件及模块
git clone https://github.com/1172510217/voting_dapp.git
cd voting_dapp
npm install
- 运行ganache-cli
./node_modules/.bin/ganache-cli --host "108.61.126.96" --port 8080
- 需保证ganache-cli在整个服务器运行过程中一直运行
- host参数替换为你的服务器网址,port参数替换为你需要监听的端口
运行
- 编译合约
var Web3 = require('web3');
var solc = require('solc');
var web3 = new Web3(new Web3.providers.HttpProvider('http://108.61.126.96:8080'));
var compiledCode = solc.compile(fs.readFileSync('Voting.sol').toString());
- 部署合约
var Voting = compiledCode.contracts[':Voting'];
var abi = JSON.parse(Voting.interface);
var byteCode = Voting.bytecode;
var candidates =['Alice','Bob','Cary'];
var candidatesHex = new Array(candidates.length);
for (let i = 0; i < candidates.length; i++){candidatesHex[i] = web3.utils.asciiToHex(candidates[i]);}
var account;
web3.eth.getAccounts().then(function(res){account=res[0]});
var VotingContract = new web3.eth.Contract(abi);
var contractInstance = VotingContract.deploy({data:byteCode,arguments:[candidatesHex]}).send({from:account,gas:4700000});
- 修改index.js
- 修改第1行中的网址为你的ganache-cli监听网址
- 修改合约部署地址为你的实际部署地址:可以在ganache-cli中找到对应的contractAddr
- 修改server.js
- 修改最终监听的端口号为一个不同于ganache-cli监听端口号的非熟知端口号,比如8888
- 修改最后一行中的网址为你的服务器网址(和ganache-cli的网址一致)
- 运行服务器
node server.js
注意
nohup ./node_modules/.bin/ganache-cli --host 108.61.126.9 --port 8080 > ganache_out.log 2>&1 &
nohup node server.js > server_out.log 2>&1 &