Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Solidity suggest me to implement a receive ether function when I have a fallback function?

Tags:

solidity

The recent change in Solidity changed the fallback function format from just function() to fallback(), which is pretty nice for beginners to understand what is going on, but I have a question about a suggestion that the compiler gives me when I implement such a fallback.

For example, a piece of code from my project:

pragma solidity ^0.6.1;

contract payment{
    mapping(address => uint) _balance;

    fallback() payable external {
        _balance[msg.sender] += msg.value;
    }
}

Everything goes fine, but the compiler suggests that:

Warning: This contract has a payable fallback function, but no receive ether function.
Consider adding a receive ether function.

What does it mean by a receive ether function? I tried looking it up and many examples I could find is just another fallback function.

I am using version 0.6.1+commit.e6f7d5a4

like image 510
Viewerisland Avatar asked Jan 08 '20 17:01

Viewerisland


People also ask

What does receive function do in Solidity?

receive() A contract can now have only one receive function that is declared with the syntax receive() external payable {…} (without the function keyword). It executes on calls to the contract with no data ( calldata ), such as calls made via send() or transfer() .

How do you use fallback function Solidity?

The solidity fallback function is executed if none of the other functions match the function identifier or no data was provided with the function call. Only one unnamed function can be assigned to a contract and it is executed whenever the contract receives plain Ether without any data.

How do you get ether in Solidity?

In order to receive ethers in Solidity (or any other native coin in any EVM blockchain), we need to create a receive() function with the payable modifier. This shot is written for Solidity versions newer than 0.6.

In which scenarios is a fallback function triggered?

Fallback functions are triggered when the function signature does not match any of the available functions in a Solidity contract.


1 Answers

As a complement to the accepted answer, here's how you should define the unnamed fallback and receive functions to solve this error:

contract MyContract {

    fallback() external payable {
        // custom function code
    }

    receive() external payable {
        // custom function code
    }
}
like image 73
Thomas C. G. de Vilhena Avatar answered Sep 21 '22 19:09

Thomas C. G. de Vilhena