SolidityIn

Receive and fallback functions

Lesson 12 of 40 · Ether

When someone sends ETH to a contract address without calling any function, Solidity runs a special function. A receive function, declared as receive() external payable, handles plain ETH transfers that come with empty call data.

A fallback function runs when the call data does not match any function in the contract, or when there is data but no receive function. Mark it payable if it should also accept ETH. Proxy contracts rely on fallback to forward every call.

If a contract has neither function, plain ETH transfers revert. That is a safe default, and it protects you from receiving funds by mistake. ETH can still be forced in through selfdestruct, so never depend on the balance being exactly what you expect.

Keep these functions cheap. Senders using transfer or send forward only 2300 gas, so a receive function that does more than emit an event may run out of gas for them.

contract Receiver {
    event Received(address indexed from, uint256 amount);
    event FallbackCalled(address indexed from, bytes data);

    receive() external payable {
        emit Received(msg.sender, msg.value);
    }
    fallback() external payable {
        emit FallbackCalled(msg.sender, msg.data);
    }
}

Try it yourself

Compile it, then remove the receive function and think about what happens when someone sends plain ETH. Then add a counter that increases on each receive, and consider the 2300 gas limit.

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

Quick check: Which function runs when ETH is sent with no call data?