SolidityIn

Build a crowdfunding contract

Lesson 39 of 40 · Projects

Now you combine what you have learned. A crowdfunding contract accepts ETH from many people until a deadline. If the goal is reached, the creator can withdraw the money. If not, every contributor can take their money back.

Plan the state first: the creator, the goal, the deadline, and a mapping of how much each person gave. Then write the functions: contribute, withdraw for the creator, and refund for contributors. Each function checks the time and the total before it moves any ETH.

Notice the safety habits. State is updated before ETH is sent, the contract uses call and checks the result, and withdraw can only run once. These are the same checks-effects-interactions rules from the Ether module.

Think about what could go wrong: what if nobody contributes, or the creator is a contract that rejects ETH? Good contracts handle the edge cases on purpose, and tests are how you prove it.

contract Crowdfund {
    address public immutable creator = msg.sender;
    uint256 public immutable goal;
    uint256 public immutable deadline;
    uint256 public raised;
    bool public withdrawn;
    mapping(address => uint256) public given;

    constructor(uint256 goalWei, uint256 durationDays) {
        goal = goalWei;
        deadline = block.timestamp + durationDays * 1 days;
    }
    function contribute() external payable {
        require(block.timestamp < deadline, "Ended");
        given[msg.sender] += msg.value;
        raised += msg.value;
    }
    function withdraw() external {
        require(msg.sender == creator, "Not creator");
        require(block.timestamp >= deadline && raised >= goal, "Not ready");
        require(!withdrawn, "Done");
        withdrawn = true;
        (bool ok, ) = creator.call{value: raised}("");
        require(ok, "Failed");
    }
    function refund() external {
        require(block.timestamp >= deadline && raised < goal, "No refund");
        uint256 amt = given[msg.sender];
        given[msg.sender] = 0;
        (bool ok, ) = msg.sender.call{value: amt}("");
        require(ok, "Failed");
    }
}

Try it yourself

Add an event called Contributed(address indexed who, uint256 amount) and emit it inside contribute, then compile.

Press Compile to check your code in the browser. Short fragments are wrapped in a contract automatically.

Quick check: What happens to contributors if the goal is not reached?