[Ethereum] What’s a fallback function when using address.send(…)

addressescontract-developmentcontract-invocationetherfallback-function

This code is in my contract:

 contract A {
      address x = 0x1234...;
      x.send(10);
 }

What would fallback function in the contract at address 0x1234… look like?

 contract B {
     ...
 }

I can't find any info on these fallback functions except here:

enter image description here

Best Answer

Yay, found it in solidity docs in FAQ section:

What is the deal with function () { ... } inside Solidity contracts? How can a function not have a name?

This function is called “fallback function” and it is called when someone just sent Ether to the contract without providing any data or if someone messed up the types so that they tried to call a function that does not exist.

The default behaviour (if no fallback function is explicitly given) in these situations is to throw an exception.

If the contract is meant to receive Ether with simple transfers, you should implement the fallback function as:

function() payable { }

Another use of the fallback function is to e.g. register that your contract received ether by using an event.

Attention: If you implement the fallback function take care that it uses as little gas as possible, because send() will only supply a limited amount.

Also possibly of use:

Is it possible to pass arguments to the fallback function?

The fallback function cannot take parameters.

Under special circumstances, you can send data. If you take care that none of the other functions is invoked, you can access the data by msg.data.

More information here on Github:

Fallback functions are triggered when the function signature does not match any of the available functions in a Solidity contract. For example, if you do address.call(bytes4(bytes32(sha3("thisShouldBeAFunction(uint,bytes32)"))), 1, "test"), then the EVM will try to call "thisShouldBeAFunction" at that address. If it does not exist, then the fallback function is triggered.

send() specifies a blank function signature and thus it will always trigger the fallback function if it exists.

Fallback functions requiring payable were a breaking change introduced with Solidity version 0.4.0.

Related Topic