A low-level Solidity method called delegatecall
in Ethereum enables a smart contract to assign some of the execution of its code to another contract. When a contract makes a delegatecall
, the calling contract's
In other words, delegatecall
allows interaction with another contract's code, while preserving the caller's storage. This is often used in contract upgradeability patterns or when a contract needs to delegate functionality to another contract.
delegatecall
The usage of delegatecall
in Solidity is demonstrated here:
pragma solidity ^0.5.12;//RECEIVERcontract Receiver{uint256 public recevierValue;function setValueOfReciever(uint256 _recevierValue) public{recevierValue = _recevierValue;}}// CALLERcontract Caller{uint256 public callerValue;function callsetValueOfReciever(address _reciverAddress) public{(bool success,) = _recieverAddress.delegatecall(abi.encodeWithSignature("setValueOfReciever(uint256)", 100));require(success, " Delegate Call failed");}}
Line 3: We make a Receiver
contract.
Lines 6–10: We make a function called setValueOfReciever
that sets the value of the contract variable named recevierValue
.
Line 14: We make Caller
contracts.
Lines 17–21: We make the function name callsetValueOfReciever
that takes the address
of the Reciever
contract function and calls the setValueOfReciever
function using delegatecall
. The desired message is then printed.
Note: The
delegatecall
function generates abytes
result value and aboolean
success value. The result value contains any data returned by thedelegatecall
function, while the success value indicates if thedelegatecall
was successful.
Free Resources