Blockchain

A crowdfunding smart contract in Solidity: what the tutorials leave out

Search for a Solidity crowdfunding contract and you will find plenty of tutorials. They teach the idea well. They stop before the parts that decide whether a contract can safely hold other people's money.

A crowdfunding contract is a good first Solidity project, which is why there are so many tutorials for it. Most of them build the same thing: a campaign with a goal and a deadline, a function to pledge, a function for the creator to withdraw, and a function for backers to get a refund. Several say so themselves: the code is for learning, not for real funds.

This post is about the gap between that tutorial contract and one that can hold real pledges. It comes from building and testing a full escrow, installment and voting system. If you are choosing between building and buying, the Blockchain Edition page shows the finished version.

What the tutorial version does

The core is small. Here is the real pledge function from our escrow contract:

function pledge(uint256 id) external payable {
    Campaign storage c = _campaigns[id];
    if (c.creator == address(0)) revert NoSuchCampaign();
    if (c.token != address(0)) revert WrongCurrency();
    if (msg.value == 0) revert ZeroAmount();
    if (block.timestamp >= c.deadline) revert CampaignEnded();

    c.raised += msg.value;
    _pledges[id][msg.sender] += msg.value;

    emit Pledged(id, msg.sender, msg.value);
}

It checks the campaign, records the pledge and nothing else. It makes no outside call, so it needs no reentrancy guard. That is the easy half. The functions that send money out are where tutorials stop short.

Seven things a contract holding real money also needs

1. A reentrancy guard on every function that sends value. A recipient can be a contract that calls back in while it is being paid, to take the money twice. Update state before sending, and add a guard as a second layer. Then test it: write an attacker contract and assert the exact guard error. A test that passes with the guard removed proves nothing.

2. A fee that cannot be raised under the creator's feet. If the platform owner can change the fee, they can front-run a creator's transaction and raise it first. Let the creator pass the highest fee they accept inside their own transaction, and cap the fee in the code.

3. A bounded send. A recipient can answer a payment with megabytes of return data, which costs the caller a huge amount of gas. A plain call that copies the reply can make a permissionless function cost millions of gas. Send with no return data copied.

4. A plan for odd tokens. If you accept ERC-20 tokens, some return false, some return nothing, some take a fee on transfer, some call back into your contract. Keep an allow-list, check the balance before and after each transfer, and test with hostile token mocks.

5. Accounting that ignores the contract balance. Anyone can force ETH into a contract. Pay out and refund from recorded pledges, never from the balance, so extra money changes nothing.

6. Safe arithmetic for shares. Pro-rata refunds and fee calculations should use overflow-safe multiply-then-divide, and be tested with enormous amounts.

7. No admin function that moves pledged money. The owner may set the fee for new campaigns, approve tokens and collect fees already earned. Nothing more. Say so in the specification, then test that it is true.

Testing beyond "it works"

Unit tests prove the happy path. Three more kinds of test matter for a contract like this:

Our whole system has 540 automated tests. The first draft of the suite missed things the mutation tests found, which is the point of running them.

See the rules run: open the live demo. It uses the real contracts in your browser, and rejects every action the rules do not allow, with the reason.

Before real money

Tests are not an audit. Anything holding real funds should get an independent review, and the contract should be deployed to a public test network first so the whole flow, including the wallet, is exercised end to end.

Frequently asked questions

Is a tutorial crowdfunding contract safe for real funds?

Not as it stands. Most tutorials say they are for learning. They usually omit reentrancy guards on every path, fee protection, bounded sends, token checks and attack tests.

Which tools should I use to test a Solidity contract?

Hardhat or Foundry, with a recent Solidity 0.8 compiler. Add fuzz and invariant tests, and a mutation testing script to check that your tests catch real bugs.

Should refunds be pushed or pulled?

Pulled. Let each backer claim their own refund. Looping through every backer to send money can run out of gas, and one failing recipient can block the rest.

Want crowdfunding with smart-contract escrow, already built and tested?

Escrow, installment payouts, backer voting and reward tokens, with your brand and your fees. Try the live demo or book a call.

See the Blockchain Edition →

Keep reading: How blockchain crowdfunding worksHow to start a crowdfunding businessSetting the platform fee