near-smart-contracts

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

NEAR Smart Contracts Development

NEAR智能合约开发

Comprehensive guide for developing secure and efficient smart contracts on NEAR Protocol using Rust and the NEAR SDK (v5.x).
使用Rust和NEAR SDK(v5.x)在NEAR Protocol上开发安全高效智能合约的综合指南。

When to Apply

适用场景

Reference these guidelines when:
  • Writing new NEAR smart contracts in Rust
  • Reviewing existing contract code for security and optimization
  • Implementing cross-contract calls and callbacks
  • Managing contract state and storage
  • Testing and deploying NEAR contracts
  • Optimizing gas usage and performance
在以下场景中参考本指南:
  • 用Rust编写新的NEAR智能合约
  • 评审现有合约代码的安全性与优化空间
  • 实现跨合约调用及回调
  • 管理合约状态与存储
  • 测试与部署NEAR合约
  • 优化Gas消耗与性能

Getting Started

入门指南

Prerequisites

前置条件

Install the required tools before starting development:
bash
undefined
开始开发前安装所需工具:
bash
undefined

Install Rust (if not already installed)

Install Rust (if not already installed)

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

Add wasm32 target for compiling contracts

Add wasm32 target for compiling contracts

rustup target add wasm32-unknown-unknown
rustup target add wasm32-unknown-unknown

Install cargo-near (build, deploy, and manage contracts)

Install cargo-near (build, deploy, and manage contracts)

Install near-cli-rs (interact with NEAR network)

Install near-cli-rs (interact with NEAR network)

Create a New Project

创建新项目

CRITICAL: ALWAYS run
cargo near new
to create new projects. NEVER manually create Cargo.toml, lib.rs, or any project files. The command generates all required files with correct configurations.
bash
undefined
重要提示:请始终使用
cargo near new
创建新项目。切勿手动创建Cargo.toml、lib.rs或任何项目文件。该命令会生成所有配置正确的必要文件。
bash
undefined

REQUIRED: Create a new contract project using the official template

REQUIRED: Create a new contract project using the official template

cargo near new my-contract
cargo near new my-contract

Navigate to project directory

Navigate to project directory

cd my-contract
cd my-contract

Build the contract

Build the contract

cargo near build
cargo near build

Run tests

Run tests

cargo test

**Why `cargo near new` is mandatory:**
- Generates correct `Cargo.toml` with proper dependencies and build settings
- Creates proper project structure with `src/lib.rs` template
- Includes integration test setup in `tests/` directory
- Configures release profile with `overflow-checks = true`
- Sets up correct crate-type for WASM compilation
- Avoids common configuration mistakes that cause build failures

**DO NOT:**
- Manually create `Cargo.toml`
- Manually create `src/lib.rs`
- Copy-paste project structure from examples
- Skip this step and create files directly
cargo test

**为什么必须使用`cargo near new`:**
- 生成配置正确的`Cargo.toml`,包含合适的依赖项和构建设置
- 创建带有`src/lib.rs`模板的标准项目结构
- 包含`tests/`目录下的集成测试设置
- 配置发布配置文件并启用`overflow-checks = true`
- 设置正确的WASM编译crate类型
- 避免导致构建失败的常见配置错误

**请勿:**
- 手动创建`Cargo.toml`
- 手动创建`src/lib.rs`
- 从示例中复制粘贴项目结构
- 跳过此步骤直接创建文件

Project Structure

项目结构

my-contract/
├── Cargo.toml          # Dependencies and project config
├── src/
│   └── lib.rs          # Main contract code
├── tests/              # Integration tests
│   └── test_basics.rs
└── README.md
my-contract/
├── Cargo.toml          # 依赖项与项目配置
├── src/
│   └── lib.rs          # 主合约代码
├── tests/              # 集成测试
│   └── test_basics.rs
└── README.md

Deploy to Testnet

部署到测试网

bash
undefined
bash
undefined

Create a testnet account (if needed)

Create a testnet account (if needed)

near account create-account sponsor-by-faucet-service my-contract.testnet autogenerate-new-keypair save-to-keychain network-config testnet create
near account create-account sponsor-by-faucet-service my-contract.testnet autogenerate-new-keypair save-to-keychain network-config testnet create

Build in release mode

Build in release mode

cargo near build --release
cargo near build --release

Deploy to testnet

Deploy to testnet

cargo near deploy my-contract.testnet without-init-call network-config testnet sign-with-keychain send
undefined
cargo near deploy my-contract.testnet without-init-call network-config testnet sign-with-keychain send
undefined

Rule Categories by Priority

按优先级划分的规则类别

PriorityCategoryImpactPrefix
1Security & SafetyCRITICAL
security-
2Contract StructureHIGH
structure-
3State ManagementHIGH
state-
4Cross-Contract CallsMEDIUM-HIGH
xcc-
5Contract UpgradesMEDIUM-HIGH
upgrade-
6Chain SignaturesMEDIUM-HIGH
chain-
7Gas OptimizationMEDIUM
gas-
8Yield & ResumeMEDIUM
yield-
9TestingMEDIUM
testing-
10Best PracticesMEDIUM
best-
优先级类别影响程度前缀
1安全与防护关键
security-
2合约结构
structure-
3状态管理
state-
4跨合约调用中高
xcc-
5合约升级中高
upgrade-
6链签名中高
chain-
7Gas优化
gas-
8暂停与恢复
yield-
9测试
testing-
10最佳实践
best-

1. Security & Safety (CRITICAL)

1. 安全与防护(关键)

  • security-storage-checks
    - Always validate storage operations and check deposits
  • security-access-control
    - Implement proper access control using
    predecessor_account_id
  • security-reentrancy
    - Protect against reentrancy attacks (update state before external calls)
  • security-overflow
    - Use
    overflow-checks = true
    in Cargo.toml to prevent overflow
  • security-callback-validation
    - Validate callback results and handle failures
  • security-private-callbacks
    - Mark callbacks as
    #[private]
    to prevent external calls
  • security-yoctonear-validation
    - Validate attached deposits with
    #[payable]
    functions
  • security-sybil-resistance
    - Implement minimum deposit checks to prevent spam
  • security-storage-checks
    - 始终验证存储操作并检查押金
  • security-access-control
    - 使用
    predecessor_account_id
    实现适当的访问控制
  • security-reentrancy
    - 防止重入攻击(外部调用前更新状态)
  • security-overflow
    - 在Cargo.toml中启用
    overflow-checks = true
    以防止溢出
  • security-callback-validation
    - 验证回调结果并处理失败情况
  • security-private-callbacks
    - 将回调标记为
    #[private]
    以防止外部调用
  • security-yoctonear-validation
    - 对带有
    #[payable]
    注解的函数验证附带的押金
  • security-sybil-resistance
    - 实施最低押金检查以防止垃圾信息攻击

2. Contract Structure (HIGH)

2. 合约结构(高)

  • structure-near-bindgen
    - Use
    #[near(contract_state)]
    macro for contract struct (replaces old
    #[near_bindgen]
    )
  • structure-initialization
    - Implement proper initialization with
    #[init]
    patterns
  • structure-versioning
    - Plan for contract upgrades with versioning mechanisms
  • structure-events
    - Use
    env::log_str()
    and structured event logging (NEP-297)
  • structure-standards
    - Follow NEAR Enhancement Proposals (NEPs) for standards
  • structure-serializers
    - Use
    #[near(serializers = [json, borsh])]
    for data structs
  • structure-panic-default
    - Use
    #[derive(PanicOnDefault)]
    to require initialization
  • structure-near-bindgen
    - 使用
    #[near(contract_state)]
    宏定义合约结构体(替代旧版
    #[near_bindgen]
  • structure-initialization
    - 使用
    #[init]
    模式实现正确的初始化逻辑
  • structure-versioning
    - 规划带有版本机制的合约升级方案
  • structure-events
    - 使用
    env::log_str()
    和结构化事件日志(NEP-297)
  • structure-standards
    - 遵循NEAR改进提案(NEPs)中的标准
  • structure-serializers
    - 对数据结构体使用
    #[near(serializers = [json, borsh])]
  • structure-panic-default
    - 使用
    #[derive(PanicOnDefault)]
    强制要求初始化

3. State Management (HIGH)

3. 状态管理(高)

  • state-collections
    - Use SDK collections from
    near_sdk::store
    :
    IterableMap
    ,
    IterableSet
    ,
    Vector
    ,
    LookupMap
    ,
    LookupSet
    ,
    UnorderedMap
    ,
    UnorderedSet
    ,
    TreeMap
  • state-serialization
    - Use Borsh for state, JSON for external interfaces
  • state-lazy-loading
    - Use SDK collections for lazy loading to save gas (loaded on-demand, not all at once)
  • state-pagination
    - Implement pagination with
    .skip()
    and
    .take()
    for large datasets
  • state-migration
    - Plan state migration strategies using versioning
  • state-storage-cost
    - Remember: 1 NEAR ≈ 100kb storage, contracts pay for their storage
  • state-unique-prefixes
    - Use unique byte prefixes for all collections (avoid collisions)
  • state-native-vs-sdk
    - Native collections (Vec, HashMap) load all data; use only for <100 entries
  • state-collections
    - 使用
    near_sdk::store
    中的SDK集合:
    IterableMap
    IterableSet
    Vector
    LookupMap
    LookupSet
    UnorderedMap
    UnorderedSet
    TreeMap
  • state-serialization
    - 状态使用Borsh序列化,外部接口使用JSON
  • state-lazy-loading
    - 使用SDK集合实现懒加载以节省Gas(按需加载,而非一次性全部加载)
  • state-pagination
    - 对大型数据集使用
    .skip()
    .take()
    实现分页
  • state-migration
    - 使用版本化规划状态迁移策略
  • state-storage-cost
    - 注意:1 NEAR ≈ 100kb存储,合约需自行支付存储费用
  • state-unique-prefixes
    - 为所有集合使用唯一字节前缀(避免冲突)
  • state-native-vs-sdk
    - 原生集合(Vec、HashMap)会加载所有数据;仅适用于条目数<100的场景

4. Cross-Contract Calls (MEDIUM-HIGH)

4. 跨合约调用(中高)

  • xcc-promise-chaining
    - Chain promises correctly
  • xcc-callback-handling
    - Handle all callback scenarios (success, failure)
  • xcc-gas-management
    - Allocate appropriate gas for cross-contract calls
  • xcc-error-handling
    - Implement robust error handling
  • xcc-result-unwrap
    - Never unwrap promise results without checks
  • xcc-promise-chaining
    - 正确链式调用Promise
  • xcc-callback-handling
    - 处理所有回调场景(成功、失败)
  • xcc-gas-management
    - 为跨合约调用分配适当的Gas
  • xcc-error-handling
    - 实现健壮的错误处理逻辑
  • xcc-result-unwrap
    - 切勿在未检查的情况下解包Promise结果

5. Contract Upgrades & Migration (MEDIUM-HIGH)

5. 合约升级与迁移(中高)

  • upgrade-migration
    - Use enums for state versioning and implement
    migrate
    method with
    #[init(ignore_state)]
  • upgrade-self-update
    - Pattern for contracts that can update themselves programmatically
  • upgrade-cleanup-old-state
    - Always remove old state structures to free storage
  • upgrade-dao-controlled
    - Use multisig or DAO for production upgrade governance
  • upgrade-migration
    - 使用枚举进行状态版本化,并使用
    #[init(ignore_state)]
    实现
    migrate
    方法
  • upgrade-self-update
    - 支持合约以编程方式自我更新的模式
  • upgrade-cleanup-old-state
    - 始终移除旧状态结构以释放存储空间
  • upgrade-dao-controlled
    - 生产环境中使用多签或DAO进行升级治理

6. Chain Signatures (MEDIUM-HIGH)

6. 链签名(中高)

  • chain-signatures
    - Derive foreign blockchain addresses, request MPC signatures, and build multichain transactions
  • chain-callback-handling
    - Handle MPC signature callbacks properly
  • chain-gas-allocation
    - Allocate sufficient gas for MPC calls (yield/resume pattern)
  • chain-signatures
    - 派生外部区块链地址、请求MPC签名并构建多链交易
  • chain-callback-handling
    - 正确处理MPC签名回调
  • chain-gas-allocation
    - 为MPC调用分配足够的Gas(暂停/恢复模式)

7. Gas Optimization (MEDIUM)

7. Gas优化(中)

  • gas-batch-operations
    - Batch operations to reduce transaction costs
  • gas-minimal-state-reads
    - Minimize state reads and writes (cache in memory)
  • gas-efficient-collections
    - Choose appropriate collection types (LookupMap vs IterableMap)
  • gas-view-functions
    - Mark read-only functions as view (
    &self
    in Rust)
  • gas-avoid-cloning
    - Avoid unnecessary cloning of large data structures
  • gas-early-validation
    - Use
    require!
    early to save gas on invalid inputs
  • gas-prepaid-gas
    - Attach appropriate gas for cross-contract calls (recommended: 30 TGas)
  • gas-batch-operations
    - 批量操作以降低交易成本
  • gas-minimal-state-reads
    - 最小化状态读写(在内存中缓存)
  • gas-efficient-collections
    - 选择合适的集合类型(LookupMap vs IterableMap)
  • gas-view-functions
    - 将只读函数标记为view(Rust中使用
    &self
  • gas-avoid-cloning
    - 避免对大型数据结构进行不必要的克隆
  • gas-early-validation
    - 尽早使用
    require!
    以在无效输入时节省Gas
  • gas-prepaid-gas
    - 为跨合约调用附加适当的Gas(推荐:30 TGas)

8. Yield & Resume (MEDIUM)

8. 暂停与恢复(中)

  • yield-resume
    - Create yielded promises, signal resume, handle timeouts, and manage state between yield/resume
  • yield-gatekeeping
    - Protect resume methods from unauthorized callers
  • yield-resume
    - 创建暂停的Promise、触发恢复、处理超时,并管理暂停/恢复之间的状态
  • yield-gatekeeping
    - 保护恢复方法免受未授权调用者的访问

9. Testing (MEDIUM)

9. 测试(中)

  • testing-integration-tests
    - Use
    near-sandbox
    +
    near-api
    for integration tests
  • testing-unit-tests
    - Write comprehensive unit tests with mock contexts
  • testing-sandbox
    - Test with local sandbox environment before testnet/mainnet
  • testing-edge-cases
    - Test boundary conditions, overflow, and empty states
  • testing-gas-profiling
    - Profile gas usage in integration tests
  • testing-cross-contract
    - Test cross-contract calls and callbacks thoroughly
  • testing-failure-scenarios
    - Test promise failures and timeout scenarios
  • testing-time-travel
    - Use
    sandbox.fast_forward()
    for time-sensitive tests
  • testing-integration-tests
    - 使用
    near-sandbox
    +
    near-api
    进行集成测试
  • testing-unit-tests
    - 编写带有模拟上下文的全面单元测试
  • testing-sandbox
    - 在测试网/主网部署前使用本地沙箱环境测试
  • testing-edge-cases
    - 测试边界条件、溢出及空状态
  • testing-gas-profiling
    - 在集成测试中分析Gas消耗
  • testing-cross-contract
    - 全面测试跨合约调用及回调
  • testing-failure-scenarios
    - 测试Promise失败及超时场景
  • testing-time-travel
    - 使用
    sandbox.fast_forward()
    进行时间敏感型测试

10. Best Practices (MEDIUM)

10. 最佳实践(中)

  • best-contract-tools
    - Use
    near-sdk-contract-tools
    for NEP standards (FT, NFT, etc.) and NEP-297 structured events
  • best-panic-messages
    - Provide clear, actionable panic messages
  • best-logging
    - Use
    env::log_str()
    for debugging and event emission
  • best-documentation
    - Document public methods, parameters, and complex logic
  • best-error-types
    - Define custom error types or use descriptive strings
  • best-constants
    - Use constants for magic numbers and configuration
  • best-require-macro
    - Use
    require!
    instead of
    assert!
    for better error messages
  • best-promise-return
    - Return promises from cross-contract calls for proper tracking
  • best-sdk-crates
    - Reuse SDK-exported crates (borsh, serde, base64, etc.)
  • best-account-id-encoding
    - Encode AccountIds in base32 for 40% storage savings
  • best-contract-tools
    - 使用
    near-sdk-contract-tools
    实现NEP标准(FT、NFT等)及NEP-297结构化事件
  • best-panic-messages
    - 提供清晰、可操作的panic提示信息
  • best-logging
    - 使用
    env::log_str()
    进行调试和事件发射
  • best-documentation
    - 为公共方法、参数及复杂逻辑编写文档
  • best-error-types
    - 定义自定义错误类型或使用描述性字符串
  • best-constants
    - 使用常量替代魔法数字和配置值
  • best-require-macro
    - 使用
    require!
    而非
    assert!
    以获得更好的错误信息
  • best-promise-return
    - 从跨合约调用中返回Promise以实现正确追踪
  • best-sdk-crates
    - 复用SDK导出的crate(borsh、serde、base64等)
  • best-account-id-encoding
    - 使用base32编码AccountId以节省40%的存储空间

How to Use

使用方法

Read individual rule files for detailed explanations and code examples:
rules/security-storage-checks.md
rules/structure-near-bindgen.md
rules/state-collections.md
rules/xcc-promise-chaining.md
rules/upgrade-migration.md
rules/chain-signatures.md
rules/yield-resume.md
rules/best-contract-tools.md
rules/testing-integration-tests.md
Each rule file contains:
  • Brief explanation of why it matters
  • Incorrect code example with explanation
  • Correct code example with explanation
  • Additional context and NEAR-specific considerations
阅读单个规则文件以获取详细说明和代码示例:
rules/security-storage-checks.md
rules/structure-near-bindgen.md
rules/state-collections.md
rules/xcc-promise-chaining.md
rules/upgrade-migration.md
rules/chain-signatures.md
rules/yield-resume.md
rules/best-contract-tools.md
rules/testing-integration-tests.md
每个规则文件包含:
  • 规则重要性的简要说明
  • 错误代码示例及解释
  • 正确代码示例及解释
  • 额外背景信息及NEAR特定注意事项

Latest Tools & Versions

最新工具与版本

Development Tools

开发工具

  • cargo-near: Latest - Build, deploy, and manage contracts (
    cargo near build
    ,
    cargo near deploy
    )
  • near-cli-rs: Latest - Command-line interface for NEAR (
    near contract call
    ,
    near contract view
    )
  • rustc: Latest stable - Rust compiler
  • near-sandbox: Latest - Local sandbox environment for integration testing
  • near-api-rs: Latest - Rust API client for interacting with NEAR (replaces near-workspaces-rs for tests)
  • omni-transaction-rs: Latest - Build transactions for multiple blockchains (Bitcoin, Ethereum, etc.)
  • cargo-near:最新版本 - 构建、部署及管理合约(
    cargo near build
    cargo near deploy
  • near-cli-rs:最新版本 - NEAR命令行界面(
    near contract call
    near contract view
  • rustc:最新稳定版 - Rust编译器
  • near-sandbox:最新版本 - 用于集成测试的本地沙箱环境
  • near-api-rs:最新版本 - 用于与NEAR交互的Rust API客户端(替代测试用的near-workspaces-rs)
  • omni-transaction-rs:最新版本 - 为多链(比特币、以太坊等)构建交易

SDK Versions

SDK版本

  • near-sdk-rs: v5.x (v6.x coming with structured errors support)
  • near-sdk-contract-tools: Latest - Derive macros for NEP standards (FT, NFT, Storage Management)
  • near-sdk-rs:v5.x(v6.x即将发布,支持结构化错误)
  • near-sdk-contract-tools:最新版本 - 用于NEP标准(FT、NFT、存储管理)的派生宏

Key Features

核心特性

  • Unified macro syntax:
    #[near(contract_state)]
    replaces
    #[near_bindgen]
    + derives
  • Flexible serialization:
    #[near(serializers = [json, borsh])]
    for data structs
  • Store collections:
    near_sdk::store::IterableMap
    ,
    IterableSet
    ,
    LookupMap
    ,
    LookupSet
    ,
    Vector
    ,
    UnorderedMap
    ,
    UnorderedSet
    ,
    TreeMap
  • Simplified cross-contract calls: High-level promise API with
    Promise::new()
    and
    .then()
  • Built-in NEP support: FT (NEP-141), NFT (NEP-171), and other standards
  • Result handling:
    #[handle_result]
    for methods returning
    Result<T, E>
    without panicking
  • Yield/Resume: Contracts can yield execution and wait for external services to resume
  • Chain Signatures: Sign transactions for other blockchains (Bitcoin, Ethereum, Solana, etc.)
  • Contract Tools: Derive macros for Owner, Pause, Role-based access control patterns
  • 统一宏语法
    #[near(contract_state)]
    替代
    #[near_bindgen]
    +派生注解
  • 灵活序列化:对数据结构体使用
    #[near(serializers = [json, borsh])]
  • 存储集合
    near_sdk::store::IterableMap
    IterableSet
    LookupMap
    LookupSet
    Vector
    UnorderedMap
    UnorderedSet
    TreeMap
  • 简化跨合约调用:使用
    Promise::new()
    .then()
    的高级Promise API
  • 内置NEP支持:FT(NEP-141)、NFT(NEP-171)及其他标准
  • 结果处理
    #[handle_result]
    用于返回
    Result<T, E>
    的方法,避免panic
  • 暂停/恢复:合约可暂停执行并等待外部服务恢复
  • 链签名:为其他区块链(比特币、以太坊、Solana等)签署交易
  • 合约工具:用于所有者、暂停、基于角色的访问控制模式的派生宏

Resources

资源链接

Storage Costs Reference

存储成本参考

StorageCostNotes
1 byte0.00001 NEAR~10kb per 0.1 NEAR
100 KB~1 NEARApproximate reference
AccountId64+ bytesCan save 40% with base32 encoding
Contract codeVariablePaid by contract account
存储资源成本说明
1字节0.00001 NEAR约0.1 NEAR可存储10kb数据
100 KB~1 NEAR近似参考值
AccountId64+字节使用base32编码可节省40%空间
合约代码可变由合约账户支付费用

SDK Collections Reference

SDK集合参考

CollectionIterableClearOrderedRangeUse Case
Vector
YesYesYesYesOrdered list with index access
LookupMap
NoNoNoNoFast key-value, no iteration needed
LookupSet
NoNoNoNoFast membership checks
IterableMap
YesYesYesNoKey-value with iteration
IterableSet
YesYesYesNoSet with iteration
UnorderedMap
YesYesNoNoKey-value, unordered iteration
UnorderedSet
YesYesNoNoSet, unordered iteration
TreeMap
YesYesYesYesSorted key-value with range queries
集合类型可迭代可清空有序支持范围查询适用场景
Vector
带索引访问的有序列表
LookupMap
快速键值对,无需迭代
LookupSet
快速成员检查
IterableMap
支持迭代的键值对
IterableSet
支持迭代的集合
UnorderedMap
键值对,无序迭代
UnorderedSet
集合,无序迭代
TreeMap
支持范围查询的有序键值对