Contrats évolutifs
Modèles de proxy
Contrats évolutifs est une leçon Web3 & DApp Development Fundamentals gratuite sur CoddyKit. Ceci est la leçon 4 sur 4. Tu peux lire la leçon complète ci-dessous gratuitement — puis la pratiquer en direct dans le navigateur avec un éditeur de code intégré et un tuteur IA 24/7. Elle fait partie du parcours d'apprentissage Web3 & DApp Development Fundamentals, et ta progression se synchronise sur le web et l'application CoddyKit. Le cours Web3 & DApp Development Fundamentals comprend 4 leçons au total.
Certaines parties de cette leçon n'ont pas encore été traduites et s'affichent en anglais.
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-upgradeablePair it with the Hardhat Upgrades plugin to deploy and manage proxies safely.
npm install @openzeppelin/contracts-upgradeable @openzeppelin/hardhat-upgradesDeploying 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 byinitializer) 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.
Questions Fréquemment Posées
La leçon « Contrats évolutifs » est-elle gratuite ?
Oui — le texte complet de « Contrats évolutifs » est gratuit à lire ici sur le web. Pour la pratiquer de manière interactive (un éditeur de code intégré et un tuteur IA 24/7) et déverrouiller le reste du cours Web3 & DApp Development Fundamentals, passe à CoddyKit PRO. Le cours Web3 & DApp Development Fundamentals comprend 4 leçons au total.
Qu'est-ce que j'apprendrai dans « Contrats évolutifs » ?
Modèles de proxy Tu pratiques Web3 & DApp Development Fundamentals avec du code pratique que tu exécutes directement dans le navigateur, et un tuteur IA 24/7 répond à tes questions au fur et à mesure que tu avances dans la leçon.
Dois-je avoir de l'expérience pour commencer Web3 & DApp Development Fundamentals ?
Aucune expérience préalable n'est requise. Web3 & DApp Development Fundamentals sur CoddyKit est structuré pour les débutants jusqu'aux apprenants avancés, donc tu peux commencer ici ou depuis le début et avancer à ton rythme. Ceci est la leçon 4 sur 4.
Combien de temps prend la leçon « Contrats évolutifs » ?
La plupart des leçons CoddyKit prennent environ 5–10 minutes. Chacune est courte et interactive, tu progresses régulièrement et tu repiques exactement où tu t'es arrêté sur le web et l'app.
Peux-tu écrire et exécuter du code dans cette leçon Web3 & DApp Development Fundamentals ?
Oui. Chaque leçon Web3 & DApp Development Fundamentals inclut un éditeur de code intégré, tu écris et exécutes du vrai code directement dans ton navigateur et tu reçois des retours IA instantanés — aucune configuration locale requise.
Toutes les leçons de ce cours
- Pourquoi OpenZeppelin
- Contrôle des accès
- Extensions de jetons
- Contrats évolutifs