solana-development

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Solana Development

Solana 开发

Build Solana programs using Anchor framework or native Rust. Both approaches share the same core concepts (accounts, PDAs, CPIs, tokens) but differ in syntax and abstraction level.
使用Anchor框架或原生Rust构建Solana程序。两种方法共享相同的核心概念(账户、PDA、CPI、代币),但在语法和抽象层级上有所不同。

Quick Start

快速开始

Recommended: Anchor Framework

推荐方案:Anchor框架

Anchor provides macros and tooling that reduce boilerplate and increase developer productivity:
rust
use anchor_lang::prelude::*;

declare_id!("YourProgramID");

#[program]
pub mod my_program {
    use super::*;

    pub fn initialize(ctx: Context<Initialize>, data: u64) -> Result<()> {
        ctx.accounts.account.data = data;
        Ok(())
    }
}

#[derive(Accounts)]
pub struct Initialize<'info> {
    #[account(init, payer = user, space = 8 + 8)]
    pub account: Account<'info, MyAccount>,
    #[account(mut)]
    pub user: Signer<'info>,
    pub system_program: Program<'info, System>,
}

#[account]
pub struct MyAccount {
    pub data: u64,
}
When to use Anchor:
  • Building DeFi, NFT, or standard programs
  • Need TypeScript client generation with IDL
  • Want faster development with less boilerplate
  • Following common Solana patterns
  • New to Solana development
Installation:
bash
cargo install --git https://github.com/coral-xyz/anchor avm --locked --force
avm install latest
avm use latest
anchor --version
Create project:
bash
anchor init my_project
cd my_project
anchor build
anchor test
→ See references/anchor.md for complete Anchor guide
Anchor提供宏和工具来减少样板代码,提升开发者效率:
rust
use anchor_lang::prelude::*;

declare_id!("YourProgramID");

#[program]
pub mod my_program {
    use super::*;

    pub fn initialize(ctx: Context<Initialize>, data: u64) -> Result<()> {
        ctx.accounts.account.data = data;
        Ok(())
    }
}

#[derive(Accounts)]
pub struct Initialize<'info> {
    #[account(init, payer = user, space = 8 + 8)]
    pub account: Account<'info, MyAccount>,
    #[account(mut)]
    pub user: Signer<'info>,
    pub system_program: Program<'info, System>,
}

#[account]
pub struct MyAccount {
    pub data: u64,
}
何时使用Anchor:
  • 构建DeFi、NFT或标准程序
  • 需要基于IDL生成TypeScript客户端
  • 希望通过更少的样板代码实现更快开发
  • 遵循通用Solana开发模式
  • 刚接触Solana开发
安装步骤:
bash
cargo install --git https://github.com/coral-xyz/anchor avm --locked --force
avm install latest
avm use latest
anchor --version
创建项目:
bash
anchor init my_project
cd my_project
anchor build
anchor test
→ 完整Anchor指南请查看 references/anchor.md

Advanced: Native Rust

进阶方案:原生Rust

Native Rust provides maximum control, optimization potential, and deeper understanding of Solana's runtime:
rust
use solana_program::{
    account_info::AccountInfo,
    entrypoint,
    entrypoint::ProgramResult,
    pubkey::Pubkey,
    msg,
};

entrypoint!(process_instruction);

pub fn process_instruction(
    program_id: &Pubkey,
    accounts: &[AccountInfo],
    instruction_data: &[u8],
) -> ProgramResult {
    msg!("Processing instruction");
    // Manual account parsing and validation
    // Manual instruction routing
    Ok(())
}
When to use Native Rust:
  • Need maximum compute efficiency (CU optimization critical)
  • Require advanced features (versioned transactions, durable nonces, ALTs)
  • Learning Solana fundamentals from first principles
  • Building highly optimized or specialized programs
  • Framework overhead is unacceptable
Setup:
bash
cargo new my_program --lib
cd my_program
原生Rust提供最大的控制权、优化潜力,能让你更深入理解Solana的运行时机制:
rust
use solana_program::{
    account_info::AccountInfo,
    entrypoint,
    entrypoint::ProgramResult,
    pubkey::Pubkey,
    msg,
};

entrypoint!(process_instruction);

pub fn process_instruction(
    program_id: &Pubkey,
    accounts: &[AccountInfo],
    instruction_data: &[u8],
) -> ProgramResult {
    msg!("Processing instruction");
    // Manual account parsing and validation
    // Manual instruction routing
    Ok(())
}
何时使用原生Rust:
  • 需要极致的计算效率(CU优化至关重要)
  • 需要使用进阶功能(版本化交易、持久化随机数、ALT)
  • 从基础原理学习Solana核心知识
  • 构建高度优化或特殊用途的程序
  • 无法接受框架带来的开销
设置步骤:
bash
cargo new my_program --lib
cd my_program

Configure Cargo.toml (see native-rust.md)

Configure Cargo.toml (see native-rust.md)

cargo build-sbf

**→ See [references/native-rust.md](references/native-rust.md) for complete native Rust guide**
cargo build-sbf

**→ 完整原生Rust指南请查看 [references/native-rust.md](references/native-rust.md)**

Core Concepts

核心概念

Essential knowledge for all Solana developers, regardless of framework:
所有Solana开发者都需要掌握的必备知识,与使用的框架无关:

Foundational Concepts

基础概念

  • accounts.md - Account model, ownership, rent, validation patterns
  • pda.md - Program Derived Addresses: derivation, canonical bumps, signing patterns
  • cpi.md - Cross-Program Invocations: calling other programs safely
  • accounts.md - 账户模型、所有权、租金、验证模式
  • pda.md - 程序派生地址(PDA):派生方式、规范随机数、签名模式
  • cpi.md - 跨程序调用(CPI):安全调用其他程序

Program Integration

程序集成

  • tokens-overview.md - Token account structures and ATAs
  • tokens-operations.md - Create, mint, transfer, burn, close operations
  • tokens-validation.md - Account validation patterns
  • tokens-2022.md - Token Extensions Program features
  • tokens-patterns.md - Common patterns and security
  • testing-overview.md - Test pyramid and strategy
  • testing-frameworks.md - Mollusk, Anchor test, Native Rust
  • testing-practices.md - Best practices and patterns
  • surfpool.md - Local development with Surfpool: mainnet forking, cheatcodes, IaC
  • deployment.md - Deploy, upgrade, verify, and manage programs
  • production-deployment.md - Verified builds for production (Anchor 0.32.1 workflow)
  • tokens-overview.md - 代币账户结构与关联代币账户(ATA)
  • tokens-operations.md - 创建、铸造、转移、销毁、关闭操作
  • tokens-validation.md - 账户验证模式
  • tokens-2022.md - Token Extensions Program功能
  • tokens-patterns.md - 通用模式与安全实践
  • testing-overview.md - 测试金字塔与策略
  • testing-frameworks.md - Mollusk、Anchor测试、原生Rust测试
  • testing-practices.md - 最佳实践与模式
  • surfpool.md - 使用Surfpool进行本地开发:主网分叉、作弊码、基础设施即代码(IaC)
  • deployment.md - 部署、升级、验证与程序管理
  • production-deployment.md - 生产环境的可验证构建(Anchor 0.32.1工作流)

Implementation Details

实现细节

  • serialization.md - Account data layout, Borsh, zero-copy patterns
  • error-handling.md - Custom error types, propagation, client-side handling
  • security.md - Security best practices and defensive programming patterns
  • serialization.md - 账户数据布局、Borsh、零拷贝模式
  • error-handling.md - 自定义错误类型、错误传播、客户端处理
  • security.md - 安全最佳实践与防御式编程模式

Advanced Features

进阶功能

  • compute-optimization.md - CU optimization techniques and benchmarking
  • versioned-transactions.md - Address Lookup Tables for 256+ accounts
  • durable-nonces.md - Offline signing with durable transaction nonces
  • transaction-lifecycle.md - Submission, retry patterns, confirmations
  • compute-optimization.md - CU优化技术与基准测试
  • versioned-transactions.md - 地址查找表(ALT)支持256+账户
  • durable-nonces.md - 使用持久化交易随机数进行离线签名
  • transaction-lifecycle.md - 提交、重试模式、确认机制

Low-Level Details

底层细节

  • sysvars.md - System variables (Clock, Rent, EpochSchedule, SlotHashes)
  • builtin-programs.md - System Program and Compute Budget Program
  • sysvars.md - 系统变量(Clock、Rent、EpochSchedule、SlotHashes)
  • builtin-programs.md - 系统程序与计算预算程序

Resources

资源

  • resources.md - Official docs, tools, learning paths, community
  • resources.md - 官方文档、工具、学习路径、社区资源

Common Tasks Quick Reference

常见任务速查

Create a new program:
  • Anchor:
    anchor init my_project
    anchor.md#getting-started
  • Native:
    cargo new my_program --lib
    native-rust.md#setup
Initialize a PDA account:
  • Anchor: Use
    #[account(init, seeds = [...], bump)]
    pda.md#anchor
  • Native: Manual
    invoke_signed
    with System Program → pda.md#native
Transfer SPL tokens:
  • Anchor: Use
    anchor_spl::token::transfer
    tokens-operations.md#transferring-tokens
  • Native: CPI to Token Program → tokens-operations.md#transferring-tokens
Test your program:
  • Both: Mollusk for fast unit tests → testing-frameworks.md#mollusk-testing
  • Anchor:
    anchor test
    for integration tests → testing-frameworks.md#anchor-specific-testing
Local development with mainnet forking:
  • Both:
    surfpool start
    for mainnet-forked local network → surfpool.md
Test with mainnet state (Jupiter, Raydium CPIs):
  • Both: Use Surfpool JIT forking → surfpool.md#mainnet-forking
Profile compute units in detail:
  • Both:
    surfnet_profileTransaction
    cheatcode → surfpool.md#transaction-profiling
Deploy to devnet:
  • Anchor:
    anchor deploy
    deployment.md#anchor
  • Native:
    solana program deploy
    deployment.md#native
Deploy to production (verified builds):
  • Both:
    solana-verify build
    +
    solana program deploy
    production-deployment.md
Optimize compute units:
  • Both: Profile with Mollusk bencher → compute-optimization.md
Handle 40+ accounts:
  • Both: Use Address Lookup Tables → versioned-transactions.md
Offline transaction signing:
  • Both: Use durable nonces → durable-nonces.md
创建新程序:
  • Anchor:
    anchor init my_project
    anchor.md#getting-started
  • 原生Rust:
    cargo new my_program --lib
    native-rust.md#setup
初始化PDA账户:
  • Anchor: 使用
    #[account(init, seeds = [...], bump)]
    pda.md#anchor
  • 原生Rust: 通过System Program手动调用
    invoke_signed
    pda.md#native
转移SPL代币:
  • Anchor: 使用
    anchor_spl::token::transfer
    tokens-operations.md#transferring-tokens
  • 原生Rust: 通过CPI调用代币程序 → tokens-operations.md#transferring-tokens
测试程序:
  • 两种方式均适用:使用Mollusk进行快速单元测试 → testing-frameworks.md#mollusk-testing
  • Anchor: 使用
    anchor test
    进行集成测试 → testing-frameworks.md#anchor-specific-testing
使用主网分叉进行本地开发:
  • 两种方式均适用:
    surfpool start
    启动主网分叉本地网络 → surfpool.md
使用主网状态测试(Jupiter、Raydium CPI):
  • 两种方式均适用:使用Surfpool JIT分叉 → surfpool.md#mainnet-forking
详细分析计算单元:
  • 两种方式均适用:
    surfnet_profileTransaction
    作弊码 → surfpool.md#transaction-profiling
部署到devnet:
  • Anchor:
    anchor deploy
    deployment.md#anchor
  • 原生Rust:
    solana program deploy
    deployment.md#native
部署到生产环境(可验证构建):
  • 两种方式均适用:
    solana-verify build
    +
    solana program deploy
    production-deployment.md
优化计算单元:
  • 两种方式均适用:使用Mollusk bencher进行性能分析 → compute-optimization.md
处理40+账户:
  • 两种方式均适用:使用地址查找表 → versioned-transactions.md
离线交易签名:
  • 两种方式均适用:使用持久化随机数 → durable-nonces.md

Decision Guide

决策指南

Your NeedRecommended ApproachReason
Standard DeFi/NFT programAnchorFaster development, proven patterns
TypeScript client neededAnchorAuto-generates IDL and client types
Learning Solana fundamentalsNative Rust firstUnderstand the platform deeply
Compute optimization criticalNative RustDirect control, minimal overhead
Advanced tx features (ALTs, nonces)Either (slight edge to Native)Framework-agnostic features
Fast prototypingAnchorLess boilerplate, faster iteration
Maximum control over every detailNative RustNo abstraction layer
Team familiar with frameworksAnchorLower learning curve
Program size mattersNative RustSmaller compiled programs
Note: You can also start with Anchor for rapid development, then optimize critical paths with native Rust patterns if needed.
你的需求推荐方案原因
标准DeFi/NFT程序Anchor开发速度更快,模式成熟
需要TypeScript客户端Anchor自动生成IDL和客户端类型
学习Solana基础原理先使用原生Rust深入理解平台底层机制
计算优化至关重要原生Rust直接控制,开销最小
需要进阶交易功能(ALT、随机数)均可(原生Rust略占优势)与框架无关的功能
快速原型开发Anchor样板代码少,迭代更快
对细节完全掌控原生Rust无抽象层
团队熟悉框架开发Anchor学习曲线更低
程序体积很重要原生Rust编译后的程序体积更小
注意: 你也可以先使用Anchor进行快速开发,之后如果需要,再用原生Rust模式优化关键路径。

Framework Comparison

框架对比

AspectAnchorNative Rust
Setup complexitySimple (
anchor init
)
Manual (Cargo.toml, entrypoint)
BoilerplateMinimal (macros handle it)Significant (manual everything)
Account validationDeclarative (
#[account(...)]
)
Manual (explicit checks)
SerializationAutomatic (Borsh via macros)Manual (Borsh or custom)
Type safetyHigh (compile-time checks)High (but more verbose)
IDL generationAutomaticManual or tools
Client libraryTypeScript + Rust auto-genManual client code
Testing
anchor test
, Mollusk
Mollusk, cargo test
Deployment
anchor deploy
solana program deploy
Compute overheadSmall (~1-3% typical)None (direct)
Program sizeSlightly largerSmaller
Learning curveGentler (abstractions help)Steeper (need SVM knowledge)
DebuggingGood (clear macro errors)More complex (lower level)
CommunityLarge (most use Anchor)Growing (optimization focus)
维度Anchor原生Rust
设置复杂度简单(
anchor init
手动配置(Cargo.toml、入口函数)
样板代码极少(宏自动处理)大量(所有操作均需手动实现)
账户验证声明式(
#[account(...)]
手动实现(显式检查)
序列化自动(通过宏使用Borsh)手动实现(Borsh或自定义)
类型安全高(编译时检查)高(但更冗长)
IDL生成自动生成手动或通过工具生成
客户端库自动生成TypeScript + Rust客户端手动编写客户端代码
测试
anchor test
、Mollusk
Mollusk、cargo test
部署
anchor deploy
solana program deploy
计算开销小(通常1-3%)无(直接调用)
程序体积略大更小
学习曲线平缓(抽象层辅助)陡峭(需要SVM知识)
调试良好(宏错误清晰)更复杂(底层实现)
社区规模庞大(多数开发者使用)增长中(聚焦优化)

Typical Development Workflow

典型开发流程

Anchor Workflow

Anchor开发流程

  1. Init:
    anchor init my_project
  2. Define accounts: Use
    #[derive(Accounts)]
    with constraints
  3. Implement instructions: Write functions in
    #[program]
    module
  4. Define state: Use
    #[account]
    macro for account structures
  5. Test: Write tests in
    tests/
    , run
    anchor test
  6. Deploy:
    anchor deploy
    to configured network
  7. Client: Import generated IDL and types in TypeScript/Rust
  1. 初始化
    anchor init my_project
  2. 定义账户:使用
    #[derive(Accounts)]
    添加约束
  3. 实现指令:在
    #[program]
    模块中编写函数
  4. 定义状态:使用
    #[account]
    宏定义账户结构
  5. 测试:在
    tests/
    目录编写测试,运行
    anchor test
  6. 部署
    anchor deploy
    到配置好的网络
  7. 客户端:在TypeScript/Rust中导入生成的IDL和类型

Native Rust Workflow

原生Rust开发流程

  1. Setup:
    cargo new my_program --lib
    , configure Cargo.toml
  2. Define entrypoint: Implement
    process_instruction
    function
  3. Define state: Manual Borsh serialization structs
  4. Implement instructions: Manual routing and account parsing
  5. Validate accounts: Explicit ownership, signer, writable checks
  6. Test: Write Mollusk tests, run
    cargo test
  7. Build:
    cargo build-sbf
  8. Deploy:
    solana program deploy target/deploy/program.so
  9. Client: Build client manually or use web3.js/rs
  1. 设置
    cargo new my_program --lib
    ,配置Cargo.toml
  2. 定义入口函数:实现
    process_instruction
    函数
  3. 定义状态:手动实现Borsh序列化结构体
  4. 实现指令:手动路由和解析账户
  5. 验证账户:显式检查所有权、签名者、可写性
  6. 测试:编写Mollusk测试,运行
    cargo test
  7. 构建
    cargo build-sbf
  8. 部署
    solana program deploy target/deploy/program.so
  9. 客户端:手动构建客户端或使用web3.js/rs

Best Practices

最佳实践

General (Both Approaches)

通用(两种方案均适用)

Always validate accounts: Check ownership, signers, mutability ✅ Use checked arithmetic:
.checked_add()
,
.checked_sub()
, etc. ✅ Test extensively: Unit tests, integration tests, edge cases ✅ Handle errors gracefully: Return descriptive errors ✅ Document your code: Explain account requirements and constraints ✅ Version your programs: Plan for upgrades and migrations ✅ Use PDAs for program-owned accounts: Don't pass private keys ✅ Minimize compute units: Profile and optimize hot paths ✅ Add security.txt: Make it easy for researchers to contact you
始终验证账户:检查所有权、签名者、可变性 ✅ 使用安全算术
.checked_add()
.checked_sub()
等方法 ✅ 充分测试:单元测试、集成测试、边缘场景测试 ✅ 优雅处理错误:返回描述性错误信息 ✅ 编写代码文档:说明账户要求和约束 ✅ 程序版本化:规划升级与迁移方案 ✅ 使用PDA管理程序所有账户:不要传递私钥 ✅ 最小化计算单元消耗:分析并优化热点路径 ✅ 添加security.txt:方便研究人员联系你

Anchor-Specific

Anchor专属

Use
InitSpace
derive
: Auto-calculate account space ✅ Prefer
has_one
constraints
: Clearer than custom constraints ✅ Use
Program<'info, T>
: Validate program accounts in CPIs ✅ Emit events: Use
emit!
for important state changes ✅ Group related constraints: Keep account validation readable
使用
InitSpace
派生
:自动计算账户空间 ✅ 优先使用
has_one
约束
:比自定义约束更清晰 ✅ 使用
Program<'info, T>
:在CPI中验证程序账户 ✅ 触发事件:使用
emit!
记录重要状态变更 ✅ 分组相关约束:保持账户验证逻辑可读性

Native Rust-Specific

原生Rust专属

Use
next_account_info
: Safe account iteration ✅ Cache PDA bumps: Store bump in account, use
create_program_address
Zero-copy when possible: 50%+ CU savings for large structs ✅ Minimize logging: Especially avoid pubkey formatting (expensive) ✅ Build verifiable: Use
solana-verify build
for production
使用
next_account_info
:安全迭代账户 ✅ 缓存PDA随机数:将随机数存储在账户中,使用
create_program_address
尽可能使用零拷贝:大型结构体可节省50%以上的CU ✅ 最小化日志输出:尤其避免公钥格式化(开销大) ✅ 构建可验证程序:生产环境使用
solana-verify build

Security Considerations

安全注意事项

Both frameworks require security vigilance:
⚠️ Common vulnerabilities:
  • Missing signer checks
  • Integer overflow/underflow
  • Account confusion attacks
  • PDA substitution
  • Arbitrary CPI targets
  • Missing account ownership checks
  • Insufficient rent exemption
  • Account closing without zeroing
→ For defensive programming patterns and secure coding practices, see security.md
That guide provides:
  • Core security rules and principles
  • Account validation patterns
  • Arithmetic safety guidelines
  • Pre-deployment security checklist
→ For comprehensive security audits, use the
solana-security
skill
That skill provides:
  • Systematic vulnerability analysis
  • Attack scenarios and exploit POCs
  • Framework-specific security reviews
  • Professional audit workflows
两种框架都需要注意安全问题:
⚠️ 常见漏洞:
  • 缺失签名者检查
  • 整数溢出/下溢
  • 账户混淆攻击
  • PDA替换
  • 任意CPI目标
  • 缺失账户所有权检查
  • 租金豁免不足
  • 账户关闭未清零
→ 防御式编程模式与安全编码实践请查看 security.md
该指南包含:
  • 核心安全规则与原则
  • 账户验证模式
  • 算术安全指南
  • 部署前安全检查清单
→ 如需全面安全审计,请使用
solana-security
技能
该技能提供:
  • 系统性漏洞分析
  • 攻击场景与POC漏洞利用
  • 框架专属安全审查
  • 专业审计流程

When to Switch or Combine

何时切换或结合使用

Start with Anchor, optimize later:
  • Build MVP with Anchor for speed
  • Profile to find CU bottlenecks
  • Optimize critical paths with native patterns
  • Keep Anchor for non-critical code
Start with Native, add Anchor features:
  • Build core program logic in native Rust
  • Use Anchor's client generation separately
  • Leverage anchor-spl for common patterns
  • Maintain control where it matters
Use both in a workspace:
toml
[workspace]
members = [
    "programs/core",      # Native Rust
    "programs/wrapper",   # Anchor facade
]
先使用Anchor,后续优化:
  • 使用Anchor快速构建MVP
  • 分析找到CU瓶颈
  • 使用原生模式优化关键路径
  • 非关键代码继续使用Anchor
先使用原生Rust,添加Anchor特性:
  • 用原生Rust构建核心程序逻辑
  • 单独使用Anchor的客户端生成功能
  • 利用anchor-spl实现通用模式
  • 在关键场景保持控制权
在工作区中同时使用两者:
toml
[workspace]
members = [
    "programs/core",      # 原生Rust
    "programs/wrapper",   # Anchor封装层
]

Getting Help

获取帮助

Next Steps

下一步

New to Solana?
  1. Read accounts.md - Understand the account model
  2. Read anchor.md - Start with Anchor framework
  3. Read security.md - Learn secure coding from the start
  4. Build a simple program following testing-overview.md
  5. Deploy to devnet using deployment.md
Coming from another blockchain?
  1. Read accounts.md - Solana's model is different
  2. Read pda.md - Unique to Solana
  3. Choose Anchor for familiar framework experience
  4. Explore resources.md for migration guides
Want to optimize?
  1. Start with working Anchor program
  2. Profile with compute-optimization.md
  3. Learn native patterns from native-rust.md
  4. Refactor bottlenecks selectively
Building production apps?
  1. Master security considerations
  2. Use testing-practices.md for comprehensive best practices
  3. Follow production-deployment.md for verified builds
  4. Get security audit with
    solana-security
    skill
刚接触Solana?
  1. 阅读 accounts.md - 理解账户模型
  2. 阅读 anchor.md - 从Anchor框架开始
  3. 阅读 security.md - 从一开始就学习安全编码
  4. 按照 testing-overview.md 构建简单程序
  5. 使用 deployment.md 部署到devnet
来自其他区块链?
  1. 阅读 accounts.md - Solana的账户模型与其他区块链不同
  2. 阅读 pda.md - Solana独有的特性
  3. 选择Anchor以获得熟悉的框架开发体验
  4. 查看 resources.md 获取迁移指南
想要优化程序?
  1. 先完成可运行的Anchor程序
  2. 使用 compute-optimization.md 进行性能分析
  3. native-rust.md 学习原生模式
  4. 选择性重构瓶颈代码
构建生产应用?
  1. 掌握 安全注意事项
  2. 使用 testing-practices.md 中的全面最佳实践
  3. 遵循 production-deployment.md 进行可验证构建
  4. 使用
    solana-security
    技能进行安全审计