What is delegatecall in Ethereum?
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.
Code example of 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");}}
Code explanation
Line 3: We make a
Receivercontract.Lines 6–10: We make a function called
setValueOfRecieverthat sets the value of the contract variable namedrecevierValue.Line 14: We make
Callercontracts.Lines 17–21: We make the function name
callsetValueOfRecieverthat takes theaddressof theRecievercontract function and calls thesetValueOfRecieverfunction usingdelegatecall. The desired message is then printed.
Note: The
delegatecallfunction generates abytesresult value and abooleansuccess value. The result value contains any data returned by thedelegatecallfunction, while the success value indicates if thedelegatecallwas successful.
Free Resources