Skip to content

Commit 1a8ab36

Browse files
Bonus Assignment
1 parent b8e81b9 commit 1a8ab36

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed

Bonus Assignment

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
pragma solidity ^0.8.0;
2+
3+
contract Voting {
4+
struct Candidate {
5+
uint id;
6+
string name;
7+
uint voteCount;
8+
}
9+
mapping(address => bool) public voters;
10+
Candidate[] public candidates;
11+
address public owner;
12+
event Voted(uint indexed candidateId, address voter);
13+
14+
modifier onlyOwner() {
15+
require(msg.sender == owner, "Only the owner can perform this action");
16+
_;
17+
}
18+
19+
20+
constructor(string[] memory candidateNames) {
21+
owner = msg.sender;
22+
for (uint i = 0; i < candidateNames.length; i++) {
23+
candidates.push(Candidate({
24+
id: i,
25+
name: candidateNames[i],
26+
voteCount: 0
27+
}));
28+
}
29+
}
30+
31+
32+
function addCandidate(string memory name) public onlyOwner {
33+
uint newId = candidates.length;
34+
candidates.push(Candidate({
35+
id: newId,
36+
name: name,
37+
voteCount: 0
38+
}));
39+
}
40+
41+
function vote(uint candidateId) public {
42+
require(!voters[msg.sender], "You have already voted");
43+
require(candidateId < candidates.length, "Invalid candidate ID");
44+
45+
voters[msg.sender] = true;
46+
candidates[candidateId].voteCount++;
47+
48+
emit Voted(candidateId, msg.sender);
49+
}
50+
51+
52+
function getNumCandidates() public view returns (uint) {
53+
return candidates.length;
54+
}
55+
56+
57+
function getCandidate(uint candidateId) public view returns (uint, string memory, uint) {
58+
require(candidateId < candidates.length, "Invalid candidate ID");
59+
Candidate memory candidate = candidates[candidateId];
60+
return (candidate.id, candidate.name, candidate.voteCount);
61+
}
62+
}

0 commit comments

Comments
 (0)