The receive Function
Learn about the Solidity’s receive payable function.
A contract in Solidity can only have one receive function, which is declared using the receive
keyword (without the function
keyword). The receive function within a contract serves a specific purpose and is crucial in handling Ether transfers. This function can’t take parameters, can’t return anything, and must be externally visible and mutable in its payable state. It can be virtual, overrideable, and modifiable.
Characteristics of the receive function
No parameters or return values: The receive function accepts no parameters and returns no value; it’s only intended to receive Ether.
External and payable: The receive function must be
external payable
. Theexternal
visibility modification enables the function to be invoked from outside the contract, and thepayable
modifier indicates that it can receive Ether.No overloading: The receive function, unlike conventional functions, can’t be overloaded with different argument types. A contract can only have one receive function.
Implicit invocation: When the contract receives a simple Ether transfer (via the
.send()
or.transfer()
function calls), the receive function is implicitly invoked. When no function with a matchingcalldata
is supplied in the transaction, it’s called automatically.
Purpose of the receive function
The receive function’s principal job is to handle standard Ether transfers to a contract. When a user provides Ether to a contract without specifying a function to call, the receive function is the point at which Ether is processed. When Ether is given to the contract, it’s often used for accepting payments, managing Ether balances, and executing basic tasks.
Gas limitations in the receive function
The amount of gas available for execution is a critical limitation of the receive function. The receive function can rely on just 2,300 gas in the worst-case situation (equivalent to using the .send()
or .transfer()
function calls). This gas stipend is quite restricted and only allows for rudimentary operations. The following operations require more gas than the stipend of 2,300:
Adding additional storage: Writing to storage is gas-intensive and exceeds the gas stipend.
Creating a new contract: Deploying a new contract consumes significantly more gas than the available stipend.
Invoking an external function: Calling an external function that consumes substantial gas, such as a complex computation or an external contract with high gas costs, might result in running out of gas.
Transferring Ether: Initiating a further Ether transfer from the receive function consumes additional gas.
Get hands-on with 1200+ tech skills courses.