0Pricing
Blockchain Smart Contracts with Solidity · Lección

Implementación del patrón de proxy UUPS

Aprenda a implementar el Universal Upgradeable Proxy Standard (UUPS) con OpenZeppelin para actualizar contratos de forma segura.

Implementación del patrón de proxy UUPS es una lección gratuita de Blockchain Smart Contracts with Solidity en CoddyKit. Esta es la lección 2 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de Blockchain Smart Contracts with Solidity, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Blockchain Smart Contracts with Solidity incluye 4 lecciones en total.

Partes de esta lección aún no han sido traducidas y se muestran en inglés.

Understanding UUPS

The Universal Upgradeable Proxy Standard (UUPS) is a popular design pattern for creating upgradeable smart contracts. It allows you to change a contract's logic without changing its address on the blockchain.

This is crucial for fixing bugs, adding new features, or adapting to changing requirements without losing user data or contract state.

How UUPS Works

UUPS uses a proxy contract that holds the contract's state (data) and a separate implementation contract that holds the contract's logic (functions).

  • Proxy Contract: A simple, unchanging contract that forwards calls to the current implementation.
  • Implementation Contract: Contains the actual business logic. This is the contract that gets upgraded.

The key difference in UUPS is that the upgrade logic resides within the implementation contract, not the proxy.

Trusting OpenZeppelin

Implementing upgradeable contracts correctly is complex and prone to errors. That's why we rely on battle-tested libraries like OpenZeppelin Contracts.

OpenZeppelin provides secure and audited implementations of proxy patterns, including UUPS, making it much safer and easier to build upgradeable contracts.

Building UUPS Contracts

To make your contract UUPS-compatible, it needs to inherit from OpenZeppelin's UUPSUpgradeable contract. This base contract provides the necessary functions and modifiers for upgradeability.

Remember, upgradeable contracts use an initializer function instead of a constructor, as the proxy never calls the implementation's constructor directly.

Our First Upgradeable Contract

Here's a basic contract, MyContractV1, ready for UUPS upgrades. Notice it inherits from OpenZeppelin's UUPSUpgradeable. You'll typically install OpenZeppelin contracts via npm and import them.

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

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

contract MyContractV1 is UUPSUpgradeable {
    // This contract will contain our initial logic
    // We'll add an initializer in the next scene
}

Initializing UUPS Contracts

In upgradeable contracts, you cannot use a regular constructor. The proxy contract is deployed once, and its constructor is called. The implementation contract's constructor is never called when the proxy is deployed or upgraded.

Instead, you use an initializer function. This function is called once, typically right after the proxy is deployed, to set up the initial state of your logic contract.

Initializing State

Let's add an initializer to our MyContractV1. We use __UUPSUpgradeable_init() and __Ownable_init() to properly initialize base contracts, and Reinitializer(1) to prevent multiple initializations.

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

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

contract MyContractV1 is Initializable, UUPSUpgradeable, OwnableUpgradeable {
    string public message;

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

    function initialize(string memory initialMessage) public initializer {
        __UUPSUpgradeable_init();
        __Ownable_init(); // Initialize Ownable for access control
        message = initialMessage;
    }

    function setMessage(string memory newMessage) public onlyOwner {
        message = newMessage;
    }

    // Required for UUPS, defines who can upgrade
    function _authorizeUpgrade(address newImplementation) internal override onlyOwner {}
}

Deploying Your UUPS Contract

Deploying UUPS contracts involves using an upgrades plugin (e.g., for Hardhat or Truffle). This plugin handles creating the proxy and linking it to your initial implementation contract.

  • It deploys your implementation contract.
  • It deploys the proxy contract, pointing to your implementation.
  • It calls the initialize function on the proxy.

This process ensures your contract is correctly set up for future upgrades.

Performing an Upgrade

When you want to upgrade your contract, you deploy a new version of your implementation contract (e.g., MyContractV2). Then, you call an upgrade function on the existing proxy contract, telling it to point to the new implementation.

The _authorizeUpgrade function in your implementation contract controls who has permission to perform this upgrade, often restricted to the contract owner.

Upgrading Your Logic

Let's imagine we want to add a new feature to MyContractV1. We create MyContractV2, inheriting from MyContractV1 to carry over its state and existing logic. We then add our new function.

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

import "./MyContractV1.sol"; // Assuming MyContractV1 is in the same directory

contract MyContractV2 is MyContractV1 {
    uint public counter; // New state variable

    // We don't need a new initializer unless we have new base contracts
    // to initialize, or specific V2 setup.

    function incrementCounter() public onlyOwner {
        counter++;
    }

    // Existing functions like setMessage and message getter are still available
    // via the proxy, using the logic from MyContractV2.
}

UUPS Key Concepts

Which of the following statements are TRUE regarding the Universal Upgradeable Proxy Standard (UUPS) implemented with OpenZeppelin?

UUPS: Secure Upgrades

In this lesson, you learned about the Universal Upgradeable Proxy Standard (UUPS) and how to implement it using OpenZeppelin Contracts.

  • UUPS separates state (proxy) from logic (implementation).
  • You use UUPSUpgradeable as a base contract.
  • initialize functions replace constructors for setup.
  • OpenZeppelin's upgrade plugins simplify deployment and upgrades.

UUPS is a powerful pattern for building future-proof smart contracts!

Preguntas frecuentes

¿La lección «Implementación del patrón de proxy UUPS» es gratis?

Sí — el texto completo de «Implementación del patrón de proxy UUPS» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de Blockchain Smart Contracts with Solidity, actualiza a CoddyKit PRO. El curso de Blockchain Smart Contracts with Solidity incluye 4 lecciones en total.

¿Qué aprenderé en «Implementación del patrón de proxy UUPS»?

Aprenda a implementar el Universal Upgradeable Proxy Standard (UUPS) con OpenZeppelin para actualizar contratos de forma segura. Practicas Blockchain Smart Contracts with Solidity con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.

¿Necesito experiencia previa para empezar Blockchain Smart Contracts with Solidity?

No se requiere experiencia previa. Blockchain Smart Contracts with Solidity en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 2 de 4.

¿Cuánto tiempo toma la lección «Implementación del patrón de proxy UUPS»?

La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.

¿Puedo escribir y ejecutar código en esta lección de Blockchain Smart Contracts with Solidity?

Sí. Cada lección de Blockchain Smart Contracts with Solidity incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.

Todas las lecciones de este curso

  1. ¿Por qué utilizar contratos actualizables?
  2. Implementación del patrón de proxy UUPS
  3. Estándar Diamond (proxies multifaceta)
  4. Patrón Transparent Proxy y layout de almacenamiento
← Volver a Blockchain Smart Contracts with Solidity