New to blockchain software development? Read my beginners guide here

Guide to delegatecall in Solidity

Created on August 2022 • Tags: ethereumsolidityguides

A guide on Solidity's delegatecall

Delegatecall is a function in Solidity, that lets you execute another contract’s function while using the original contract’s storage, msg.value and msg.sender.

I’ll explain it with an example.

Below we have two contracts. They both have the same layout in storage (a string and an address).

The only place that greeting or greetingLastUpdatedBy is set is in contract B.

But we want to use that function (setGreeting) inside contract A.

  • First we would deploy contract B and get its address.
  • Then we deploy contract A
  • Then call setOtherContract() on contract A, so that contract A knows the address of the deployed contract B.
  • Then call sayHello() on contract A. This will delegate a call to otherContract, calling the setGreeting function but it will use the contract A’s storage.
  • If you look at the data in contract A, it will be unchanged
  • But look at the data in contract B and you will see greeting and greetingLastUpdatedBy was updated.
pragma solidity ^0.8.4;

contract B {
string public greeting;
address public greetingLastUpdatedBy;

function setGreeting(string _greeting) public {
greeting = _greeting;
greetingLastUpdatedBy = msg.sender;
}
}

contract A {
string public greeting;
address public greetingLastUpdatedBy;
address public otherContract;

function setOtherContract(address _addr) public {
otherContract = _addr;
}

function sayHello() public {
(bool success, bytes memory data) = otherContract.delegatecall(
abi.encodeWithSignature("setGreeting(string)", "Hello, world")
);
}
}

Spotted a typo or have a suggestion to make this crypto dev article better? Please let me know!

See all posts (70+ more)

See all posts (70+ more)

Was this post helpful? 📧

If you liked this content and want to receive emails about future posts like this, enter your email. I'll never spam you.

Or follow me on @CryptoGuide_Dev on twitter

By using this site, you agree that you have read and understand its Privacy Policy and Terms of Use.
Use any information on this site at your own risk, I take no responsibility for the accuracy of safety of the information on this site.