Created
December 20, 2016 22:18
-
-
Save RFV/99b188f0cf9e0154c290699dfd62c931 to your computer and use it in GitHub Desktop.
Ballot Smart Contract
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
contract Ballot { | |
enum Vote { | |
None, | |
Direct { proposal: Proposal }, | |
Delegated { to: address } | |
} | |
struct Voter { vote: Vote; weight: uint; } | |
using Proposal = uint8; | |
chairperson: address; | |
numProposals: uint8; | |
voters: mapping(address => Voter); | |
voteCounts: mapping(Proposal => uint); | |
// Create a new ballot with $(_numProposals) different proposals. | |
function Ballot(_numProposals: uint8) { | |
chairperson = msg.sender; | |
numProposals = _numProposals; | |
} | |
// Give $(voter) the right to vote on this ballot. | |
// May only be called by $(chairperson). | |
function giveRightToVote(voter: address) { | |
if (msg.sender != chairperson) return; | |
if (voters[voter].vote != Vote.None) return; | |
voters[voter].weight = 1; | |
} | |
// Delegate your vote to the voter $(to) or vote for proposal $(to). | |
function vote(uint to) { | |
if (to == 0) _vote(Vote.None); | |
else if (to <= numProposals) _vote(Vote.Direct(Proposal(to))); | |
else _vote(Vote.Delegated(address(to))); | |
} | |
function _vote(Vote memory vote) internal { | |
var sender = voters[msg.sender]; | |
switch (vote) { | |
case let Vote.Direct(proposal): | |
sender.vote = vote; | |
voteCounts[proposal] += sender.weight; | |
break; | |
case let Vote.Delegated(to), voters[to].voted != Vote.None: | |
_vote(voters[to].voted); | |
break; | |
case let Vote.Delegated(to): | |
sender.vote = vote; | |
voters[to].weight += sender.weight; | |
break; | |
default: | |
return; | |
} | |
} | |
function winningProposal() constant returns (winningProposal: Proposal) { | |
var winningVoteCount: uint = 0; | |
var proposal: Proposal = 1; | |
while (proposal = numProposals) { | |
if (voteCounts[proposal] > winningVoteCount) { | |
winningVoteCount = voteCounts[proposal]; | |
winningProposal = proposal; | |
} | |
++proposal; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment