receive() & fallback()
receive()
A contract can have at most one
receive
function. The receive function is executed on a call to the contract with empty calldata. This is the function that is executed on plain Ether transfers.If no such function exists, but a payable fallback function exists, the fallback function will be called on a plain Ether transfer. If neither a receive Ether nor a payable fallback function is present, the contract cannot receive Ether through a transaction that does not represent a payable function call and throws an exception.
In the worst case, the
receive
function can only rely on 2300 gas being available (for example whensend
ortransfer
is used), leaving little room to perform other operations except basic logging.
fallback()
A contract can have at most one
fallback
function that is executed on a call to the contract if none of the other functions match the given function signature, or if no data was supplied at all and there is noreceive
function.The fallback function always receives data, but in order to also receive Ether it must be marked
payable.
This function must also haveexternal
visibility. A fallback function can be virtual, can override and can have modifiers.If the version with parameters is used,
input
will contain the full data sent to the contract (equal tomsg.data
) and can return data inoutput
. The returned data will not be ABI-encoded. Instead it will be returned without modifications (not even padding).In the worst case, if a payable fallback function is also used in place of a receive function, it can only rely on 2300 gas being available (see receive Ether function for a brief description of the implications of this).
Like any function, the fallback function can execute complex operations as long as there is enough gas passed on to it.
Last updated