solana-development
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseSolana 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 --versionCreate 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_programConfigure 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.md#getting-started
anchor init my_project - Native: → native-rust.md#setup
cargo new my_program --lib
Initialize a PDA account:
- Anchor: Use → pda.md#anchor
#[account(init, seeds = [...], bump)] - Native: Manual with System Program → pda.md#native
invoke_signed
Transfer SPL tokens:
- Anchor: Use → tokens-operations.md#transferring-tokens
anchor_spl::token::transfer - 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: for integration tests → testing-frameworks.md#anchor-specific-testing
anchor test
Local development with mainnet forking:
- Both: for mainnet-forked local network → surfpool.md
surfpool start
Test with mainnet state (Jupiter, Raydium CPIs):
- Both: Use Surfpool JIT forking → surfpool.md#mainnet-forking
Profile compute units in detail:
- Both: cheatcode → surfpool.md#transaction-profiling
surfnet_profileTransaction
Deploy to devnet:
- Anchor: → deployment.md#anchor
anchor deploy - Native: → deployment.md#native
solana program deploy
Deploy to production (verified builds):
- Both: +
solana-verify build→ production-deployment.mdsolana program deploy
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.md#getting-started
anchor init my_project - 原生Rust: → native-rust.md#setup
cargo new my_program --lib
初始化PDA账户:
- Anchor: 使用 → pda.md#anchor
#[account(init, seeds = [...], bump)] - 原生Rust: 通过System Program手动调用→ pda.md#native
invoke_signed
转移SPL代币:
- Anchor: 使用 → tokens-operations.md#transferring-tokens
anchor_spl::token::transfer - 原生Rust: 通过CPI调用代币程序 → tokens-operations.md#transferring-tokens
测试程序:
- 两种方式均适用:使用Mollusk进行快速单元测试 → testing-frameworks.md#mollusk-testing
- Anchor: 使用进行集成测试 → testing-frameworks.md#anchor-specific-testing
anchor test
使用主网分叉进行本地开发:
- 两种方式均适用:启动主网分叉本地网络 → surfpool.md
surfpool start
使用主网状态测试(Jupiter、Raydium CPI):
- 两种方式均适用:使用Surfpool JIT分叉 → surfpool.md#mainnet-forking
详细分析计算单元:
- 两种方式均适用:作弊码 → surfpool.md#transaction-profiling
surfnet_profileTransaction
部署到devnet:
- Anchor: → deployment.md#anchor
anchor deploy - 原生Rust: → deployment.md#native
solana program deploy
部署到生产环境(可验证构建):
- 两种方式均适用:+
solana-verify build→ production-deployment.mdsolana program deploy
优化计算单元:
- 两种方式均适用:使用Mollusk bencher进行性能分析 → compute-optimization.md
处理40+账户:
- 两种方式均适用:使用地址查找表 → versioned-transactions.md
离线交易签名:
- 两种方式均适用:使用持久化随机数 → durable-nonces.md
Decision Guide
决策指南
| Your Need | Recommended Approach | Reason |
|---|---|---|
| Standard DeFi/NFT program | Anchor | Faster development, proven patterns |
| TypeScript client needed | Anchor | Auto-generates IDL and client types |
| Learning Solana fundamentals | Native Rust first | Understand the platform deeply |
| Compute optimization critical | Native Rust | Direct control, minimal overhead |
| Advanced tx features (ALTs, nonces) | Either (slight edge to Native) | Framework-agnostic features |
| Fast prototyping | Anchor | Less boilerplate, faster iteration |
| Maximum control over every detail | Native Rust | No abstraction layer |
| Team familiar with frameworks | Anchor | Lower learning curve |
| Program size matters | Native Rust | Smaller 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
框架对比
| Aspect | Anchor | Native Rust |
|---|---|---|
| Setup complexity | Simple ( | Manual (Cargo.toml, entrypoint) |
| Boilerplate | Minimal (macros handle it) | Significant (manual everything) |
| Account validation | Declarative ( | Manual (explicit checks) |
| Serialization | Automatic (Borsh via macros) | Manual (Borsh or custom) |
| Type safety | High (compile-time checks) | High (but more verbose) |
| IDL generation | Automatic | Manual or tools |
| Client library | TypeScript + Rust auto-gen | Manual client code |
| Testing | | Mollusk, cargo test |
| Deployment | | |
| Compute overhead | Small (~1-3% typical) | None (direct) |
| Program size | Slightly larger | Smaller |
| Learning curve | Gentler (abstractions help) | Steeper (need SVM knowledge) |
| Debugging | Good (clear macro errors) | More complex (lower level) |
| Community | Large (most use Anchor) | Growing (optimization focus) |
| 维度 | Anchor | 原生Rust |
|---|---|---|
| 设置复杂度 | 简单( | 手动配置(Cargo.toml、入口函数) |
| 样板代码 | 极少(宏自动处理) | 大量(所有操作均需手动实现) |
| 账户验证 | 声明式( | 手动实现(显式检查) |
| 序列化 | 自动(通过宏使用Borsh) | 手动实现(Borsh或自定义) |
| 类型安全 | 高(编译时检查) | 高(但更冗长) |
| IDL生成 | 自动生成 | 手动或通过工具生成 |
| 客户端库 | 自动生成TypeScript + Rust客户端 | 手动编写客户端代码 |
| 测试 | | Mollusk、cargo test |
| 部署 | | |
| 计算开销 | 小(通常1-3%) | 无(直接调用) |
| 程序体积 | 略大 | 更小 |
| 学习曲线 | 平缓(抽象层辅助) | 陡峭(需要SVM知识) |
| 调试 | 良好(宏错误清晰) | 更复杂(底层实现) |
| 社区规模 | 庞大(多数开发者使用) | 增长中(聚焦优化) |
Typical Development Workflow
典型开发流程
Anchor Workflow
Anchor开发流程
- Init:
anchor init my_project - Define accounts: Use with constraints
#[derive(Accounts)] - Implement instructions: Write functions in module
#[program] - Define state: Use macro for account structures
#[account] - Test: Write tests in , run
tests/anchor test - Deploy: to configured network
anchor deploy - Client: Import generated IDL and types in TypeScript/Rust
- 初始化:
anchor init my_project - 定义账户:使用添加约束
#[derive(Accounts)] - 实现指令:在模块中编写函数
#[program] - 定义状态:使用宏定义账户结构
#[account] - 测试:在目录编写测试,运行
tests/anchor test - 部署:到配置好的网络
anchor deploy - 客户端:在TypeScript/Rust中导入生成的IDL和类型
Native Rust Workflow
原生Rust开发流程
- Setup: , configure Cargo.toml
cargo new my_program --lib - Define entrypoint: Implement function
process_instruction - Define state: Manual Borsh serialization structs
- Implement instructions: Manual routing and account parsing
- Validate accounts: Explicit ownership, signer, writable checks
- Test: Write Mollusk tests, run
cargo test - Build:
cargo build-sbf - Deploy:
solana program deploy target/deploy/program.so - Client: Build client manually or use web3.js/rs
- 设置:,配置Cargo.toml
cargo new my_program --lib - 定义入口函数:实现函数
process_instruction - 定义状态:手动实现Borsh序列化结构体
- 实现指令:手动路由和解析账户
- 验证账户:显式检查所有权、签名者、可写性
- 测试:编写Mollusk测试,运行
cargo test - 构建:
cargo build-sbf - 部署:
solana program deploy target/deploy/program.so - 客户端:手动构建客户端或使用web3.js/rs
Best Practices
最佳实践
General (Both Approaches)
通用(两种方案均适用)
✅ Always validate accounts: Check ownership, signers, mutability
✅ Use checked arithmetic: , , 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:方便研究人员联系你
.checked_add().checked_sub()Anchor-Specific
Anchor专属
✅ Use derive: Auto-calculate account space
✅ Prefer constraints: Clearer than custom constraints
✅ Use : Validate program accounts in CPIs
✅ Emit events: Use for important state changes
✅ Group related constraints: Keep account validation readable
InitSpacehas_oneProgram<'info, T>emit!✅ 使用派生:自动计算账户空间
✅ 优先使用约束:比自定义约束更清晰
✅ 使用:在CPI中验证程序账户
✅ 触发事件:使用记录重要状态变更
✅ 分组相关约束:保持账户验证逻辑可读性
InitSpacehas_oneProgram<'info, T>emit!Native Rust-Specific
原生Rust专属
✅ Use : Safe account iteration
✅ Cache PDA bumps: Store bump in account, use
✅ Zero-copy when possible: 50%+ CU savings for large structs
✅ Minimize logging: Especially avoid pubkey formatting (expensive)
✅ Build verifiable: Use for production
next_account_infocreate_program_addresssolana-verify build✅ 使用:安全迭代账户
✅ 缓存PDA随机数:将随机数存储在账户中,使用
✅ 尽可能使用零拷贝:大型结构体可节省50%以上的CU
✅ 最小化日志输出:尤其避免公钥格式化(开销大)
✅ 构建可验证程序:生产环境使用
next_account_infocreate_program_addresssolana-verify buildSecurity 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 skill
solana-securityThat 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
获取帮助
- Anchor: Discord, Docs
- Solana: Stack Exchange, Discord
- General: See resources.md for comprehensive links
- Anchor:Discord、官方文档
- Solana:Stack Exchange、Discord
- 通用资源:查看 resources.md 获取全面链接
Next Steps
下一步
New to Solana?
- Read accounts.md - Understand the account model
- Read anchor.md - Start with Anchor framework
- Read security.md - Learn secure coding from the start
- Build a simple program following testing-overview.md
- Deploy to devnet using deployment.md
Coming from another blockchain?
- Read accounts.md - Solana's model is different
- Read pda.md - Unique to Solana
- Choose Anchor for familiar framework experience
- Explore resources.md for migration guides
Want to optimize?
- Start with working Anchor program
- Profile with compute-optimization.md
- Learn native patterns from native-rust.md
- Refactor bottlenecks selectively
Building production apps?
- Master security considerations
- Use testing-practices.md for comprehensive best practices
- Follow production-deployment.md for verified builds
- Get security audit with skill
solana-security
刚接触Solana?
- 阅读 accounts.md - 理解账户模型
- 阅读 anchor.md - 从Anchor框架开始
- 阅读 security.md - 从一开始就学习安全编码
- 按照 testing-overview.md 构建简单程序
- 使用 deployment.md 部署到devnet
来自其他区块链?
- 阅读 accounts.md - Solana的账户模型与其他区块链不同
- 阅读 pda.md - Solana独有的特性
- 选择Anchor以获得熟悉的框架开发体验
- 查看 resources.md 获取迁移指南
想要优化程序?
- 先完成可运行的Anchor程序
- 使用 compute-optimization.md 进行性能分析
- 从 native-rust.md 学习原生模式
- 选择性重构瓶颈代码
构建生产应用?
- 掌握 安全注意事项
- 使用 testing-practices.md 中的全面最佳实践
- 遵循 production-deployment.md 进行可验证构建
- 使用技能进行安全审计
solana-security