OpenZeppelin Contracts for Stellar 项目设置

本文提供了一个关于如何使用OpenZeppelin Contracts为Stellar/Soroban智能合约项目进行开发环境设置的指南。它涵盖了安装Rust工具链和Soroban CLI、创建新项目以及配置OpenZeppelin依赖项的步骤,并介绍了Soroban的导入约定和合约模式。

Stellar 设置

Soroban/Stellar 开发设置

安装 Rust 工具链 (v1.84.0+) 和 Soroban WASM 目标:

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

安装 Stellar CLI:

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

创建一个新的 Soroban 项目:

stellar contract init my_project

这将创建一个 Cargo workspace,合约位于 contracts/*/ 中。

OpenZeppelin 依赖项

在添加之前,请从 stellar-contracts repo 查找当前版本。由于该库处于积极开发中,请使用 = 精确锁定版本。

将 OpenZeppelin crates 添加到 Cargo.toml[workspace.dependencies] 下:

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

然后,在每个合约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 }

可用 crates:stellar-accessstellar-accountsstellar-contract-utilsstellar-fee-abstractionstellar-governancestellar-macrosstellar-tokens

仅添加合约实际使用的 crates。stellar-macros 提供了 proc-macro 属性(例如 #[when_not_paused]#[only_owner]#[derive(Upgradeable)]),并且在大多数合约中都需要。

代码模式

导入使用下划线作为 crate 根(Rust 约定):

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;

合约在 struct 上使用 #[contract],在 impl 块上使用 #[contractimpl](来自 soroban_sdk):

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

##[contract]
pub struct MyToken;

##[contractimpl]
impl MyToken {
    // 在此处实现 trait 方法
}

trait 实现是每个 trait 独立的 impl 块(例如,FungibleTokenPausable)。守卫宏如 #[when_not_paused]#[only_owner] 修饰单个函数。

平台注意事项

  • 在 Stellar 中,读取操作是免费的。 优化以最小化写入;读取和计算都很便宜。优先选择清晰、可读的代码,而非微优化。
  • 实例存储 TTL 扩展是开发人员的责任。 OpenZeppelin 库处理其他存储条目的 TTL 扩展,但合约必须扩展其自身的 instance 存储条目以防止过期。

构建和测试

将合约构建为 WASM:

stellar contract build

这是 cargo build --target wasm32v1-none --release 的快捷方式。输出文件位于 target/wasm32v1-none/release/

运行测试:

cargo test

soroban-sdk testutils 会自动为 crate 内的单元测试启用。

  • 原文链接: github.com/OpenZeppelin/...
  • 登链社区 AI 助手,为大家转译优秀英文文章,如有翻译不通的地方,还请包涵~
点赞 0
收藏 0
分享
本文参与登链社区写作激励计划 ,好文好收益,欢迎正在阅读的你也加入。

0 条评论

请先 登录 后评论
OpenZeppelin
OpenZeppelin
江湖只有他的大名,没有他的介绍。