Send ETH (transfer, send, call)

How to send Ether

You can send Ether to other contracts by

  • transfer (2300 gas, throws error)

  • send (2300 gas, returns bool)

  • call (forward all gas or set gas, returns bool)

How to receive Ether

A contract receiving Ether must have at least one of the functions below

  • receive() external payable

  • fallback() external payable

  • receive() is called if msg.data is empty, otherwise fallback() is called.

Which method should you use?

  • call in combination with re-entrancy guard is the recommended method to use after December 2019.

Guard against re-entrancy

  • Making all state changes before calling other contracts.

  • Using re-entrancy guard modifier.

Example

Example - Call

  • call is a low level function to interact with other contracts

  • This is the recommended method to use when you're just sending Ether via calling the fallback function

  • However it is not the recommend way to call existing functions

Call - Specify Function

Delegatecall

  • delegatecall is a low level function similar to call

  • delegatecall syntax is exactly the same as call syntax except it cannot accept the value option but only gas

  • When contract A executes delegatecall to contract B, B's code is executed

  • with contract A's storage, msg.sender and msg.value

  • A popular and very useful use case for delegatecall is upgradable contracts

    • Upgradable contracts use a proxy contract which forwards all the function calls to the implementation contract using delegatecall

    • The address of the proxy contract remains constant while new implementations can be deployed multiple times

    • The address of the new implementation gets updated in the proxy contract

Last updated