Skip to content
Tutorials Center
My learning

Topics

Lesson 25 of 47 ยท Object-Oriented Solidity

Proxies and Upgradeable Contracts

Learn how delegatecall proxies upgrade contracts, why storage layout clashes break them, transparent vs UUPS proxies, initializers and the risks.

A deployed contract's code can never change. That is a feature when you want users to trust it, and a problem when you find a bug. The most common workaround is the proxy pattern: users talk to a small, permanent contract (the proxy) that holds all the data and forwards every call to a separate implementation (or "logic") contract. To upgrade, you point the proxy at a new implementation. The address users know, and the balances stored there, stay the same.

The trick that makes this work is delegatecall, which you met in ABI Encoding and Low-Level Calls: the implementation's code runs against the proxy's storage. That is also where the danger lives, because the code and the data now have to agree about where each variable sits.

Two contracts, one address

Proxy Fixed address. Holds all the state.
Implementation Holds the code. Can be swapped.
delegatecall Runs that code on the proxy's storage.
1 / 2

The delegatecall proxy

The proxy has almost no code of its own. Its fallback function copies the incoming calldata, delegatecalls the implementation, and returns or reverts with whatever the implementation produced.

sequenceDiagram
    participant U as User
    participant P as Proxy (storage lives here)
    participant I as Implementation (code only)
    U->>P: transfer(bob, 5)
    P->>I: delegatecall(same calldata)
    I-->>P: runs, writes to PROXY storage
    P-->>U: return data or revert

The user only ever knows the proxy's address. The implementation address is an internal detail that can change.

A minimal proxy looks like this (read-only; real proxies use assembly to forward return data efficiently):

SOLIDITY
// Read-only sketch. Do not deploy: it has no access control and no safe slot.
contract NaiveProxy {
    address public implementation;   // slot 0 -- remember this!

    function upgradeTo(address newImplementation) external {
        implementation = newImplementation;
    }

    fallback() external payable {
        (bool ok, bytes memory ret) = implementation.delegatecall(msg.data);
        require(ok, "delegatecall failed");
        assembly { return(add(ret, 32), mload(ret)) }
    }
}

Notice the comment on slot 0. The proxy keeps implementation in storage slot 0. If the implementation also declares its first variable (say, address owner) the compiler gives it slot 0 as well. Both contracts now think slot 0 is theirs.

Storage layout clashes

Storage slots are numbered in declaration order (see Storage, Memory and Calldata). When code runs through delegatecall, it uses its own idea of the slot numbers on the proxy's storage. So two things must hold:

  1. The proxy's own variables must not overlap with the implementation's variables.
  2. A new implementation must keep the old variables at the same slots.

The stand-in below models storage as a map from slot to value, and an implementation as functions that act on that map. The first proxy keeps the implementation address at slot 0, like the naive sketch.

JS A proxy whose own variable collides

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The initializer wrote the owner into slot 0, which overwrote the pointer to the implementation. The proxy is now bricked, and in a real contract that could mean locked funds.

The fix: keep proxy variables out of the way

The standard answer is EIP-1967. The proxy stores its implementation address (and admin) at a pseudo-random slot, computed from a hash of a fixed string minus one, so it will never match a slot the compiler assigns to an ordinary variable. For the implementation slot that value is 0x360894a1...382bbc. Libraries such as OpenZeppelin implement this for you.

Layout clashes also happen between versions of the implementation. Rules for upgrading safely:

  • Never reorder, remove or change the type of an existing state variable.
  • Only add new variables at the end.
  • Do not insert variables into a base contract that others inherit from.
  • Many teams reserve room with a uint256[50] private __gap; array in base contracts so they can add variables later.
JS An upgrade that shifts the layout

Press Run (or Ctrl + Enter) to see the console output here.

No output.

With the bad layout the "owner" is now the number 2 (the old counter value sitting in slot 1) and the "count" is 0. Nothing reverted: the code simply read the wrong slots. This is why upgrade tooling (such as the OpenZeppelin upgrades plugins) compares the old and new layouts and refuses unsafe upgrades.

Initializers instead of constructors

A constructor runs once, when the implementation is deployed, and writes into the implementation's storage, not the proxy's. So an upgradeable contract has no useful constructor. Instead it has an ordinary function, conventionally initialize, that sets up the state through the proxy, and a guard that lets it run only once. Immutables and constants are fine, since they live in code rather than storage.

Two traps to remember:

  • Call initialize in the same transaction that deploys the proxy, usually by passing the encoded call to the proxy's constructor. Otherwise someone can front-run you and become the owner.
  • Initialize or lock the implementation itself. An implementation contract is a real contract too. If nobody initializes it, an attacker could claim it. OpenZeppelin's _disableInitializers() in the implementation's constructor prevents that.
JS A one-time initializer

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Transparent vs UUPS

Both patterns use a delegatecall proxy. They differ in where the upgrade function lives.

Transparent proxy UUPS proxy
Upgrade logic lives in The proxy The implementation
Proxy size and call cost Larger; checks who the caller is on each call Smaller and cheaper per call
Main risk Admin and user calls must not clash on selectors A new implementation that forgets the upgrade function locks upgrades forever
Access control A proxy admin address (often a separate ProxyAdmin contract) Whatever the implementation enforces, for example onlyOwner in _authorizeUpgrade

In a transparent proxy, the admin address can only manage the proxy, and every other address is forwarded to the implementation. That is how selector clashes between admin functions and implementation functions are avoided. UUPS (EIP-1822) moves the upgrade function into the implementation, which makes the proxy a thin forwarder.

There are other patterns too: beacon proxies (many proxies share one beacon that holds the implementation address, so you upgrade them all at once), minimal proxies or clones (EIP-1167, a tiny fixed forwarder, used to deploy many cheap copies of one contract, not upgradeable), and diamonds (EIP-2535, several implementation contracts behind one proxy).

The real risks

Upgradeability is a trade-off, not a free feature.

  • Trust. Whoever can call the upgrade function can replace the code and take everything. Put that power behind a multisig and a timelock (see Audits, Tools and Best Practices), and tell users who holds it.
  • Bugs in the process. Layout mistakes, an uninitialized implementation or a missing initializer guard are all common sources of real losses.
  • Complexity. Auditors have more to check, and you can no longer say "the code cannot change".
  • selfdestruct and delegatecall inside an implementation. Code that runs through a proxy acts in the proxy's context, so a destructive or untrusted operation there can harm the proxy. Avoid both in logic contracts.

If your contract is small and simple, an immutable deployment with a migration plan is often safer than an upgradeable one.

What is real: delegatecall running the implementation's code on the proxy's storage, slot-number clashes, why initializers replace constructors, and the transparent-vs-UUPS trade-off. What is the stand-in: storage is a JavaScript Map keyed by slot, "implementations" are plain objects, and nothing is compiled, hashed, paid for in gas or reverted.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. In a proxy setup, whose storage holds the contract's data?

    delegatecall runs the implementation's code against the proxy's storage, so all state lives in the proxy and survives an upgrade.
  2. 2. Why does an upgradeable implementation not use a normal constructor?

    The constructor runs at deployment of the implementation only. The proxy's storage is never touched, so initial values must be set by an initializer function called through the proxy.
  3. 3. Which change to V2 of an implementation is the SAFE way to add a variable?

    Existing variables must keep their slots. New ones go at the end (or into a reserved gap), otherwise the new code reads the wrong data.
  4. 4. What is a key difference between transparent and UUPS proxies?

    Both use delegatecall. UUPS moves upgrade logic into the implementation (a smaller proxy, but forgetting it locks upgrades), while a transparent proxy keeps it in the proxy and checks the caller on each call.

Summary

  • A proxy holds the state and delegatecalls an implementation that holds the code; upgrading means changing the implementation address.
  • Storage slots are shared by proxy and implementation, so clashes break things silently; EIP-1967 places proxy variables in far-away slots.
  • Upgrade safely: never reorder or retype variables, only append, and use storage gaps in base contracts.
  • Use an initialize function guarded to run once, call it in the deployment transaction, and lock the implementation.
  • Transparent proxies keep upgrade logic in the proxy; UUPS keeps it in the implementation.
  • Upgradeability means users must trust the upgrader: use a multisig and timelock, or skip upgrades for simple contracts.

Next: Building an ERC-20 Token.