TExcelTAD
Home › Solidity › Mini Project: Crowdfunding

Mini Project: Crowdfunding

In this project you'll build a crowdfunding contract, step by step. Creators start campaigns with a funding goal and a deadline; backers pledge ether; if the goal is reached by the deadline the creator claims the funds, otherwise every backer can get a refund. It brings together much of the course: structs and mappings, payable functions, custom errors, events, modifiers, inheritance, safe ether transfers and testing with simulated users.

Everything runs on the playground's local EVM with test ether. This is a programming exercise, not a template for raising real money: a production version would need an audit.

The rules we'll implement:

Phase Allowed
Before the deadline anyone can pledge; backers can unpledge
After the deadline, goal reached the creator can claim once
After the deadline, goal missed each backer can refund their pledge

Step 1: Campaigns as structs

A campaign is a record, so it's a struct, stored in a mapping by id. launch creates one and emits an event so front ends can list campaigns.

solidity · try it yourself
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

import "hardhat/console.sol";

contract Crowdfund {
    struct Campaign {
        address creator;
        uint256 goal;
        uint256 pledged;
        uint64 deadline;
        bool claimed;
    }

    uint256 public count;
    mapping(uint256 => Campaign) public campaigns;

    event Launched(uint256 indexed id, address indexed creator, uint256 goal, uint64 deadline);

    error InvalidGoal();
    error InvalidDuration(uint256 duration);

    function launch(uint256 goal, uint256 duration) external returns (uint256 id) {
        if (goal == 0) revert InvalidGoal();
        if (duration == 0 || duration > 90 days) revert InvalidDuration(duration);
        id = ++count;
        campaigns[id] = Campaign({
            creator: msg.sender,
            goal: goal,
            pledged: 0,
            deadline: uint64(block.timestamp + duration),
            claimed: false
        });
        emit Launched(id, msg.sender, goal, uint64(block.timestamp + duration));
    }
}

contract Main {
    function main() external {
        Crowdfund cf = new Crowdfund();
        uint256 id = cf.launch(10 ether, 7 days);
        (address creator, uint256 goal, , uint64 deadline, ) = cf.campaigns(id);
        console.log("campaign", id, "by Main?", creator == address(this));
        console.log("goal (ETH):", goal / 1 ether, "deadline:", deadline);
        cf.launch(1 ether, 365 days);
    }
}
campaign 1 by Main? true
goal (ETH): 10 deadline: 1767830400
main() failed: custom error InvalidDuration(31536000)

Ids start at 1 (++count), so id 0 means "no campaign", a handy sentinel. The duration limit is validated with a custom error that reports the bad value.

Step 2: Pledging ether

Backers send ether with pledge(id), a payable function. We track each backer's amount per campaign in a nested mapping. unpledge lets backers change their mind before the deadline. Note the checks-effects-interactions order when sending ether back.

A Backer helper contract plays each user, so the crowdfund sees distinct msg.sender addresses.

solidity · try it yourself
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

import "hardhat/console.sol";

contract Crowdfund {
    struct Campaign { address creator; uint256 goal; uint256 pledged; uint64 deadline; bool claimed; }

    uint256 public count;
    mapping(uint256 => Campaign) public campaigns;
    mapping(uint256 => mapping(address => uint256)) public pledgedBy;

    event Launched(uint256 indexed id, address indexed creator, uint256 goal, uint64 deadline);
    event Pledged(uint256 indexed id, address indexed backer, uint256 amount);
    event Unpledged(uint256 indexed id, address indexed backer, uint256 amount);

    error NoSuchCampaign(uint256 id);
    error Ended(uint256 id);
    error AmountTooHigh(uint256 pledged, uint256 requested);

    function launch(uint256 goal, uint256 duration) external returns (uint256 id) {
        id = ++count;
        campaigns[id] = Campaign(msg.sender, goal, 0, uint64(block.timestamp + duration), false);
        emit Launched(id, msg.sender, goal, uint64(block.timestamp + duration));
    }

    function pledge(uint256 id) external payable {
        Campaign storage c = campaigns[id];
        if (c.creator == address(0)) revert NoSuchCampaign(id);
        if (block.timestamp >= c.deadline) revert Ended(id);
        c.pledged += msg.value;
        pledgedBy[id][msg.sender] += msg.value;
        emit Pledged(id, msg.sender, msg.value);
    }

    function unpledge(uint256 id, uint256 amount) external {
        Campaign storage c = campaigns[id];
        if (block.timestamp >= c.deadline) revert Ended(id);
        uint256 mine = pledgedBy[id][msg.sender];
        if (amount > mine) revert AmountTooHigh(mine, amount);
        pledgedBy[id][msg.sender] = mine - amount;       // effects first
        c.pledged -= amount;
        (bool ok, ) = payable(msg.sender).call{value: amount}("");   // interaction last
        require(ok, "send failed");
        emit Unpledged(id, msg.sender, amount);
    }
}

contract Backer {
    receive() external payable {}
    function pledge(Crowdfund cf, uint256 id) external payable { cf.pledge{value: msg.value}(id); }
    function unpledge(Crowdfund cf, uint256 id, uint256 amount) external { cf.unpledge(id, amount); }
}

contract Main {
    constructor() payable {}

    function main() external {
        Crowdfund cf = new Crowdfund();
        uint256 id = cf.launch(10 ether, 7 days);
        Backer ann = new Backer();
        Backer ben = new Backer();

        ann.pledge{value: 4 ether}(cf, id);
        ben.pledge{value: 3 ether}(cf, id);
        ben.unpledge(cf, id, 1 ether);

        (, , uint256 pledged, , ) = cf.campaigns(id);
        console.log("total pledged:", pledged / 1 ether, "ETH");
        console.log("ben pledged  :", cf.pledgedBy(id, address(ben)) / 1 ether, "ETH");
        console.log("ben wallet   :", address(ben).balance / 1 ether, "ETH");
    }
}
total pledged: 6 ETH
ben pledged  : 2 ETH
ben wallet   : 1 ETH
event Launched(id: 1, creator: 0x5FbDB2315678afecb367f032d93F642f64180aa3, goal: 10000000000000000000, deadline: 1767830400)
event Pledged(id: 1, backer: 0xB7A5bd0345EF1Cc5E66bf61BdeC17D2461fBd968, amount: 4000000000000000000)
event Pledged(id: 1, backer: 0xeEBe00Ac0756308ac4AaBfD76c05c4F3088B8883, amount: 3000000000000000000)
event Unpledged(id: 1, backer: 0xeEBe00Ac0756308ac4AaBfD76c05c4F3088B8883, amount: 1000000000000000000)

Step 3: Controlling time for tests

Claims and refunds depend on the deadline, but the playground's block time is fixed (as in a single test transaction). Real frameworks solve this with cheatcodes like Foundry's vm.warp. We'll do it with inheritance: the contract reads time through a virtual function _now(), and a test version overrides it with an adjustable clock.

solidity
function _now() internal view virtual returns (uint256) {
    return block.timestamp;
}
solidity
contract TestCrowdfund is Crowdfund {
    uint256 private offset;
    function warp(uint256 secondsForward) external { offset += secondsForward; }
    function _now() internal view override returns (uint256) { return block.timestamp + offset; }
}

The production contract (Crowdfund) never contains the warp function, so users can't manipulate its clock. Only the test subclass can.

Step 4: The complete contract

Now we add claim for successful campaigns and refund for failed ones, with a modifier for the "campaign exists" check. Two campaigns are run side by side: one reaches its goal, one doesn't.

solidity · try it yourself
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

import "hardhat/console.sol";

contract Crowdfund {
    struct Campaign { address creator; uint256 goal; uint256 pledged; uint64 deadline; bool claimed; }

    uint256 public count;
    mapping(uint256 => Campaign) public campaigns;
    mapping(uint256 => mapping(address => uint256)) public pledgedBy;

    event Launched(uint256 indexed id, address indexed creator, uint256 goal, uint64 deadline);
    event Pledged(uint256 indexed id, address indexed backer, uint256 amount);
    event Claimed(uint256 indexed id, uint256 amount);
    event Refunded(uint256 indexed id, address indexed backer, uint256 amount);

    error NoSuchCampaign(uint256 id);
    error Ended(uint256 id);
    error NotEnded(uint256 id, uint256 deadline);
    error NotCreator(address caller);
    error GoalNotReached(uint256 pledged, uint256 goal);
    error GoalReached();
    error AlreadyClaimed();
    error NothingToRefund();

    modifier exists(uint256 id) {
        if (campaigns[id].creator == address(0)) revert NoSuchCampaign(id);
        _;
    }

    function _now() internal view virtual returns (uint256) {
        return block.timestamp;
    }

    function launch(uint256 goal, uint256 duration) external returns (uint256 id) {
        require(goal > 0 && duration > 0 && duration <= 90 days, "bad parameters");
        id = ++count;
        uint64 deadline = uint64(_now() + duration);
        campaigns[id] = Campaign(msg.sender, goal, 0, deadline, false);
        emit Launched(id, msg.sender, goal, deadline);
    }

    function pledge(uint256 id) external payable exists(id) {
        Campaign storage c = campaigns[id];
        if (_now() >= c.deadline) revert Ended(id);
        c.pledged += msg.value;
        pledgedBy[id][msg.sender] += msg.value;
        emit Pledged(id, msg.sender, msg.value);
    }

    function claim(uint256 id) external exists(id) {
        Campaign storage c = campaigns[id];
        if (msg.sender != c.creator) revert NotCreator(msg.sender);
        if (_now() < c.deadline) revert NotEnded(id, c.deadline);
        if (c.pledged < c.goal) revert GoalNotReached(c.pledged, c.goal);
        if (c.claimed) revert AlreadyClaimed();
        c.claimed = true;                                           // effects
        (bool ok, ) = payable(c.creator).call{value: c.pledged}(""); // interaction
        require(ok, "send failed");
        emit Claimed(id, c.pledged);
    }

    function refund(uint256 id) external exists(id) {
        Campaign storage c = campaigns[id];
        if (_now() < c.deadline) revert NotEnded(id, c.deadline);
        if (c.pledged >= c.goal) revert GoalReached();
        uint256 amount = pledgedBy[id][msg.sender];
        if (amount == 0) revert NothingToRefund();
        pledgedBy[id][msg.sender] = 0;                              // effects
        (bool ok, ) = payable(msg.sender).call{value: amount}("");  // interaction
        require(ok, "send failed");
        emit Refunded(id, msg.sender, amount);
    }
}

contract TestCrowdfund is Crowdfund {
    uint256 private offset;
    function warp(uint256 secondsForward) external { offset += secondsForward; }
    function _now() internal view override returns (uint256) { return block.timestamp + offset; }
}

contract Person {
    receive() external payable {}
    function launch(Crowdfund cf, uint256 goal, uint256 duration) external returns (uint256) { return cf.launch(goal, duration); }
    function pledge(Crowdfund cf, uint256 id) external payable { cf.pledge{value: msg.value}(id); }
    function claim(Crowdfund cf, uint256 id) external { cf.claim(id); }
    function refund(Crowdfund cf, uint256 id) external { cf.refund(id); }
}

contract Main {
    constructor() payable {}

    function eth(address a) internal view returns (uint256) {
        return a.balance / 1 ether;
    }

    function main() external {
        TestCrowdfund cf = new TestCrowdfund();
        Person maker = new Person();      // creator of both campaigns
        Person ann = new Person();
        Person ben = new Person();

        uint256 garden = maker.launch(cf, 5 ether, 7 days);
        uint256 robot = maker.launch(cf, 20 ether, 7 days);

        ann.pledge{value: 3 ether}(cf, garden);
        ben.pledge{value: 2 ether}(cf, garden);
        ann.pledge{value: 4 ether}(cf, robot);

        // claiming too early fails
        try maker.claim(cf, garden) {} catch (bytes memory err) {
            console.log("early claim rejected?", bytes4(err) == Crowdfund.NotEnded.selector);
        }

        cf.warp(8 days);                  // move past the deadline

        maker.claim(cf, garden);          // goal reached: 5 of 5
        ann.refund(cf, robot);            // goal missed: 4 of 20

        console.log("maker received:", eth(address(maker)), "ETH");
        console.log("ann wallet    :", eth(address(ann)), "ETH");
        console.log("contract left :", eth(address(cf)), "ETH");
    }
}
early claim rejected? true
maker received: 5 ETH
ann wallet    : 4 ETH
contract left : 0 ETH
event Launched(id: 1, creator: 0xB7A5bd0345EF1Cc5E66bf61BdeC17D2461fBd968, goal: 5000000000000000000, deadline: 1767830400)
event Launched(id: 2, creator: 0xB7A5bd0345EF1Cc5E66bf61BdeC17D2461fBd968, goal: 20000000000000000000, deadline: 1767830400)
event Pledged(id: 1, backer: 0xeEBe00Ac0756308ac4AaBfD76c05c4F3088B8883, amount: 3000000000000000000)
event Pledged(id: 1, backer: 0x10C6E9530F1C1AF873a391030a1D9E8ed0630D26, amount: 2000000000000000000)
event Pledged(id: 2, backer: 0xeEBe00Ac0756308ac4AaBfD76c05c4F3088B8883, amount: 4000000000000000000)
event Claimed(id: 1, amount: 5000000000000000000)
event Refunded(id: 2, backer: 0xeEBe00Ac0756308ac4AaBfD76c05c4F3088B8883, amount: 4000000000000000000)

Read the events from top to bottom: they're the campaign's complete, auditable history, exactly what a front end would display.

Step 5: Test the unhappy paths

A contract holding other people's money must refuse every invalid action. This final test suite reuses the contract from step 4 (copied in full so the example runs on its own) and checks each rule with try/catch:

solidity · try it yourself
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

import "hardhat/console.sol";

contract Crowdfund {
    struct Campaign { address creator; uint256 goal; uint256 pledged; uint64 deadline; bool claimed; }
    uint256 public count;
    mapping(uint256 => Campaign) public campaigns;
    mapping(uint256 => mapping(address => uint256)) public pledgedBy;

    error NoSuchCampaign(uint256 id);
    error Ended(uint256 id);
    error NotEnded(uint256 id, uint256 deadline);
    error NotCreator(address caller);
    error GoalNotReached(uint256 pledged, uint256 goal);
    error GoalReached();
    error AlreadyClaimed();
    error NothingToRefund();

    modifier exists(uint256 id) {
        if (campaigns[id].creator == address(0)) revert NoSuchCampaign(id);
        _;
    }

    function _now() internal view virtual returns (uint256) { return block.timestamp; }

    function launch(uint256 goal, uint256 duration) external returns (uint256 id) {
        require(goal > 0 && duration > 0 && duration <= 90 days, "bad parameters");
        id = ++count;
        campaigns[id] = Campaign(msg.sender, goal, 0, uint64(_now() + duration), false);
    }

    function pledge(uint256 id) external payable exists(id) {
        Campaign storage c = campaigns[id];
        if (_now() >= c.deadline) revert Ended(id);
        c.pledged += msg.value;
        pledgedBy[id][msg.sender] += msg.value;
    }

    function claim(uint256 id) external exists(id) {
        Campaign storage c = campaigns[id];
        if (msg.sender != c.creator) revert NotCreator(msg.sender);
        if (_now() < c.deadline) revert NotEnded(id, c.deadline);
        if (c.pledged < c.goal) revert GoalNotReached(c.pledged, c.goal);
        if (c.claimed) revert AlreadyClaimed();
        c.claimed = true;
        (bool ok, ) = payable(c.creator).call{value: c.pledged}("");
        require(ok, "send failed");
    }

    function refund(uint256 id) external exists(id) {
        Campaign storage c = campaigns[id];
        if (_now() < c.deadline) revert NotEnded(id, c.deadline);
        if (c.pledged >= c.goal) revert GoalReached();
        uint256 amount = pledgedBy[id][msg.sender];
        if (amount == 0) revert NothingToRefund();
        pledgedBy[id][msg.sender] = 0;
        (bool ok, ) = payable(msg.sender).call{value: amount}("");
        require(ok, "send failed");
    }
}

contract TestCrowdfund is Crowdfund {
    uint256 private offset;
    function warp(uint256 s) external { offset += s; }
    function _now() internal view override returns (uint256) { return block.timestamp + offset; }
}

contract Person {
    receive() external payable {}
    function launch(Crowdfund cf, uint256 goal, uint256 d) external returns (uint256) { return cf.launch(goal, d); }
    function pledge(Crowdfund cf, uint256 id) external payable { cf.pledge{value: msg.value}(id); }
    function claim(Crowdfund cf, uint256 id) external { cf.claim(id); }
    function refund(Crowdfund cf, uint256 id) external { cf.refund(id); }
}

contract Main {
    uint256 passed;
    constructor() payable {}

    function expectError(bool ok, bytes memory err, bytes4 expected, string memory name) internal {
        bool good = !ok && bytes4(err) == expected;
        if (good) passed++;
        console.log(good ? "PASS" : "FAIL", name);
    }

    function main() external {
        TestCrowdfund cf = new TestCrowdfund();
        Person maker = new Person();
        Person ann = new Person();
        Person mallory = new Person();
        uint256 id = maker.launch(cf, 5 ether, 7 days);
        ann.pledge{value: 5 ether}(cf, id);

        bool ok; bytes memory err;
        (ok, err) = address(cf).call{value: 1 ether}(abi.encodeCall(Crowdfund.pledge, (99)));
        expectError(ok, err, Crowdfund.NoSuchCampaign.selector, "pledge to unknown campaign");

        (ok, err) = address(mallory).call(abi.encodeCall(Person.claim, (cf, id)));
        expectError(ok, err, Crowdfund.NotCreator.selector, "stranger cannot claim");

        (ok, err) = address(ann).call(abi.encodeCall(Person.refund, (cf, id)));
        expectError(ok, err, Crowdfund.NotEnded.selector, "no refund before deadline");

        cf.warp(7 days);              // exactly at the deadline

        (ok, err) = address(mallory).call{value: 1 ether}(abi.encodeCall(Person.pledge, (cf, id)));
        expectError(ok, err, Crowdfund.Ended.selector, "no pledges at the deadline");

        (ok, err) = address(ann).call(abi.encodeCall(Person.refund, (cf, id)));
        expectError(ok, err, Crowdfund.GoalReached.selector, "no refund when goal reached");

        maker.claim(cf, id);
        (ok, err) = address(maker).call(abi.encodeCall(Person.claim, (cf, id)));
        expectError(ok, err, Crowdfund.AlreadyClaimed.selector, "cannot claim twice");

        console.log("passed", passed, "of 6");
        console.log("maker received:", address(maker).balance / 1 ether, "ETH");
    }
}
PASS pledge to unknown campaign
PASS stranger cannot claim
PASS no refund before deadline
PASS no pledges at the deadline
PASS no refund when goal reached
PASS cannot claim twice
passed 6 of 6
maker received: 5 ETH

The revert data of the inner error passes unchanged through the Person helpers, so Main can compare selectors directly.

Ideas to extend the project

  • Add a minimum pledge and a maximum duration per creator.
  • Pay out in an ERC-20 token instead of ether, using approve + transferFrom (see ERC-20 Tokens).
  • Mint an ERC-721 "backer badge" to everyone who pledged to a successful campaign.
  • Add a nonReentrant guard to claim, refund and unpledge, even though they already follow checks-effects-interactions.
  • Write the same tests in Foundry (vm.warp, vm.prank, vm.expectRevert) as described in Testing & Deployment.

Test yourself

Why does the contract read time through a virtual _now() function?

  1. block.timestamp is not available in Solidity
  2. So a test subclass can override it and move time forward, while the production contract uses block.timestamp
  3. To save gas
  4. Because deadlines must be in milliseconds

In refund, why is pledgedBy[id][msg.sender] set to 0 before sending ether?

  1. To emit the event
  2. So a re-entering backer can't be refunded twice (checks-effects-interactions)
  3. Because call needs a zero balance
  4. It's not necessary

How does the project simulate several different users?

  1. Each is a Person helper contract with its own address
  2. By changing tx.origin
  3. By passing addresses as arguments
  4. With multiple Main contracts