Skip to content
Solidity

Payable, receive & fallback (ETH flows)

Receive ETH via payable functions and the receive/fallback hooks.

By EZ4Code Team
payablereceivefallbackether

Code

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

contract EthVault {
    receive() external payable {
        // called on plain ETH transfer (no calldata)
    }

    fallback() external payable {
        // called when no function signature matches
    }

    function deposit() external payable {
        require(msg.value > 0, "send eth");
    }

    function withdraw(uint256 amount) external {
        payable(msg.sender).transfer(amount); // 2300 gas stub, reverts on failure
    }

    function withdrawCall(uint256 amount) external {
        (bool ok, ) = payable(msg.sender).call{value: amount}("");
        require(ok, "transfer failed");
    }

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

Explanation

payable marks functions that accept ETH; msg.value is in wei (1 ETH = 1e18 wei). receive() triggers on empty-calldata ETH transfers; fallback() triggers on unknown function signatures or non-empty calldata transfers. transfer/send forward only 2300 gas (a stub) and revert on failure — safe against reentrancy but breaks with gas-consuming recipients. call{value:...} forwards all gas and returns a bool; always check the return value. Prefer call for withdrawals and guard reentrancy with a mutex.

More Solidity Snippets