6

a contract just with a payable function can receive ether,

but why does the contract need to be add a receive()function to receive ether?

is there different between obtained ether via payable function and obtained ether via receive()?

a noob quesetion, thanks a lot

2 Answers 2

14

We can transfer ETH to smart contracts without calling a payable function.

To handle these scenarios when someone sends ETH directly to a contract we use receive and fallback functions.

If someone sends ETH to a smart contract without passing calldata and there is a receive() function, the receive() function is executed. If there is no receive() function, then the fallback() is executed (and if there is no receive nor fallback, then the transaction reverts).

If ETH are sent to smart contracts with calldata's and the function selector doesn't match any existing function in the contract, the fallback() function is executed (again, if no fallback is implemented, the transaction reverts).

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

contract Receive_FallBack {
    event ReceivedEth(uint256 amount);

    function fundme() public payable {
        emit ReceivedEth(msg.value);
    }

    receive() external payable  { 
        fundme();
    }

    fallback() external payable {
        fundme();
    }

    //            is msg.data empty?
    //            /                \
    //           yes                no
    //          /                    \
    //  receive() exists?        is the function selector fundMe()?
    //      /      \                    /      \
    //    yes       no                 no      yes
    //    /          \                /          \
    // receive()     fallback() exists?         fundMe()
    //                  /       \ 
    //                 yes       no
    //                /           \ 
    //          fallback()    transaction is reverted
}

1
  • I like this graph below lol, nice!
    – Howard
    Sep 14, 2022 at 7:26
5

receive() is for receiving ether without calling data. e.g address.call{value : 1 ether}();

payable function is for receiving ether with data e.g address.call{value : 1 ether}(abi.encodeWithSignature('function()')

1
  • instructive answer!
    – JESSE Bin
    Apr 4, 2022 at 2:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.