JobPlus知识库 IT 工业智能4.0 文章
REMIX智能合约实例BALLOT分析

pragma solidity ^0.4.0;
contract Ballot { //投票类

struct Voter { //投票人
uint weight; //权重
bool voted; //该投票人是否投票,true表示已投票,false表示未投票
uint8 vote; //给谁(提案索引号)投票
address delegate; //委托的投票代表
}
struct Proposal { //提案
uint voteCount; //提案累计获得票数
}

address chairperson; // 投票主持人
mapping(address => Voter) voters; //声明一个状态变量voters,保存每个独立地址的Voter结构体
Proposal[] proposals; //声明一个存储Proposal结构的动态数组

/// Create a new ballot with $(_numProposals) different proposals. //用_numProposals个不同提案创建一个新的投票
function Ballot(uint8 _numProposals) public {
chairperson = msg.sender; //合约发送者为投票主持人
voters[chairperson].weight = 1; //主持人权重为1
proposals.length = _numProposals; //提案个数
}

/// Give $(toVoter) the right to vote on this ballot.
/// May only be called by $(chairperson).//投票主持人给每个投票者投票权,只能由投票主持人调用
function giveRightToVote(address toVoter) public {
if (msg.sender != chairperson || voters[toVoter].voted) return; //若合约发送者不是主持人或者投票者已经投票,则返回
voters[toVoter].weight = 1; // 给每个投票者各自投票权限
}

/// Delegate your vote to the voter $(to). //将自己(该函数的调用者)的投票权委托给委托人to
function delegate(address to) public {
Voter storage sender = voters[msg.sender]; // assigns reference 指定引用
if (sender.voted) return;
while (voters[to].delegate != address(0) && voters[to].delegate != msg.sender)
to = voters[to].delegate;//当委托人的票也委托给了别人时,将委托人to指向委托人的委托人。
if (to == msg.sender) return;//当委托人的委托人是自己时,返回。这里不允许自己委托给自己。
sender.voted = true;//自己已投票
sender.delegate = to;//将自己的委托人设为委托人to
Voter storage delegateTo = voters[to];//将委托人的信息保存到delegateTo中
if (delegateTo.voted)//若委托人已投票,则将自己的权重赋给委托人的票数
proposals[delegateTo.vote].voteCount += sender.weight;
else
delegateTo.weight += sender.weight; //若委托人未投票,则将自己的权重增加到委托人权重上。
}

/// Give a single vote to proposal $(toProposal).//这里自己(调用函数者)给提案投票,包括委托的票。
function vote(uint8 toProposal) public {
Voter storage sender = voters[msg.sender];//指定引用
if (sender.voted || toProposal >= proposals.length) return;//若自己已经投票或要投的提案索引范围超过给定提案数组范围,则返回
sender.voted = true;//自己已投票
sender.vote = toProposal;//自己给提案索引toProposal投票
proposals[toProposal].voteCount += sender.weight; //给提案索引为toProposal的票数加上自己的权重
}

//根据当前所有的投票计算出胜出的提案
function winningProposal() public constant returns (uint8 _winningProposal) {
uint256 winningVoteCount = 0;
for (uint8 prop = 0; prop < proposals.length; prop++)
if (proposals[prop].voteCount > winningVoteCount) {
winningVoteCount = proposals[prop].voteCount;
_winningProposal = prop;
}
}

}


msg.sender表示当前执行函数者的地址


如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!

¥ 打赏支持
5人赞 举报
分享到
用户评价(0)

暂无评价,你也可以发布评价哦:)

扫码APP

扫描使用APP

扫码使用

扫描使用小程序