SolidityIn

Build a voting contract

Lesson 40 of 40 · Projects

A voting contract shows how to model people and choices. The chairperson registers voters, each voter can vote once, and the proposal with the most votes wins.

Structs hold each voter's status and each proposal's vote count. A mapping from address to Voter lets you check in one step whether someone is allowed to vote and whether they already did.

Looping over proposals to find the winner is fine here because the list is small and the loop sits in a view function, which is free when called off-chain. For a very large list, you would track the leader as votes come in instead.

Try extending it: add a deadline, let voters delegate their vote, or allow the chairperson to close voting. Each change teaches a new pattern.

contract Ballot {
    struct Voter { bool allowed; bool voted; }
    struct Proposal { string name; uint256 votes; }

    address public chair = msg.sender;
    mapping(address => Voter) public voters;
    Proposal[] public proposals;

    constructor(string[] memory names) {
        for (uint256 i = 0; i < names.length; i++) proposals.push(Proposal(names[i], 0));
    }
    function allow(address v) external {
        require(msg.sender == chair, "Not chair");
        voters[v].allowed = true;
    }
    function vote(uint256 p) external {
        Voter storage me = voters[msg.sender];
        require(me.allowed && !me.voted, "Cannot vote");
        me.voted = true;
        proposals[p].votes += 1;
    }
    function winner() external view returns (string memory) {
        uint256 best;
        for (uint256 i = 1; i < proposals.length; i++)
            if (proposals[i].votes > proposals[best].votes) best = i;
        return proposals[best].name;
    }
}

Try it yourself

Add a deadline set in the constructor, and make vote revert after it passes. Then compile.

Press Compile to check your code in the browser. Short fragments are wrapped in a contract automatically.

Quick check: Why is a Voter struct stored in a mapping?