0

I am a bit confused with the fallback function in Solidity using Remix IDE, as far as I understand, the fallback function is limited to 2300 gas. However, when I call the fallback function by using the 'Transact' button in Remix, it does not fail even though it uses more than 2300 gas.

// let anyone send ether to the contract
fallback() external payable { 
    require(msg.data.length == 0);
}

Am I misunderstanding how fallback functions work and is my implementation of the fallback secure for when I want users to be able to send Ether to the contract? I also check the length of the data to ensure the function isn't used for other purposes.

Yilmaz
  • 35,338
  • 10
  • 157
  • 202
RishtarCode47
  • 365
  • 1
  • 4
  • 18

2 Answers2

0

In the worst case, if a payable fallback function is also used in place of a receive function, it can only rely on 2300 gas being available (see receive Ether function for a brief description of the implications of this).

Source: https://docs.soliditylang.org/en/v0.8.17/contracts.html#fallback-function

There is no limit on the fallback function itself. But if it's invoked from another contract though the transfer() native function, then the limit is applied.

Example: If you invoke the fallback() directly, it succeeds even though it consumes more than 2300 gas. If you invoke it through the transfer() function, it fails with "insufficient gas" error as it's only provided 2300 gas units. Comment out the number = 1 and it will work from the transfer() as well (because empty fallback uses less than 2300 gas).

pragma solidity ^0.8;

contract MyContract {
  uint256 number;

  fallback() external payable {
    number = 1;
  }
}

contract Sender {
  address myContract;

  constructor(address _myContract) {
    myContract = _myContract;
  }

  function invokeFallback() external {
    payable(myContract).transfer(0);
  } 
}
Petr Hejda
  • 40,554
  • 8
  • 72
  • 100
0

fallback function is invoked by the EVM under those 2 conditions

  • a function that does not exist in contract, gets called, since function does not exist contract is falling back to fallback function

  • when contract receives ether (if you are on etherum, only native token whcih is ether, any other token does not count) fallback is called. That is why we have payable modifier.

EVM provides 2300 gas. if fallback gets called by EVM but it costs more than 2300 gas, the function call will throw an exception and any state change will be reverted.

Yilmaz
  • 35,338
  • 10
  • 157
  • 202