Introduction

Hi, I'm cardene, a software engineer and technical writer focused on blockchain and AI.

I've also authored Japanese technical books on specification-driven development with LLMs and decentralized application (DApp) development.

I also build and publish a variety of tools, libraries, and open-source projects.

This article introduces upgradeable contracts, which allow smart contract applications to be upgraded.

Smart contracts are often described as immutable, so the idea of upgrading one may sound contradictory.

We will first look at what upgradeable contracts are, how they work, their advantages and disadvantages, and the precautions they require. The second half walks through practical implementations.

The examples and diagrams are from the original January 2023 article. Some implementation details and tooling may differ in newer versions of OpenZeppelin.

What are upgradeable contracts?

Overview of upgradeable contracts

Overview

Upgradeable contracts are, as the name suggests, contracts whose application logic can be upgraded.

The usual rule is that the bytecode of a deployed smart contract cannot simply be edited.

But what if we deploy a new contract and switch from using the old contract to using the new one?

The existing contracts themselves remain unchanged. We merely switch which contract supplies the logic. The following sections explain how this works.

Why make contracts upgradeable?

As explained above, deployed smart contract code cannot ordinarily be modified.

Immutability improves trust in the code, but it also makes it impossible to patch bugs or add functionality to that deployed bytecode.

This can be inconvenient, particularly if a critical vulnerability puts funds at risk and there is no mechanism for responding to it.

For this reason, many projects using smart contracts incorporate upgrade mechanisms.

How to make contracts upgradeable

One way to achieve upgradeability is through a proxy contract.

The term proxy refers to an intermediary. The Japanese Wikipedia article describes a proxy server as an intermediary that accesses the internet on behalf of clients, for purposes such as faster access or secure communication.

Wikipedia: Proxy (Japanese)

Similarly, a proxy contract sits between the caller and the smart contract that implements the actual processing, referred to here as the logic contract.

The diagram below illustrates the arrangement.

A proxy forwarding calls to ContractA

The user first calls the proxy contract, which then forwards the call to ContractA.

Changing the proxy's target allows it to forward calls to ContractB instead.

A proxy forwarding calls to ContractB

Neither ContractA nor ContractB needs to be modified. Only the target contract address held by the proxy changes.

If smart contracts are immutable, how can the target address be changed?

The address is stored as a state variable, and a function updates its value. Access to this function must be restricted to authorized parties, such as the account that deployed and administers the proxy in a simple example.

When forwarding a call to the logic contract, the proxy uses delegatecall.

A delegatecall executes the target's code in the context of the calling contract. As a result, the logic contract's code operates on the proxy's storage rather than its own.

For more information about delegatecall, see the following article.

[Solidity Bug Bounty] An introduction to delegatecall vulnerabilities

Five approaches to upgradeability

There are several ways to make a smart contract application upgradeable.

Five approaches

  • Deploy a replacement contract and migrate data from the old contract.
  • Separate data storage and business logic into two contracts.
  • Use a proxy pattern in which a proxy calls a logic contract via delegatecall.
  • Have a main contract store addresses of contracts implementing individual features, allowing those implementations to be replaced.
  • Use the diamond pattern, separating functionality into multiple contracts.

Let's examine each approach.

Deploy a new contract and migrate data

Deploy a new contract while the old contract is still available.

Then migrate data, balances, and other relevant state from the old contract to the replacement.

The final step is to convince users of the old contract to switch to the new one.

It is important to demonstrate that the data and balances were migrated correctly and prevent users from accidentally sending funds to the old contract.

The drawback is that migrating state and balances every time a new version is deployed may take considerable time and incur high gas costs.

Separate data and logic into two contracts

Create two contracts: a data contract that holds state and a logic contract.

The data contract stores state such as user balances and addresses. It also stores the authorized logic contract's address, preventing unauthorized contracts from modifying data.

In the arrangement described here, the user interacts with the data contract, and the data remains stored there. The logic contract holds the data contract's address and interacts with it to retrieve and update state.

The data contract's code remains unchanged. Updating its authorized logic contract address allows the logic to be replaced.

Managing multiple contracts and preventing malicious contracts from accessing state requires careful authorization and authentication design.

Proxy Pattern

This is the proxy contract approach introduced earlier.

It also involves two contracts: a state-holding proxy contract and a logic contract.

Proxy Pattern

  • Users interact only with the proxy contract.
  • The proxy stores the logic contract address and invokes its code through delegatecall.
  • Because the logic contract is called through delegatecall, state is stored in the proxy, and execution results are returned to the user.

For a more detailed explanation of delegatecall, see the following article.

[Solidity Bug Bounty] An introduction to delegatecall vulnerabilities

Solidity provides a fallback function that can run when a call does not match any declared function. A proxy typically uses this mechanism.

The proxy does not declare all of the functions provided by its logic contract. Without a forwarding fallback, calling an implementation function on the proxy would fail.

When the fallback runs, the proxy uses delegatecall to execute the current logic contract's code.

Changing the implementation address stored by the proxy changes which logic contract handles these calls.

The proxy pattern is more complex than the preceding approaches and introduces additional security risks, so understanding its behavior is important.

Strategy Pattern

This arrangement consists of a main contract and several satellite contracts, each responsible for particular functionality.

The main contract stores data and interacts with each satellite contract through its interface and address.

Implementing a new satellite contract and registering its address with the main contract makes it possible to replace or add functionality supported by the main contract's architecture.

This resembles the proxy pattern, but the main contract contains its own core application logic and directly manages state while delegating specific responsibilities to the satellites. A conventional proxy also holds state, but delegates execution of its implementation logic through delegatecall.

The advantage is that targeted changes can be made without modifying core functionality.

However, a vulnerability in the main contract may still compromise the entire system.

Diamond pattern

The diamond pattern extends the proxy concept.

Instead of a single logic contract, it uses multiple contracts called facets, each implementing particular functions.

The proxy maintains a mapping from function selectors to facet addresses.

When a user calls a function, the proxy looks up the responsible facet and executes its code through delegatecall.

The diamond pattern offers the following advantages.

Upgrades can be limited to individual features

Instead of replacing an entire implementation, a diamond can upgrade a subset of functions by replacing the relevant facet or selector mappings.

With a conventional proxy, even a small upgrade may require deploying a new implementation contract.

Addressing the 24KB contract size limit

A contract's deployed runtime bytecode is subject to a 24 KiB (24,576-byte) size limit under EIP170.

Implementing a large number of functions in one contract may exceed that limit.

The diamond pattern distributes functionality across multiple contracts, each subject to its own size limit.

Access can be controlled for specific functionality

In a simple proxy pattern, permission to upgrade the implementation generally allows replacement of the entire implementation contract.

A diamond can make upgrades more granular by managing individual functions or facets. Such per-feature access control must still be explicitly implemented; the diamond pattern does not automatically enforce it.

Advantages and disadvantages of upgradeability

Advantages

Advantages

  • Vulnerabilities can be patched through upgrades.
  • New functionality can be added.
  • Developers can experiment with features and improve the application over time.

Disadvantages

Disadvantages

  • Upgradeability changes the immutability guarantees of application behavior and affects decentralization and security.
  • Users must trust the parties authorized to upgrade the contract not to make arbitrary or malicious changes.
  • Additional complexity can introduce vulnerabilities.
  • Teams may launch projects before they are adequately prepared because they expect to fix problems later.
  • Inadequate access control or centralized upgrade authority can allow unauthorized or malicious upgrades.

Precautions for upgradeable contracts

Appropriate access control

Configure authorization and access control to prevent unauthorized upgrades.

For example, restrict upgrades to an authorized owner or governance mechanism.

Improving security

Contract upgrades are complex and can introduce vulnerabilities.

Security audits and bug bounty programs can help identify problems.

For more information about bug bounties, see the following article.

[Solidity Bug Bounty] An introduction to bug bounty programs

Designing the upgrade procedure

Users of an upgradeable contract must place some trust in the parties authorized to perform upgrades.

A multisignature wallet requiring approval from multiple signers or a DAO voting process can help distribute that authority.

Calculating costs

Upgrading contracts incurs costs.

For example, migrating data and balances from an old contract to a new one can require multiple transactions and substantial gas fees.

Estimate these costs before performing an upgrade.

Introducing a timelock

A timelock prevents certain actions from being executed until a predetermined delay has elapsed.

During an upgrade, unexpected operations could cause inconsistent behavior or even loss of funds. A defined restriction period can prevent certain unexpected operations.

In practice, an upgrade timelock usually delays execution of the upgrade itself, giving users time to review the proposed change. Pausing other application operations requires a separate mechanism.

Constructors cannot initialize proxy storage

A logic contract can have a constructor, but the constructor does not run in the proxy's context when the proxy invokes the deployed implementation through delegatecall.

The implementation has already been deployed, so its constructor has already executed against its own storage.

An initializer that runs once in the proxy's context is therefore needed. OpenZeppelin provides mechanisms such as Initializable.sol for this purpose.

Keeping storage layouts compatible

In simple delegatecall examples, state variable types and their declaration order must be aligned between contracts. When upgrading a proxy, the critical requirement is compatibility between successive implementation storage layouts and avoidance of collisions with proxy-specific storage slots.

A storage collision occurs when different variables or contracts use the same storage location for incompatible purposes.

The following article explains how smart contracts store data.

[Solidity Bug Bounty] An introduction to accessing private data

Because delegatecall uses the proxy's storage, incompatible changes to variable types or ordering in the logic contract can produce unexpected results.

For a detailed explanation, see the following article.

[Solidity Bug Bounty] An introduction to delegatecall vulnerabilities

Proxy Pattern

Overview of proxy patterns

The previous section introduced upgradeable contracts. Here, we examine proxy contracts in more detail.

The proxy pattern encompasses architectures in which a proxy sits between the user and the logic contract.

As shown in the earlier diagrams, the user accesses the proxy, and the proxy forwards calls to the logic contract.

Changing the logic contract that receives forwarded calls makes the overall application upgradeable.

We will examine three common proxy patterns.

Proxy Pattern

  • Transparent Proxy
  • UUPS Proxy
  • Beacon Proxy

Transparent Proxy

The proxy contract uses delegatecall to invoke the logic contract.

For more about delegatecall, see the following article.

[Solidity Bug Bounty] An introduction to delegatecall vulnerabilities

In the OpenZeppelin arrangement described here, changing the implementation that the proxy invokes is performed through a ProxyAdmin contract controlled by an authorized administrator.

The green lines in the diagram represent delegatecall operations.

Transparent Proxy architecture

Users interact with the proxy, which delegates calls to the configured implementation contract.

The administrator calls ProxyAdmin to change the implementation address used by the proxy.

The administrator of ProxyAdmin can also transfer its administrative ownership, subject to the implementation's access controls.

UUPS Proxy

The UUPS pattern is similar to the Transparent Proxy pattern, but the upgrade mechanism is implemented differently.

With a Transparent Proxy, a separate ProxyAdmin contract can administer upgrades. In UUPS, upgrade functions instead reside in the implementation and are normally invoked through the proxy.

The original explanation describes this as ProxyAdmin being accessible through the proxy; more precisely, UUPS does not inherently require a separate ProxyAdmin contract. It places upgrade logic in the implementation itself.

If appropriate authorization is not implemented, unauthorized parties may be able to change the implementation to which the proxy delegates.

Because the upgrade mechanism resides in the implementation, replacing the implementation can also change or disable the upgrade mechanism itself, subject to compatibility and safety checks.

The green lines in the diagram represent delegatecall operations.

UUPS Proxy architecture

Beacon Proxy

Unlike a conventional Transparent or UUPS proxy arrangement, the beacon pattern allows multiple proxies to share an upgrade mechanism.

It is useful when several instances of an application are deployed.

Each proxy has its own state and uses a shared beacon to determine the implementation contract to which it should delegate.

The beacon supplies the indirection between the proxies and the logic contract.

The green lines in the diagram represent delegatecall operations.

Beacon Proxy architecture

Updating the shared beacon's implementation in one transaction changes which implementation all proxies referencing that beacon will use for subsequent calls.

This does not mean that the upgrade transaction itself executes each proxy's application functions.

The beacon thus provides a common mechanism for managing implementation changes across multiple proxies, while the authority to update it is controlled separately.

Implementing proxy patterns

Proxy pattern implementation

Let's implement the proxy patterns.

The code is available in the following repository.

Setup

First, prepare the development environment shared by all three implementations.

Installing Node.js and npm

If Node.js and npm are not installed, follow the instructions in this article.

Creating a directory

Create a working directory.

bash
$ mkdir proxy-pattern
$ cd proxy-pattern

Installing dependencies

Install the required packages.

bash
$ npm i @openzeppelin/contracts @openzeppelin/contracts-upgradeable @openzeppelin/hardhat-upgrades chai dotenv hardhat hardhat-gas-reporter

Hardhat

Next, set up Hardhat, a Solidity development environment that makes writing and running tests straightforward.

bash
$ npx hardhat

888    888                      888 888               888
888    888                      888 888               888
888    888                      888 888               888
8888888888  8888b.  888d888 .d88888 88888b.   8888b.  888888
888    888     "88b 888P"  d88" 888 888 "88b     "88b 888
888    888 .d888888 888    888  888 888  888 .d888888 888
888    888 888  888 888    Y88b 888 888  888 888  888 Y88b.
888    888 "Y888888 888     "Y88888 888  888 "Y888888  "Y888

👷 Welcome to Hardhat v2.12.5 👷‍

? What do you want to do? … 
❯ Create a JavaScript project
  Create a TypeScript project
  Create an empty hardhat.config.js
  Quit

Running the command displays interactive prompts like the following. In the original tutorial, the defaults were accepted by pressing Enter.

bash
Give Hardhat a star on Github if you're enjoying it! 💞✨

     https://github.com/NomicFoundation/hardhat

Please take a moment to complete the 2022 Solidity Survey: https://hardhat.org/solidity-survey-2022

The displayed output indicates that the Hardhat project was created.

bash
.
├── README.md
├── contracts
│   └── Lock.sol
├── hardhat.config.js
├── node_modules
├── package-lock.json
├── package.json
├── scripts
│   └── deploy.js
└── test
    └── Lock.js

The above shows the expected project structure.

hardhat.config.js

Open hardhat.config.js.

javascript
require("@nomicfoundation/hardhat-toolbox");
require('@openzeppelin/hardhat-upgrades');

require("dotenv").config();
require("hardhat-gas-reporter")

module.exports = {
  solidity: {
    version: "0.8.17",
    settings: {
      optimizer: {
        enabled: true,
        runs: 200,
      },
    },
  },
  networks: {
    hardhat: {
      blockGasLimit: 30_000_000,
    },
  },
  gasReporter: {
    enabled: true,
    currency: 'USD',
    gasPrice: 21
  }
};

Paste the configuration above into the file and save it. This completes the setup.

Transparent Proxy

We will start with the Transparent Proxy pattern.

Creating the contracts

Create the files contracts/TransparentLogic.sol and contracts/TransparentLogicV2.sol.

bash
$ touch contracts/TransparentLogic.sol
$ touch contracts/TransparentLogicV2.sol
TransparentLogic.sol

Open TransparentLogic.sol and paste in the following code.

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

import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";

contract TransparentLogic is Initializable {
    address public owner;
    string public name;
    uint256 public age;

    /// @notice 一度だけ実行される関数。constructorの代わり。
    function initialize() public initializer {
        owner = msg.sender;
    }

    /// @notice プロフィール情報を更新する関数。
    /// @param _name 名前。
    /// @param _age 年齢。
    function setProfile(string memory _name, uint256 _age) external {
        name = _name;
        age = _age;
    }

    /// @notice プロフィール情報を取得する関数。
    /// @return name 名前。
    /// @return age 年齢。
    function getProfile() external view returns(string memory, uint256){
        return (name, age);
    }

}

The contract defines three state variables: owner, name, and age.

The initialize function can run once and stores the caller's address in owner.

The setProfile function stores the supplied values in name and age.

The getProfile function retrieves the values of name and age.

TransparentLogicV2.sol

Open TransparentLogicV2.sol, the upgraded implementation, and paste in the following code.

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

import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";

contract TransparentLogicV2 is Initializable {
    address public owner;
    string public name;
    uint256 public age;
    string public favoriteFruit;

    /// @notice 一度だけ実行される関数。constructorの代わり。
    function initialize() public initializer {
        owner = msg.sender;
    }

    /// @notice プロフィール情報を更新する関数。
    /// @param _name 名前。
    /// @param _fruit 好きな果物。
    /// @param _age 年齢。
    function setProfile(
        string memory _name,
        string memory _fruit,
        uint256 _age
    ) external {
        name = _name;
        favoriteFruit = _fruit;
        age = _age;
    }

    /// @notice プロフィール情報を取得する関数。
    /// @return name 名前。
    /// @return favoriteFruit 好きな果物。
    /// @return age 年齢。
    function getProfile() external view returns(
        string memory, string memory, uint256
    ){
        return (name, favoriteFruit, age);
    }

}

Notice that a new variable, favoriteFruit, has been added.

This completes the contract implementations.

Creating the test

Now create the test file.

bash
$ touch test/test-transparent.js

Open test-transparent.js and paste in the following code.

javascript
const { expect } = require("chai");
const { ethers, upgrades } = require("hardhat");

describe("TransparentLogic", function () {
    beforeEach(async function () {
        // アドレスの作成
        [owner, wallet1, wallet2] = await ethers.getSigners();

        // TransparentLogicとTransparentLogicV2コントラクトを取得。
        transparentLogic = await ethers.getContractFactory("TransparentLogic", owner);
        transparentLogicV2 = await ethers.getContractFactory("TransparentLogicV2", owner);

        // TransparentLogicコントラクトをデプロイ。
        transparentLogicInstance = await upgrades.deployProxy(transparentLogic);
    });

    describe('test TransparentLogic', function () {
        it("Owner変数の値を確認", async function () {
            expect((await transparentLogicInstance.owner())).to.equal(owner.address);
        })

        it("setProfile関数を実行して、name: Cardene, age: 23を格納", async function () {
            await transparentLogicInstance.setProfile("Cardene", 23);
            expect((await transparentLogicInstance.name())).to.equal("Cardene");
            expect((await transparentLogicInstance.age())).to.equal(23);

        })

        it("transparentLogicV2コントラクトに更新", async function () {
            const transparentLogicV2Instance = await upgrades.upgradeProxy(
                transparentLogicInstance.address,
                transparentLogicV2
            );
        })

        it("setProfile関数を実行して、name: Cardene V2, favoriteFruit: Pear, age: 30を格納", async function () {
            await transparentLogicV2Instance.setProfile("Cardene V2", "Pear", 30);
            expect((await transparentLogicV2Instance.name())).to.equal("Cardene V2");
            expect((await transparentLogicV2Instance.age())).to.equal(30);
            expect((await transparentLogicV2Instance.favoriteFruit())).to.equal("Pear");
        })
    });
});

The test performs the following steps.

Steps

  • Deploy the TransparentLogic contract through a proxy.
  • Check the value of the TransparentLogic contract's owner variable through the proxy.
  • Call setProfile and check that the name and age variables have changed.
  • Upgrade the proxy to use TransparentLogicV2.
  • Call TransparentLogicV2's setProfile and check that name, favoriteFruit, and age have changed.

Deploying with deployProxy prepares the application for subsequent implementation upgrades.

Calling upgradeProxy performs the upgrade.

Running the test

Run the following command.

bash
$ npx hardhat compile
$ npx hardhat test

The output below is the successful test output reported in the original tutorial.

bash
Compiled 2 Solidity files successfully

  TransparentLogic
    test TransparentLogic
Owner Address: [object Promise]
      ✓ Owner変数の値を確認
Name: [object Promise]
Age: [object Promise]
      ✓ name: Cardene, age: 23の格納
Name V2: [object Promise]
Age V2: [object Promise]
Fruit V2: [object Promise]
      ✓ Upgrade Contract

·-------------------------------------|---------------------------|-------------|-----------------------------·
|        Solc version: 0.8.17         ·  Optimizer enabled: true  ·  Runs: 200  ·  Block limit: 30000000 gas  │
······································|···························|·············|······························
|  Methods                                                                                                    │
·······················|··············|·············|·············|·············|···············|··············
|  Contract            ·  Method      ·  Min        ·  Max        ·  Avg        ·  # calls      ·  usd (avg)  │
·······················|··············|·············|·············|·············|···············|··············
|  TransparentLogic    ·  setProfile  ·          -  ·          -  ·      74204  ·            1  ·          -  │
·······················|··············|·············|·············|·············|···············|··············
|  TransparentLogicV2  ·  setProfile  ·          -  ·          -  ·      97662  ·            1  ·          -  │
·······················|··············|·············|·············|·············|···············|··············
|  Deployments                        ·                                         ·  % of limit   ·             │
······································|·············|·············|·············|···············|··············
|  TransparentLogic                   ·          -  ·          -  ·     395099  ·        1.3 %  ·          -  │
······································|·············|·············|·············|···············|··············
|  TransparentLogicV2                 ·          -  ·          -  ·     459451  ·        1.5 %  ·          -  │
·-------------------------------------|-------------|-------------|-------------|---------------|-------------·

  3 passing (2s)

UUPS Proxy

Next, implement the UUPS Proxy pattern.

The implementation is based on the following tutorial.

Creating the contracts

Create contracts/UUPSLogic.sol and contracts/UUPSLogicV2.sol.

bash
$ touch contracts/UUPSLogic.sol
$ touch contracts/UUPSLogicV2.sol
UUPSLogic.sol

Open UUPSLogic.sol and paste in the following code.

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

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

contract UUPSLogic is Initializable, ERC20Upgradeable, UUPSUpgradeable, OwnableUpgradeable {
    string public myName;
    uint256 public myAge;

    /// @notice 一度だけ実行される関数。constructorの代わり。
    function initialize() public initializer {
        __ERC20_init("Cardene Token", "CARD");
        __Ownable_init();
        __UUPSUpgradeable_init();
        _mint(msg.sender, 1000 * 10 ** decimals());
    }

    /// @notice msg.senderがコントラクトのアプグレード許可されていない時に処理を元に戻す関数。
    /// @dev 基本的にonlyOwnerなどのアクセス修飾子をつける。
    function _authorizeUpgrade(address) internal override onlyOwner {}

    /// @notice プロフィール情報を更新する関数。
    /// @param _name 名前。
    /// @param _age 年齢。
    function setProfile(string memory _name, uint256 _age) external {
        myName = _name;
        myAge = _age;
    }

    /// @notice プロフィール情報を取得する関数。
    /// @return name 名前。
    /// @return age 年齢。
    function getProfile() external view returns(string memory, uint256){
        return (myName, myAge);
    }

}

The structure resembles TransparentLogic.sol but inherits additional contracts.

The initialize function also performs operations such as minting ERC20 tokens.

UUPSLogicV2.sol

Open UUPSLogicV2.sol, the upgraded implementation, and paste in the following code.

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

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

contract UUPSLogicV2 is Initializable, ERC20Upgradeable, UUPSUpgradeable, OwnableUpgradeable {
    string public myName;
    uint256 public myAge;
    string public favoriteFruit;

    /// @notice 一度だけ実行される関数。constructorの代わり。
    function initialize() public initializer {
        __ERC20_init("Cardene Token", "CARD");
        __Ownable_init();
        __UUPSUpgradeable_init();
    }

    /// @notice msg.senderがコントラクトのアプグレード許可されていない時に処理を元に戻す関数。
    /// @dev 基本的にonlyOwnerなどのアクセス修飾子をつける。
    function _authorizeUpgrade(address) internal override onlyOwner {}

    /// @notice プロフィール情報を更新する関数。
    /// @param _name 名前。
    /// @param _fruit 好きな果物。
    /// @param _age 年齢。
    function setProfile(
        string memory _name,
        string memory _fruit,
        uint256 _age
    ) external {
        myName = _name;
        favoriteFruit = _fruit;
        myAge = _age;
    }

    /// @notice プロフィール情報を取得する関数。
    /// @return name 名前。
    /// @return favoriteFruit 好きな果物。
    /// @return age 年齢。
    function getProfile() external view returns(
        string memory, string memory, uint256
    ){
        return (myName, favoriteFruit, myAge);
    }

}

The structure again resembles TransparentLogicV2.sol.

This completes the contract implementations.

Creating the test

Create the test file.

bash
$ touch test/test-uups.js

Open test-uups.js and paste in the following code.

javascript
const { expect } = require("chai");
const { ethers, upgrades } = require("hardhat");

describe("UUPSLogic", function () {
    beforeEach(async function () {
        // アドレスの作成
        [owner, wallet1, wallet2] = await ethers.getSigners();

        // UUPSLogicとUUPSLogicV2コントラクトを取得。
        UUPSLogic = await ethers.getContractFactory("UUPSLogic", owner);
        UUPSLogicV2 = await ethers.getContractFactory("UUPSLogicV2", owner);

        // UUPSLogicコントラクトをデプロイ。
        UUPSLogicInstance = await upgrades.deployProxy(
            UUPSLogic,
            { kind: 'uups' }
        );
    });

    describe('test UUPSLogic', function () {
        it("setProfile関数を実行して、name: Cardene, age: 23を格納", async function () {
            await UUPSLogicInstance.setProfile("Cardene", 23);
            expect((await UUPSLogicInstance.myName())).to.equal("Cardene");
            expect((await UUPSLogicInstance.myAge())).to.equal(23);

        })

        it("UUPSLogicV2コントラクトに更新", async function () {
            UUPSLogicV2Instance = await upgrades.upgradeProxy(
                UUPSLogicInstance.address,
                UUPSLogicV2
            );
        })

        it("setProfile関数を実行して、name: Cardene V2, favoriteFruit: Pear, age: 30を格納", async function () {
            await UUPSLogicV2Instance.setProfile("Cardene V2", "Pear", 30);
            expect((await UUPSLogicV2Instance.myName())).to.equal("Cardene V2");
            expect((await UUPSLogicV2Instance.myAge())).to.equal(30);
            expect((await UUPSLogicV2Instance.favoriteFruit())).to.equal("Pear");
        })
    });
});

The test follows the same procedure as test-transparent.js.

Using deployProxy prepares the contract for upgrades, and upgradeProxy performs an upgrade.

The main difference from the Transparent Proxy example is that the deployProxy call specifies { kind: 'uups' }.

This tells the deployment tooling to use the UUPS Proxy pattern.

Running the test

Run the following command.

bash
$ npx hardhat compile
$ npx hardhat test test/test-uups.js

The output below is the successful test output reported in the original tutorial.

bash
UUPSLogic
    test UUPSLogic
Warning: A proxy admin was previously deployed on this network

    This is not natively used with the current kind of proxy ('uups').
    Changes to the admin will have no effect on this new proxy.

      ✓ setProfile関数を実行して、name: Cardene, age: 23を格納
Warning: A proxy admin was previously deployed on this network

    This is not natively used with the current kind of proxy ('uups').
    Changes to the admin will have no effect on this new proxy.

      ✓ UUPSLogicV2コントラクトに更新
Warning: A proxy admin was previously deployed on this network

    This is not natively used with the current kind of proxy ('uups').
    Changes to the admin will have no effect on this new proxy.

      ✓ setProfile関数を実行して、name: Cardene V2, favoriteFruit: Pear, age: 30を格納

·-------------------------------------|---------------------------|-------------|-----------------------------·
|        Solc version: 0.8.17         ·  Optimizer enabled: true  ·  Runs: 200  ·  Block limit: 30000000 gas  │
······································|···························|·············|······························
|  Methods                                                                                                    │
·······················|··············|·············|·············|·············|···············|··············
|  Contract            ·  Method      ·  Min        ·  Max        ·  Avg        ·  # calls      ·  usd (avg)  │
·······················|··············|·············|·············|·············|···············|··············
|  TransparentLogic    ·  setProfile  ·          -  ·          -  ·      71934  ·            1  ·          -  │
·······················|··············|·············|·············|·············|···············|··············
|  TransparentLogicV2  ·  setProfile  ·          -  ·          -  ·      95317  ·            1  ·          -  │
·······················|··············|·············|·············|·············|···············|··············
|  UUPSLogic           ·  upgradeTo   ·          -  ·          -  ·      39160  ·            2  ·          -  │
·······················|··············|·············|·············|·············|···············|··············
|  Deployments                        ·                                         ·  % of limit   ·             │
······································|·············|·············|·············|···············|··············
|  UUPSLogic                          ·          -  ·          -  ·    1566159  ·        5.2 %  ·          -  │
······································|·············|·············|·············|···············|··············
|  UUPSLogicV2                        ·          -  ·          -  ·    1518171  ·        5.1 %  ·          -  │
·-------------------------------------|-------------|-------------|-------------|---------------|-------------·

  3 passing (2s)

Beacon Proxy

Finally, implement the Beacon Proxy pattern.

Creating the contracts

Create contracts/BeaconLogic.sol and contracts/BeaconLogicV2.sol.

bash
$ touch contracts/BeaconLogic.sol
$ touch contracts/BeaconLogicV2.sol
BeaconLogic.sol

Open BeaconLogic.sol and paste in the following code.

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

import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";

contract BeaconLogic is Initializable {
    address public owner;
    string public name;
    uint256 public age;

    /// @notice 一度だけ実行される関数。constructorの代わり。
    function initialize() public initializer {
        owner = msg.sender;
    }

    /// @notice プロフィール情報を更新する関数。
    /// @param _name 名前。
    /// @param _age 年齢。
    function setProfile(string memory _name, uint256 _age) external {
        name = _name;
        age = _age;
    }

    /// @notice プロフィール情報を取得する関数。
    /// @return name 名前。
    /// @return age 年齢。
    function getProfile() external view returns(string memory, uint256){
        return (name, age);
    }

}

Apart from the contract name, this implementation is the same as TransparentLogic.sol.

BeaconLogicV2.sol

Open BeaconLogicV2.sol, the upgraded implementation, and paste in the following code.

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

import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";

contract BeaconLogicV2 is Initializable {
    address public owner;
    string public name;
    uint256 public age;
    string public favoriteFruit;

    /// @notice 一度だけ実行される関数。constructorの代わり。
    function initialize() public initializer {
        owner = msg.sender;
    }

    /// @notice プロフィール情報を更新する関数。
    /// @param _name 名前。
    /// @param _fruit 好きな果物。
    /// @param _age 年齢。
    function setProfile(
        string memory _name,
        string memory _fruit,
        uint256 _age
    ) external {
        name = _name;
        favoriteFruit = _fruit;
        age = _age;
    }

    /// @notice プロフィール情報を取得する関数。
    /// @return name 名前。
    /// @return favoriteFruit 好きな果物。
    /// @return age 年齢。
    function getProfile() external view returns(
        string memory, string memory, uint256
    ){
        return (name, favoriteFruit, age);
    }

}

Its contents likewise resemble TransparentLogicV2.sol.

Creating the test

Create the test file.

bash
$ touch test/test-beacon.js

Open test-beacon.js and paste in the following code.

javascript
const { expect } = require("chai");
const { ethers, upgrades } = require("hardhat");

describe("TransparentLogic", function () {
    beforeEach(async function () {
        // アドレスの作成
        [owner, wallet1, wallet2] = await ethers.getSigners();

        // BeaconLogicとBeaconLogicV2コントラクトを取得。
        beaconLogic = await ethers.getContractFactory("BeaconLogic", owner);
        beaconLogicV2 = await ethers.getContractFactory("BeaconLogicV2", owner);

        // BeaconLogicコントラクトをデプロイ。
        beaconInstance = await upgrades.deployBeacon(beaconLogic);
        beaconLogicInstance = await upgrades.deployBeaconProxy(
            beaconInstance,
            beaconLogic
        );
    });

    describe('test BeaconLogic', function () {
        it("Owner変数の値を確認", async function () {
            expect((await beaconLogicInstance.owner())).to.equal(owner.address);
        })

        it("setProfile関数を実行して、name: Cardene, age: 23を格納", async function () {
            await beaconLogicInstance.setProfile("Cardene", 23);
            expect((await beaconLogicInstance.name())).to.equal("Cardene");
            expect((await beaconLogicInstance.age())).to.equal(23);

        })

        it("transparentLogicV2コントラクトに更新", async function () {
            await upgrades.upgradeBeacon(
                beaconInstance.address,
                beaconLogicV2
            );
            beaconLogicV2Instance = beaconLogicV2.attach(beaconLogicInstance.address)
        })

        it("setProfile関数を実行して、name: Cardene V2, favoriteFruit: Pear, age: 30を格納", async function () {
            await beaconLogicV2Instance.setProfile("Cardene V2", "Pear", 30);
            expect((await beaconLogicV2Instance.name())).to.equal("Cardene V2");
            expect((await beaconLogicV2Instance.age())).to.equal(30);
            expect((await beaconLogicV2Instance.favoriteFruit())).to.equal("Pear");
        })
    });
});

The test is largely the same as test-transparent.js.

The difference is that deployBeacon is used to deploy an upgradeable beacon.

Then deployBeaconProxy is used to deploy one or more proxies referencing the beacon.

The upgrade is performed through upgradeBeacon, which updates the beacon to reference the new implementation. The proxy address can then be used with the upgraded implementation's ABI.

Once the beacon is upgraded, every BeaconProxy pointing to that beacon uses the new implementation.

Running the test

Run the following command.

bash
$ npx hardhat compile
$ npx hardhat test test/test-beacon.js

The output below is the successful test output reported in the original tutorial.

bash
TransparentLogic
    test BeaconLogic
Warning: A proxy admin was previously deployed on this network

    This is not natively used with the current kind of proxy ('beacon').
    Changes to the admin will have no effect on this new proxy.

      ✓ Owner変数の値を確認
Warning: A proxy admin was previously deployed on this network

    This is not natively used with the current kind of proxy ('beacon').
    Changes to the admin will have no effect on this new proxy.

      ✓ setProfile関数を実行して、name: Cardene, age: 23を格納
Warning: A proxy admin was previously deployed on this network

    This is not natively used with the current kind of proxy ('beacon').
    Changes to the admin will have no effect on this new proxy.

      ✓ transparentLogicV2コントラクトに更新
Warning: A proxy admin was previously deployed on this network

    This is not natively used with the current kind of proxy ('beacon').
    Changes to the admin will have no effect on this new proxy.

      ✓ setProfile関数を実行して、name: Cardene V2, favoriteFruit: Pear, age: 30を格納

·--------------------------------|---------------------------|-------------|-----------------------------·
|      Solc version: 0.8.17      ·  Optimizer enabled: true  ·  Runs: 200  ·  Block limit: 30000000 gas  │
·································|···························|·············|······························
|  Methods                                                                                               │
··················|··············|·············|·············|·············|···············|··············
|  Contract       ·  Method      ·  Min        ·  Max        ·  Avg        ·  # calls      ·  usd (avg)  │
··················|··············|·············|·············|·············|···············|··············
|  BeaconLogic    ·  setProfile  ·          -  ·          -  ·      77106  ·            1  ·          -  │
··················|··············|·············|·············|·············|···············|··············
|  BeaconLogicV2  ·  setProfile  ·          -  ·          -  ·     100564  ·            1  ·          -  │
··················|··············|·············|·············|·············|···············|··············
|  UUPSLogic      ·  upgradeTo   ·          -  ·          -  ·      32699  ·            1  ·          -  │
··················|··············|·············|·············|·············|···············|··············
|  Deployments                   ·                                         ·  % of limit   ·             │
·································|·············|·············|·············|···············|··············
|  BeaconLogic                   ·          -  ·          -  ·     395099  ·        1.3 %  ·          -  │
·································|·············|·············|·············|···············|··············
|  BeaconLogicV2                 ·          -  ·          -  ·     459451  ·        1.5 %  ·          -  │
·--------------------------------|-------------|-------------|-------------|---------------|-------------·

  4 passing (3s)

Conclusion

Summary of upgradeable contracts

This article introduced upgradeable smart contracts.

Key takeaways

  • Understand what upgradeable contracts are.
  • Understand how contract upgrade mechanisms work.
  • Learn how to implement upgradeable contracts.

There are other approaches and possibilities beyond the examples implemented here. Explore additional techniques and their security trade-offs before choosing an upgrade mechanism.

If you have questions, feel free to reach out on Twitter.

References

https://santexgroup.com/blog/is-it-possible-to-upgrade-a-smart-contract-once-deployed/

https://docs.openzeppelin.com/upgrades-plugins/1.x/writing-upgradeable