投票Demo

2019-04-28  本文已影响0人  蜗牛也有梦想

pragma solidity ^0.4.22;

contract Ballot{

// 这里声明了一个新的复合类型用于稍后的变量
// 它用来表示一个选民
struct Voter{
    uint weight;// 计票的权重
    bool voted;
    address delegate;// 被委托人
    uint vote;// 投票提案的索引
    
}

// 提案的类型
struct Proposal{
    bytes32 name;// 简称(最长32个字节)
    uint voteCount;// 得票数
}

address public chairperson;

// 这声明了一个状态变量,为每个可能的地址存储一个 `Voter`。
mapping(address => Voter) public voters;

// 一个 `Proposal` 结构类型的动态数组
Proposal[] public proposals;

constructor(bytes32[] proposalNames) public{
    chairperson = msg.sender;
    voters[chairperson].weight = 1;
    for(uint i = 0; i < proposalNames.length; i++){
        proposals.push(Proposal({ name:proposalNames[i],voteCount:0 }));
    }
}

function giveRightToVote(address voter) public{
    
    require(msg.sender == chairperson,"Only chairperson can give right to vote.");
    
    require(!voters[voter].voted,"The voter already voted.");
    
    require(voters[voter].weight == 0,"you do not have vote weight");
    
    voters[voter].weight = 1;
}

function delegate(address to) public{
    Voter storage sender = voters[msg.sender];
    require(!sender.voted,"The voter already voted.");
    require(to != msg.sender,"Self-delegation is disallowed.");
    
    while(voters[to].delegate != address(0)){
        to = voters[to].delegate;
        require(to != msg.sender, "Found loop in delegation.");
    }
    
    sender.voted = true;
    sender.delegate = to;
    Voter storage delegate_ = voters[to];
    if(delegate_.voted){
        proposals[delegate_.vote].voteCount += sender.weight;
    }else{
        delegate_.weight += sender.weight;
    }
}

function vote(uint proposal) public{
    Voter storage sender = voters[msg.sender];
    require(!sender.voted,"Already voted.");
    sender.voted = true;
    sender.vote = proposal;
    proposals[proposal].voteCount += sender.weight;
}

function winningProposal() public view returns(uint winningProposal_){
    uint winningVoteCount = 0;
    for(uint p = 0; p < proposals.length; p++){
        winningVoteCount = proposals[p].voteCount;
        winningProposal_ = p;
    }
}

function winnerName() public view returns(bytes32 winnerName_){
    winnerName_ = proposals[winningProposal()].name;
}

}

上一篇 下一篇

猜你喜欢

热点阅读