-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy pathballot.sol
127 lines (108 loc) · 2.92 KB
/
ballot.sol
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
/**
* @file ballot.sol
* @author Jackson Ng <[email protected]>
* @date created 22nd Apr 2019
* @date last modified 30th Apr 2019
*/
pragma solidity ^0.5.0;
contract Ballot {
struct vote{
address voterAddress;
bool choice;
}
struct voter{
string voterName;
bool voted;
}
uint private countResult = 0;
uint public finalResult = 0;
uint public totalVoter = 0;
uint public totalVote = 0;
address public ballotOfficialAddress;
string public ballotOfficialName;
string public proposal;
mapping(uint => vote) private votes;
mapping(address => voter) public voterRegister;
enum State { Created, Voting, Ended }
State public state;
//creates a new ballot contract
constructor(
string memory _ballotOfficialName,
string memory _proposal) public {
ballotOfficialAddress = msg.sender;
ballotOfficialName = _ballotOfficialName;
proposal = _proposal;
state = State.Created;
}
modifier condition(bool _condition) {
require(_condition);
_;
}
modifier onlyOfficial() {
require(msg.sender ==ballotOfficialAddress);
_;
}
modifier inState(State _state) {
require(state == _state);
_;
}
event voterAdded(address voter);
event voteStarted();
event voteEnded(uint finalResult);
event voteDone(address voter);
//add voter
function addVoter(address _voterAddress, string memory _voterName)
public
inState(State.Created)
onlyOfficial
{
voter memory v;
v.voterName = _voterName;
v.voted = false;
voterRegister[_voterAddress] = v;
totalVoter++;
emit voterAdded(_voterAddress);
}
//declare voting starts now
function startVote()
public
inState(State.Created)
onlyOfficial
{
state = State.Voting;
emit voteStarted();
}
//voters vote by indicating their choice (true/false)
function doVote(bool _choice)
public
inState(State.Voting)
returns (bool voted)
{
bool found = false;
if (bytes(voterRegister[msg.sender].voterName).length != 0
&& !voterRegister[msg.sender].voted){
voterRegister[msg.sender].voted = true;
vote memory v;
v.voterAddress = msg.sender;
v.choice = _choice;
if (_choice){
countResult++; //counting on the go
}
votes[totalVote] = v;
totalVote++;
found = true;
}
emit voteDone(msg.sender);
return found;
}
//end votes
function endVote()
public
inState(State.Voting)
onlyOfficial
{
state = State.Ended;
finalResult = countResult; //move result from private countResult to public finalResult
emit voteEnded(finalResult);
}
}