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
| pragma solidity ^0.8.0;
contract Voting { struct Candidate { string name; uint256 voteCount; }
Candidate[] public candidates;
mapping(address => bool) public hasVoted;
function addCandidate(string memory name) public { candidates.push(Candidate(name, 0)); }
function vote(uint256 candidateId) public { require(candidateId < candidates.length, "Invalid candidate ID"); require(!hasVoted[msg.sender], "You have already voted");
candidates[candidateId].voteCount += 1; hasVoted[msg.sender] = true; }
function getCandidateCount() public view returns (uint256) { return candidates.length; }
function getCandidate(uint256 candidateId) public view returns (string memory, uint256) { require(candidateId < candidates.length, "Invalid candidate ID"); Candidate memory candidate = candidates[candidateId]; return (candidate.name, candidate.voteCount); } }
|