-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathElection.sol
41 lines (32 loc) · 1.14 KB
/
Election.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
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract Election {
struct Candidate {
uint id;
string name;
uint voteCount;
}
mapping(address => bool) public voters;
mapping(uint => Candidate) public candidates;
uint public candidatesCount;
event votedEvent(uint indexed candidateId);
constructor() {
addCandidate("Candidate 1");
addCandidate("Candidate 2");
}
function addCandidate(string memory _name) private {
candidatesCount++;
candidates[candidatesCount] = Candidate(candidatesCount, _name, 0);
}
function vote(uint _candidateId) public {
require(!voters[msg.sender], "Already voted.");
require(_candidateId > 0 && _candidateId <= candidatesCount, "Invalid candidate.");
voters[msg.sender] = true;
candidates[_candidateId].voteCount++;
emit votedEvent(_candidateId);
}
function getCandidate(uint _candidateId) public view returns (Candidate memory) {
require(_candidateId > 0 && _candidateId <= candidatesCount, "Invalid candidate ID.");
return candidates[_candidateId];
}
}