-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvote.sol
53 lines (41 loc) · 1.5 KB
/
vote.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
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract LeaderElection {
struct Candidate {
uint256 voteCount;
bool exists;
}
mapping(address => Candidate) public candidates;
address[] public candidateAddresses;
bool public electionEnded;
address public electedLeader;
event Vote(address indexed candidate, address indexed voter);
constructor(address[] memory _candidates) {
require(_candidates.length > 0, "At least one candidate required");
for (uint256 i = 0; i < _candidates.length; i++) {
candidates[_candidates[i]].exists = true;
candidateAddresses.push(_candidates[i]);
}
}
function vote(address candidate) external {
require(!electionEnded, "Election has ended");
require(candidates[candidate].exists, "Invalid candidate");
candidates[candidate].voteCount++;
emit Vote(candidate, msg.sender);
}
function endElection() external {
require(!electionEnded, "Election has already ended");
electionEnded = true;
uint256 maxVotes = 0;
address winningCandidate;
for (uint256 i = 0; i < candidateAddresses.length; i++) {
address candidate = candidateAddresses[i];
uint256 votes = candidates[candidate].voteCount;
if (votes > maxVotes) {
maxVotes = votes;
winningCandidate = candidate;
}
}
electedLeader = winningCandidate;
}
}