Simply sending Ether to a contract, will run the contract's code. In Solidity, this code maps to what it calls the fallback function.
How much work can be done in a fallback function?
contract-designcontract-developmentfallback-functionreentrant-attackssolidity
Simply sending Ether to a contract, will run the contract's code. In Solidity, this code maps to what it calls the fallback function.
How much work can be done in a fallback function?
Best Answer
The fallback function can do as much computation as how much gas it gets.
There are 2 cases (basically
recipient.send
andrecipient.call{value:...}("")
) and case 2 has security implications and is a key part of how theDAO was attacked and exploited on June 17 2016.Case 1: 2300 gas
A
recipient
contract's fallback function only gets a 2300 gas stipend if it was invoked withrecipient.transfer
orrecipient.send
. This is the same as an external account payingrecipient
withweb3.eth.sendTransaction({to:recipient, gas:21000, ...})
.The last part of an Ethereum blog post explains:
Examples of an external process include web3.js filters and watches.
Note: Since Dec 2019,
recipient.transfer
andrecipient.send
are no longer recommended: Is transfer() still safe after the Istanbul update?Case 2: As much gas as it gets, watch out for security
recipient.call{value:...}("")
(and using related functions like.callcode
,.delegatecall
) will provide the fallback function with virtually[1] as much gas as the caller has remaining.To obtain the same effects (2300 gas stipend) and security as Case 1, callers must explicitly limit the gas to zero when invoking the
recipient
by:recipient.call{gas: 0, value: ...}("")
(theDAO did not limit the gas and suffered a reentrant attack on June 17 2016.)
Footnotes
[1] Explanation of why a fallback function gets almost all, but not all of the gas. chriseth (Solidity author) said: