Lab 2: Build and Test a Voting Smart Contract With Hardhat: Proposals, One Vote Per Person and Deadlines
Goal
Build a contract where the owner adds candidates, each address votes once, voting closes at a deadline, and anyone can ask for the winner.
Setup
Use the Hardhat project from the Hardhat lesson, or create a new one with npx hardhat init.
Contract
Save as contracts/Voting.sol.
solidity
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
contract Voting {
struct Candidate {
string name;
uint256 votes;
}
address public immutable owner;
uint256 public deadline;
Candidate[] public candidates;
mapping(address => bool) public hasVoted;
event CandidateAdded(uint256 indexed id, string name);
event Voted(address indexed voter, uint256 indexed candidateId);
error NotOwner();
error VotingClosed();
error AlreadyVoted();
error InvalidCandidate();
error StillOpen();
error NoCandidates();
constructor(uint256 durationSeconds) {
owner = msg.sender;
deadline = block.timestamp + durationSeconds;
}
modifier onlyOwner() {
if (msg.sender != owner) revert NotOwner();
_;
}
function addCandidate(string calldata name) external onlyOwner {
if (block.timestamp >= deadline) revert VotingClosed();
candidates.push(Candidate(name, 0));
emit CandidateAdded(candidates.length - 1, name);
}
function vote(uint256 candidateId) external {
if (block.timestamp >= deadline) revert VotingClosed();
if (hasVoted[msg.sender]) revert AlreadyVoted();
if (candidateId >= candidates.length) revert InvalidCandidate();
hasVoted[msg.sender] = true;
candidates[candidateId].votes += 1;
emit Voted(msg.sender, candidateId);
}
function candidateCount() external view returns (uint256) {
return candidates.length;
}
function winner() external view returns (string memory name, uint256 votes) {
if (block.timestamp < deadline) revert StillOpen();
if (candidates.length == 0) revert NoCandidates();
uint256 best = 0;
for (uint256 i = 1; i < candidates.length; i++) {
if (candidates[i].votes > candidates[best].votes) best = i;
}
return (candidates[best].name, candidates[best].votes);
}
}
Tests
Save as test/Voting.js.
javascript
const { expect } = require("chai");
const { ethers } = require("hardhat");
const { time } = require("@nomicfoundation/hardhat-network-helpers");
describe("Voting", function () {
let voting, owner, alice, bob;
beforeEach(async function () {
[owner, alice, bob] = await ethers.getSigners();
const Voting = await ethers.getContractFactory("Voting");
voting = await Voting.deploy(3600); // one hour
await voting.waitForDeployment();
await voting.addCandidate("Asha");
await voting.addCandidate("Ravi");
});
it("counts a vote", async function () {
await voting.connect(alice).vote(0);
const c = await voting.candidates(0);
expect(c.votes).to.equal(1n);
});
it("blocks a second vote from the same address", async function () {
await voting.connect(alice).vote(0);
await expect(voting.connect(alice).vote(1)).to.be.revertedWithCustomError(voting, "AlreadyVoted");
});
it("rejects an invalid candidate", async function () {
await expect(voting.connect(alice).vote(9)).to.be.revertedWithCustomError(voting, "InvalidCandidate");
});
it("only the owner can add candidates", async function () {
await expect(voting.connect(alice).addCandidate("Hacker")).to.be.revertedWithCustomError(voting, "NotOwner");
});
it("does not allow winner() before the deadline", async function () {
await expect(voting.winner()).to.be.revertedWithCustomError(voting, "StillOpen");
});
it("returns the winner after the deadline", async function () {
await voting.connect(alice).vote(1);
await voting.connect(bob).vote(1);
await voting.vote(0);
await time.increase(3601);
const [name, votes] = await voting.winner();
expect(name).to.equal("Ravi");
expect(votes).to.equal(2n);
});
it("rejects votes after the deadline", async function () {
await time.increase(3601);
await expect(voting.connect(alice).vote(0)).to.be.revertedWithCustomError(voting, "VotingClosed");
});
});
bash
px hardhat test
All seven tests should pass. The time.increase helper moves the local chain clock forward, so you do not have to wait an hour.
Think About Weaknesses
- Anyone can create many addresses and vote many times (a Sybil attack). Real systems need identity or token-based rules
- Votes are public. Private voting needs more advanced cryptography
- A tie returns the first candidate with the highest votes
Extensions
- Add a whitelist of eligible voters
- Allow the owner to extend the deadline once
- Show vote counts in the ethers.js page from the DApp lesson
Conclusion
You built a voting contract with custom errors, access control and a deadline, and tested success and failure cases with Hardhat.
Quick Summary: goal; setup; contract; tests; weaknesses; extensions.