What delegatecall actually does

A normal external call executes code in the callee’s context. By contrast, delegatecall executes the callee’s bytecode in the storage context of the calling contract.

That means:

  • address(this) refers to the calling contract
  • storage writes affect the caller’s storage
  • msg.sender and msg.value are preserved from the original call
  • the code being executed comes from another address

This is the key difference:

Call typeCode executed atStorage usedmsg.sender seen by callee
calltarget contracttarget contractcalling contract
delegatecalltarget contractcaller contractoriginal external caller

This behavior is useful when you want to separate logic from state. It is the mechanism behind many proxy patterns and upgradeable contracts.


A minimal example

The simplest way to understand delegatecall is to look at a tiny proxy and implementation pair.

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

contract LogicV1 {
    uint256 public value;

    function setValue(uint256 newValue) external {
        value = newValue;
    }
}

contract SimpleProxy {
    address public implementation;

    constructor(address _implementation) {
        implementation = _implementation;
    }

    fallback() external payable {
        address impl = implementation;

        assembly {
            calldatacopy(0, 0, calldatasize())

            let result := delegatecall(
                gas(),
                impl,
                0,
                calldatasize(),
                0,
                0
            )

            returndatacopy(0, 0, returndatasize())

            switch result
            case 0 { revert(0, returndatasize()) }
            default { return(0, returndatasize()) }
        }
    }
}

If a user calls setValue(42) on SimpleProxy, the proxy forwards the call to LogicV1, but the value variable is stored in the proxy’s storage, not in LogicV1.

That is the core idea: code lives elsewhere; state stays here.


Why delegatecall is useful

1. Upgradeable contracts

A proxy can keep its address stable while swapping the implementation contract behind it. This is common in production systems where users, integrations, and token approvals depend on a fixed contract address.

2. Shared logic across multiple instances

Multiple proxies can point to the same implementation, reducing deployment cost and simplifying maintenance.

3. Modular behavior

A contract can delegate specific functionality to separate modules. This is less common than proxy upgrades, but it can be useful for plugin-like systems.

4. Gas and deployment efficiency

Logic contracts can be deployed once and reused. The proxy is small, while the implementation contains the code.


The biggest risk: storage layout mismatch

Because delegatecall writes to the caller’s storage, the implementation must match the proxy’s storage layout exactly.

If the implementation expects slot 0 to contain uint256 value, but the proxy uses slot 0 for address implementation, then a write to value may overwrite the implementation address. That can immediately break the contract or create a security issue.

Example of a dangerous mismatch

contract Proxy {
    address public implementation; // slot 0
}

contract BadLogic {
    uint256 public value; // also slot 0 in its own layout

    function setValue(uint256 newValue) external {
        value = newValue; // writes to proxy.slot0
    }
}

If setValue is called through the proxy, the uint256 write may corrupt the proxy’s implementation address. In practice, this can render the proxy unusable.

Best practice

Use a well-defined storage layout and never reorder or remove state variables in upgradeable contracts. Append new variables only at the end, and use storage gaps when following upgradeable patterns.


How proxies usually avoid collisions

A common approach is to store critical proxy data in fixed, unstructured storage slots rather than in ordinary sequential slots.

For example, an implementation address can be stored at a slot derived from a hash, making it extremely unlikely to collide with application storage.

This is the idea behind many standardized proxy patterns. The proxy keeps its own admin and implementation pointers in reserved slots, while the implementation uses normal storage slots for application state.

Practical rule

  • Keep proxy metadata in dedicated reserved slots
  • Keep application state in the implementation layout
  • Never let implementation code assume it owns the proxy’s metadata slots

Preserving initialization safely

Since the implementation contract is not constructed in the proxy’s storage context, constructors do not initialize proxy state. Instead, upgradeable systems use initializer functions.

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

contract TokenLogic {
    address public owner;
    uint256 public totalSupply;
    bool private initialized;

    function initialize(address _owner, uint256 _supply) external {
        require(!initialized, "already initialized");
        initialized = true;

        owner = _owner;
        totalSupply = _supply;
    }
}

Why this matters

If you deploy the implementation directly, its constructor runs in its own storage. But when called through a proxy, the constructor does not initialize proxy storage. Without an initializer, the proxy may start in an unsafe or unusable state.

Best practices for initialization

  • Use a one-time initializer guarded by a boolean or versioned initializer
  • Call initialization immediately after deploying the proxy
  • Avoid leaving initialization functions publicly callable after setup
  • Consider disabling initializers on the implementation contract itself if it should never be used directly

msg.sender and authorization surprises

A common misunderstanding is that delegatecall changes the caller identity. It does not.

Inside the delegated code:

  • msg.sender is still the original external caller
  • msg.value is still the original ether sent to the proxy
  • address(this) is the proxy address

This is helpful for access control, but it can also be dangerous if the implementation assumes it is being called directly.

Example

function onlyOwnerAction() external {
    require(msg.sender == owner, "not owner");
    // ...
}

If this function is executed through a proxy, the owner variable must exist in the proxy’s storage at the expected slot. If it does not, authorization may fail or behave unpredictably.

Development tip

When writing implementation contracts for proxies, always test them through the proxy address, not just by deploying the implementation directly.


Handling return data and reverts

A proxy must forward both successful return data and revert data. If it does not, debugging becomes painful and error handling breaks.

The assembly pattern in the earlier example does three important things:

  1. copies calldata into memory
  2. executes delegatecall
  3. copies returndata back and either returns or reverts with it

This preserves the original function’s ABI behavior. Without this forwarding, the proxy would swallow errors or return malformed data.

Why this matters in production

  • Frontends rely on revert reasons
  • Integrations expect standard ABI-encoded return values
  • Debugging is much easier when the proxy does not alter error payloads

Security pitfalls to avoid

1. Untrusted implementation addresses

If an attacker can change the implementation address, they can execute arbitrary code in the proxy’s storage context. That is effectively full control.

Mitigation: restrict upgrades to a trusted admin, multisig, or governance process.

2. Selfdestruct risk

If delegated code can trigger selfdestruct, the behavior can be catastrophic depending on the compiler version and execution context. Even where semantics have changed over time, destructive low-level behavior in delegated code should be treated as highly dangerous.

Mitigation: never delegate to unreviewed code.

3. Storage collision

As discussed, mismatched layouts can overwrite critical state.

Mitigation: use established upgradeable patterns and strict layout discipline.

4. Function selector clashes

A proxy may define its own functions, and the implementation may define functions with the same selector. This can cause unexpected routing behavior.

Mitigation: keep proxy surface area minimal and reserve admin functions carefully.

5. Initialization bugs

An uninitialized proxy can often be claimed by the first caller if the initializer is public and not protected.

Mitigation: initialize immediately and lock initialization after use.


When to use delegatecall and when not to

Use caseGood fit?Notes
Upgradeable proxy architectureYesMost common and well-established use
Shared logic across many instancesYesSaves deployment cost
Plugin systems with trusted modulesSometimesRequires strict governance and review
Arbitrary user-supplied code executionNoExtremely risky
Simple application contractsUsually noDirect calls are safer and easier to reason about

If you do not need code reuse at the storage-context level, prefer normal calls or library functions. delegatecall adds complexity and expands the blast radius of bugs.


Development best practices

Keep the proxy small

A proxy should do as little as possible:

  • store implementation/admin pointers
  • forward calls
  • expose minimal upgrade controls

The less logic in the proxy, the fewer chances for selector conflicts and state bugs.

Use versioned upgrades

When changing storage or behavior, introduce a new implementation version and migrate carefully. Never assume old state can be reshaped safely without review.

Test through the proxy

Unit tests should cover:

  • initialization
  • normal function calls through the proxy
  • upgrade behavior
  • access control through delegated execution
  • storage persistence across upgrades

Audit storage layout changes

Before deploying a new implementation:

  • compare storage layouts
  • ensure new variables are appended only
  • verify inherited contracts did not change ordering
  • check that reserved gaps remain intact

Treat delegated code as part of the trust boundary

If the implementation is upgradeable, the upgrade authority is effectively a security-critical role. Protect it with multisig, timelocks, or governance controls where appropriate.


A practical mental model

Think of delegatecall as “borrow this code, but keep my state.”

That model helps explain both its power and its danger:

  • the proxy owns the state
  • the implementation owns the logic
  • the caller interacts with the proxy
  • the implementation must be written for the proxy’s storage layout

If any of those assumptions break, the system becomes fragile.


Conclusion

delegatecall enables some of the most important patterns in Solidity, especially upgradeable contracts and modular execution. But it is not a general-purpose abstraction layer. It is a low-level tool that requires disciplined storage design, strict access control, and careful testing.

Use it when you need stable addresses with replaceable logic. Avoid it when a simpler architecture will do. In advanced Solidity systems, the safest delegatecall is the one you can fully explain, fully test, and fully constrain.

Learn more with useful resources