Mise en œuvre du modèle de proxy UUPS
Apprenez à mettre en œuvre le Universal Upgradeable Proxy Standard (UUPS) avec OpenZeppelin pour effectuer des mises à niveau sécurisées des contrats.
Mise en œuvre du modèle de proxy UUPS est une leçon Blockchain Smart Contracts with Solidity gratuite sur CoddyKit. Ceci est la leçon 2 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 Blockchain Smart Contracts with Solidity, et ta progression se synchronise sur le web et l'application CoddyKit. Le cours Blockchain Smart Contracts with Solidity comprend 4 leçons au total.
Certaines parties de cette leçon n'ont pas encore été traduites et s'affichent en anglais.
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
initializefunction 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
UUPSUpgradeableas a base contract. initializefunctions replace constructors for setup.- OpenZeppelin's upgrade plugins simplify deployment and upgrades.
UUPS is a powerful pattern for building future-proof smart contracts!
Questions Fréquemment Posées
La leçon « Mise en œuvre du modèle de proxy UUPS » est-elle gratuite ?
Oui — le texte complet de « Mise en œuvre du modèle de proxy UUPS » 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 Blockchain Smart Contracts with Solidity, passe à CoddyKit PRO. Le cours Blockchain Smart Contracts with Solidity comprend 4 leçons au total.
Qu'est-ce que j'apprendrai dans « Mise en œuvre du modèle de proxy UUPS » ?
Apprenez à mettre en œuvre le Universal Upgradeable Proxy Standard (UUPS) avec OpenZeppelin pour effectuer des mises à niveau sécurisées des contrats. Tu pratiques Blockchain Smart Contracts with Solidity 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 Blockchain Smart Contracts with Solidity ?
Aucune expérience préalable n'est requise. Blockchain Smart Contracts with Solidity 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 2 sur 4.
Combien de temps prend la leçon « Mise en œuvre du modèle de proxy UUPS » ?
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 Blockchain Smart Contracts with Solidity ?
Oui. Chaque leçon Blockchain Smart Contracts with Solidity 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 des contrats évolutifs ?
- Mise en œuvre du modèle de proxy UUPS
- Standard Diamond (proxies multifacettes)
- Modèle de proxy transparent et organisation du stockage