|
| 1 | +// SPDX-License-Identifier: MIT |
| 2 | +pragma solidity 0.8.26; |
| 3 | + |
| 4 | +contract SimpleVotingSystem { |
| 5 | + struct Candidate { |
| 6 | + uint id; |
| 7 | + string name; |
| 8 | + uint voteCount; |
| 9 | + } |
| 10 | + |
| 11 | + address public owner; |
| 12 | + mapping(uint => Candidate) public candidates; |
| 13 | + mapping(address => bool) public voters; |
| 14 | + uint[] private candidateIds; |
| 15 | + |
| 16 | + modifier onlyOwner() { |
| 17 | + require(msg.sender == owner, "Only the contract owner can perform this action"); |
| 18 | + _; |
| 19 | + } |
| 20 | + |
| 21 | + constructor() { |
| 22 | + owner = msg.sender; |
| 23 | + } |
| 24 | + |
| 25 | + function addCandidate(string memory _name) public onlyOwner { |
| 26 | + require(bytes(_name).length > 0, "Candidate name cannot be empty"); |
| 27 | + uint candidateId = candidateIds.length + 1; |
| 28 | + candidates[candidateId] = Candidate(candidateId, _name, 0); |
| 29 | + candidateIds.push(candidateId); |
| 30 | + } |
| 31 | + |
| 32 | + function vote(uint _candidateId) public { |
| 33 | + require(!voters[msg.sender], "You have already voted"); |
| 34 | + require(_candidateId > 0 && _candidateId <= candidateIds.length, "Invalid candidate ID"); |
| 35 | + |
| 36 | + voters[msg.sender] = true; |
| 37 | + candidates[_candidateId].voteCount += 1; |
| 38 | + } |
| 39 | + |
| 40 | + function getTotalVotes(uint _candidateId) public view returns (uint) { |
| 41 | + require(_candidateId > 0 && _candidateId <= candidateIds.length, "Invalid candidate ID"); |
| 42 | + return candidates[_candidateId].voteCount; |
| 43 | + } |
| 44 | + |
| 45 | + function getCandidatesCount() public view returns (uint) { |
| 46 | + return candidateIds.length; |
| 47 | + } |
| 48 | + |
| 49 | + // Optional: Function to get candidate details by ID |
| 50 | + function getCandidate(uint _candidateId) public view returns (Candidate memory) { |
| 51 | + require(_candidateId > 0 && _candidateId <= candidateIds.length, "Invalid candidate ID"); |
| 52 | + return candidates[_candidateId]; |
| 53 | + } |
| 54 | +} |
0 commit comments