打开ganache, 这个在本地启动了一个测试链,如下图片:
node_modules/.bin/ganache-cli
屏幕截图 2021-06-19 210334.png
创建投票合约, 创建一个文件Voting.sol, 内容如下
pragma solidity ^0.4.17;
contract Voting {
mapping(bytes32 => uint8) public votesReceived;
bytes32[] public candidateList;
constructor(bytes32[] candidateNames) public {
candidateList = candidateNames;
}
function totalVotesFor(bytes32 candidate) public view returns (uint8) {
require(validCandidate(candidate));
return votesReceived[candidate];
}
function voteForCandidate(bytes32 candidate) public {
require(validCandidate(candidate));
votesReceived[candidate] += 1;
}
function validCandidate(bytes32 candidate) public view returns (bool) {
for (uint256 i = 0; i < candidateList.length; i++) {
if (candidateList[i] == candidate) {
return true;
}
}
return false;
}
}
打开node, 依次输入
Web3 = require('web3')
web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
//如下是测试是否连上了
web3.eth.getBalance('0xA8213aA010c9C3c09d7a547115c74145BE677FB1')
BigNumber { s: 1, e: 20, c: [ 1000000 ] }
读取代码,并进行编译
code = fs.readFileSync('Voting.sol').toString()
solc = require('solc')
compiledCode = solc.compile(code)
网友评论