The truth about fallback functions in Solidity
When it comes to deploying smart contracts on the Ethereum blockchain, the importance of fallback functions is heightened due to their immutability. There’s no going back after a smart contract is deployed.
So, what do fallback functions do exactly?
Fallback functions in Solidity are executed when a function identifier does not match any of the available functions in a smart contract or if there was no data supplied at all. They are unnamed, they can’t accept arguments, they can’t return anything, and there can only ever be one fallback function in a smart contract. In short, they’re a safety valve of sorts.
Pretty straightforward, right? What exactly warranted a blog post like this? Well, Solidity developers made a default design choice with fallback functions that’s particularly interesting:
Fallback functions are executed whenever a particular contract receives plain Ether without any other data associated with the transaction. This default design choice makes sense and helps protect users, however, depending on your use case, it may be critical that your smart contract receive plain Ether via a fallback function.
To do so the fallback function must include the payable
modifier:
contract ExampleContract {
function() payable {
...
}
}
If there is no payable
fallback function and the contract receives plain Ether without any other data, the contract will issue an exception and return the Ether to the sender.
What if a contract is supposed to do something once Ether is sent to it? The fallback function can only rely on 2300 gas being available. This doesn’t leave much room to perform other operations, particularly expensive ones like writing to storage, creating contracts, calling external functions, and sending Ether. Therefore, fallback functions must be simplistic and inexpensive.
Take Aways
- Fallback functions are particularly important given the immutability of smart contracts
- Fallback functions are triggered when a function identifier does not match the available functions in a smart contract or if no data is supplied at all
- Fallback functions are executed when a contract receives plain Ether without any other data associated with the transaction
- To receive Ether fallback functions must include the
payable
modifier - Fallback function can only rely on being able to use 2300 gas which leaves little room to perform additional operations
- Fallback functions should be made simplistic and inexpensive