Testing Upgradeable Smart Contracts: UUPS and Transparent Proxy

Testing Upgradeable Smart Contracts: UUPS and Transparent Proxy

Upgradeable smart contracts are one of the most powerful and most dangerous patterns in Solidity. The ability to fix bugs and add features after deployment is genuinely useful — but the proxy pattern introduces an entirely new category of bugs that standard unit tests will miss: storage layout collisions, broken initializer patterns, state corruption across upgrades, and upgrade authorization bypasses.

If you deploy an upgradeable contract without a rigorous testing strategy for the upgrade mechanism itself, you are shipping a system where the upgrade path is untested production code. This guide covers how to test UUPS and TransparentProxy contracts thoroughly using the OpenZeppelin Hardhat Upgrades plugin.

The Two Proxy Patterns

OpenZeppelin provides two main upgradeable proxy patterns:

TransparentUpgradeableProxy separates admin from user. The proxy contract itself handles the upgrade logic. Admin calls go to the proxy; user calls are delegated to the implementation. The admin can never interact with the implementation directly through the proxy.

UUPS (EIP-1822) moves the upgrade logic into the implementation contract. The proxy is a thin shell. The implementation must include an upgradeTo function, and only the implementation can authorize upgrades. This is more gas-efficient and is the current recommended pattern.

Both patterns use delegatecall under the hood: the proxy stores all state, the implementation contains all logic, and calls to the proxy execute the implementation's code in the proxy's storage context.

Setup: OpenZeppelin Hardhat Upgrades Plugin

npm install --save-dev @openzeppelin/hardhat-upgrades
npm install @openzeppelin/contracts-upgradeable

Add to hardhat.config.ts:

import "@openzeppelin/hardhat-upgrades";

Writing Upgradeable Contracts

The rules for upgradeable contracts differ from regular contracts:

  1. No constructor — use initializer functions instead
  2. No immutable variables
  3. Never change storage variable order across upgrades
  4. New storage variables go at the end

Here's a sample contract pair for testing:

// contracts/VaultV1.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";

contract VaultV1 is Initializable, UUPSUpgradeable, OwnableUpgradeable {
    IERC20Upgradeable public token;
    mapping(address => uint256) public balances;
    uint256 public totalDeposited;

    /// @custom:oz-upgrades-unsafe-allow constructor
    constructor() {
        _disableInitializers();
    }

    function initialize(address _token) public initializer {
        __Ownable_init(msg.sender);
        __UUPSUpgradeable_init();
        token = IERC20Upgradeable(_token);
    }

    function deposit(uint256 amount) external {
        token.transferFrom(msg.sender, address(this), amount);
        balances[msg.sender] += amount;
        totalDeposited += amount;
    }

    function withdraw(uint256 amount) external {
        require(balances[msg.sender] >= amount, "Insufficient balance");
        balances[msg.sender] -= amount;
        totalDeposited -= amount;
        token.transfer(msg.sender, amount);
    }

    function _authorizeUpgrade(address newImplementation) internal override onlyOwner {}
}

The V2 adds a fee mechanism and a new storage variable:

// contracts/VaultV2.sol
import "./VaultV1.sol";

contract VaultV2 is VaultV1 {
    uint256 public withdrawalFee; // New storage variable — MUST go after V1 variables
    address public feeRecipient;
    uint256 public totalFeesCollected;

    function initializeV2(uint256 _fee, address _feeRecipient) public reinitializer(2) {
        withdrawalFee = _fee;
        feeRecipient = _feeRecipient;
    }

    function withdraw(uint256 amount) external override {
        require(balances[msg.sender] >= amount, "Insufficient balance");
        
        uint256 fee = (amount * withdrawalFee) / 10000; // basis points
        uint256 netAmount = amount - fee;
        
        balances[msg.sender] -= amount;
        totalDeposited -= amount;
        totalFeesCollected += fee;
        
        if (fee > 0) {
            token.transfer(feeRecipient, fee);
        }
        token.transfer(msg.sender, netAmount);
    }

    function version() external pure returns (string memory) {
        return "2.0.0";
    }
}

Testing Initial Deployment and Initialization

import { expect } from "chai";
import { ethers, upgrades } from "hardhat";
import { VaultV1, MockERC20 } from "../typechain-types";

describe("VaultV1 — deployment and initialization", () => {
  let vault: VaultV1;
  let token: MockERC20;
  let owner: any;
  let user: any;

  beforeEach(async () => {
    [owner, user] = await ethers.getSigners();

    const MockERC20 = await ethers.getContractFactory("MockERC20");
    token = await MockERC20.deploy("Test Token", "TEST", 18);

    const VaultV1 = await ethers.getContractFactory("VaultV1");
    vault = await upgrades.deployProxy(VaultV1, [token.target], {
      kind: "uups",
      initializer: "initialize",
    }) as VaultV1;
  });

  it("deploys with correct initial state", async () => {
    expect(await vault.token()).to.equal(token.target);
    expect(await vault.totalDeposited()).to.equal(0);
    expect(await vault.owner()).to.equal(owner.address);
  });

  it("cannot be initialized twice", async () => {
    await expect(
      vault.initialize(token.target)
    ).to.be.revertedWithCustomError(vault, "InvalidInitialization");
  });

  it("proxy address is different from implementation address", async () => {
    const implAddress = await upgrades.erc1967.getImplementationAddress(
      vault.target as string
    );
    expect(implAddress).to.not.equal(vault.target);
  });

  it("only owner can upgrade", async () => {
    const VaultV2 = await ethers.getContractFactory("VaultV2");
    await expect(
      upgrades.upgradeProxy(vault.target as string, VaultV2.connect(user))
    ).to.be.revertedWithCustomError(vault, "OwnableUnauthorizedAccount");
  });
});

Testing the Upgrade Path

This is the core of upgradeable contract testing — proving that the upgrade works correctly:

describe("VaultV1 → VaultV2 upgrade", () => {
  let vault: VaultV1;
  let token: MockERC20;
  let owner: any;
  let user1: any;
  let user2: any;
  let proxyAddress: string;

  // Pre-upgrade state we want to verify is preserved
  const USER1_DEPOSIT = ethers.parseEther("1000");
  const USER2_DEPOSIT = ethers.parseEther("500");

  beforeEach(async () => {
    [owner, user1, user2] = await ethers.getSigners();

    const MockERC20 = await ethers.getContractFactory("MockERC20");
    token = await MockERC20.deploy("Test Token", "TEST", 18);

    // Mint tokens to users
    await token.mint(user1.address, USER1_DEPOSIT);
    await token.mint(user2.address, USER2_DEPOSIT);

    // Deploy V1
    const VaultV1 = await ethers.getContractFactory("VaultV1");
    vault = await upgrades.deployProxy(VaultV1, [token.target], {
      kind: "uups",
    }) as VaultV1;
    proxyAddress = vault.target as string;

    // Make deposits in V1
    await token.connect(user1).approve(proxyAddress, USER1_DEPOSIT);
    await vault.connect(user1).deposit(USER1_DEPOSIT);

    await token.connect(user2).approve(proxyAddress, USER2_DEPOSIT);
    await vault.connect(user2).deposit(USER2_DEPOSIT);
  });

  it("preserves all user balances after upgrade", async () => {
    const VaultV2 = await ethers.getContractFactory("VaultV2");
    const vaultV2 = await upgrades.upgradeProxy(proxyAddress, VaultV2) as any;
    await vaultV2.initializeV2(50, owner.address); // 0.5% fee

    // Same proxy address — same state
    expect(await vaultV2.balances(user1.address)).to.equal(USER1_DEPOSIT);
    expect(await vaultV2.balances(user2.address)).to.equal(USER2_DEPOSIT);
  });

  it("preserves totalDeposited after upgrade", async () => {
    const VaultV2 = await ethers.getContractFactory("VaultV2");
    await upgrades.upgradeProxy(proxyAddress, VaultV2);

    const vaultV2 = await ethers.getContractAt("VaultV2", proxyAddress);
    expect(await vaultV2.totalDeposited()).to.equal(USER1_DEPOSIT + USER2_DEPOSIT);
  });

  it("new V2 functions work after upgrade", async () => {
    const VaultV2 = await ethers.getContractFactory("VaultV2");
    await upgrades.upgradeProxy(proxyAddress, VaultV2);

    const vaultV2 = await ethers.getContractAt("VaultV2", proxyAddress);
    await vaultV2.initializeV2(100, owner.address); // 1% fee

    expect(await vaultV2.version()).to.equal("2.0.0");
    expect(await vaultV2.withdrawalFee()).to.equal(100);
  });

  it("withdrawal applies fee after upgrade", async () => {
    const VaultV2 = await ethers.getContractFactory("VaultV2");
    await upgrades.upgradeProxy(proxyAddress, VaultV2);

    const vaultV2 = await ethers.getContractAt("VaultV2", proxyAddress);
    await vaultV2.initializeV2(200, owner.address); // 2% fee

    const withdrawAmount = ethers.parseEther("500");
    const expectedFee = withdrawAmount * 200n / 10000n; // 2%
    const expectedNet = withdrawAmount - expectedFee;

    const userBalanceBefore = await token.balanceOf(user1.address);
    await vaultV2.connect(user1).withdraw(withdrawAmount);
    const userBalanceAfter = await token.balanceOf(user1.address);

    expect(userBalanceAfter - userBalanceBefore).to.equal(expectedNet);
    expect(await token.balanceOf(owner.address)).to.equal(expectedFee);
  });

  it("implementation address changes after upgrade", async () => {
    const implBefore = await upgrades.erc1967.getImplementationAddress(proxyAddress);

    const VaultV2 = await ethers.getContractFactory("VaultV2");
    await upgrades.upgradeProxy(proxyAddress, VaultV2);

    const implAfter = await upgrades.erc1967.getImplementationAddress(proxyAddress);
    expect(implAfter).to.not.equal(implBefore);
  });

  it("proxy address does not change after upgrade", async () => {
    const VaultV2 = await ethers.getContractFactory("VaultV2");
    const vaultV2 = await upgrades.upgradeProxy(proxyAddress, VaultV2);

    // The proxy address should be identical
    expect(vaultV2.target).to.equal(proxyAddress);
  });
});

Testing Storage Layout Validation

The OpenZeppelin plugin validates storage layout compatibility at deploy time, but you should also test this explicitly:

it("validates storage layout compatibility before upgrading", async () => {
  // This test verifies the plugin's validation catches incompatible layouts
  const BadVaultV2 = await ethers.getContractFactory("BadVaultV2");
  // BadVaultV2 has a new variable inserted BEFORE existing variables — storage collision!
  
  await expect(
    upgrades.validateUpgrade(proxyAddress, BadVaultV2)
  ).to.be.rejectedWith(/storage layout/i);
});

The "bad" V2 would look like:

// contracts/BadVaultV2.sol — DO NOT DEPLOY THIS
contract BadVaultV2 is Initializable, UUPSUpgradeable, OwnableUpgradeable {
    uint256 public newVariable; // WRONG: inserted before existing variables
    IERC20Upgradeable public token; // This now occupies slot 1, was slot 0 in V1
    mapping(address => uint256) public balances; // Slot collision!
    // ...
}

The plugin catches this, but writing an explicit test documents the expectation and ensures the check runs in your test suite.

Testing the reinitializer Pattern

V2 initialization must only run once. Test this explicitly:

describe("V2 initializer", () => {
  it("can only be called once", async () => {
    const VaultV2Factory = await ethers.getContractFactory("VaultV2");
    const vaultV2 = await upgrades.upgradeProxy(proxyAddress, VaultV2Factory);
    
    await vaultV2.initializeV2(100, owner.address);
    
    // Second call must revert
    await expect(
      vaultV2.initializeV2(200, user1.address)
    ).to.be.revertedWithCustomError(vaultV2, "InvalidInitialization");
  });

  it("new variables have zero values before initializeV2 is called", async () => {
    const VaultV2Factory = await ethers.getContractFactory("VaultV2");
    const vaultV2 = await upgrades.upgradeProxy(proxyAddress, VaultV2Factory);

    // Before initializeV2: new variables are default values
    expect(await vaultV2.withdrawalFee()).to.equal(0);
    expect(await vaultV2.feeRecipient()).to.equal(ethers.ZeroAddress);
  });
});

Testing TransparentUpgradeableProxy

Transparent proxies have a slightly different testing setup. The proxy admin is a separate contract:

describe("TransparentProxy vault", () => {
  let vault: VaultV1;
  let proxyAdmin: any;

  beforeEach(async () => {
    [owner, user] = await ethers.getSigners();

    const VaultV1 = await ethers.getContractFactory("VaultV1");
    vault = await upgrades.deployProxy(VaultV1, [token.target], {
      kind: "transparent",
    }) as VaultV1;

    // Get the ProxyAdmin contract address
    const adminAddress = await upgrades.erc1967.getAdminAddress(vault.target as string);
    proxyAdmin = await ethers.getContractAt("ProxyAdmin", adminAddress);
  });

  it("proxy admin is a separate contract", async () => {
    const adminAddress = await upgrades.erc1967.getAdminAddress(vault.target as string);
    expect(adminAddress).to.not.equal(ethers.ZeroAddress);
    expect(adminAddress).to.not.equal(vault.target);
  });

  it("admin address is separate from owner", async () => {
    const adminAddress = await upgrades.erc1967.getAdminAddress(vault.target as string);
    // For Transparent proxies, the ProxyAdmin contract owns the upgrade rights
    // The owner of ProxyAdmin is the deployer
    const adminContract = await ethers.getContractAt("ProxyAdmin", adminAddress);
    expect(await adminContract.owner()).to.equal(owner.address);
  });
});

Testing Upgrade Authorization

The upgrade authorization function is security-critical. Test all paths:

describe("Upgrade authorization", () => {
  it("owner can authorize upgrade", async () => {
    const VaultV2 = await ethers.getContractFactory("VaultV2");
    // Should not throw
    await expect(
      upgrades.upgradeProxy(proxyAddress, VaultV2.connect(owner))
    ).to.not.be.rejected;
  });

  it("non-owner cannot authorize upgrade", async () => {
    const VaultV2 = await ethers.getContractFactory("VaultV2");
    await expect(
      upgrades.upgradeProxy(proxyAddress, VaultV2.connect(user1))
    ).to.be.revertedWithCustomError(vault, "OwnableUnauthorizedAccount");
  });

  it("emits Upgraded event on successful upgrade", async () => {
    const VaultV2 = await ethers.getContractFactory("VaultV2");
    const tx = upgrades.upgradeProxy(proxyAddress, VaultV2);

    // The ERC1967 Upgraded event is emitted by the proxy
    await expect(tx).to.emit(
      await ethers.getContractAt("ERC1967Proxy", proxyAddress),
      "Upgraded"
    );
  });
});

Gas Costs of Upgrade Operations

Upgrades themselves have a gas cost. For contracts used by many users, even temporary unavailability during an upgrade matters. Test gas bounds:

it("upgrade transaction fits within gas budget", async () => {
  const VaultV2 = await ethers.getContractFactory("VaultV2");
  const tx = await upgrades.upgradeProxy(proxyAddress, VaultV2);
  const receipt = await tx.deploymentTransaction()?.wait();

  // Upgrade should cost less than 200k gas
  expect(receipt?.gasUsed).to.be.lessThan(200_000n);
});

Continuous Monitoring for Upgrade Events

Once your upgrade tests pass and you deploy, the risk doesn't end. Unauthorized upgrade attempts, unexpected proxy admin changes, and storage corruption from future upgrades all need to be caught in production.

HelpMeTest can monitor your proxy contracts continuously — watching for unexpected Upgraded events, unauthorized admin access, and behavioral regressions after legitimate upgrades. It's the production-side complement to your pre-deployment upgrade test suite.

Summary

Testing upgradeable contracts requires going beyond function-level unit tests to cover the upgrade mechanism itself. The critical tests are:

  1. Initialization: Initializers run exactly once, cannot be called again
  2. State preservation: All user balances and state survive the upgrade
  3. Storage layout: New implementations are layout-compatible with existing proxies
  4. Authorization: Only authorized addresses can trigger upgrades
  5. Proxy identity: The proxy address stays constant across upgrades
  6. New functionality: V2 features work correctly post-upgrade
  7. Re-initialization: reinitializer gates run exactly once

The OpenZeppelin Hardhat Upgrades plugin automates the hardest parts — storage layout validation and proxy management — but the business logic tests (state preservation, authorization, new features) are your responsibility to write. An upgradeable contract with untested upgrade paths is a contract with a dangerous unreviewed attack surface.

Read more

Start now free