2

It seems that calling a payable function will transfer eth directly even without explicitly calling transfer(). For example:

contract Storage {
    receive() external payable {}

    // Fallback function is called when msg.data is not empty
    fallback() external payable {}

    function getBalance() public view returns (uint) {
        return address(this).balance;
    }

    function getMoney() public payable returns (bool) {
        // payable(address(this)).transfer(msg.value);
        return true;
    }

}

Say I have an instance of Storage is at address x. If I call getMoney() with msg.value=1, the balance of x will increase by 1, both with and without "payable(address(this)).transfer(msg.value);". Is this expected?

1 Answer 1

2

Yes, it is correct. Each functions and addresses declared payable can receive ether. In this case if you declare getMoney() function in this way:

function getMoney() public payable returns (bool) {
   return true;
}

and you insert a value into msg.value box (in Remix IDE) the function will to transfer the amount at address of smart contract.

More information here.

IMPORTANT: Keep in mind payable is a modifier not a function!

2
  • Thanks for the answer. What's the underlying method that actually does the transfer in getMoney() then? My concern is that transfer() and call() behave differently and the latter you also need to do a require() to prevent a reentrance attack. Mar 18, 2022 at 18:28
  • The payable() modifier is the method that make the transfer of eth from your account to smart contract's address (in this case). Definitely call() function is reccomende to use because you can specify the value of gas that you're willing to pay and also you can check the value of return from this function to verify if the transaction have been correctily executed. Mar 18, 2022 at 22:17

Your Answer

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

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