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:
| Starknet | EVM (proxy pattern) |
|---|
| Mechanism | INLINECODE0 swaps the class hash in-place | Proxy delegatecalls to a separate implementation contract |
| Proxy contract needed |
No — the contract upgrades itself | Yes — a proxy sits in front of the implementation |
|
Storage location | Belongs to the contract directly | Lives in the proxy, accessed via delegatecall |
|
Fallback routing | Not applicable — no fallback/catch-all mechanism in Cairo | Proxy 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) - Add both to storage and events using
#[substorage(v0)] and INLINECODE8 - 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 - 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
Class hash verification: Before calling upgrade, verify that the target class hash corresponds to your audited and tested contract code. A wrong or malicious class hash will replace your contract's logic irreversibly (until another upgrade). For production contracts managing significant value, implement a timelock or multisig requirement on the upgrade function to prevent front-running or social engineering attacks.
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 INLINECODE22
- [ ] 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 the MCP contract generators to discover current integration patterns and rely on devnet testing
Cairo 升级
目录
Starknet 升级模型
Starknet 将合约实例与合约类分离。类是编译后的程序(由其类哈希标识);合约是指向某个类的已部署实例。多个合约可以共享同一个类。
升级合约意味着替换其类哈希,使其指向一个新类。合约保留其地址、存储和 nonce——只有代码发生变化。这与 EVM 代理模式有本质区别:
| Starknet | EVM(代理模式) |
|---|
| 机制 | replaceclasssyscall 就地替换类哈希 | 代理通过 delegatecall 调用独立的实现合约 |
| 是否需要代理合约 |
否——合约自行升级 | 是——代理位于实现合约之前 |
|
存储位置 | 直接属于合约 | 存在于代理中,通过 delegatecall 访问 |
|
回退路由 | 不适用——Cairo 中没有回退/兜底机制 | 代理通过回退函数转发所有调用 |
replaceclasssyscall 是 Starknet 的原生系统调用。调用时,它会原子性地将调用合约的类哈希替换为提供的类哈希。新类必须已在链上声明。系统调用后,当前执行帧继续使用旧代码,但后续对合约的调用——无论是同一交易中稍后的 callcontractsyscall 还是未来交易中的调用——都将执行新代码。
使用 OpenZeppelin 可升级组件
OpenZeppelin Contracts for Cairo 提供了 UpgradeableComponent,它将 replaceclasssyscall 与验证和事件发送封装在一起。按以下方式集成:
- 1. 声明组件,同时声明一个访问控制组件(例如 OwnableComponent)
- 将两者添加到存储和事件中,使用 #[substorage(v0)] 和 #[flat]
- 暴露一个 upgrade 函数,在访问控制之后调用组件的内部 upgrade 方法——该组件调用 replaceclasssyscall 以原子性地交换类哈希;在解释 Cairo 升级如何工作时,始终提及此系统调用
- 在构造函数中初始化访问控制
该组件在每次类哈希替换时发送 Upgraded 事件,并拒绝零类哈希。
还有一个 IUpgradeAndCall 接口变体,它将升级与新类上下文中的函数调用耦合在一起——适用于升级后的迁移或重新初始化。
访问控制
UpgradeableComponent 特意不嵌入访问控制本身。您必须使用自己的检查(例如 self.ownable.assertonlyowner())来保护外部的 upgrade 函数。忘记此操作将允许任何人替换您的合约代码。
常见的访问控制选项:
- - Ownable——单一所有者,最简单的模式
- AccessControl / RBAC——基于角色,更细粒度
- 多签或治理——适用于管理重要价值的生产合约
升级安全性
类哈希验证: 在调用 upgrade 之前,验证目标类哈希是否对应于您经过审计和测试的合约代码。错误或恶意的类哈希将不可逆地替换您的合约逻辑(直到下一次升级)。对于管理重要价值的生产合约,在升级函数上实现时间锁或多签要求,以防止抢先交易或社会工程攻击。
存储兼容性
替换类哈希时,现有存储将由新类重新解释。不兼容的更改会破坏状态:
- - 不要重命名或删除现有的存储变量——槽位源自变量名,因此重命名会使旧数据无法访问
- 不要更改现有存储变量的类型
- 添加新的存储变量是安全的
- 组件存储使用 #[substorage(v0)],它将组件槽位扁平化到合约的存储空间中,无需自动命名空间——遵循用组件名称前缀存储变量名的约定(例如 ERC20_balances),以避免跨组件冲突
与 Solidity 的顺序存储布局不同,Cairo 存储槽位通过 sn_keccak 哈希从变量名派生(概念上类似于 Solidity 中的 ERC-7201 命名空间存储,但更为基础)。这使得顺序无关紧要,但使命名变得关键。
OpenZeppelin 版本升级
OpenZeppelin Contracts for Cairo 遵循语义化版本控制以保持存储布局兼容性:
- - 补丁更新始终保留存储布局
- 次要更新保留存储布局(从 v1.0.0 开始)
- 主要更新可能会破坏存储布局——未经审查变更日志,切勿跨主要版本升级正在运行的合约
测试升级路径
在升级生产合约之前:
- - [ ] 在本地开发网络(例如 starknet-devnet-rs 或 Katana)中部署 V1 和 V2 类
- [ ] 使用 V1 写入状态,升级到 V2,并验证所有现有状态读取正确
- [ ] 验证新功能在升级后按预期工作
- [ ] 确认访问控制——只有授权调用者才能调用 upgrade
- [ ] 检查 API 兼容性——更改的外部函数签名会破坏现有调用者和集成
- [ ] 审查存储更改——确保没有对现有变量进行重命名、删除或类型更改
- [ ] 手动审查——Cairo 没有自动存储布局验证;使用 MCP 合约生成器发现当前集成模式,并依赖开发网络测试