0Pricing
Web3 & DApp Development Fundamentals · Aula

Contratos atualizáveis

Padrões de proxy

Contratos atualizáveis é uma aula grátis de Web3 & DApp Development Fundamentals no CoddyKit. Esta é a aula 4 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de Web3 & DApp Development Fundamentals, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Web3 & DApp Development Fundamentals inclui 4 aulas no total.

Partes desta aula ainda não foram traduzidas e aparecem em 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.

Perguntas Frequentes

A aula “Contratos atualizáveis” é grátis?

Sim — o texto completo de “Contratos atualizáveis” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de Web3 & DApp Development Fundamentals, atualize para CoddyKit PRO. O curso de Web3 & DApp Development Fundamentals inclui 4 aulas no total.

O que vou aprender em “Contratos atualizáveis”?

Padrões de proxy Você pratica Web3 & DApp Development Fundamentals com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.

Preciso ter experiência prévia para começar Web3 & DApp Development Fundamentals?

Nenhuma experiência prévia é necessária. Web3 & DApp Development Fundamentals no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 4 de 4.

Quanto tempo leva a aula “Contratos atualizáveis”?

A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.

Posso escrever e executar código nesta aula de Web3 & DApp Development Fundamentals?

Sim. Cada aula de Web3 & DApp Development Fundamentals inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.

Todas as aulas deste curso

  1. Por que usar OpenZeppelin
  2. Controle de acesso
  3. Extensões de tokens
  4. Contratos atualizáveis
← Voltar para Web3 & DApp Development Fundamentals