-
Notifications
You must be signed in to change notification settings - Fork 0
/
voting.sol
60 lines (47 loc) · 1.78 KB
/
voting.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
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract Voting {
struct Candidate {
uint id;
string name;
uint voteCount;
}
struct Voter {
bool hasVoted;
uint votedCandidateId;
}
address public owner;
mapping(uint => Candidate) public candidates;
mapping(address => Voter) public voters;
uint public candidatesCount;
event CandidateAdded(uint indexed candidateId, string name);
event Voted(address indexed voter, uint indexed candidateId);
modifier onlyOwner() {
require(msg.sender == owner, "Only owner can perform this action");
_;
}
constructor() {
owner = msg.sender;
}
function addCandidate(string memory _name) public onlyOwner {
candidatesCount++;
candidates[candidatesCount] = Candidate(candidatesCount, _name, 0);
emit CandidateAdded(candidatesCount, _name);
}
function vote(uint _candidateId) public {
require(!voters[msg.sender].hasVoted, "You have already voted");
require(_candidateId > 0 && _candidateId <= candidatesCount, "Invalid candidate ID");
voters[msg.sender].hasVoted = true;
voters[msg.sender].votedCandidateId = _candidateId;
candidates[_candidateId].voteCount++;
emit Voted(msg.sender, _candidateId);
}
function getCandidate(uint _candidateId) public view returns (uint, string memory, uint) {
Candidate memory candidate = candidates[_candidateId];
return (candidate.id, candidate.name, candidate.voteCount);
}
function getVoteCount(uint _candidateId) public view returns (uint) {
require(_candidateId > 0 && _candidateId <= candidatesCount, "Invalid candidate ID");
return candidates[_candidateId].voteCount;
}
}