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 contextData used by the task is used to execute the called contract's code, and the called contract has access to the calling contract's state variables. This indicates that the called contract can change the calling contract's state variables.

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;
//RECEIVER
contract Receiver
{
uint256 public recevierValue;
function setValueOfReciever(uint256 _recevierValue) public
{
recevierValue = _recevierValue;
}
}
// CALLER
contract 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 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 a bytes result value and a boolean success value. The result value contains any data returned by the delegatecall function, while the success value indicates if the delegatecall was successful.

Copyright ©2024 Educative, Inc. All rights reserved