Skip to content
Tutorials Center
My learning

Topics

Lesson 40 of 47 ยท Projects

Project: Crowdfunding With Refunds

Build an all-or-nothing crowdfunding contract in Solidity with a goal, a deadline, a state machine, creator withdrawal and pull-based refunds, plus a JavaScript stand-in.

Crowdfunding sites like to promise "all or nothing": if the goal is reached by the deadline, the creator gets the money, and if not, every backer gets a refund. On a traditional site you trust the company to keep that promise. In a contract the promise is code, which nobody can bend. This project builds that contract, and it is a good place to practice three ideas together: a small state machine, the withdrawal pattern for paying out safely, and careful use of time.

You will read the complete Solidity contract (read-only, since the site cannot compile or deploy it) and then run a JavaScript stand-in with the same state machine and the same checks. The stand-in is not Solidity. There is no real ether, and a thrown error does not undo changes by itself, so the class checks everything before it changes anything.

All or nothing

Goal Total needed in wei.
Deadline Contributions stop here.
Success Creator withdraws everything.
Failure Each backer takes their own refund.

The outcome depends only on the total and the clock.

1 / 2

Designing the state machine

A campaign is always in exactly one of four states. You could store a state variable, but here the state follows from three facts we already keep: whether the funds were withdrawn, whether the deadline has passed, and whether the total reached the goal. Computing the state from facts avoids a classic bug, which is a stored state that someone forgets to update.

stateDiagram-v2
    [*] --> Open
    Open --> Succeeded: deadline passes, total >= goal
    Open --> Failed: deadline passes, total < goal
    Succeeded --> Withdrawn: creator withdraws
    Failed --> Failed: backers refund themselves

Only Succeeded campaigns can be withdrawn, and only Failed campaigns allow refunds.

Each function is allowed in exactly one state. contribute works only while Open, withdraw only after Succeeded, and refund only after Failed. Writing that table down first makes the checks almost mechanical.

The contract

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

contract Crowdfund {
    enum State { Open, Succeeded, Failed, Withdrawn }

    address public immutable creator;
    uint256 public immutable goal;      // in wei
    uint256 public immutable deadline;  // Unix timestamp

    uint256 public totalRaised;
    bool public withdrawn;
    mapping(address => uint256) public contributions;

    event Contributed(address indexed backer, uint256 amount);
    event Withdrawn(uint256 amount);
    event Refunded(address indexed backer, uint256 amount);

    error CampaignClosed();
    error NothingSent();
    error NotCreator();
    error WrongState(State current);
    error NothingToRefund();
    error TransferFailed();

    constructor(uint256 goalWei, uint256 durationSeconds) {
        creator = msg.sender;
        goal = goalWei;
        deadline = block.timestamp + durationSeconds;
    }

    function state() public view returns (State) {
        if (withdrawn) return State.Withdrawn;
        if (block.timestamp < deadline) return State.Open;
        return totalRaised >= goal ? State.Succeeded : State.Failed;
    }

    function contribute() external payable {
        if (state() != State.Open) revert CampaignClosed();
        if (msg.value == 0) revert NothingSent();
        contributions[msg.sender] += msg.value;
        totalRaised += msg.value;
        emit Contributed(msg.sender, msg.value);
    }

    function withdraw() external {
        if (msg.sender != creator) revert NotCreator();
        State s = state();
        if (s != State.Succeeded) revert WrongState(s);

        withdrawn = true;                       // effect first
        uint256 amount = address(this).balance;
        emit Withdrawn(amount);
        (bool ok, ) = creator.call{value: amount}("");
        if (!ok) revert TransferFailed();
    }

    function refund() external {
        State s = state();
        if (s != State.Failed) revert WrongState(s);
        uint256 amount = contributions[msg.sender];
        if (amount == 0) revert NothingToRefund();

        contributions[msg.sender] = 0;          // effect first
        emit Refunded(msg.sender, amount);
        (bool ok, ) = msg.sender.call{value: amount}("");
        if (!ok) revert TransferFailed();
    }
}

Why backers pull their own refunds

The contract never loops over backers and sends everyone's money at once. That is deliberate. A loop over an unknown number of backers could run out of gas, and one backer whose address rejects payments (a contract with a failing receive function) could block everyone else. Instead each backer calls refund() to pull their own money, which is the withdrawal pattern from Sending and Receiving Ether. A failing payment then only affects the person who called.

Effects before interactions

Both withdraw and refund change state before sending ether, and send ether last. This is the checks-effects-interactions order. If the receiving address is a contract that calls back into refund() while it is being paid, the contribution is already zero and the second call reverts with NothingToRefund. Reentrancy Step by Step shows what happens when the order is reversed.

Design details worth noticing

  • state() is computed. There is no stored state to get out of sync.
  • withdrawn is a bool that locks the money. Once it is set, state() returns Withdrawn and refund() reverts, so the same money cannot go both ways.
  • Contributions past the goal are allowed. The campaign accepts money until the deadline, and the creator receives everything raised.
  • call is used for payments, with its result checked, instead of transfer, because transfer forwards only a small amount of gas. See the lesson on sending ether for the reasoning.
  • Block timestamps can be nudged by block producers by a few seconds, which is fine for deadlines measured in days.

The creator is a single address. If they lose that key, a successful campaign can never be withdrawn. A real project would use a multisig for the creator address and might add a way to rescue stuck funds after a long delay.

The stand-in implementation

The class below tracks balances in plain numbers (think of them as wei) and uses a now field as the clock. The payTo function plays the part of call{value: ...}: it moves money from the contract's balance to an address, and the demo can make one address refuse payment to show that failure stays local.

JS The crowdfunding contract as a JavaScript class

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

No output.

In campaign A, the late contribution and the early withdrawal are refused, the creator is paid once, and a second withdrawal fails. In campaign B, ann gets her money exactly once. Bo's rejecting address only hurts Bo: his refund fails and his contribution is restored, and nobody else is blocked. If the contract had looped over all backers, that one address would have frozen Ann's refund too.

Testing the invariants

Examples are good, but properties are better. A crowdfunding contract has an invariant you can state in one line: the contract's balance is never less than the unrefunded contributions while the campaign has not been withdrawn. The next stand-in runs a randomized set of campaigns (a simple fuzz loop, see Testing Contracts) and checks money conservation every time: the sum of what the creator and backers received plus what stays in the contract equals everything contributed.

JS A fuzz loop that checks money is conserved

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

No output.

Real: the rules, the state machine, pull refunds and the habit of checking an invariant over many random runs. Stand-in: amounts are plain JavaScript numbers instead of 256-bit integers, and there is no gas, so none of the failure modes of loops or out-of-gas show up here. Real fuzzing tools such as Foundry's also generate the random calls for you.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does refund() let each backer pull their own money instead of the contract refunding everyone in a loop?

    With pull payments a failing recipient only affects their own call. A push loop can fail as a whole because of a single bad address or a long list.
  2. 2. Which line order in refund() protects against reentrancy?

    Zeroing the balance before the external call means a callback into refund() finds nothing left and reverts. Sending first would let the attacker take the same money repeatedly.
  3. 3. Why is state() computed from facts instead of stored in a variable?

    The deadline passing is not a transaction, so nothing would update a stored state at that moment. Computing it from the clock, the total and the withdrawn flag cannot go stale.
  4. 4. What keeps the same money from being both withdrawn by the creator and refunded to backers?

    Once withdrawn is true, state() returns Withdrawn, and refund() accepts only the Failed state. Also, a campaign that succeeded would never be Failed anyway.

Summary

  • An all-or-nothing campaign is a small state machine: Open, then Succeeded or Failed, then Withdrawn.
  • Compute the state from facts (clock, total, withdrawn flag) so it cannot get stale, and allow each function in exactly one state.
  • Use the withdrawal pattern: backers pull their own refunds, so one bad address cannot block everyone.
  • Update state first and send ether last, and check the result of call.
  • Check invariants such as conservation of money over many random runs, in addition to example tests.
  • A single creator key is a risk. Real projects use a multisig.

Next: Project: A Token and Simple Sale.