This Solidity smart contract, named Ballot, implements a voting system with delegation. It allows voters to delegate their voting rights to others and cast votes on proposals. The contract is designed to be used for choosing one of the provided proposals.
- Represents a single voter and includes fields such as weight, voted status, delegate, and the index of the voted proposal.
- Represents a single proposal with a short name and the number of accumulated votes.
- The address of the chairperson who deploys the contract and has the initial voting weight.
giveRightToVote
: Allows the chairperson to grant voting rights to a specific address.delegate
: Allows a voter to delegate their vote to another address.vote
: Allows a voter to cast their vote on a specific proposal.
- The contract includes functions (
winningProposal
andwinnerName
) to determine the winning proposal based on the accumulated votes.
- Deploy the contract by providing an array of proposal names.
- The chairperson can grant voting rights to specific addresses using the
giveRightToVote
function.
- Voters can either cast their votes directly using the
vote
function or delegate their votes to other addresses using thedelegate
function.
- Use the
winnerName
function to retrieve the name of the winning proposal after the voting process is complete.
- Only the chairperson can grant voting rights to prevent unauthorized voting.
- The contract checks for delegation loops to avoid infinite loops during the delegation process.
- Various require statements are used to ensure that voters have the right to vote and that they haven't voted before.
// Deploy the contract with proposal names
Ballot ballot = new Ballot(["Proposal A", "Proposal B", "Proposal C"]);
// Chairperson grants voting rights
ballot.giveRightToVote(address);
// Voters cast their votes or delegate
ballot.vote(0);
ballot.delegate(anotherAddress);
// Determine the winner
bytes32 winner = ballot.winnerName();