TExcelTAD
Home › Solidity › Upgradeable Contracts & Proxies

Upgradeable Contracts & Proxies

Deployed code is immutable. That's a feature (users know the rules can't change under them) but also a problem: bugs can't be patched and features can't be added. Proxy patterns work around it by splitting a contract in two:

  • a proxy that holds the address users talk to, plus all the state and ether;
  • an implementation (logic contract) that holds the code.

The proxy forwards every call to the implementation with delegatecall. Upgrading means pointing the proxy at a new implementation. The address and the data stay the same.

delegatecall

delegatecall runs another contract's code in the context of the caller: the code reads and writes the caller's storage, and msg.sender and msg.value stay unchanged.

call delegatecall
Code that runs the target's the target's
Storage used the target's the caller's
msg.sender inside the caller the original sender
address(this) inside the target the caller
solidity · try it yourself
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

import "hardhat/console.sol";

contract Logic {
    uint256 public number;          // slot 0
    address public lastCaller;      // slot 1

    function setNumber(uint256 n) external {
        number = n;
        lastCaller = msg.sender;
    }
}

contract Caller {
    uint256 public number;          // same layout as Logic
    address public lastCaller;

    function viaCall(Logic logic, uint256 n) external {
        logic.setNumber(n);
    }

    function viaDelegatecall(Logic logic, uint256 n) external {
        (bool ok, ) = address(logic).delegatecall(abi.encodeCall(Logic.setNumber, (n)));
        require(ok, "delegatecall failed");
    }
}

contract Main {
    function main() external {
        Logic logic = new Logic();
        Caller caller = new Caller();

        caller.viaCall(logic, 7);
        console.log("after call        : logic", logic.number(), "caller", caller.number());

        caller.viaDelegatecall(logic, 42);
        console.log("after delegatecall: logic", logic.number(), "caller", caller.number());
        console.log("caller.lastCaller is Main?", caller.lastCaller() == address(this));
    }
}
after call        : logic 7 caller 0
after delegatecall: logic 7 caller 42
caller.lastCaller is Main? true

With delegatecall, Logic's code wrote 42 into Caller's storage, and msg.sender inside was still Main.

A minimal upgradeable proxy

The proxy stores the implementation address in a special slot (ERC-1967 uses keccak256("eip1967.proxy.implementation") - 1) so it can't collide with the implementation's own variables. Its fallback forwards every call:

solidity · try it yourself
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

import "hardhat/console.sol";

contract CounterV1 {
    uint256 public count;
    function increment() external { count += 1; }
    function version() external pure returns (string memory) { return "v1"; }
}

contract CounterV2 {
    uint256 public count;                                  // same slot 0: layout preserved
    function increment() external { count += 10; }         // changed behaviour
    function decrement() external { count -= 1; }          // new function
    function version() external pure returns (string memory) { return "v2"; }
}

contract Proxy {
    bytes32 private constant IMPL_SLOT = bytes32(uint256(keccak256("eip1967.proxy.implementation")) - 1);
    bytes32 private constant ADMIN_SLOT = bytes32(uint256(keccak256("eip1967.proxy.admin")) - 1);

    constructor(address impl) {
        _set(IMPL_SLOT, impl);
        _set(ADMIN_SLOT, msg.sender);
    }

    function upgradeTo(address newImpl) external {
        require(msg.sender == _get(ADMIN_SLOT), "only admin");
        _set(IMPL_SLOT, newImpl);
    }

    fallback() external payable {
        address impl = _get(IMPL_SLOT);
        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()) }
        }
    }

    function _get(bytes32 slot) private view returns (address a) {
        assembly { a := sload(slot) }
    }

    function _set(bytes32 slot, address a) private {
        assembly { sstore(slot, a) }
    }
}

contract Main {
    function main() external {
        Proxy proxy = new Proxy(address(new CounterV1()));
        CounterV1 counter = CounterV1(address(proxy));       // use the proxy with V1's ABI

        counter.increment();
        counter.increment();
        console.log(counter.version(), "count:", counter.count());

        proxy.upgradeTo(address(new CounterV2()));
        CounterV2 counter2 = CounterV2(address(proxy));      // same address, new ABI
        counter2.increment();
        counter2.decrement();
        console.log(counter2.version(), "count:", counter2.count());
    }
}
v1 count: 2
v2 count: 11

The count survived the upgrade, because it lives in the proxy. Only the code changed.

Rules for upgradeable code

  1. No constructors for state. A constructor runs in the implementation's context, not the proxy's. Use an initialize() function instead, and make sure it can run only once (an unprotected initializer is an access-control bug).
  2. Never reorder or remove state variables. Only append new ones at the end. Changing the layout makes new code read old data from the wrong slots:
solidity · try it yourself
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

import "hardhat/console.sol";

contract V1 {
    address public owner;        // slot 0
    uint256 public balance;      // slot 1
    function init() external { owner = msg.sender; balance = 500; }
}

contract V2Broken {
    uint256 public balance;      // now slot 0: reads the old owner bits!
    address public owner;        // now slot 1
    function readBalance() external view returns (uint256) { return balance; }
}

contract Host {
    address public owner;
    uint256 public balance;
    function run(address impl, bytes calldata data) external returns (bytes memory) {
        (bool ok, bytes memory ret) = impl.delegatecall(data);
        require(ok, "failed");
        return ret;
    }
}

contract Main {
    function main() external {
        Host host = new Host();
        host.run(address(new V1()), abi.encodeCall(V1.init, ()));
        bytes memory ret = host.run(address(new V2Broken()), abi.encodeCall(V2Broken.readBalance, ()));
        console.log("V2 sees balance =", abi.decode(ret, (uint256)));
        console.log("the real balance =", host.balance());
    }
}
V2 sees balance = 546584486846459126461364135121053344201067465379
the real balance = 500

The broken V2 interprets the owner address as a number. Tools such as the OpenZeppelin Upgrades plugin check storage layouts automatically before every upgrade.

  1. Be careful with selfdestruct and delegatecall inside the implementation, and initialize (or disable initializers on) the implementation contract itself.

Patterns and trade-offs

Pattern Upgrade logic lives in Notes
Transparent proxy the proxy (admin-only) admin calls never reach the implementation
UUPS (ERC-1822) the implementation (upgradeTo) cheaper proxy; forgetting upgradeTo in V2 freezes upgrades
Beacon proxy a shared beacon contract upgrade many proxies at once
Minimal clone (ERC-1167) not upgradeable cheap copies of one implementation

Upgradeability is a trust trade-off: whoever controls the upgrade key can change the rules. Projects often put upgrades behind a multisig and a timelock so users can react before a change takes effect.

Test yourself

With delegatecall, whose storage does the target's code modify?

  1. The target's
  2. The caller's
  3. Both
  4. Neither

Why do upgradeable contracts use initialize() instead of a constructor?

  1. Constructors are deprecated
  2. A constructor would run in the implementation's context, so the proxy's storage would stay empty
  3. Constructors can't take arguments
  4. To save gas

Which change is safe in a new implementation version?

  1. Swapping the order of two state variables
  2. Removing an unused state variable
  3. Appending a new state variable at the end
  4. Changing a uint256 variable to address