在16年的时候很多人嘲笑以太坊的功能弱:也就能用在小学生选班长上! Solidity语言中就把这个选班长合约做成一个经典案例了。
找到相关的合约代码研究了下,发现还蛮复杂的。一时间还不知从何入手呢。
去掉些复杂的条件,找到最核心的东东,试了试,还蛮顺利地就实现了。代码如下:
pragma solidity >0.4.23 <0.7.0;
contract Voting {
mapping (string => uint ) public votesReceived;
mapping (address => bool) private addrRecoded;
string[] public candidateList = ["lemool", "jackey", "hello"];
function totalVotesFor(string memory candidate) view public returns (uint) {
return votesReceived[candidate];
}
function voteForCandidate(string memory candidate) payable public {
require(!addrRecoded[msg.sender]);
addrRecoded[msg.sender] = true;
uint m = msg.value / 0.1 ether;
votesReceived[candidate] += m;
}
}
做几点说明: