Advanced Functions

Fallback and Receive Functions

Beginner Level

These are special functions that handle Ether transfers to contracts and calls to non-existent functions.

1) Receive function

  • Triggered when the contract receives plain Ether with empty calldata.
  • Must be external and payable.

Example:


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

contract ReceiveExample {
    event Received(address sender, uint256 amount);

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

2) Fallback function

  • Triggered when a non-existent function is called or when Ether is sent with data.
  • Can be payable or non-payable.

Example:


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

contract FallbackExample {
    event FallbackCalled(address sender, uint256 amount, bytes data);

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

Continue Learning

Explore more topics in Solidity or browse other tutorials.