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 function
contract A {
uint n;
function set(uint value) external {
n = value;
}
function() external payable {
n = 0;
}
}
// contract to interact with contract A
contract 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 A
address payable payableA = address(uint160(address(a)));
return(payableA.send(2 ether));
}
}

Explanation

  • Line 1: We import the pragma package.
  • Line 4–13: We create a contract A that has a state variable n, a function set() that accepts a value and stores it in n, and a fallback function.
  • Line 16–25: We create one more contract example to interact with the contract A. We call a non-existing function of contract A (line 19) and then try to send ether to 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 the ether failed.

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved