Solidity has a receive
keyword. What is it and how do I use it?
Solidity – What is the ‘receive’ Keyword in Solidity?
fallback-functionkeywordreceivesoliditysolidity-0.6.x
fallback-functionkeywordreceivesoliditysolidity-0.6.x
Solidity has a receive
keyword. What is it and how do I use it?
Best Answer
TL;DR
receive
is a new keyword in Solidity 0.6.x that is used as a fallback function that is only able to receive ether.receive() external payable
— for empty calldata (and any value)fallback() external payable
— when no other function matches (not even the receive function). Optionallypayable
.Long Answer
Solidity 0.6.x introduced the
receive
keyword in order to make contracts more explicit when their fallback functions are called. Thereceive
method is used as a fallback function in a contract and is called when ether is sent to a contract with no calldata. If thereceive
method does not exist, it will use thefallback
function.From the docs:
To use it, you can include it in your contract in the following way:
When evaluating whether to use
receive
orfallback
, consider the following:This is why in version 0.6.x, the fallback function was split into two separate functions:
receive() external payable
— for empty calldata (and any value)fallback() external payable
— when no other function matches (not even the receive function). Optionallypayable
.This separation provides an alternative to the fallback function for contracts that want to receive plain ether.
Edit based on Ismael's comment: The 2300 gas stipend required by
.send()
and.transfer()
apply toreceive()
in the same way that they apply to.transfer()
. Additionally, contracts compiled with pre-0.6.0 solc versions are able to interact with thereceive()
function.Additional information can be found in the Ethereum blog post here.