Skip to content
Tutorials Center
My learning

Topics

Lesson 39 of 47 ยท Projects

Project: A Voting Contract

Build a Solidity voting contract with proposals, voter registration, one vote per address, a deadline and a tally, then test the same logic in a JavaScript stand-in.

A vote is a perfect first project. The rules are small and the stakes of getting them wrong are easy to see: one person must not vote twice, outsiders must not vote at all, and nobody may vote after the deadline. Those three rules use mappings, access control, time checks and custom errors, which makes this project a review of the Language Basics and Contract Structure chapters.

In this project you will design the rules, read a complete Solidity contract for them, and then run a JavaScript stand-in that follows the same logic, including a tiny test suite. The Solidity code is read-only here because the site cannot compile or deploy it. The stand-in is not Solidity: it has no real accounts, no gas and no automatic rollback, so you will see where a thrown error stands in for a revert.

The rules of our vote

Proposals Fixed when the vote is created.
Registration Only the chairperson adds voters.
One vote each A registered address votes once.
Deadline No registering or voting after it.

Four rules, each with a matching check in the code.

1 / 2

Design first: state and rules

Before writing code, list what the contract must remember. Proposals need a name and a vote count, so a struct in an array is a natural fit (Strings, Bytes, Arrays and Structs). Two mappings record who is registered and who has already voted. A deadline is a timestamp saved at deployment and never changed, which makes it a good immutable (Constructors, Constants and Immutables).

Then list the failures: calling a chairperson-only function as someone else, registering the same person twice, voting without registration, voting twice, voting for a proposal that does not exist, and acting after the deadline. Each failure gets a custom error so a caller and a test can see exactly what went wrong.

The contract

SOLIDITY
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

contract Voting {
    struct Proposal {
        string name;
        uint256 votes;
    }

    address public immutable chairperson;
    uint256 public immutable votingEnds;

    Proposal[] public proposals;
    mapping(address => bool) public registered;
    mapping(address => bool) public hasVoted;

    event VoterRegistered(address indexed voter);
    event Voted(address indexed voter, uint256 indexed proposalId);

    error NotChairperson();
    error VotingClosed();
    error VotingStillOpen();
    error AlreadyRegistered();
    error NotRegistered();
    error AlreadyVoted();
    error UnknownProposal(uint256 proposalId);
    error NoProposals();

    modifier onlyChairperson() {
        if (msg.sender != chairperson) revert NotChairperson();
        _;
    }

    modifier whileOpen() {
        if (block.timestamp >= votingEnds) revert VotingClosed();
        _;
    }

    constructor(string[] memory names, uint256 durationSeconds) {
        if (names.length == 0) revert NoProposals();
        chairperson = msg.sender;
        votingEnds = block.timestamp + durationSeconds;
        for (uint256 i = 0; i < names.length; i++) {
            proposals.push(Proposal({name: names[i], votes: 0}));
        }
    }

    function register(address voter) external onlyChairperson whileOpen {
        if (registered[voter]) revert AlreadyRegistered();
        registered[voter] = true;
        emit VoterRegistered(voter);
    }

    function vote(uint256 proposalId) external whileOpen {
        if (!registered[msg.sender]) revert NotRegistered();
        if (hasVoted[msg.sender]) revert AlreadyVoted();
        if (proposalId >= proposals.length) revert UnknownProposal(proposalId);

        hasVoted[msg.sender] = true;
        proposals[proposalId].votes += 1;
        emit Voted(msg.sender, proposalId);
    }

    function proposalCount() external view returns (uint256) {
        return proposals.length;
    }

    function winner() external view returns (string memory name, uint256 votes) {
        if (block.timestamp < votingEnds) revert VotingStillOpen();
        uint256 best = 0;
        for (uint256 i = 1; i < proposals.length; i++) {
            if (proposals[i].votes > proposals[best].votes) best = i;
        }
        return (proposals[best].name, proposals[best].votes);
    }
}

Walk through the decisions. The checks run before any state changes, and hasVoted is set before the tally changes, so even a surprising caller could not vote twice. There is no external call anywhere, so reentrancy is not a concern here. The winner function loops over proposals, which is fine for a handful and a poor idea for thousands, as Gas Costs and Optimization explains. It uses a strict > so that on a tie the earliest proposal wins, which is a rule you should state openly rather than leave as a surprise. Events record each registration and vote so that a website can display them without reading storage (Events and Logs).

Votes here are public. Anyone can see which address voted for what, because that is how public chains work. A secret ballot needs extra techniques such as commit-reveal or zero-knowledge proofs, which are outside this project.

The stand-in implementation

The stand-in uses a class with the same functions. The part of msg.sender is played by a first argument, and the part of block.timestamp by a clock you set by hand. A thrown Revert stands in for revert. Unlike a real revert it does not undo changes, so the class does every check before it changes anything, exactly like the Solidity code.

JS The voting contract as a JavaScript class

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Every rule from the design list shows up once. The registered voter ann cannot vote twice, cy cannot vote at all, the unknown id 7 is refused, and the clock decides when voting stops and the winner can be read.

Tests for each rule

A contract this small deserves a test per rule (Testing Contracts). In Hardhat or Foundry you would write them in JavaScript or Solidity and run them on a local chain. Here is the shape of one Foundry test, read-only:

SOLIDITY
// test/Voting.t.sol (Foundry, sketch)
function test_RevertWhen_VotingTwice() public {
    vm.prank(chair);
    voting.register(ann);

    vm.startPrank(ann);
    voting.vote(0);
    vm.expectRevert(Voting.AlreadyVoted.selector);
    voting.vote(1);
    vm.stopPrank();
}

The stand-in below does the same job with a minimal test runner, so you can see the idea of one assertion per rule. It repeats a smaller copy of the class so the TryIt stands on its own, and it also tests the tie rule.

JS A tiny test suite for the voting rules

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Real: the rules, the order of checks, and the idea of one test per rule. Stand-in: JavaScript exceptions are not reverts, and the clock is a plain field. In a real test you also assert on emitted events and storage after a failure to prove that nothing changed.

Ideas to extend it

  • Delegation: let a voter pass their vote to someone else, which needs a mapping of delegates and care about loops of delegation.
  • Weighted votes: weigh votes by a token balance, then read about snapshots, since balances that change during a vote can be gamed.
  • Gas-friendly tally: keep a running leader in vote() instead of looping in winner().
  • Self-registration with a fee or a signature: reuse the signed-message ideas from Oracles, Randomness and Off-Chain Data.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does vote set hasVoted[msg.sender] = true before updating the tally?

    Checks first, then effects, is a habit that protects against repeated calls. Here there are no external calls, but the habit costs nothing and keeps the contract safe if it grows.
  2. 2. Which Solidity feature stores the deadline cheaply because it never changes after deployment?

    Immutables are fixed at deployment and embedded in the contract code, so reading them avoids a storage read.
  3. 3. What is a weakness of winner() as written?

    A loop costs gas in proportion to the list length. For a few proposals it is fine. For many, track the leader while voting instead.
  4. 4. In the stand-in, what plays the role of block.timestamp?

    There is no blockchain, so the class keeps a clock value that the script advances. The deadline check compares it with votingEnds.

Summary

  • Design a contract by listing its state, its rules and its failure cases before writing code.
  • Mappings track registration and votes, a struct array holds proposals, and an immutable deadline fixes the schedule.
  • Custom errors and guard modifiers make each rule visible and testable.
  • Run all checks before changing state, and decide openly how ties are handled.
  • Write at least one test per rule, including the failure paths.
  • Votes on a public chain are public. Secret ballots need extra techniques.

Next: Project: Crowdfunding With Refunds.