What is the fallback function in Solidity?
Overview
In Solidity, a fallback function is an external function with neither a name, parameters, or return values. It is executed in one of the following cases:
- If a function identifier doesn’t match any of the available functions in a smart contract.
- If there was no data supplied along with the function call.
Only one such unnamed function can be assigned to a contract.
Properties of the fallback function
- They are unnamed functions.
- They cannot accept arguments.
- They cannot return anything.
- There can be only one fallback function in a smart contract.
- It is compulsory to mark it external.
- It should be marked as payable. If not, the contract will throw an exception if it receives ether without any data.
- It is limited to 2300 gas if invoked by other functions.
Example
Let's see an example of calling a function in Solidity in the code snippet below:
pragma solidity ^0.5.12;// contract with fallback functioncontract A {uint n;function set(uint value) external {n = value;}function() external payable {n = 0;}}// contract to interact with contract Acontract example {function callA(A a) public returns (bool) {// calling a non-existing function(bool success,) = address(a).call(abi.encodeWithSignature("setter()"));require(success);// sending ether to Aaddress payable payableA = address(uint160(address(a)));return(payableA.send(2 ether));}}
Explanation
- Line 1: We import the
pragmapackage. - Line 4–13: We create a contract
Athat has a state variablen, a functionset()that accepts a value and stores it inn, and a fallback function. - Line 16–25: We create one more contract
exampleto interact with the contractA. We call a non-existing function of contractA(line 19) and then try to sendetherto the contract (line 24).
Output
- The function call in line 19 does not exist in the contract
A. So, its fallback function will be invoked. - Line 24 will return
false, as sending of theetherfailed.
Free Resources
Copyright ©2025 Educative, Inc. All rights reserved