试试投票合约 / 学习智能合约#8

试试投票合约 / 学习智能合约#8

voting.jpg

在16年的时候很多人嘲笑以太坊的功能弱:也就能用在小学生选班长上! Solidity语言中就把这个选班长合约做成一个经典案例了。

找到相关的合约代码研究了下,发现还蛮复杂的。一时间还不知从何入手呢。

去掉些复杂的条件,找到最核心的东东,试了试,还蛮顺利地就实现了。代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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;
}
}

做几点说明:

  1. 将候选人类型设为了”string” 而不是”bytes32”,这样可以很方便地交互。”bytes32”是个大坑,现在新版的必须将字符串转成十六过制类型才能存入,否则一个劲地报错!
  2. 投票合约和代币一样,就是做个表格记录候选人的票数,理解这点就很简单了。其它的附加条件可以先不用。
  3. 投票通过”msg.value”来收费,0.1个币一票,充分体现什么叫资本主义。

This page is synchronized from the post: ‘试试投票合约 / 学习智能合约#8’

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×