Skip to content

Instantly share code, notes, and snippets.

@chriseth
Created July 7, 2015 15:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chriseth/be5ba6787620e81888d7 to your computer and use it in GitHub Desktop.
Save chriseth/be5ba6787620e81888d7 to your computer and use it in GitHub Desktop.
Ballot
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