delegatecall runs another contract's code in the caller's context: the caller's storage, balance, address(this), msg.sender and msg.value. The called code reads and writes storage by slot number, not by variable name, so if the two contracts disagree about which variable lives in which slot, writes land on the wrong data. That is a storage collision. To use delegatecall safely, only delegate to code you trust and control, give that code one shared storage layout (fixed ERC-1967 slots for proxy fields, ERC-7201 namespaces for application state), check the target has code, and never let a caller choose the target.
What does delegatecall actually do?
DELEGATECALL (opcode 0xF4, added in the Homestead fork by EIP-7) borrows code without borrowing state. Compare the three call types:
CALL | DELEGATECALL | STATICCALL | |
|---|---|---|---|
| Code that runs | Target's | Target's | Target's |
| Storage it touches | Target's | Caller's | Target's, read-only |
msg.sender inside | Caller | Original sender | Caller |
msg.value inside | Value sent | Original value | 0 |
address(this) inside | Target | Caller | Target |
| ETH balance used | Target's | Caller's | Target's |
This is what makes proxies, libraries with external functions, modular wallets such as Safe, and diamonds (EIP-2535) possible. If you need the background on proxies first, see how upgradeable proxy contracts work.
From the storage's point of view, delegated code is your own code: it can overwrite any slot, move the caller's ETH and tokens, and use every approval users have given the caller.
How does a storage collision happen?
Solidity assigns state variables to slots in declaration order, starting at slot 0, packing small types together where they fit. Mappings and dynamic arrays take one slot as a base and hash from it. The compiler does this per contract. It has no idea that another contract will run against the same storage.
Here is the classic broken proxy on Ethereum:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
contract NaiveProxy {
address public implementation; // slot 0
constructor(address impl) {
implementation = impl;
}
fallback() external payable {
address impl = implementation;
assembly {
calldatacopy(0, 0, calldatasize())
let ok := delegatecall(gas(), impl, 0, calldatasize(), 0, 0)
returndatacopy(0, 0, returndatasize())
switch ok
case 0 { revert(0, returndatasize()) }
default { return(0, returndatasize()) }
}
}
}
contract Logic {
address public owner; // also slot 0
function setOwner(address newOwner) external {
owner = newOwner; // through the proxy, this overwrites `implementation`
}
}
Calling setOwner through the proxy writes the new owner into slot 0, which the proxy reads as its implementation address. Every later call is delegated to that owner's address. If it is an externally owned account, there is no code to run, and a delegatecall to an address without code succeeds and returns nothing. The contract has silently stopped working, and calls that should revert now look successful.
Collisions come in a few recurring shapes:
- Proxy against implementation. Proxy bookkeeping (implementation, admin, beacon) shares low slots with the logic contract's variables, as above.
- Version against version. V2 inserts, removes, reorders or retypes a variable, or changes the inheritance order, so it reads V1's data from the wrong slots. Balances, owners and initialisation flags get reinterpreted.
- Module against module. A wallet or diamond delegates to several facets that each declare variables from slot 0.
- Re-delegated EOAs. Under EIP-7702, a regular wallet can point to smart account code. The account's storage survives when the owner switches to a different delegate, so the new code inherits whatever the old code left in its slots.
A real example: in July 2022 an attacker took over Audius governance because a variable in its custom proxy overlapped the storage of OpenZeppelin's Initializable flags. The overlap made the initializer check pass on contracts that had already been set up, so the attacker could call initialize again and install their own settings.
How do I lay out storage so it can't collide?
Put proxy fields in ERC-1967 slots
ERC-1967 stores the implementation address at keccak256("eip1967.proxy.implementation") - 1, which is 0x3608...2bbc, and the admin and beacon at similarly derived slots. A pseudo-random 256-bit slot will never be reached by ordinary sequential layout, and subtracting one means nobody knows a preimage that hashes to it. Use OpenZeppelin's ERC1967Proxy, TransparentUpgradeableProxy or BeaconProxy rather than writing your own.
Put application state in an ERC-7201 namespace
ERC-7201 goes one step further for the logic itself: group a contract's variables in a struct and store that struct at a location derived from a namespace string.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
contract VaultLogic {
/// @custom:storage-location erc7201:myproject.storage.Vault
struct VaultStorage {
address owner;
uint256 totalDeposits;
mapping(address => uint256) balances;
}
// keccak256(abi.encode(uint256(keccak256("myproject.storage.Vault")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant VAULT_STORAGE_LOCATION =
0x01388c1ac0e22fdabcff266ab4b83c430c1afe88c444a5a57cba68546f9a8100;
function _vault() private pure returns (VaultStorage storage $) {
assembly {
$.slot := VAULT_STORAGE_LOCATION
}
}
function deposit() external payable {
VaultStorage storage $ = _vault();
$.balances[msg.sender] += msg.value;
$.totalDeposits += msg.value;
}
}
The @custom:storage-location annotation lets tools such as the OpenZeppelin upgrades plugins understand the layout, and OpenZeppelin Contracts v5 uses exactly this scheme for its own upgradeable contracts. Namespaces solve version-against-version and module-against-module collisions in one step: each component owns a struct far away from every other, and you can append fields to the end of a struct in later versions.
Solidity 0.8.29 and later also accept a contract-level base slot, contract Vault layout at <slot> { ... }, which moves the whole inherited layout. It is useful for EIP-7702 delegates and diamonds, but check that your auditors' and upgrade tools support it before relying on it.
Rules that still apply inside a namespace
- Only append fields to the end of a namespaced struct. Never reorder, remove or retype existing fields.
- Never put a struct or fixed-size array inside the namespaced struct if you might extend it later; it can't grow without shifting what follows it.
- Use a distinct namespace string per component, and never reuse one for a different struct.
Which other delegatecall mistakes cause losses?
Storage layout is only half of it. These are the other patterns behind real incidents:
- Delegating to an untrusted or user-supplied target. If an attacker can influence the address you
delegatecall, they run arbitrary code as your contract and can spend every approval users have given it. The 2021 Furucombo exploit worked this way. Keep an allowlist that only governance can change, and prefer immutable targets. - Assuming a missing contract will revert. A
delegatecallto an address with no code returnstrue. Checktarget.code.length > 0, or use OpenZeppelin'sAddress.functionDelegateCall, which reverts withAddressEmptyCodeand bubbles up revert reasons. - Reusing
msg.valuein a loop. In a payablemulticallthat delegates to itself several times, every inner call sees the fullmsg.value. One deposit can be credited many times. A critical bug of this kind in SushiSwap's MISO auction contracts was found and rescued in 2021 before anyone exploited it. Makemulticallnon-payable, or track ETH explicitly. - Leaving the implementation usable directly. The implementation is a live contract. In 2017 an attacker took ownership of the shared Parity multisig library and self-destructed it, freezing over 500,000 ETH in wallets that delegated to it. Call
_disableInitializers()in implementation constructors. Since Dencun, EIP-6780 limitsSELFDESTRUCTso it no longer deletes code except in the transaction that created the contract, but a delegatedSELFDESTRUCTstill sends the caller's entire ETH balance away. - Forgetting that
msg.senderis preserved. Delegated code sees the original caller, so authorisation checks in the target protect the caller's storage only if both contracts agree on what "owner" means. Do access control in one place.
Contracts that must never be delegated into can enforce it, the way Uniswap v3's NoDelegateCall does:
abstract contract NoDelegateCall {
address private immutable self = address(this);
modifier noDelegateCall() {
require(address(this) == self, "delegatecall not allowed");
_;
}
}
When you do need a delegate call, wrap it so every check happens every time:
import {Address} from "@openzeppelin/contracts/utils/Address.sol";
mapping(address => bool) public trustedModule; // changed only by governance
function _runModule(address module, bytes calldata data) internal returns (bytes memory) {
require(trustedModule[module], "untrusted module");
// reverts on empty code and re-throws the module's revert data
return Address.functionDelegateCall(module, data);
}
If a call fails and you need the underlying reason, see what "execution reverted" means and how to find the real cause.
How do I test for collisions before deploying?
Compare layouts between versions. Foundry prints the slot, offset and type of every variable:
forge inspect VaultV1 storageLayout > v1.txt
forge inspect VaultV2 storageLayout > v2.txt
diff v1.txt v2.txt # existing rows must be identical; new rows only at the end
The OpenZeppelin plugins (@openzeppelin/hardhat-upgrades, openzeppelin-foundry-upgrades) do this automatically, understand ERC-7201 namespaces and refuse unsafe upgrades. Run them in CI, not just before mainnet.
Assert that critical slots survive normal use. Read raw storage in a test and check that application calls never touch proxy fields:
bytes32 constant IMPL_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
function test_DepositDoesNotTouchImplementationSlot() public {
address before = address(uint160(uint256(vm.load(address(proxy), IMPL_SLOT))));
VaultLogic(address(proxy)).deposit{value: 1 ether}();
address afterwards = address(uint160(uint256(vm.load(address(proxy), IMPL_SLOT))));
assertEq(afterwards, before);
}
Turn that into an invariant across random call sequences, as described in writing fuzz and invariant tests in Foundry, and you cover paths you didn't think to write by hand.
Check deployed contracts. cast storage $PROXY <slot> --rpc-url $RPC_URL reads any slot on a live proxy, and cast implementation $PROXY reads the ERC-1967 implementation slot directly. Do this after every upgrade.
Review the upgrade itself. Route upgrades and module changes through a multisig and a timelock, simulate them, and check that a proposal is not an unexpected delegatecall. That check is exactly what failed in the 2025 Bybit theft described in how a team should hold crypto safely. Before a smart contract audit, document your layout and every delegate target.
Checklist
- Only
delegatecallinto code you trust, preferably immutable or behind an allowlist changed by governance. - Never take the target address from calldata supplied by arbitrary callers.
- Store proxy fields in ERC-1967 slots and application state in ERC-7201 namespaced structs.
- Append-only layouts: never reorder, remove, retype or re-inherit existing variables.
- Check
target.code.lengthor useAddress.functionDelegateCallso empty targets revert. - Make delegating
multicallfunctions non-payable, or account formsg.valueonce. - Call
_disableInitializers()in implementation constructors; addnoDelegateCallwhere delegation must be impossible. - Diff storage layouts in CI with
forge inspector the OpenZeppelin plugins, and read critical slots after each upgrade. - For EIP-7702 delegates, assume old storage is still there when you switch implementations.
Get the weekly commit
New blockchain deep dives every week.