[Ethereum] fallback function is accepting more than 2300 gas

contract-developmentfallback-functionsolidity

Quoting from solidity doc:

In such a context, there is usually very little gas available to the
function call (to be precise, 2300 gas), so it is important to make
fallback functions as cheap as possible. In particular, the following
operations will consume more gas than the stipend provided to a
fallback function (updating state variable a to 100):

  1. Writing to storage
  2. Creating a contract
  3. Calling an external function which consumes a large amount of gas
  4. Sending Ether

So ideally I should not use complex logic in fallback function. And fallback function can not use more than 2300 gas.

I gave this a try.

pragma solidity ^0.4.18;

contract TestFallback{
    uint public a = 0;
    uint public loopsize = 100;

    function updateLoopSize(uint _size) public {
        loopsize = _size;
    }

    function() public payable{
        uint i = 0;
        for (i=0; i<loopsize; i=i+1){
            a +=1;
        }
    }
}

I called the fallback function with loopsize = 100. The function executed successfully with following gas consumption:

gas : 3000000; transaction cost : 585049; execution cost: 563777

Now, this confused me with the paragraph I just read. I even tried making calculations as well as token transfers in fallback function. They consumed more than 100,000 gas but executed successfully. So what am I missing?

  1. Can I use complex logic inside fallback function?
  2. If I need to execute some function (like send tokens) as soon as the user's pay ethers to smart contract, what are possible approaches apart from writing the logic in fallback function.

PS: For second query, I don't think making a payable function will help. As in that case users have to call a specific method of smart contract. But I want that user's just send Ethers from any wallet and recieve assets. (User's don't need any abi to send eth to contract)

Best Answer

The fallback function is just like any other function: it gets as much gas as you pass to it.

What's different about the fallback function is that it's the one invoked when someone does a simple ether transfer, e.g. msg.sender.transfer(amount) in a smart contract, or a transfer from an exchange, etc. In those cases, very little gas is sent along, so if you want those cases to succeed, you should be careful about what you put in the fallback function.

I think there are other reasons to avoid the fallback function, notably around helping to prevent mistakes. See https://programtheblockchain.com/posts/2017/12/16/be-careful-when-using-the-solidity-fallback-function/.

Related Topic