-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBallot.sol
More file actions
109 lines (84 loc) · 2.43 KB
/
Ballot.sol
File metadata and controls
109 lines (84 loc) · 2.43 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
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
pragma solidity ^0.4.24;
contract Ballot {
string public vote;
constructor (string _vote) public {
vote = _vote;
}
function contractAddress() public view returns (address) {
return address(this);
}
}
contract BallotFactory {
address owner;
bool isOpen;
uint64 maxVote;
string public winner;
string[] candidates;
// KYC to prevent multiple votes
// 0 = Unregistered, 1 = Registered, 2 = Voted
mapping(address => uint) voterStatus;
mapping(address => address) voterContracts;
mapping(string => uint) candidateVotes;
event newVote(address owner, address ballotAddress);
modifier canVote {
require(voterStatus[msg.sender] == 1);
_;
}
modifier onlyOpen {
require(isOpen);
_;
}
modifier onlyClosed {
require(!isOpen);
_;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
constructor (uint64 _maxVote) public {
owner = msg.sender;
maxVote = _maxVote;
isOpen = true;
}
function withdraw() public onlyOwner returns(bool) {
owner.transfer(address(this).balance);
return true;
}
function approveAddress(address _address) public onlyOwner returns(bool) {
voterStatus[_address] = 1;
return true;
}
function closeBallot() public onlyOwner onlyOpen payable returns(bool){
// Prevent accidental closing of ballot
require(msg.value >= 1 ether);
isOpen = false;
return true;
}
function createVote(string _vote) public canVote onlyOpen returns(bool) {
Ballot ballot = new Ballot(_vote);
voterContracts[msg.sender] = ballot.contractAddress();
voterStatus[msg.sender] = 2;
candidateVotes[_vote] += 1;
candidates.push(_vote);
emit newVote(msg.sender, voterContracts[msg.sender]);
return true;
}
function getWinner() onlyOwner onlyClosed public returns (string) {
uint count;
bool tied;
string memory currentWinner;
for(uint i=0; i < candidates.length; i++){
uint currentCount = candidateVotes[candidates[i]];
if(currentCount > count){
currentWinner = candidates[i];
count = currentCount;
tied = false;
}else if(currentCount == count){
tied = true;
}
}
winner = currentWinner;
return tied ? 'tied' : winner
}
}