0Pricing
Web3 & DApp Development Fundamentals · Lección

Contratos actualizables

Patrones de proxy

Contratos actualizables es una lección gratuita de Web3 & DApp Development Fundamentals en CoddyKit. Esta es la lección 4 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 Web3 & DApp Development Fundamentals, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Web3 & DApp Development Fundamentals incluye 4 lecciones en total.

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

The Immutability Problem

Deployed contract code cannot be changed. If you find a bug or need a new feature, the code is frozen at its address.

Upgradeable contracts work around this using a proxy pattern that lets you swap the logic while keeping the same address and data.

The Proxy Pattern

Upgradeability splits a contract into two parts:

  • Proxy — holds the state and a pointer to the logic; users interact with it.
  • Implementation — holds the code, no permanent state.

The proxy delegatecalls into the implementation, so logic runs against the proxy's storage.

How delegatecall Works

delegatecall executes another contract's code in the caller's storage context. So when the proxy delegatecalls the implementation:

  • Code comes from the implementation.
  • Storage read/written is the proxy's.

Upgrading just changes which implementation the proxy points to.

Initializers, Not Constructors

Constructors run at deploy time and do not affect proxy storage. Upgradeable contracts use an initialize function instead:

import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; contract Box is Initializable { uint256 public value; function initialize(uint256 v) public initializer { value = v; } }
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";

contract Box is Initializable {
    uint256 public value;
    function initialize(uint256 v) public initializer {
        value = v;
    }
}

The Upgradeable Library

OpenZeppelin ships a separate package for this. Its modules use initializers instead of constructors:

npm install @openzeppelin/contracts-upgradeable

Pair it with the Hardhat Upgrades plugin to deploy and manage proxies safely.

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

Deploying a Proxy

The Hardhat Upgrades plugin deploys the implementation and proxy together, calling your initializer:

const { ethers, upgrades } = require("hardhat"); const Box = await ethers.getContractFactory("Box"); const box = await upgrades.deployProxy(Box, [42]); await box.waitForDeployment();

The array holds the initializer arguments.

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

const Box = await ethers.getContractFactory("Box");
const box = await upgrades.deployProxy(Box, [42]);
await box.waitForDeployment();

Performing an Upgrade

To upgrade, deploy a new implementation and point the existing proxy at it:

const BoxV2 = await ethers.getContractFactory("BoxV2"); const upgraded = await upgrades.upgradeProxy( await box.getAddress(), BoxV2 );

The address and stored state are preserved; only the logic changes.

const BoxV2 = await ethers.getContractFactory("BoxV2");
const upgraded = await upgrades.upgradeProxy(
  await box.getAddress(),
  BoxV2
);

Storage Layout Rules

Because the proxy keeps its storage, new versions must preserve the storage layout:

  • Never reorder or remove existing state variables.
  • Only append new variables at the end.
  • Reserve gaps in base contracts for future fields.

The plugin checks for unsafe changes and warns you.

Transparent vs UUPS

Two common proxy styles:

  • Transparent — upgrade logic lives in the proxy; simple but slightly more gas.
  • UUPS — upgrade logic lives in the implementation (via UUPSUpgradeable); cheaper, but you must not forget to include it.

UUPS is now the generally recommended default.

Upgradeability Trade-offs

Upgradeability is powerful but adds risk:

  • Whoever controls upgrades can change the rules — a centralization concern.
  • Storage and initializer mistakes can brick the contract.

Guard the upgrade authority with a multisig or timelock, and test upgrades thoroughly.

Disabling Initializers in the Implementation

An implementation contract should never be initialized directly. Lock it in its constructor:

constructor() { _disableInitializers(); }

This prevents an attacker from taking over the standalone implementation while leaving the proxy's initializer usable.

constructor() {
    _disableInitializers();
}

Quick Check

Test your understanding of upgradeable contracts.

Recap

You learned how upgradeable contracts work.

  • A proxy holds state and delegatecalls a swappable implementation.
  • Use initialize (guarded by initializer) instead of a constructor.
  • The Hardhat Upgrades plugin deploys and upgrades proxies safely.
  • Preserve storage layout: only append variables; use gaps.
  • Choose Transparent or UUPS, and protect upgrade authority with a multisig or timelock.

Preguntas frecuentes

¿La lección «Contratos actualizables» es gratis?

Sí — el texto completo de «Contratos actualizables» 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 Web3 & DApp Development Fundamentals, actualiza a CoddyKit PRO. El curso de Web3 & DApp Development Fundamentals incluye 4 lecciones en total.

¿Qué aprenderé en «Contratos actualizables»?

Patrones de proxy Practicas Web3 & DApp Development Fundamentals 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 Web3 & DApp Development Fundamentals?

No se requiere experiencia previa. Web3 & DApp Development Fundamentals 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 4 de 4.

¿Cuánto tiempo toma la lección «Contratos actualizables»?

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 Web3 & DApp Development Fundamentals?

Sí. Cada lección de Web3 & DApp Development Fundamentals 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é OpenZeppelin
  2. Control de acceso
  3. Extensiones de tokens
  4. Contratos actualizables
← Volver a Web3 & DApp Development Fundamentals