-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBallotWithStages.solidity
More file actions
63 lines (53 loc) · 2.01 KB
/
BallotWithStages.solidity
File metadata and controls
63 lines (53 loc) · 2.01 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
pragma solidity ^0.5.9;
contract Ballot {
struct Voter {
uint weight;
bool voted;
uint8 vote;
}
struct Proposal {
uint voteCount;
}
enum Stage {Init,Reg, Vote, Done}
Stage public stage = Stage.Init;
address chairperson;
mapping(address => Voter) voters;
Proposal[] proposals;
uint startTime;
/// Create a new ballot with $(_numProposals) different proposals.
constructor(uint8 _numProposals) public {
chairperson = msg.sender;
voters[chairperson].weight = 2; // weight is 2 for testing purposes
proposals.length = _numProposals;
stage = Stage.Reg;
startTime = now;
}
/// Give $(toVoter) the right to vote on this ballot.
/// May only be called by $(chairperson).
function register(address toVoter) public {
if (stage != Stage.Reg) {return;}
if (msg.sender != chairperson || voters[toVoter].voted) return;
voters[toVoter].weight = 1;
voters[toVoter].voted = false;
if (now > (startTime+ 10 seconds)) {stage = Stage.Vote; startTime = now;}
}
/// Give a single vote to proposal $(toProposal).
function vote(uint8 toProposal) public {
if (stage != Stage.Vote) {return;}
Voter storage sender = voters[msg.sender];
if (sender.voted || toProposal >= proposals.length) return;
sender.voted = true;
sender.vote = toProposal;
proposals[toProposal].voteCount += sender.weight;
if (now > (startTime+ 10 seconds)) {stage = Stage.Done;}
}
function winningProposal() public view returns (uint8 _winningProposal) {
if (stage != Stage.Done) {return _winningProposal;}
uint256 winningVoteCount = 0;
for (uint8 prop = 0; prop < proposals.length; prop++)
if (proposals[prop].voteCount > winningVoteCount) {
winningVoteCount = proposals[prop].voteCount;
_winningProposal = prop;
}
}
}