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 payablefallback()
external payablereceive()
is called ifmsg.data
is empty, otherwisefallback()
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 contractsThis is the recommended method to use when you're just sending Ether via calling the
fallback
functionHowever it is not the recommend way to call existing functions
Call - Specify Function
Delegatecall
delegatecall
is a low level function similar tocall
delegatecall
syntax is exactly the same ascall
syntax except it cannot accept thevalue
option but onlygas
When contract A executes
delegatecall
to contract B, B's code is executedwith contract A's storage,
msg.sender
andmsg.value
A popular and very useful use case for
delegatecall
is upgradable contractsUpgradable 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