Skip to content
Tutorials Center
My learning

Topics

Lesson 18 of 47 ยท Contract Structure

Sending and Receiving Ether

Learn how Solidity contracts receive and send ether: payable, receive, fallback, call vs transfer vs send, the withdrawal pattern and selfdestruct changes.

Contracts do not only hold data, they hold money. Every account on Ethereum, contract or not, has an ether balance, and a contract can receive ETH, keep it and send it onward according to its code. Crowdfunding, escrow, auctions and token sales are all built on this, which also makes it the place where the most expensive mistakes happen.

This lesson explains how a contract opts in to receiving ether (payable, receive, fallback), the three ways to send it and why only one is recommended, the withdrawal ("pull") pattern, and the surprising ways ether can reach a contract that never agreed to take it.

Ether in, ether out

payable Marks a function that accepts ETH.
receive Handles a plain transfer with no data.
fallback Catches calls that match nothing.
call Sends ETH and forwards gas.
1 / 2

payable: opting in

By default a function rejects ether: if a transaction sends a value to a non-payable function, it reverts. To accept ETH, mark the function payable. Inside it, msg.value holds the amount in wei.

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

contract TipJar {
    mapping(address => uint256) public tips;

    function tip() external payable {
        require(msg.value > 0, "send something");
        tips[msg.sender] += msg.value;
    }

    function jarBalance() external view returns (uint256) {
        return address(this).balance;
    }
}

address(this).balance is the contract's own ETH balance. The ether arrives before the function body runs, so the balance already includes msg.value inside a payable function.

Addresses come in two flavors. An address payable has the members for sending ether; a plain address does not. Convert with payable(addr). See Value Types.

receive and fallback

What happens when someone sends ETH to a contract with a plain wallet transfer, with no function name at all? Solidity has two special functions for that, and neither uses the function keyword:

SOLIDITY
contract Catcher {
    event Received(address from, uint256 amount);
    event FallbackCalled(address from, uint256 amount, bytes data);

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

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

The rules for choosing between them:

  • If the call data is empty and a receive function exists, receive runs.
  • Otherwise, if the data matches no function, fallback runs. A fallback with payable also accepts ether.
  • With empty data, no receive but a payable fallback, the fallback runs.
  • With neither, the call reverts. A contract without receive or a payable fallback refuses plain ETH transfers.

Keep both short. A receive function reached through transfer or send gets only 2,300 gas, enough for little more than an event. Fallback functions also power proxies, which forward unknown calls to another contract (Proxies and Upgradeable Contracts).

Three ways to send ETH

To send from a contract, you need an address payable:

SOLIDITY
payable(to).transfer(amount);                 // reverts on failure, 2,300 gas
bool ok = payable(to).send(amount);           // returns false on failure, 2,300 gas
(bool ok2, ) = payable(to).call{value: amount}("");  // forwards gas, returns success flag
require(ok2, "send failed");
Gas forwarded On failure Status
transfer 2,300 reverts discouraged
send 2,300 returns false discouraged
call{value: x}("") all but 1/64 returns false recommended, with a check

transfer and send were once considered safe because 2,300 gas is too little for the receiver to call back into your contract. But gas costs change over time, and many legitimate receivers (smart-contract wallets, multisigs) need more than 2,300 gas, so transfers to them fail for no good reason. Today the standard advice is: use call, always check the returned boolean, and defend against reentrancy yourself with the rule below.

call hands control to the receiver, and a malicious receiver can call back into your contract before your function finishes. Always update your own state (reduce the balance) before sending. This is "checks-effects-interactions", and Reentrancy Step by Step shows what goes wrong without it.

The withdrawal pattern

Imagine an auction that refunds the previous bidder by pushing ETH to them every time a new bid arrives. If that bidder is a contract whose receive always reverts, nobody can ever outbid them and the auction is stuck. Pushing money in the middle of other logic hands every receiver a veto.

The fix is the pull (withdrawal) pattern: record what each person is owed, and let them collect it in a separate transaction.

SOLIDITY
mapping(address => uint256) public pending;

function creditRefund(address to, uint256 amount) internal {
    pending[to] += amount;
}

function withdraw() external {
    uint256 amount = pending[msg.sender];
    require(amount > 0, "nothing to withdraw");
    pending[msg.sender] = 0;                         // effect first
    (bool ok, ) = payable(msg.sender).call{value: amount}("");
    require(ok, "send failed");                      // interaction last
}

If someone's receiver is broken, only their own withdrawal fails. Everyone else is unaffected. You will use this shape in Project: Crowdfunding With Refunds and Project: Escrow and English Auction.

Ether you did not ask for

Even a contract with no receive and no payable function can end up holding ETH:

  • selfdestruct: a contract can destroy itself and send its balance to any address, and the destination cannot refuse.
  • Pre-funding: ETH can be sent to an address before the contract is deployed there (contract addresses can be computed in advance).
  • Block rewards and withdrawals: validator rewards can be directed to any address.

The practical rule: never use address(this).balance as the source of truth for your logic, such as require(address(this).balance == total). Someone can break that equality by force-sending one wei. Track deposits in your own variables and treat the real balance as an upper bound.

The selfdestruct opcode itself has changed. Solidity has marked it deprecated since 0.8.18. After the Dencun network upgrade of 2024 (EIP-6780), selfdestruct no longer deletes a contract's code or storage unless it runs in the same transaction that created the contract. In all other cases it only transfers the ETH. So do not design anything that relies on contracts being deleted.

A wallet model you can run

The stand-in below is not the EVM. It models accounts as entries in a Map and lets a "contract" object push and pull money, so you can watch why pull wins. The first run pays winners by pushing in a loop, and one broken receiver blocks the rest. The second run credits balances and lets everyone withdraw.

JS Push payout versus pull withdrawal

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

No output.

In the push run, Mallory's receiver rejects the payment, the whole transaction reverts (the stand-in restores a snapshot, as the EVM would), and nobody is paid, not even Alice. One bad receiver blocks everyone. In the pull run, Mallory's failure only hurts Mallory.

The second model shows the force-sent ether trap. A contract tracks deposited itself, while the "chain" lets a selfdestruct-like function push a balance in with no code running.

JS Why balance is not bookkeeping

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

No output.

Real: payable and non-payable behavior, the receive and fallback routing rules, the 2,300 gas stipend, the pull pattern and force-sent ether. Stand-in: balances in a Map, receivers as plain functions, and no gas, no call stack and no real selfdestruct.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A user sends ETH to a function that is not marked payable. What happens?

    Non-payable functions reject any value, so the whole transaction reverts and the sender keeps their ETH (minus gas).
  2. 2. A plain ETH transfer with empty call data arrives at a contract that has both receive and fallback. Which runs?

    With empty call data, receive takes priority. Fallback handles calls whose data matches no function.
  3. 3. Why is call{value: x}("") preferred over transfer today?

    transfer and send forward only 2,300 gas, which many contract receivers cannot work with. call forwards gas, so you must check the result and update state before calling.
  4. 4. Why should you not write require(address(this).balance == totalDeposits)?

    A receiver cannot refuse force-sent ether, so the real balance can exceed your bookkeeping. Track deposits in your own variables.

Summary

  • A function accepts ether only if it is payable; msg.value is the amount in wei, and address(this).balance is the contract's balance.
  • receive() handles empty-data transfers; fallback() handles calls that match nothing, and needs payable to take ether.
  • Send with call{value: x}(""), check the returned boolean, and change your state before the call. transfer and send are discouraged because of their fixed 2,300 gas.
  • Prefer pull payments: record what each user is owed and let them withdraw, so one failing receiver cannot block others.
  • Ether can arrive without your code running, so do not rely on address(this).balance for logic.
  • selfdestruct is deprecated and, since EIP-6780, no longer removes code except in the creating transaction.

Next: Storage, Memory and Calldata.