A fallback function is executed when a contract receives Ether without any additional data. For your contract to receive Ether and added to the total balance of the contract there must be a fallback function and it must be declared as payable. If this function does not exists, the contract cannot receive Ether and will throw an exception. If you do not have this function and the contract receives Ether it will be sent back to the sender.
The fallback function can only rely on a small amount of gas being available (2300 gwei) leaving little room to perform any other operation except basic logging. The following operations will consume more gas than the 2300 gas stipend:
- Writing to the block chain
- Creating a smart contract
- Calling an external function which consumes a large amount of gas
- Sending an Ether transaction
A contract can have one unnamed function. This function cannot have any arguments, cannot return anything and has to have external visibility. This function is executed when none of the other functions match the given function identifier (or if no data was supplied in the transaction message). Like any other Solidity function, the fallback function can execute complex operations as long as there is enough gas to perform the transaction.
Fallback Function
The fallback function is called when one calls a function that does not exist in the contract or when one sends ether to a contract with send, transfer or call. Fallback function:
- Cannot have a name
- Cannot have any inputs and outputs
- Must be declared as external
- Must be declared as payable to receive Ether
- To receive ether the function needs to be declared as payable
- It receives 2300 gas from transfer and send and can receive more gas when using the call method
An example of a fallback function is below. It is very simple to add to your smart contract.
Function () external payable {
}
Try it in Remix
For more information read the docs.
This code is for learning and entertainment purposes only. The code has not been audited and use at your own risk. Remember smart contracts are experimental and could contain bugs.
Click here for more information about how to use the Ethereum test network and how to obtain test ETH.
1 thought on “Fallback function in Solidity smart contracts”