How a crowdfunding contract works, step by step
Goal, deadline, contributions, and refunds: a walk through the small state machine behind an on-chain crowdfunding app.
Hammad Iqbal
Software Engineer
Crowdfunding is one of the cleanest first projects in Web3, because the rules fit on a napkin: people pledge money toward a goal, and either the goal is met by the deadline and the creator gets paid, or everyone gets a refund. A contract can enforce that without anyone holding the funds in the middle.
- A campaign is a goal, a deadline, a creator, and a record of who pledged what.
- After the deadline the campaign is either successful or refundable, never both.
- Refunds should be pulled by contributors, not pushed by the contract.
The state the contract keeps
Each campaign stores the creator's address, the funding goal, the deadline, the total raised, and a mapping from each contributor to the amount they pledged. Everything else, such as titles and images, belongs off-chain, with only a pointer or hash stored on-chain.
The three actions
Almost every rule is a require check on time and totals. The contract is a small state machine, and the work is making impossible states unreachable.
- contribute: accepted only before the deadline, adds to the total and to the contributor's balance
- withdraw: only the creator, only after the deadline, only if the goal was reached, and only once
- refund: only after the deadline, only if the goal was missed, returns that contributor's own amount
Pull payments, not push
Looping over every contributor to send refunds can run out of gas and lets one failing address block everyone. Letting each contributor call refund for themselves keeps each transaction small and independent. It is also the safer pattern against reentrancy, which is a topic for its own post.
A crowdfunding contract is a deadline, a goal, and a ledger. Keep the rules few and make every illegal transition revert.
Have a project this kind of thinking applies to?
Tell me what you're building — I read every message myself.