
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 61 62 63 64 65 66 67 68 69 70 |
// SPDX-License-Identifier: MIT pragma solidity >=0.6.12 <0.9.0; /** * @title VotingSystem * @dev A simple voting system that allows users to propose and vote on different options. */ contract VotingSystem { struct Proposal { string description; uint voteCount; } address public chairperson; mapping(address => bool) public voters; Proposal[] public proposals; /** * @dev Sets the chairperson and initializes the contract with a default proposal. * @param initialProposal The description of the initial proposal. */ constructor(string memory initialProposal) { chairperson = msg.sender; addProposal(initialProposal); } /** * @dev Adds a new proposal. Only the chairperson can add proposals. * @param proposalDescription The description of the proposal. */ function addProposal(string memory proposalDescription) public { require(msg.sender == chairperson, "Only the chairperson can add proposals."); proposals.push(Proposal({ description: proposalDescription, voteCount: 0 })); } /** * @dev Allows an address to be registered as a voter. * @param voter The address of the voter. */ function registerVoter(address voter) public { require(msg.sender == chairperson, "Only the chairperson can register voters."); voters[voter] = true; } /** * @dev Casts a vote to a proposal. Only registered voters can vote. * @param proposalIndex The index of the proposal in the proposals array. */ function vote(uint proposalIndex) public { require(voters[msg.sender], "Only registered voters can vote."); require(proposalIndex < proposals.length, "Invalid proposal index."); proposals[proposalIndex].voteCount += 1; } /** * @dev Returns the description and vote count of a proposal. * @param proposalIndex The index of the proposal in the proposals array. * @return description The description of the proposal. * @return voteCount The number of votes the proposal has received. */ function getProposal(uint proposalIndex) public view returns (string memory description, uint voteCount) { require(proposalIndex < proposals.length, "Invalid proposal index."); Proposal storage proposal = proposals[proposalIndex]; return (proposal.description, proposal.voteCount); } } |