Guide to delegatecall in Solidity
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 tootherContract
, calling thesetGreeting
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
andgreetingLastUpdatedBy
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!
Previous post
📙 Solidity Auditing online quiz
Learn how to audit smart contracts by looking at some example code and trying to find the bugs
⛽ Solidity Gas Optimizations Guide
How to optimize and reduce gas usage in your smart contracts in Solidity
🧪 Guide to testing with Foundry
Guide to adding testing for your Solidity contracts, using the Foundry and Forge tools
📌 Guide to UTXO
UTXO and the UTXO set (used by blockchains such as Bitcoin) explained
📐 Solidity Assembly Guide
Introduction guide to using assembly in your Solidity smart contracts
📦 Ethereum EOF format explained
Information explaining what the upcoming Ethereum EOF format is all about