forked from arawrdn/Create-Voting-DApps
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCode
More file actions
39 lines (30 loc) · 1.13 KB
/
Code
File metadata and controls
39 lines (30 loc) · 1.13 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
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import "@openzeppelin/contracts/access/Ownable.sol";
contract Voting is Ownable {
struct Candidate {
string name;
uint256 voteCount;
}
mapping(uint256 => Candidate) public candidates;
mapping(address => bool) public hasVoted;
uint256 public candidatesCount;
event Voted(address indexed voter, uint256 candidateId);
constructor(string[] memory candidateNames) {
for (uint256 i = 0; i < candidateNames.length; i++) {
candidates[i] = Candidate(candidateNames[i], 0);
candidatesCount++;
}
}
function vote(uint256 candidateId) external {
require(candidateId < candidatesCount, "Invalid candidate");
require(!hasVoted[msg.sender], "Already voted");
hasVoted[msg.sender] = true;
candidates[candidateId].voteCount++;
emit Voted(msg.sender, candidateId);
}
function getCandidate(uint256 candidateId) external view returns (string memory name, uint256 votes) {
Candidate memory c = candidates[candidateId];
return (c.name, c.voteCount);
}
}