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):
- Writing to storage
- Creating a contract
- Calling an external function which consumes a large amount of gas
- 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?
- Can I use complex logic inside fallback function?
- 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)