solidity – Transferring Value into a Contract’s Fallback Function: Methods and Best Practices

evmfallback-functionsoliditytransactions

I'm trying to figure out what happens when you send a value to a contract.

If the destination address (to) is a contract, then the EVM will execute the contract and will attempt to call the function named in the data payload of your transaction. If there is no data in your transaction, the EVM will call a fallback function and, if that function is payable, will execute it to determine what to do next. If there is no code in fallback function, then the effect of the transaction will be to increase the balance of the contract, exactly like a payment to a wallet. If there is no fallback function or non-payable fallback function, then transaction will be reverted.

It's pretty clear what happens when there is a payable function or a fallback payable function; they will be called and the value will be transferred into the contract. But, what does it mean when there is no code in fallback function? Does this mean a function declaration without anything in the body like following?

function() public payable {

}

Also, how does the effect of the transaction will be to increase the balance of the contract happen behind the scene?

Best Answer

The guide is slightly off, as if there is no data in your transaction and you send ether in it, the EVM will first try to call a function receive() payable {...} if you have it. This is a function that handles receiving the ether, but if you want you can omit it and then the EVM will call the fallback function.

The fallback function is what happens when the payload data of the transaction does not fit into any other function in the contract, or if there is no payload in the transaction. The fallback function without code is exactly what you have described: function() public payable {}

"The effect of the transaction will be to increase the balance of the contract" means that the contractAddress.balance will increase by the amount of ether that you have sent. It is automatically done with all the ether that has been sent to the payable functions, thus no code inside the receive or fallback functions is necessary. You only need code there if you want to do extra-stuff.

Hope that covers it.

Related Topic