GitHub stars
223

Install

/plugin install openzeppelin-skills@openzeppelin-skills

Run it inside Claude Code after adding the marketplace with /plugin marketplace add OpenZeppelin/openzeppelin-skills.

Contents

Discovered from source

Skills 12

Develop Secure Smart Contracts with OpenZeppelin

Core Workflow

Understand the Request Before Responding

For conceptual questions ("How does Ownable work?"), explain without generating code. For implementation requests, proceed with the workflow below.

CRITICAL: Always Read the Project First

Before generating code or suggesting changes:

  1. Search the user's project for existing contracts (Glob for **/*.sol, **/*.cairo, **/*.rs, **/*.move, etc.)
  2. Read the relevant contract files to understand what already exists
  3. Default to integration, not replacement — when users say "add pausability" or "make it upgradeable", they mean modify their existing code, not generate something new. Only replace if explicitly requested ("start fresh", "replace this").

If a file cannot be read, surface the failure explicitly — report the path attempted and the reason. Ask whether the path is correct. Never silently fall back to a generic response as if the file does not exist.

Fundamental Rule: Prefer Library Components Over Custom Code

Before writing ANY logic, search the OpenZeppelin library for an existing component:

  1. Exact match exists? Import and use it directly — inherit, implement its trait, compose with it. Done.
  2. Close match exists? Import and extend it — override only functions the library marks as overridable (virtual, hooks, configurable parameters).
  3. No match exists? Only then write custom logic. Confirm by browsing the library's directory structure first.

NEVER copy or embed library source code into the user's contract. Always import from the dependency so the project receives security updates. Never hand-write what the library already provides:

  • Never write a custom paused modifier when Pausable or ERC20Pausable exists
  • Never write require(msg.sender == owner) when Ownable exists
  • Never implement ERC165 logic when the library's base contracts already handle it

Methodology

The primary workflow is pattern discovery from library source code:

  1. Inspect what the user's project already imports
  2. Read the dependency source and docs in the project's installed packages
  3. Identify what functions, modifiers, hooks, and storage the dependency requires
  4. Apply those requirements to the user's contract

See Pattern Discovery and Integration below for the full step-by-step procedure.

CLI Generators as Reference

Use npx @openzeppelin/contracts-cli to generate reference implementations for pattern discovery: generate a baseline to a file, generate with a feature enabled to another file, diff them, and apply the changes to the user's code. The CLI output is the canonical correct integration — use it as the source of truth for what imports, inheritance, storage, and overrides a feature requires.

See CLI Generators for details on the generate-compare-apply workflow.

If no CLI command exists for what's needed, use the generic pattern discovery methodology from Pattern Discovery and Integration. The absence of a CLI command does not mean the library lacks support — it only means there is no generator.

Pattern Discovery and Integration

Procedural guide for discovering and applying OpenZeppelin contract integration patterns by reading dependency source code. Works for any ecosystem and any library version.

Prerequisite: Always follow the library-first decision tree above (prefer library components over custom code, never copy/embed source).

Step 1: Identify Dependencies and Search the Library

  1. Search the project for contract files: Glob for **/*.sol, **/*.cairo, **/*.rs, **/*.move, or the relevant extension from the lookup table below.
  2. Read import/use statements in existing contracts to identify which OpenZeppelin components are already in use.
  3. Locate the installed dependency in the project's dependency tree:
    • Solidity: node_modules/@openzeppelin/contracts/ (Hardhat/npm) or lib/openzeppelin-contracts/ (Foundry/forge)
    • Cairo: resolve from Scarb.toml dependencies — source cached by Scarb
    • Stylus: resolve from Cargo.toml — source in target/ or the cargo registry cache (~/.cargo/registry/src/)
    • Stellar: resolve from Cargo.toml — same cargo cache locations as Stylus
    • Sui Move: resolve from Move.toml — after a build, the MVR source is cached under ~/.move/ and mirrored per-dependency in build/<project_package>/sources/dependencies/<move_package_name>/
  4. Browse the dependency's directory listing to discover available components. Use Glob patterns against the installed source (e.g., node_modules/@openzeppelin/contracts/**/*.sol). Do not assume knowledge of the library's contents — always verify by listing directories.
  5. If the dependency is not installed locally, clone or browse the canonical repository (see lookup table below).

Step 2: Read the Dependency Source and Documentation

  1. Read the source file of the component relevant to the user's request.
  2. Look for documentation within the source: NatSpec comments (///, /** */) in Solidity, doc comments (///) in Rust and Cairo, and README files in the component's directory.
  3. Determine the integration strategy using the decision tree from the Critical Principle:
    • If the component satisfies the need directly → import and use as-is.
    • If customization is needed → identify extension points the library provides (virtual functions, hook functions, configurable constructor parameters). Import and extend.
    • Only if no component covers the need → write custom logic.
  4. Identify the public API: functions/methods exposed, events emitted, errors defined.
  5. Identify integration requirements — this is the critical step:
    • Functions the integrator MUST implement (abstract functions, trait methods, hooks)
    • Modifiers, decorators, or guards that must be applied to the integrator's functions
    • Constructor or initializer parameters that must be passed
    • Storage variables or state that must be declared
    • Inheritance or trait implementations required (always via import, never via copy)
  6. Search for example contracts or tests in the same repository that demonstrate correct usage. Look in test/, tests/, examples/, or mocks/ directories.

Step 3: Extract the Minimal Integration Pattern

From Step 2, construct the minimal set of changes needed:

  • Imports / use statements to add
  • Inheritance / trait implementations to add (always via import from the dependency)
  • Storage to declare
  • Constructor / initializer changes (new parameters, initialization calls)
  • New functions to add (required overrides, hooks, public API)
  • Existing functions to modify (add modifiers, call hooks, emit events)

If the contract is upgradeable, any of the above may affect storage compatibility. Consult the relevant upgrade skill before applying.

Do not include anything beyond what the dependency requires. This is the minimal diff between "contract without the feature" and "contract with the feature."

Step 4: Apply Patterns to the User's Contract

  1. Read the user's existing contract file.
  2. Apply the changes from Step 3 using the Edit tool. Do not replace the entire file — integrate into existing code.
  3. Check for conflicts: duplicate access control systems, conflicting function overrides, incompatible inheritance. Resolve before finishing.
  4. Do not ask the user to make changes themselves — apply directly.

Repository and Documentation Lookup Table

EcosystemRepositoryDocumentationFile ExtensionDependency Location
Solidityopenzeppelin-contractsdocs.openzeppelin.com/contracts.solnode_modules/@openzeppelin/contracts/ or lib/openzeppelin-contracts/
Cairocairo-contractsdocs.openzeppelin.com/contracts-cairo.cairoScarb cache (resolve from Scarb.toml)
Stylusrust-contracts-stylusdocs.openzeppelin.com/contracts-stylus.rsCargo cache (~/.cargo/registry/src/)
Stellarstellar-contracts (Architecture)docs.openzeppelin.com/stellar-contracts.rsCargo cache (~/.cargo/registry/src/)
Sui Movecontracts-sui (llms.txt · ARCHITECTURE)docs.openzeppelin.com/contracts-sui.moveMove Registry cache (~/.move/, resolve from Move.toml)

Directory Structure Conventions

Where to find components within each repository:

CategorySolidityCairoStylusStellar
Tokenscontracts/token/{ERC20,ERC721,ERC1155}/packages/token/contracts/src/token/packages/tokens/
Access controlcontracts/access/packages/access/contracts/src/access/packages/access/
Governancecontracts/governance/packages/governance/—packages/governance/
Proxies / Upgradescontracts/proxy/packages/upgrades/contracts/src/proxy/packages/contract-utils/
Utilities / Securitycontracts/utils/packages/utils/, packages/security/contracts/src/utils/packages/contract-utils/
Accountscontracts/account/packages/account/—packages/accounts/

Browse these paths first when searching for a component.

Sui Move isn't in this fixed grid and has no @openzeppelin/contracts-cli generator, so always use the pattern-discovery methodology above — adapt a package's examples/ as the canonical integration recipe and import via MVR rather than copying source. Discover everything else (the package set, composition and style conventions, exact APIs, and the toolchain) from the library's own metadata, starting at llms.txt; the setup-sui-contracts skill covers the full setup, dependency, --build-env build, and quality-gate flow.

Known Version-Specific Considerations

Do not assume override points from prior knowledge — always verify by reading the installed source. Functions that were virtual in an older version may no longer be in the current one, making them non-overridable. The source NatSpec will indicate the correct override point (e.g., NOTE: This function is not virtual, {X} should be overridden instead).

A known example: the Solidity ERC-20 transfer hook changed between v4 and v5. Read the installed ERC20.sol to confirm which function is virtual before recommending an override.

CLI Generators

The @openzeppelin/contracts-cli package generates reference OpenZeppelin contract implementations from the command line. Use it as the reference source in the generate-compare-apply workflow whenever a command exists for the contract type.

Discovering Commands and Options

Run npx @openzeppelin/contracts-cli --help to list available commands. Each command corresponds to a contract type (e.g., solidity-erc20, cairo-erc721, stellar-fungible). Run npx @openzeppelin/contracts-cli <command> --help to see the available options. Do not rely on prior knowledge of what options exist; check --help at the start of a conversation since the CLI may have been updated.

Generate-Compare-Apply Shortcut

When a CLI command exists for the contract type, pipe generated output to temporary files and diff them to keep generated contract code out of the conversation context:

  1. Generate baseline — run with only required options, all features disabled, pipe to a file:
    npx @openzeppelin/contracts-cli solidity-erc20 --name MyToken --symbol MTK > /tmp/oz-baseline.sol
    
  2. Generate with feature — run again with the feature enabled, pipe to a second file:
    npx @openzeppelin/contracts-cli solidity-erc20 --name MyToken --symbol MTK --pausable > /tmp/oz-variant.sol
    
  3. Compare — diff the two files to identify exactly what changed (imports, inheritance, state, constructor, functions, modifiers):
    diff /tmp/oz-baseline.sol /tmp/oz-variant.sol
    
  4. Apply — edit the user's existing contract to add the discovered changes

For interacting features (e.g., access control + upgradeability), generate a combined variant as well.

When No CLI Command Exists or a Feature Is Not Covered

The absence of a CLI command does NOT mean the library lacks support. It only means there is no generator for that contract type. Always fall back to the generic pattern discovery methodology in Pattern Discovery and Integration.

Similarly, when a CLI command exists but does not expose an option for a specific feature, do not stop there. Fall back to pattern discovery for that feature: read the installed library source to find the relevant component, extract the integration requirements, and apply them to the user's contract.

Migrate Defender Workflows to CRE

Adapt the user's workflow, preserving its intended behavior. CRE is one migration path; do not redirect a user who chose another destination. This skill covers EVM and offchain workflows using TypeScript, not every Defender capability or CRE network.

1. Read the project and establish the boundary

Inspect the Action, Monitor configuration, contract permissions when relevant, manifests, lockfiles and existing CRE configuration. Ask only for missing information that changes the design:

  • What starts execution, and which filters, timing requirements or persistent conditions apply?
  • What effect is required, who may perform it, and how are duplicates or missed executions handled?
  • Which network or external service is involved?

Check installed CLI/SDK APIs, current supported networks where applicable, and service quotas. Derive paths, package manager, scripts, config fields and target names from this project. Example layouts are not defaults.

2. Map behavior before changing code

Defender behaviorCRE starting pointPreserve or explicitly resolve
Scheduled Action / AutotaskCron trigger and handlerCadence, timezone and condition for doing work
Event Monitor and responseEVM log trigger and handler predicateEmitting address, event signature, filter semantics and confirmation requirements
Webhook-triggered ActionHTTP triggerRequest authentication and authorized callers
Notification or API actionHTTP capabilityPayload, credentials, duplicate handling and errors
Relayer-backed contract callSigned report → Forwarder → ReceiverNew caller identity and target authorization

Deployed HTTP triggers require requests signed by an authorized EVM key. Unsigned webhook sources need signing support or an authorized intermediary; an unsigned local simulation does not establish deployed compatibility.

Function-call/status monitoring, high-frequency schedules, counters and cooldowns need explicit assessment. Explain unsupported behavior without treating it as fundamentally impossible. Do not implement a changed cadence or weaker condition while awaiting approval. An HTTP trigger is not a proven workaround for service limits. Preserve expression semantics, including math.js operators and numeric precision; persistent counters need durable state and concurrency handling.

3. Consult references for the behavior being migrated

  • Event triggers or outbound notifications/API calls: Events and notifications. Read the relevant sections; receipt replay is only for event-triggered workflows.
  • Onchain writes or Relayer replacement: Onchain actions, before generating a Receiver or changing permissions.
  • Implementation or validation: Runtime and validation, for config resolution, runtime compatibility and evidence boundaries.
  • A matching error or version-specific question: Troubleshooting. Historical findings are diagnostic clues, not universal requirements.

The OpenZeppelin migration examples are optional worked examples. Use a versioned example when it matches the task; do not require its Governor, payload or folder structure.

4. Implement and validate within scope

Make a minimal diff. Import existing library components and inspect their installed APIs. Discover optional generator tools only when needed; do not assume a CRE Receiver generator exists. A notification-only workflow needs no Receiver, and monitoring an existing contract needs no replacement contract.

Local preparation does not authorize deployment, broadcasts, account-access requests, secret mutations or live notifications. Simulation can make real HTTP requests. Use an isolated destination and respect authorization already given. Keep credentials and private endpoints out of tracked files and output.

Report the behavior preserved, checks actually run, untested paths and unresolved decisions. Distinguish local tests, simulation, deployed execution and production readiness.

Review Sui Contracts

AI-assisted review of a developer's Sui Move code against OpenZeppelin Contracts for Sui: does it use the library's on-chain primitives correctly, and where does it deviate from the library's examples/, doc-comments, and documented conventions?

This is an AI code review, not a formal security audit. It supports the audit process by flagging misuse and deviations early; it does not replace an independent audit, and a clean review is not an assurance of safety.

For building an integration use develop-secure-contracts; for scaffolding a project use setup-sui-contracts. This skill reviews code that already exists.

Establish the reference before reviewing

You cannot flag "incorrect use" or "deviation" without the correct pattern in hand — so discover it from the library's own metadata, never from memory, using the discovery chain the develop-secure-contracts skill defines. Read the primitive's API and behavior at the revision the integrator builds against — resolve each OZ dependency's pinned rev from Move.lock and use that source / those doc-comments, not main. Read the library-wide docs — llms.txt, the catalogs, ARCHITECTURE.md, STYLEGUIDE.md — from the repo's current main instead: they evolve continuously and often do not exist at an older pinned rev. For each OZ primitive the code uses, load its authoritative pattern from:

  • the package's examples/ if it has them, otherwise the module-header doc-comment's idiomatic-usage block — the canonical recipe (some packages ship only the latter);
  • the modules' doc-comments and generated API reference (reached via the catalog's Docs link);
  • ARCHITECTURE.md (capability model, object ownership, initialization) and STYLEGUIDE.md (conventions).

Review the code against those, not against assumptions.

What to review

  • Correct use of OZ primitives. Does the code thread the capability/witness the component defines (rather than hand-rolling sender checks or re-implementing what the library already provides), call functions with the right arguments, and handle the documented abort conditions?
  • Who chooses the type argument — and is it the right one. For each OZ primitive parameterized by a witness or generic/phantom type, check who supplies it and whether it is the correct authority. A caller-chosen type is an authority the caller controls, so the trusted party must fix it, not the caller. And a developer-fixed type must be the right one for the action — a privileged operation gated by a lower-privilege role's Auth (or any weaker witness than the guarantee needs) is a privilege-escalation bug.
  • Deviations from the reference pattern. Compare the flow against the closest examples/ recipe (or the doc-comment's idiomatic-usage block) and flag divergences that weaken the guarantees it preserves — e.g. an object shared vs. embedded against its intended ownership model, a required setup step skipped, a returned value or receipt ignored, or an invariant the doc-comment states being bypassed.
  • Copied library source. Flag any OZ module source copied into the project instead of imported via MVR — copies miss security updates.
  • Invariants upheld. Check that the code preserves the invariants the OZ components document (in their doc-comments and ARCHITECTURE.md) — e.g. an object that must stay shared, a value that must remain bounded, a capability that must not be exposed. Flag any path that can break one.
  • Test coverage of the integration. Check that the tests exercise the abort and branch paths the OZ usage introduces (role-denied, expired, over-limit, wrong-type, and similar), not just the happy path — untested failure paths are where integration bugs hide.
  • Known issue classes (heuristic). Check the code for the classes of issue that recur in OZ-on-Sui / Move code — capability handling, rounding, object ownership, initialization — and raise suspicion where the code touches them. (The library's published audits, under audits/, inform these classes; the reports themselves are PDFs, not a findings feed.) A suspicion-raising self-check, not a reproduction of the audits or a security audit.

Code quality — enforce the conventions

Treat OpenZeppelin's Sui conventions as a first-class review dimension: report violations as findings, not optional suggestions. The rules and the review procedure are the single source of truth — apply them, don't restate them:

  • STYLEGUIDE.md — the codified rules (naming, section ordering, imports, idiomatic Move 2024, testing, docs, lint suppression).
  • .claude/commands/code-quality.md — the canonical procedure that checks .move files against STYLEGUIDE.md; run it against the code under review.
  • Lint is not optional. Build and test with the project's --build-env and --lint (see setup-sui-contracts for the exact invocation); per the styleguide, warnings must be fixed, never suppressed with #[allow(...)]. --lint enforces the compiler-checkable subset independently, so if the STYLEGUIDE.md fetch is momentarily unreachable, retry rather than skipping conventions.

Report each violation against the STYLEGUIDE.md section it breaks.

Verify before reporting

The checks above optimize for catching issues, so before writing anything, try to disprove each finding: quote the exact line and confirm the problem is really there; confirm it is a genuine deviation and not an intentional, documented choice; and confirm you can state a concrete one-line fix. Drop whatever does not survive all three, and keep the severity bar high — a short review a developer trusts beats a long one they skim.

Output

Produce one review, findings ordered by severity. Each finding: file:line — what's wrong (one clause) → the fix (one clause) — and the OZ example or doc-comment it deviates from, so the developer can compare directly. A short preamble is useful — the scope/boundary call and the build/test/lint status — and on a clean integration a single "verified and cleared" line is fine; keep the body to findings, not a recap.

If the project builds, run its checks first (sui move build / test, per setup-sui-contracts) so the review reflects compiling code, and report build/test failures separately from the pattern findings.

Boundaries

  • Reviews the integrator's code — how it uses the library — not the OpenZeppelin library internals themselves.
  • Not a security audit — no exhaustive threat modeling or completeness guarantee; recommend a formal audit for production code.
  • Complements develop-secure-contracts (integration) and setup-sui-contracts (scaffolding); it neither builds nor scaffolds.

Cairo Setup

Project Scaffolding

Install toolchain and create a project:

curl --proto '=https' --tlsv1.2 -sSf https://sh.starkup.sh | sh
scarb new my_project --test-runner=starknet-foundry

This scaffolds a complete Starknet project with snforge testing preconfigured.

OpenZeppelin Dependencies

Look up the current version from https://docs.openzeppelin.com/contracts-cairo before adding. Add to Scarb.toml:

Full library (umbrella package):

[dependencies]
openzeppelin = "<VERSION>"

Individual packages (faster builds — only compiles what you use):

[dependencies]
openzeppelin_token = "<VERSION>"
openzeppelin_access = "<VERSION>"

Available individual packages: openzeppelin_access, openzeppelin_account, openzeppelin_finance, openzeppelin_governance, openzeppelin_interfaces, openzeppelin_introspection, openzeppelin_merkle_tree, openzeppelin_presets, openzeppelin_security, openzeppelin_token, openzeppelin_upgrades, openzeppelin_utils.

openzeppelin_interfaces and openzeppelin_utils are versioned independently. Check the docs for their specific versions. All other packages share the same version.

Import Conventions

The import path depends on which dependency is declared:

  • Umbrella package (openzeppelin = "..."): use openzeppelin:: as the root
  • Individual packages (openzeppelin_token = "..."): use the package name as the root
// Individual packages
use openzeppelin_token::erc20::{ERC20Component, ERC20HooksEmptyImpl};
use openzeppelin_access::ownable::OwnableComponent;
use openzeppelin_upgrades::UpgradeableComponent;

// Umbrella package equivalents
use openzeppelin::token::erc20::{ERC20Component, ERC20HooksEmptyImpl};
use openzeppelin::access::ownable::OwnableComponent;
use openzeppelin::upgrades::UpgradeableComponent;

Components are integrated via the component! macro, embedded impls, and substorage:

component!(path: ERC20Component, storage: erc20, event: ERC20Event);

#[abi(embed_v0)]
impl ERC20MixinImpl = ERC20Component::ERC20MixinImpl<ContractState>;
impl ERC20InternalImpl = ERC20Component::InternalImpl<ContractState>;

Solidity Setup

For existing projects, detect the framework by looking for hardhat.config.* (Hardhat) or foundry.toml (Foundry). For new projects, ask the user which framework they prefer.

Hardhat Setup

  • Initialize project (only if starting a new project)
npx hardhat init        # Hardhat v2
npx hardhat --init      # Hardhat v3
  • Install OpenZeppelin Contracts:
npm install @openzeppelin/contracts
  • If using upgradeable contracts, also install the upgradeable variant:
npm install @openzeppelin/contracts-upgradeable

Foundry Setup

  • Install Foundry
curl -L https://foundry.paradigm.xyz | bash
foundryup
  • Initialize project (only if starting a new project)
forge init my-project
cd my-project
  • Add OpenZeppelin Contracts:
forge install OpenZeppelin/openzeppelin-contracts@v<VERSION>
  • If using upgradeable contracts, also add the upgradeable variant:
forge install OpenZeppelin/openzeppelin-contracts-upgradeable@v<VERSION>

Look up the current version from https://github.com/OpenZeppelin/openzeppelin-contracts/releases. Pin to a release tag — without one, forge install pulls the default branch, which may be unstable.

  • remappings.txt (if not using upgradeable contracts)
@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/
  • remappings.txt (if using upgradeable contracts)
@openzeppelin/contracts/=lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/
@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/

Note The above remappings mean that both @openzeppelin/contracts/ (including proxy contracts) and @openzeppelin/contracts-upgradeable/ come from the openzeppelin-contracts-upgradeable submodule and its subdirectories, which includes its own transitive copy of openzeppelin-contracts of the same release version number. This format is needed for Etherscan verification to work. Particularly, any copies of openzeppelin-contracts that are installed separately are NOT used.

Import Conventions

  • Standard: @openzeppelin/contracts/token/ERC20/ERC20.sol
  • Upgradeable: @openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol
  • Use upgradeable variants only when deploying behind proxies; otherwise use standard contracts.

Stellar Setup

Soroban/Stellar Development Setup

Install the Rust toolchain (v1.84.0+) and the Soroban WASM target:

curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
rustup target add wasm32v1-none

Install the Stellar CLI:

curl -fsSL https://github.com/stellar/stellar-cli/raw/main/install.sh | sh

Create a new Soroban project:

stellar contract init my_project

This creates a Cargo workspace with contracts in contracts/*/.

OpenZeppelin Dependencies

Look up the current version from the stellar-contracts repo before adding. Pin exact versions with = as the library is under active development.

Add OpenZeppelin crates to the root Cargo.toml under [workspace.dependencies]:

[workspace.dependencies]
stellar-tokens = "=<VERSION>"
stellar-access = "=<VERSION>"
stellar-contract-utils = "=<VERSION>"
stellar-macros = "=<VERSION>"

Then reference them in the per-contract contracts/*/Cargo.toml:

[dependencies]
soroban-sdk = { workspace = true }
stellar-tokens = { workspace = true }
stellar-access = { workspace = true }
stellar-contract-utils = { workspace = true }
stellar-macros = { workspace = true }

Available crates: stellar-access, stellar-accounts, stellar-contract-utils, stellar-fee-abstraction, stellar-governance, stellar-macros, stellar-tokens.

Only add the crates the contract actually uses. stellar-macros provides proc-macro attributes (for example, #[when_not_paused], #[only_owner], #[derive(Upgradeable)]) and is needed in most contracts.

Code Patterns

Imports use underscores as the crate root (Rust convention):

use stellar_tokens::fungible::{Base, FungibleToken};
use stellar_tokens::fungible::burnable::FungibleBurnable;
use stellar_access::ownable::Ownable;
use stellar_contract_utils::pausable::Pausable;
use stellar_macros::when_not_paused;

Contracts use #[contract] on the struct and #[contractimpl] on the impl block (from soroban_sdk):

use soroban_sdk::{contract, contractimpl, Env};

#[contract]
pub struct MyToken;

#[contractimpl]
impl MyToken {
    // Implement trait methods here
}

Trait implementations are separate impl blocks per trait (e.g., FungibleToken, Pausable). Guard macros like #[when_not_paused] and #[only_owner] decorate individual functions.

Platform Notes

  • Read operations are free in Stellar. Optimize for minimizing writes; reads and computation are cheap. Prefer clean, readable code over micro-optimizations.
  • Instance storage TTL extension is the developer's responsibility. The OpenZeppelin library handles TTL extension for other storage entries, but contracts must extend their own instance storage entries to prevent expiration.

Build & Test

Build the contract to WASM:

stellar contract build

This is a shortcut for cargo build --target wasm32v1-none --release. Output appears in target/wasm32v1-none/release/.

Run tests:

cargo test

soroban-sdk testutils are automatically enabled for in-crate unit tests.

Stylus Setup

Rust & Cargo Stylus Setup

Install the Rust toolchain and WASM target:

curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
rustup target add wasm32-unknown-unknown

Install the Cargo Stylus CLI:

cargo install --force cargo-stylus

Create a new Stylus project:

cargo stylus new my_project

After creating the project, verify it compiles with cargo stylus check (see Build & Deploy section below).

A Rust nightly toolchain is required. The project should include a rust-toolchain.toml specifying the nightly channel, rust-src component, and wasm32-unknown-unknown target. Check the rust-contracts-stylus repo for the current recommended nightly date.

Adding OpenZeppelin Dependencies

Look up the current version from crates.io/crates/openzeppelin-stylus before adding. Add to Cargo.toml:

[dependencies]
openzeppelin-stylus = "=<VERSION>"

Enable the export-abi feature flag for ABI generation:

[features]
export-abi = ["openzeppelin-stylus/export-abi"]

The crate must be compiled as both a library and a cdylib:

[lib]
crate-type = ["lib", "cdylib"]

Import Conventions

Imports use openzeppelin_stylus (underscores) as the crate root:

use openzeppelin_stylus::token::erc20::{Erc20, IErc20};
use openzeppelin_stylus::access::ownable::{Ownable, IOwnable};
use openzeppelin_stylus::utils::pausable::{Pausable, IPausable};
use openzeppelin_stylus::utils::introspection::erc165::IErc165;

Contracts use #[storage] and #[entrypoint] on the main struct, embedding OpenZeppelin components as fields:

#[entrypoint]
#[storage]
struct MyToken {
    erc20: Erc20,
    ownable: Ownable,
}

Public methods are exposed with #[public] and #[implements(...)]. The canonical pattern uses an empty impl block for dispatch registration, plus separate trait impl blocks:

#[public]
#[implements(IErc20<Error = erc20::Error>, IOwnable<Error = ownable::Error>)]
impl MyToken {}

#[public]
impl IErc20 for MyToken {
    type Error = erc20::Error;
    // delegate to self.erc20 ...
}

Top-level modules: access, finance, proxy, token, utils.

Build & Deploy Basics

Do NOT use plain cargo check or cargo build, since Stylus contracts require the cargo stylus CLI for correct WASM compilation.

Validate the contract compiles to valid Stylus WASM:

cargo stylus check

Export the Solidity ABI:

cargo stylus export-abi

Deploy to an Arbitrum Stylus endpoint:

cargo stylus deploy --endpoint="<RPC_URL>" --private-key-path="<KEY_FILE>"

Sui Setup

Prerequisites

Install the Sui CLI by following the Sui installation guide. The CLI bundles the Move toolchain and the Move Registry (MVR) resolver, so no separate Move install is needed.

Any time you need to investigate the library, start from its AI discovery entry point, llms.txt — it maps the library's content (the architecture doc, the contracts/ and math/ package catalogs, each package's README/examples/API reference, and audits). Follow its links rather than guessing paths.

OpenZeppelin Contracts for Sui pins a specific Sui CLI version in its top-level README (this is repo metadata, not linked from llms.txt) — read the required version there and check your local install against it. The pinned version is the tested one and safest to match; a newer patch/minor generally works too, so treat a small drift as a warning, not a blocker:

sui --version

Create a Project

Initialize a new Move package (only if starting a new project):

sui move new my_project
cd my_project

This creates Move.toml, a .gitignore, and commented-out stub modules sources/my_project.move and tests/my_project_tests.move, using Move edition = "2024". The stubs are inert placeholders (fully wrapped in /* … */); replace or delete them when you add your own modules.

OpenZeppelin Dependencies

OpenZeppelin packages are published to the Move Registry (MVR) and added to Move.toml under [dependencies] with the r.mvr format, mapping the Move package name to its MVR slug:

[dependencies]
<move_package_name> = { r.mvr = "@openzeppelin-move/<slug>" }

Do not rely on a memorized package list — it drifts as the library evolves. Discover what is available from the library's own metadata, which is the single source of truth:

  1. Start — as always — at the AI discovery entry point, llms.txt.
  2. Follow its links to every package catalog it lists — llms.txt is the authority on which catalogs exist, so read the set from there rather than assuming a fixed one (new top-level catalogs get added over time). Each catalog table lists the MVR slug, the Move package name, docs, and highlights.
  3. Read the individual package's README.md for the exact r.mvr install snippet and its module list. Confirm the slug resolves — either by looking it up on moveregistry.com or, definitively, by running the build (below), which resolves every slug against the MVR.

Catalog paths are relative to the catalog file's own directory. A catalog at <catalog-dir>/README.md lists each package by a Path relative to <catalog-dir>/, so the package's raw README is .../main/<catalog-dir>/<path>/README.md — resolve <path> against the directory of the catalog that links it, not the repo root (the bare .../main/<path>/README.md 404s). When in doubt, list the tree: gh api 'repos/OpenZeppelin/contracts-sui/git/trees/main?recursive=1' (quote the endpoint — an unquoted ? is a glob in some shells).

The Move package name (used in use statements) differs from the MVR slug — slug @openzeppelin-move/integer-math is Move package openzeppelin_math. Only add the packages the project actually uses.

A package usually contains several modules. The catalog lists packages; the building block you want is often one module among several inside a package. Read the package README's module list and its examples/ to see what a package actually exposes — don't assume one package equals one component, and don't rely on a fixed mental catalog: the set of packages and modules grows over time.

The OpenZeppelin Sui MCP exposes this same metadata as deterministic tool calls — sui-list-recipes (discover recipes), sui-get-recipe (a recipe's source plus the packages it uses, each with its install line), and sui-get-package (a package's install line + docs). When the MCP is available, query it instead of crawling the files by hand, then wire the returned install lines into Move.toml and re-home the recipe source into your package. The MCP returns data, not a buildable package — that wiring and re-homing are what turn it into one.

Packages not on the Move Registry

Not every package is on the Move Registry — some are not published there at all. When a package's README.md has no r.mvr install snippet, depend on it from a GitHub release instead — a git dependency pinned to a release tag, never a moving branch:

[dependencies]
<move_package_name> = { git = "https://github.com/OpenZeppelin/contracts-sui.git", subdir = "<catalog-dir>/<path>", rev = "<release-tag>" }

<catalog-dir>/<path> is the package's directory in the repo (the same Path its catalog row lists); pin rev to a published GitHub release tag, not a branch. Keep every OpenZeppelin dependency on one consistent revision to avoid the diamond conflict below.

Resolving version conflicts (diamond dependencies)

Two OZ packages can pull different revisions of a shared transitive dependency — for example, if one package embeds its own revision of a math package that you also depend on directly. When that happens the build aborts:

Package depends on multiple versions of the package with ID 0x…

Resolve it by adding override = true to the directly-declared dependency, which forces every consumer onto that revision:

[dependencies]
openzeppelin_math = { r.mvr = "@openzeppelin-move/integer-math", override = true }
openzeppelin_fp_math = { r.mvr = "@openzeppelin-move/fixed-point-math" }

Study the Examples and Docs Before Implementing

Do this before writing any integration code — most users don't know the full catalog, and it grows over time, so let the library show you what it provides and how it's meant to be composed. For each package you plan to use:

  1. Study its examples/. Every package ships compilable, CI-tested integration examples — these are the canonical composition recipes and the fastest way to see the real usage pattern (initialization, capability/witness flow, object ownership, tests). Prefer copying and adapting an example into sources/ over writing from scratch.

    Read examples and metadata from main; pin dependencies to a release. All AI metadata — llms.txt, the catalogs, package READMEs, STYLEGUIDE.md, and the examples/ — should be read from the main branch, which carries the latest and most complete set (a package may have examples on main that a tagged release does not). Your build dependencies, by contrast, resolve to a pinned release — an MVR slug or a git rev = "<release-tag>" (above) — so builds stay reproducible. The two can differ: an example copied from main may reference an API newer than your pinned release, in which case adapt it (or bump the pinned release) when you re-home.

    Re-home a copied example. Example modules are declared under the library's own address (e.g. module openzeppelin_access::example_reward_treasury;) — they are illustrations inside the library, not drop-in consumer code. When you copy one into sources/, rename its module to your package (module <your_package>::<module>;, where <your_package> is your Move.toml [package] name). Keep the use openzeppelin_*::… lines as-is — those reference the dependencies. If the example defines a one-time witness — a struct whose name is the module name upper-cased, consumed by init — rename that struct to match your new module name too, or init fails with "Invalid parameter … Expected a one-time witness type". You cannot define a module under a dependency's address, so a verbatim copy will not build until it is re-homed.

  2. Read the docs. Start at the documentation site for concepts and guides, then the generated API reference — reached via the Docs link in each catalog table (it points at the correct version), path .../contracts-sui/<major>.x/api/<catalog_package> where <major> matches your contracts-sui release and <catalog_package> is the short catalog name, not the Move package name — for exact signatures, parameters, and abort conditions.

  3. Read the code docs. The API reference is generated from the modules' doc-comments, so the installed source is the ground truth. Generate the same docs locally with sui move build --doc --build-env testnet (the --build-env is required whenever there are MVR deps) — this also emits the docs for every OZ dependency under build/<your_package>/docs/dependencies/<move_package_name>/ — or just read the doc-comments in the installed source.

Discover the available examples from llms.txt and each package README, then browse them in the contracts-sui repo.

Import Conventions

Import modules through the Move package name (the left side of the Move.toml entry) followed by the module name — use <move_package_name>::<module>; — then follow the usage patterns from the package's examples/ and API docs.

Some operations are exposed as method syntax (value.op(...)) via public use fun re-exports, so the underlying function may live in a different module than the type. If a free function you expect isn't found, check the package source for the public use fun lines and call it as a method.

Generate Agent Guidance

Create an AGENTS.md at the project root so any agent that later opens this project knows it is built on OpenZeppelin Contracts for Sui and where the sources of truth live. Follow the same philosophy as the contracts-sui AGENTS.md: a lean pointer file that does not restate rules — it links to the authoritative sources. Also add a CLAUDE.md containing only @AGENTS.md so Claude Code picks it up (mirroring how contracts-sui itself is set up).

# AGENTS.md

This is a Sui Move project built on **OpenZeppelin Contracts for Sui**.

## Sources of truth — read these first
- AI discovery entry point: https://raw.githubusercontent.com/OpenZeppelin/contracts-sui/main/llms.txt
  (points to the package catalogs, each package's `examples/`, the generated API reference, and audits)
- Docs: https://docs.openzeppelin.com/contracts-sui
- API reference: https://docs.openzeppelin.com/contracts-sui/<major>.x/api/<catalog_package> (`<major>` matches your contracts-sui release and `<catalog_package>` is the short catalog name; the catalog's `Docs` links carry the correct version)
- Code docs (local): `sui move build --doc --build-env testnet` → `build/<your_package>/docs/` (named after your own package; includes OZ dependencies)

## Conventions
- Before implementing, study each package's `examples/` (compilable, CI-tested composition recipes) and its API docs; prefer audited library components over custom logic.
- Import modules via the Move package name (`use <move_package_name>::<module>;`); a package typically exposes several modules — check its README and `examples/`.
- MVR-backed builds require a build env: `sui move build --build-env testnet`. If two OZ deps pull different revisions of a shared transitive package, add `override = true` to the directly-declared one.
- For fungible-asset custody, consider Sui [Address Balances](https://docs.sui.io/onchain-finance/asset-custody/address-balances/) (SIP-58) over summing `Coin` objects where it fits.
- Code style follows the OpenZeppelin Sui conventions — see Code Quality below.

## Code quality
The library's conventions are the single source of truth for Move style:
- Rules: https://raw.githubusercontent.com/OpenZeppelin/contracts-sui/main/STYLEGUIDE.md
- Design rationale: https://raw.githubusercontent.com/OpenZeppelin/contracts-sui/main/ARCHITECTURE.md
- Review procedure (reads STYLEGUIDE.md, reports/fixes violations): https://raw.githubusercontent.com/OpenZeppelin/contracts-sui/main/.claude/commands/code-quality.md

## MCP
The OpenZeppelin Sui MCP (https://mcp.openzeppelin.com/contracts/sui/mcp) serves recipes and per-package install lines as deterministic tool calls (`sui-list-recipes`, `sui-get-recipe`, `sui-get-package`) — a queryable alternative to reading `llms.txt` + the catalogs by hand. This project ships it pre-wired in `.mcp.json`. It returns data, not a buildable package — wiring the install lines into `Move.toml` and re-homing the source into this package is what turns it into one.

Also write a pre-wired MCP config at the project root so any agent understands the OpenZeppelin-on-Sui context on clone, without manual setup. Claude Code reads .mcp.json; other assistants (Cursor, Cline) take the same server URL in their own MCP config.

{
  "mcpServers": {
    "openzeppelin-sui": {
      "type": "http",
      "url": "https://mcp.openzeppelin.com/contracts/sui/mcp"
    }
  }
}

Build & Test

Because dependencies resolve through MVR, builds and tests must specify a build environment. Use testnet for development (mainnet is also available for release builds):

sui move build --build-env testnet
sui move test --build-env testnet

Without --build-env, the CLI cannot resolve r.mvr dependencies and errors with "Could not determine the correct dependencies to use for local". A green build + test on a freshly scaffolded project is the acceptance bar.

Add --lint --warnings-are-errors once the project has real code to catch style and dead-code issues early:

sui move test --build-env testnet --lint --warnings-are-errors

Testing patterns to know

A couple of Sui conventions recur when testing code built on these packages — the library's own examples/ tests are the canonical reference:

  • One-Time Witness (OTW) in tests. Modules that take an OTW consume it in init, and it can't be constructed at runtime. To exercise such a module in a unit test, expose a #[test_only] initializer that builds the OTW (its struct is constructible inside a #[test_only] context):

    #[test_only]
    public fun init_for_testing(ctx: &mut TxContext) { init(MY_OTW {}, ctx) }
    
  • Clock. Modules that depend on time take a sui::clock::Clock. In tests use create_for_testing, increment_for_testing, and destroy_for_testing.

  • Assertions. Under --warnings-are-errors, a literal abort code (assert!(cond, 0)) trips the abort_without_constant lint. In tests, use assert_eq! (from std::unit_test) or a bare assert!(cond); in non-test code, assert against a named error constant rather than a literal.

Composition constraint: a Sui init function receives no Clock (nor other runtime arguments). A component whose constructor needs a Clock therefore can't be fully built in init — create/share the object in init, then complete setup in a later entry function that takes the Clock. The package's examples/ show the intended two-step pattern.

Code Quality

Align the project's Move style with OpenZeppelin's own conventions so integrator code stays consistent with the library. As with dependencies, don't restate the rules — point at the library's single sources of truth:

  • STYLEGUIDE.md — the codified rules (Naming, Module & Package, Section ordering, Imports, Structs, Functions, Idiomatic Move 2024, Collections & object size, Testing, Lint suppression, Documentation).
  • ARCHITECTURE.md — the design rationale those rules reference (capability-based access, owned vs. shared objects, PTB composability, bounded state, upgrade safety).
  • .claude/commands/code-quality.md — the review procedure: it reads STYLEGUIDE.md and checks each .move file against it, then reports or fixes violations. The procedure is plain markdown, so any agent can follow it even though the slash command is Claude-specific.

Record these under a Code quality heading in the generated AGENTS.md (see above) so downstream agents follow the same conventions on clone.

Formatting

contracts-sui formats Move with the @mysten/prettier-plugin-move Prettier plugin — match it so integrator code lays out identically. Install it and add a .prettierrc matching the library's:

npm i -D prettier @mysten/prettier-plugin-move
{
  "tabWidth": 4,
  "printWidth": 100,
  "useModuleLabel": true,
  "autoGroupImports": "module",
  "plugins": ["@mysten/prettier-plugin-move"]
}

Then format from the repo root (Prettier silently skips .move files if the plugin isn't resolvable, so keep it in devDependencies):

npx prettier --write "**/*.move"

autoGroupImports: "module" normalizes use grouping, so run --write to let it format — don't hand-tune imports and expect --check to pass first.

The code-quality.md review procedure runs this same formatting pass after applying fixes.

Cairo Upgrades

Contents

Starknet Upgrade Model

Starknet separates contract instances from contract classes. A class is the compiled program (identified by its class hash); a contract is a deployed instance pointing to a class. Multiple contracts can share the same class.

Upgrading a contract means replacing its class hash so it points to a new class. The contract keeps its address, storage, and nonce — only the code changes. This is fundamentally different from EVM proxy patterns:

StarknetEVM (proxy pattern)
Mechanismreplace_class_syscall swaps the class hash in-placeProxy delegatecalls to a separate implementation contract
Proxy contract neededNo — the contract upgrades itselfYes — a proxy sits in front of the implementation
Storage locationBelongs to the contract directlyLives in the proxy, accessed via delegatecall
Fallback routingNot applicable — no fallback/catch-all mechanism in CairoProxy forwards all calls via fallback function

The replace_class_syscall is a native Starknet syscall. When called, it atomically replaces the calling contract's class hash with the provided one. The new class must already be declared on-chain. After the syscall, the current execution frame continues with the old code, but subsequent calls to the contract — whether via call_contract_syscall later in the same transaction or in future transactions — execute the new code.

Using the OpenZeppelin Upgradeable Component

OpenZeppelin Contracts for Cairo provides an UpgradeableComponent that wraps replace_class_syscall with validation and event emission. Integrate it as follows:

  1. Declare the component alongside an access control component (e.g., OwnableComponent)
  2. Add both to storage and events using #[substorage(v0)] and #[flat]
  3. Expose an upgrade function behind access control that calls the component's internal upgrade method — the component calls replace_class_syscall to atomically swap the class hash; always mention this syscall when explaining how Cairo upgrades work
  4. Initialize access control in the constructor

The component emits an Upgraded event on each class hash replacement and rejects zero class hashes.

There is also an IUpgradeAndCall interface variant that couples the upgrade with a function call in the new class context — useful for post-upgrade migrations or re-initialization.

Access control

The UpgradeableComponent deliberately does not embed access control itself. You must guard the external upgrade function with your own check (e.g., self.ownable.assert_only_owner()). Forgetting this allows anyone to replace your contract's code.

Common access control options:

  • Ownable — single owner, simplest pattern
  • AccessControl / RBAC — role-based, finer granularity
  • Multisig or governance — for production contracts managing significant value

Upgrade Safety

Storage compatibility

When replacing a class hash, existing storage is reinterpreted by the new class. Incompatible changes corrupt state:

  • Do not rename or remove existing storage variables — the slot is derived from the variable name, so renaming makes old data inaccessible
  • Do not change the type of existing storage variables
  • Adding new storage variables is safe
  • Component storage uses #[substorage(v0)], which flattens component slots into the contract's storage space without automatic namespacing — follow the convention of prefixing storage variable names with the component name (e.g., ERC20_balances) to avoid collisions across components

Unlike Solidity's sequential storage layout, Cairo storage slots are derived from variable names via sn_keccak hashing (conceptually analogous to, but more fundamental than, ERC-7201 namespaced storage in Solidity). This makes ordering irrelevant but makes naming critical.

OpenZeppelin version upgrades

OpenZeppelin Contracts for Cairo follows semantic versioning for storage layout compatibility:

  • Patch updates always preserve storage layout
  • Minor updates preserve storage layout (from v1.0.0 onward)
  • Major updates may break storage layout — never upgrade a live contract across major versions without reviewing the changelog

Testing upgrade paths

Before upgrading a production contract:

  • Deploy V1 and V2 classes in a local devnet (e.g., starknet-devnet-rs or Katana)
  • Write state with V1, upgrade to V2, and verify that all existing state reads correctly
  • Verify new functionality works as expected after the upgrade
  • Confirm access control — only authorized callers can invoke upgrade
  • Check API compatibility — changed external function signatures break existing callers and integrations
  • Review storage changes — ensure no renames, removals, or type changes to existing variables
  • Manual review — there is no automated storage layout validation for Cairo; use npx @openzeppelin/contracts-cli to discover current integration patterns and rely on devnet testing

Solidity Upgrades

Contents

Proxy Patterns Overview

PatternUpgrade logic lives inBest for
UUPS (UUPSUpgradeable)Implementation contract (override _authorizeUpgrade)Most projects — lighter proxy, lower deploy gas
TransparentSeparate ProxyAdmin contractWhen admin/user call separation is critical — admin cannot accidentally call implementation functions
BeaconShared beacon contractMultiple proxies sharing one implementation — upgrading the beacon atomically upgrades all proxies

All three use EIP-1967 storage slots for the implementation address, admin, and beacon.

Transparent proxy — v5 constructor change: In v5, TransparentUpgradeableProxy automatically deploys its own ProxyAdmin contract and stores the admin address in an immutable variable (set at construction time, never changeable). The second constructor parameter is the owner address for that auto-deployed ProxyAdmin — do not pass an existing ProxyAdmin contract address here. Transfer of upgrade capability is handled exclusively through ProxyAdmin ownership. This differs from v4, where ProxyAdmin was deployed separately and its address was passed to the proxy constructor.

Upgrade Restrictions Between Major Versions (v4 → v5)

Upgrading a proxy's implementation from one using OpenZeppelin Contracts v4 to one using v5 is not supported.

v4 uses sequential storage (slots in declaration order); v5 uses namespaced storage (ERC-7201, structs at deterministic slots). A v5 implementation cannot safely read state written by a v4 implementation. Manual data migration is theoretically possible but often infeasible — mapping entries cannot be enumerated, so values written under arbitrary keys cannot be relocated.

Recommended approach: Deploy new proxies with v5 implementations and migrate users to the new address — do not upgrade proxies that currently point to v4 implementations.

Updating your codebase to v5 is encouraged. The restriction above applies only to already-deployed proxies. New deployments built on v5, and upgrades within the same major version, are fully supported.

Writing Upgradeable Contracts

Use initializers instead of constructors

Proxy contracts delegatecall into the implementation. Constructors run only when the implementation itself is deployed, not when a proxy is created. Replace constructors with initializer functions:

import {Initializable} from "@openzeppelin/contracts/proxy/utils/Initializable.sol";

contract MyToken is Initializable, ERC20Upgradeable, OwnableUpgradeable {
    /// @custom:oz-upgrades-unsafe-allow constructor
    constructor() {
        _disableInitializers(); // lock the implementation
    }

    function initialize(address initialOwner) public initializer {
        __ERC20_init("MyToken", "MTK");
        __Ownable_init(initialOwner);
    }
}

Key rules:

  • Top-level initialize uses the initializer modifier
  • Parent init functions (__X_init) use onlyInitializing internally — call them explicitly, the compiler does not auto-linearize initializers like constructors
  • Always call _disableInitializers() in a constructor to prevent attackers from initializing the implementation directly
  • Do not set initial values in field declarations (e.g., uint256 x = 42) — these compile into the constructor and won't execute for the proxy. constant is safe (inlined at compile time). immutable values are stored in bytecode and shared across all proxies — the plugins flag them as unsafe by default; use /// @custom:oz-upgrades-unsafe-allow state-variable-immutable to opt in when a shared value is intended

Use the upgradeable package

Import from @openzeppelin/contracts-upgradeable for base contracts (e.g., ERC20Upgradeable, OwnableUpgradeable). Import interfaces and libraries from @openzeppelin/contracts. In v5.5+, Initializable and UUPSUpgradeable should also be imported directly from @openzeppelin/contracts — aliases in the upgradeable package will be removed in the next major release.

Storage layout rules

When upgrading, the new implementation must be storage-compatible with the old one:

  • Never reorder, remove, or change the type of existing state variables
  • Never insert new variables before existing ones
  • Only append new variables at the end
  • Never change the inheritance order of base contracts

Namespaced storage (ERC-7201)

The modern approach — all @openzeppelin/contracts-upgradeable contracts (v5+) use this. State variables are grouped into a struct at a deterministic storage slot, isolating each contract's storage and eliminating the need for storage gaps. Recommended for all contracts that may be imported as base contracts.

/// @custom:storage-location erc7201:example.main
struct MainStorage {
    uint256 value;
    mapping(address => uint256) balances;
}

// keccak256(abi.encode(uint256(keccak256("example.main")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant MAIN_STORAGE_LOCATION = 0x...;

function _getMainStorage() private pure returns (MainStorage storage $) {
    assembly { $.slot := MAIN_STORAGE_LOCATION }
}

Using a variable from namespaced storage:

function _getBalance(address account) internal view returns (uint256) {
    MainStorage storage $ = _getMainStorage();
    return $.balances[account];
}

Benefits over legacy storage gaps: safe to add variables to base contracts, inheritance order changes don't break layout, each contract's storage is fully isolated.

When upgrading, never remove a namespace by dropping it from the inheritance chain. The plugin flags deleted namespaces as an error — the state stored in that namespace becomes orphaned: the data remains on-chain but the new implementation has no way to read or write it. If a namespace is no longer actively used, keep the old contract in the inheritance chain. An unused namespace adds no runtime cost and causes no storage conflict. There is no targeted flag to suppress this error; the only bypass is unsafeSkipStorageCheck, which disables all storage layout compatibility checks and is a dangerous last resort.

Computing ERC-7201 storage locations

When generating namespaced storage code, always compute the actual STORAGE_LOCATION constant. Use the Bash tool to run the command below with the actual namespace id and embed the computed value directly in the generated code. Never leave placeholder values like 0x....

The formula is: keccak256(abi.encode(uint256(keccak256(id)) - 1)) & ~bytes32(uint256(0xff)) where id is the namespace string (e.g., "example.main").

Node.js with ethers:

node -e "const{keccak256,toUtf8Bytes,zeroPadValue,toBeHex}=require('ethers');const id=process.argv[1];const h=BigInt(keccak256(toUtf8Bytes(id)))-1n;console.log(toBeHex(BigInt(keccak256(zeroPadValue(toBeHex(h),32)))&~0xffn,32))" "example.main"

Replace "example.main" with the actual namespace id, run the command, and use the output as the constant value.

Unsafe operations

  • No selfdestruct — on pre-Dencun chains, destroys the implementation and bricks all proxies. Post-Dencun (EIP-6780), selfdestruct only destroys code if called in the same transaction as creation, but the plugins still flag it as unsafe
  • No delegatecall to untrusted contracts — a malicious target could selfdestruct or corrupt storage

Additionally, avoid using new to create contracts inside an upgradeable contract — the created contract won't be upgradeable. Inject pre-deployed addresses instead.

Hardhat Upgrades Workflow

Install the plugin:

npm install --save-dev @openzeppelin/hardhat-upgrades
npm install --save-dev @nomicfoundation/hardhat-ethers ethers  # peer dependencies

Register in hardhat.config:

require('@openzeppelin/hardhat-upgrades'); // JS
import '@openzeppelin/hardhat-upgrades';   // TS

Workflow concept — the plugin provides functions on the upgrades object (deployProxy, upgradeProxy, deployBeacon, upgradeBeacon, deployBeaconProxy). Each function:

  1. Validates the implementation for upgrade safety (storage layout, initializer patterns, unsafe opcodes)
  2. Deploys the implementation (reuses if already deployed)
  3. Deploys or updates the proxy/beacon
  4. Calls the initializer (on deploy)

The plugin tracks deployed implementations in .openzeppelin/ per-network files. Commit non-development network files to version control.

Use prepareUpgrade to validate and deploy a new implementation without executing the upgrade — useful when a multisig or governance contract holds upgrade rights.

Read the installed plugin's README or source for exact API signatures and options, as these evolve across versions.

Foundry Upgrades Workflow

Install dependencies:

forge install foundry-rs/forge-std
forge install OpenZeppelin/openzeppelin-foundry-upgrades
forge install OpenZeppelin/openzeppelin-contracts-upgradeable

Configure foundry.toml:

[profile.default]
ffi = true
ast = true
build_info = true
extra_output = ["storageLayout"]

Node.js is required — the library shells out to the OpenZeppelin Upgrades CLI for validation.

Import and use in scripts/tests:

import {Upgrades} from "openzeppelin-foundry-upgrades/Upgrades.sol";

// Deploy
address proxy = Upgrades.deployUUPSProxy(
    "MyContract.sol",
    abi.encodeCall(MyContract.initialize, (args))
);

// IMPORTANT: Before upgrading, annotate MyContractV2 with: /// @custom:oz-upgrades-from MyContract

// Upgrade and call a function
Upgrades.upgradeProxy(proxy, "MyContractV2.sol", abi.encodeCall(MyContractV2.foo, ("arguments for foo")));

// Upgrade without calling a function
Upgrades.upgradeProxy(proxy, "MyContractV2.sol", "");

Key differences from Hardhat:

  • Contracts are referenced by name string, not factory object
  • No automatic implementation tracking — annotate new versions with @custom:oz-upgrades-from or pass referenceContract in the Options struct
  • UnsafeUpgrades variant skips all validation (takes addresses instead of names) — never use in production scripts
  • Run forge clean or use --force before running scripts

Read the installed library's Upgrades.sol for the full API and Options struct.

Handling Upgrade Validation Issues

When the plugins flag a warning or error, work through this hierarchy:

  1. Fix the root cause. Determine whether the code can be restructured to eliminate the concern entirely — remove the problematic pattern or refactor storage. This is always the right first step.
  2. Use in-code annotations if the situation is genuinely safe. If restructuring isn't appropriate and you've determined the flagged pattern is actually safe, the plugins support annotations that let you document that judgment directly at the source. Check the installed plugin's docs for what's available. These annotations create a clear audit trail of intentional exceptions — use them only after evaluating the safety, not as a shortcut.
  3. Use a narrow flag if an annotation won't work. Some cases (e.g., a third-party base contract you can't modify) can't be addressed in source. Use the most targeted flag available, scoped to the specific construct.
  4. Broad bypass as a last resort, with full awareness of the risk. Options like UnsafeUpgrades (Foundry) or blanket unsafeAllow entries skip all validation for the affected scope. If you use them, comment why, and verify manually — the plugin is no longer protecting you.

Upgrade Safety Checklist

  • Storage compatibility: No reordering, removal, or type changes of existing variables. Only append new variables (or add fields to namespaced structs).
  • Initializer protection: Top-level initialize uses initializer modifier. Implementation constructor calls _disableInitializers().
  • Parent initializers called: Every inherited upgradeable contract's __X_init is called exactly once in initialize.
  • No unsafe opcodes: No selfdestruct or delegatecall to untrusted targets.
  • Function selector clashes: Proxy admin functions and implementation functions must not share selectors. UUPS and Transparent patterns handle this by design; custom proxies need manual review.
  • UUPS _authorizeUpgrade: Overridden with proper access control (e.g., onlyOwner). Forgetting this makes the proxy non-upgradeable or upgradeable by anyone.
  • Test the upgrade path: Deploy V1, upgrade to V2, verify state is preserved and new logic works. Both Hardhat and Foundry plugins can validate upgrades in test suites.
  • Reinitializer for V2+: If V2 needs new initialization logic, use reinitializer(2) modifier (not initializer, which can only run once).
  • Unique ERC-7201 namespace ids: No two contracts in the inheritance chain share the same namespace id. Colliding ids map to the same storage slot, causing silent storage corruption.

Stellar Upgrades

Contents

Soroban Upgrade Model

Soroban contracts are mutable by default. Mutability refers to the ability of a smart contract to modify its own WASM bytecode, altering its function interface, execution logic, or metadata. Soroban provides a built-in, protocol-level mechanism for contract upgrades — no proxy pattern is needed.

A contract can upgrade itself if it is explicitly designed to do so. Conversely, a contract becomes immutable simply by not provisioning any upgrade function. This is fundamentally different from EVM proxy patterns:

SorobanEVM (proxy pattern)Starknet
MechanismNative WASM bytecode replacementProxy delegatecalls to implementation contractreplace_class_syscall swaps class hash in-place
Proxy contract neededNo — the contract upgrades itselfYes — a proxy sits in front of the implementationNo — the contract upgrades itself
Storage locationBelongs to the contract directlyLives in the proxy, accessed via delegatecallBelongs to the contract directly
Opt-in to immutabilityDon't expose an upgrade functionDon't deploy a proxyDon't call the syscall

One advantage of protocol-level upgradeability is a significantly reduced risk surface compared to platforms that require proxy contracts and delegatecall forwarding.

The new implementation only becomes effective after the current invocation completes. This means if migration logic is defined in the new implementation, it cannot execute within the same call as the upgrade. An auxiliary Upgrader contract can wrap both calls to achieve atomicity (see below).

Using the OpenZeppelin Upgradeable Module

OpenZeppelin Stellar Soroban Contracts provides an upgradeable module in the contract-utils package with two main components:

ComponentUse when
UpgradeableOnly the WASM binary needs to be updated — no storage migration required
UpgradeableMigratableThe WASM binary and specific storage entries need to be modified during the upgrade

The recommended way to use these is through derive macros: #[derive(Upgradeable)] and #[derive(UpgradeableMigratable)]. These macros handle the implementation of necessary functions and set the crate version from Cargo.toml as the binary version in WASM metadata, aligning with SEP-49 guidelines.

Upgrade only

Derive Upgradeable on the contract struct, then implement UpgradeableInternal with a single required method:

  • _require_auth(e: &Env, operator: &Address) — verify the operator is authorized to perform the upgrade (e.g., check against a stored owner address)

The operator parameter is the invoker of the upgrade function and can be used for role-based access control.

Upgrade and migrate

Derive UpgradeableMigratable on the contract struct, then implement UpgradeableMigratableInternal with:

  • An associated MigrationData type defining the data passed to the migration function
  • _require_auth(e, operator) — same authorization check as above
  • _migrate(e: &Env, data: &Self::MigrationData) — perform storage modifications using the provided migration data

The derive macro ensures that migration can only be invoked after a successful upgrade, preventing state inconsistencies and storage corruption.

Atomic upgrade and migration

Because the new implementation only takes effect after the current invocation completes, migration logic in the new contract cannot run in the same call as the upgrade. An auxiliary Upgrader contract wraps both calls atomically:

use soroban_sdk::{contract, contractimpl, symbol_short, Address, BytesN, Env, Val};
use stellar_contract_utils::upgradeable::UpgradeableClient;

#[contract]
pub struct Upgrader;

#[contractimpl]
impl Upgrader {
    pub fn upgrade_and_migrate(
        env: Env,
        contract_address: Address,
        operator: Address,
        wasm_hash: BytesN<32>,
        migration_data: soroban_sdk::Vec<Val>,
    ) {
        operator.require_auth();
        let contract_client = UpgradeableClient::new(&env, &contract_address);
        contract_client.upgrade(&wasm_hash, &operator);
        env.invoke_contract::<()>(
            &contract_address,
            &symbol_short!("migrate"),
            migration_data,
        );
    }
}

Guard upgrade_and_migrate with proper access control (e.g., Ownable from the access package with #[only_owner]).

If a rollback is required, the contract can be upgraded to a newer version where rollback-specific logic is defined and performed as a migration.

Examples: See the examples/ directory of the stellar-contracts repository for full working integration examples of both Upgradeable and UpgradeableMigratable, including the Upgrader pattern.

Access Control

The upgradeable module deliberately does not embed access control itself. You must define authorization in the _require_auth method of UpgradeableInternal or UpgradeableMigratableInternal. Forgetting this allows anyone to replace your contract's code.

Common access control options:

  • Ownable — single owner, simplest pattern (available in the access package)
  • AccessControl / RBAC — role-based, finer granularity (available in the access package)
  • Multisig or governance — for production contracts managing significant value

Upgrade Safety

Caveats

The framework structures the upgrade flow but does not perform deeper checks:

  • The new contract's constructor will not be invoked — any initialization must happen via migration or a separate call
  • There is no automatic check that the new contract includes an upgrade mechanism — an upgrade to a contract without one permanently loses upgradeability
  • Storage consistency is not verified — the new contract may inadvertently introduce storage mismatches

Storage compatibility

When replacing the WASM binary, existing storage is reinterpreted by the new code. Incompatible changes corrupt state:

  • Do not remove or rename existing storage keys
  • Do not change the type of values stored under existing keys
  • Adding new storage keys is safe
  • Soroban storage uses explicit string keys (e.g., symbol_short!("OWNER")), so key naming is critical — unlike EVM sequential slots, there is no ordering dependency

Version tracking

The derive macros automatically extract the crate version from Cargo.toml and embed it as the binary version in the WASM metadata, following SEP-49. This enables on-chain version tracking and can be used to coordinate upgrade paths.

Testing upgrade paths

Before upgrading a production contract:

  • Deploy V1 on a local Soroban testnet (e.g., stellar-cli with local network)
  • Write state with V1, upgrade to V2, and verify that all existing state reads correctly
  • Verify new functionality works as expected after the upgrade
  • Confirm access control — only authorized callers can invoke upgrade
  • Check that V2 includes an upgrade mechanism — otherwise upgradeability is permanently lost
  • Verify storage key compatibility — ensure no removals, renames, or type changes to existing keys
  • Test atomic upgrade-and-migrate using the Upgrader pattern if migration is needed
  • Manual review — there is no automated storage compatibility validation for Soroban; use the derive macros for safe upgrade scaffolding and rely on testnet testing

Stylus Upgrades

Contents

Stylus Upgrade Model

Stylus contracts run on Arbitrum as WebAssembly (WASM) programs alongside the EVM. They share the same state trie, storage model, and account system as Solidity contracts. Because of this, EVM proxy patterns work identically for Stylus — a Solidity proxy can delegate to a Stylus implementation and vice versa.

StylusSolidity
Proxy mechanismSame — delegatecall to implementation contractdelegatecall to implementation contract
Storage layout#[storage] fields map to the same EVM slots as equivalent Solidity structsSequential slot allocation per Solidity rules
EIP standardsERC-1967 storage slots, ERC-1822 proxiable UUIDSame
Context detectionlogic_flag boolean in a unique storage slot (no immutable support)address(this) stored as immutable
InitializationTwo-step: constructor sets logic_flag, then set_version() via proxyConstructor + initializer via proxy
ReactivationWASM contracts must be reactivated every 365 days or after a Stylus protocol upgradeNot applicable

Existing Solidity contracts can upgrade to a Stylus (Rust) implementation via proxy patterns. The #[storage] macro lays out fields in the EVM state trie identically to Solidity, so storage slots line up when type definitions match.

Proxy Patterns

OpenZeppelin Contracts for Stylus provides three proxy patterns:

PatternKey typesBest for
UUPSUUPSUpgradeable, IErc1822Proxiable, Erc1967ProxyMost projects — upgrade logic in the implementation, lighter proxy
BeaconBeaconProxy, UpgradeableBeaconMultiple proxies sharing one implementation — updating the beacon upgrades all proxies atomically
Basic ProxyErc1967Proxy, Erc1967UtilsLow-level building block for custom proxy patterns

UUPS

The implementation contract composes UUPSUpgradeable in its #[storage] struct alongside access control (e.g., Ownable). Integration requires:

  1. Add UUPSUpgradeable (and access control) as fields in the #[storage] struct
  2. Call self.uups.constructor() and initialize access control in the constructor
  3. Expose initialize calling self.uups.set_version() — invoked via proxy after deployment
  4. Implement IUUPSUpgradeable — upgrade_to_and_call guarded by access control, upgrade_interface_version delegating to self.uups
  5. Implement IErc1822Proxiable — proxiable_uuid delegating to self.uups

The proxy contract is a thin Erc1967Proxy with a constructor that takes the implementation address and initialization data, and a #[fallback] handler that delegates all calls.

Deploy the proxy with set_version as the initialization call data. Use cargo stylus deploy or a deployer contract. The initialization data is the ABI-encoded setVersion call:

let data = MyContractAbi::setVersionCall {}.abi_encode();
// Pass `data` as the proxy constructor's second argument at deployment time.

Beacon

Multiple BeaconProxy contracts point to a single UpgradeableBeacon that stores the current implementation address. Updating the beacon upgrades all proxies in one transaction.

Context detection (Stylus-specific)

Stylus does not support the immutable keyword. Instead of storing __self = address(this), UUPSUpgradeable uses a logic_flag boolean in a unique storage slot:

  • The implementation's constructor sets logic_flag = true in its own storage.
  • When code runs via a proxy (delegatecall), the proxy's storage does not contain this flag, so it reads as false.
  • only_proxy() checks this flag to ensure upgrade functions can only be called through the proxy, not directly on the implementation.

only_proxy() also verifies that the ERC-1967 implementation slot is non-zero and that the proxy-stored version matches the implementation's VERSION_NUMBER.

Examples: See the examples/ directory of the rust-contracts-stylus repository for full working integration examples of UUPS, Beacon, and related patterns.

Access Control

Upgrade functions must be guarded with access control. OpenZeppelin's Stylus contracts do not embed access control into the upgrade logic itself — you must add it in upgrade_to_and_call:

fn upgrade_to_and_call(&mut self, new_implementation: Address, data: Bytes) -> Result<(), Vec<u8>> {
    self.ownable.only_owner()?; // or any access control check
    self.uups.upgrade_to_and_call(new_implementation, data)?;
    Ok(())
}

Common options:

  • Ownable — single owner, simplest pattern
  • AccessControl / RBAC — role-based, finer granularity
  • Multisig or governance — for production contracts managing significant value

Upgrade Safety

Storage compatibility

Stylus #[storage] fields are laid out in the EVM state trie identically to Solidity. The same storage layout rules apply when upgrading:

  • Never reorder, remove, or change the type of existing storage fields
  • Never insert new fields before existing ones
  • Only append new fields at the end of the struct
  • ERC-1967 proxy storage slots are in high, standardized locations — they will not collide with implementation storage

One difference from Solidity: nested structs in Stylus #[storage] (e.g., composing Erc20, Ownable, UUPSUpgradeable as fields) are laid out with each nested struct starting at its own deterministic slot. This is consistent with regular struct nesting in Solidity, but not with Solidity's inheritance-based flat layout where all inherited variables share a single sequential slot range.

Initialization safety

  • The implementation constructor sets logic_flag and any implementation-only state. It runs once at implementation deployment.
  • set_version() must be called via the proxy (during deployment or via upgrade_to_and_call) to write the VERSION_NUMBER into the proxy's storage.
  • If additional initialization is needed (ownership, token supply), expose a protected initialization function and include set_version() in it.
  • Failing to initialize properly can result in orphaned contracts with no owner, uninitialized state, or denied future upgrades.

UUPS upgrade checks

The UUPS implementation enforces three safety checks:

  1. Access control — restrict upgrade_to_and_call (e.g., self.ownable.only_owner())
  2. Proxy context enforcement — only_proxy() reverts if the call is not via delegatecall
  3. Proxiable UUID validation — proxiable_uuid() must return the ERC-1967 implementation slot, confirming UUPS compatibility

Reactivation

Stylus WASM contracts must be reactivated once per year (365 days) or after any Stylus protocol upgrade. Reactivation can be done using cargo-stylus or the ArbWasm precompile. If a contract is not reactivated, it becomes uncallable. This is orthogonal to proxy upgrades but must be factored into maintenance planning.

Testing upgrade paths

Before upgrading a production contract:

  • Deploy V1 implementation and proxy on a local Arbitrum devnet
  • Write state with V1, upgrade to V2 via upgrade_to_and_call, and verify that all existing state reads correctly
  • Verify new functionality works as expected after the upgrade
  • Confirm access control — only authorized callers can invoke upgrade_to_and_call
  • Check storage layout — ensure no reordering, removal, or type changes to existing fields
  • Verify VERSION_NUMBER is incremented in the new implementation
  • Test reactivation — ensure the upgraded contract can be reactivated
  • Manual review — there is no automated storage layout validation for Stylus Rust contracts; rely on struct comparison and devnet testing

Sponsors

Details

Marketplace
OpenZeppelin/openzeppelin-skills
Category
Community