> ## Documentation Index
> Fetch the complete documentation index at: https://solana.com/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> This page is part of the Solana developer documentation at https://solana.com/developers/docs. Append `.md` to any docs URL, or send `Accept: text/markdown`, to get the page as Markdown.
> Index of all pages: https://solana.com/llms.txt. Per-section indexes such as https://solana.com/developers/docs/payments/llms.txt are smaller; prefer them when working on one task.
> Coding agents: install the official Solana skill for current APIs and conventions with `npx skills add https://github.com/solana-foundation/solana-dev-skill` (also served at https://solana.com/SKILL.md).
> Code in the cookbook and task pages comes from tested example files. Prefer it over writing API calls from memory.

# 快速入门

> 了解如何使用 anchor-litesvm，以简化的语法测试 Anchor 程序

[在 crates.io 上查看 `anchor-litesvm`](https://crates.io/crates/anchor-litesvm)

## 安装

`anchor init` 会创建一个 LiteSVM 测试 `programs/<program-name>/tests/test_initialize.rs`，
并附带其自身的 `litesvm` 开发依赖。`anchor-litesvm` 自带一个版本的
`litesvm`，而来自两份 crate 副本的类型无法混用（在 Anchor 1.2.2 中，
这两组依赖甚至无法一起编译）。在程序所在的
文件夹 `programs/<program-name>` 中，删除生成的测试及其
依赖，然后添加 `anchor-litesvm`：

```bash
rm tests/test_initialize.rs
cargo remove --dev litesvm solana-message solana-transaction solana-signer solana-keypair
cargo add --dev anchor-litesvm litesvm-utils anchor-lang@1 solana-sdk@3
```

请从 `anchor_litesvm` 中导入 `LiteSVM`、`Keypair`、`Pubkey` 和 `Signer`，
而不是另外添加单独的 `litesvm` 依赖。

<Warning>
**`build_with_program` 触发 panic 并提示 `Failed to add program: Instruction(InvalidAccountData)`？**
`anchor-litesvm` 0.4 和 `litesvm-utils` 0.4 使用 LiteSVM 0.11，它无法加载
SBPF v3 程序。Anchor 1.2 及更高版本，以及 Solana CLI 4.3 及更高版本，默认构建
SBPF v3。在这些 crate 升级到更新的 LiteSVM 之前，请将程序
构建为 SBPF v0，并在不重新构建的情况下运行测试：

- **Anchor 1.2 及更高版本：**

  ```bash
  anchor build --arch v0
  anchor test --skip-build
  ```

- **使用 Solana CLI 4.3 或更高版本的 Anchor 1.1.x**，此时直接运行 `anchor build`
  会失败并提示 `Platform tools v1.52 is incompatible with SBPFv3`：请先在不带 IDL 的情况下构建
  程序，然后单独构建 IDL。

  ```bash
  anchor build --no-idl -- --arch v0
  anchor idl build -p my_program -o target/idl/my_program.json
  anchor test --skip-build
  ```

通过 AVM 安装的 Anchor 1.1.2（即 Solana 安装程序的默认设置）使用 Solana
CLI 3.1.10，它构建的是 SBPF v0，因此无需任何变通方法。
</Warning>

## 项目设置

1. 构建程序（如上所述，构建为 SBPF v0），然后将其 IDL 从
   `target/idl/` 复制到工作区根目录下的 `idls/` 文件夹中。
   `declare_program!(my_program)` 会在编译时读取 `idls/my_program.json`，
   并生成客户端类型和程序 ID `my_program::ID`。

   ```bash
   mkdir -p idls && cp target/idl/my_program.json idls/
   ```

   请在编写调用 `declare_program!` 的测试之前完成这一步：`anchor build`
   在构建 IDL 时会编译你的测试，因此找不到其
   IDL 的测试会导致构建失败。修改程序的
   指令、账户或事件后，请再次复制 IDL。

2. 请将测试放在 `programs/my_program/tests/` 中。这些页面上的示例
   会从该位置向上三级文件夹加载程序：
   `include_bytes!("../../../target/deploy/my_program.so")`。如果你的测试
   位于其他 crate 中，请使用在工作区内任意 crate 都适用的路径：
   `include_bytes!(concat!(env!("CARGO_TARGET_TMPDIR"), "/../deploy/my_program.so"))`。

## 什么是 anchor-litesvm？

`anchor-litesvm` crate 提供了**类似 anchor-client 的简化语法**，
但没有 RPC 开销。与原生 LiteSVM 相比，它可**减少 78% 的代码量**，
同时保持与 Anchor 类型的类型安全。

<Steps>
<Step title="AnchorContext">
- 与生产环境兼容的测试上下文
- 与 anchor-client 相同的 API 模式
- 管理 LiteSVM 实例、付款方和程序
- 无需 RPC 开销即可执行指令
</Step>

<Step title="Program API">
- 流式指令构建
- 类型安全的账户和参数处理
- 熟悉的 anchor-client 语法
</Step>

<Step title="账户反序列化">
- 获取并反序列化 Anchor 账户
- 自动处理 discriminator
- 支持 PDA 和自定义布局
</Step>

<Step title="事件解析">
- 从交易日志中解析事件
- 断言事件已触发
- 类型安全的事件反序列化
</Step>
</Steps>

## 快速示例

在 Anchor 1.0 中，使用 `declare_program!` 根据程序的 IDL 生成客户端类型。
该宏会创建 `client::accounts::*` 和 `client::args::*`
模块，用于类型安全的指令构建，同时生成程序 ID：

```rust
use anchor_lang::prelude::*;
use anchor_lang::system_program;
use anchor_litesvm::{AnchorLiteSVM, Signer, TestHelpers};

// Generate client types and the program ID from your program's IDL
anchor_lang::declare_program!(my_program);

#[test]
fn test_anchor_program() {
    // One-line setup with the program ID from the IDL
    let mut ctx = AnchorLiteSVM::build_with_program(
        my_program::ID,
        include_bytes!("../../../target/deploy/my_program.so"),
    );

    // Create a funded account via TestHelpers on ctx.svm
    let user = ctx.svm.create_funded_account(10_000_000_000).unwrap();

    // Derive PDA
    let seed: u64 = 42;
    let pda = ctx.svm.get_pda(
        &[b"user", user.pubkey().as_ref(), &seed.to_le_bytes()],
        &my_program::ID,
    );

    // Build instruction using generated client types
    let ix = ctx.program()
        .accounts(my_program::client::accounts::Initialize {
            user: user.pubkey(),
            user_account: pda,
            system_program: system_program::ID,
        })
        .args(my_program::client::args::Initialize {
            seed,
            name: "test".to_string(),
        })
        .instruction()
        .unwrap();

    // Execute and assert in one chain
    ctx.execute_instruction(ix, &[&user])
        .unwrap()
        .assert_success();

    // Fetch and deserialize the account
    let account: my_program::accounts::MyAccount = ctx.get_account(&pda).unwrap();
    assert_eq!(account.name, "test");
}
```

<Info>
  `declare_program!(my_program)` 会在编译时从 `idls/my_program.json` 读取 IDL
  （它会在 crate 目录及其父目录中搜索 `idls` 目录）。`my_program::ID` 是 IDL 中的地址，与你的
  程序的 `declare_id!` 相同。调用该宏的位置还必须引入 `anchor_lang`，
  因此请在其上方添加 `use anchor_lang::prelude::*;`。
</Info>

## 对比：原生 LiteSVM 与 anchor-litesvm

### 之前（原生 LiteSVM）

```rust
use litesvm::LiteSVM;
use solana_keypair::Keypair;
use solana_signer::Signer;
use solana_program::instruction::{AccountMeta, Instruction};
use solana_message::Message;
use solana_transaction::Transaction;

let mut svm = LiteSVM::new();
svm.add_program(program_id, program_bytes).unwrap();

let payer = Keypair::new();
svm.airdrop(&payer.pubkey(), 10_000_000_000).unwrap();

// Manually compute 8-byte discriminator
let discriminator = {
    let mut hasher = sha2::Sha256::new();
    hasher.update(b"global:initialize");
    let result = hasher.finalize();
    result[..8].to_vec()
};

// Manually serialize args and build instruction
let mut data = discriminator;
data.extend_from_slice(&borsh::to_vec(&args).unwrap());

let accounts = vec![
    AccountMeta::new(user.pubkey(), true),
    AccountMeta::new(user_pda, false),
    AccountMeta::new_readonly(system_program::id(), false),
];

let ix = Instruction::new_with_bytes(program_id, &data, accounts);
let tx = Transaction::new_signed_with_payer(
    &[ix],
    Some(&payer.pubkey()),
    &[&payer],
    svm.latest_blockhash(),
);
svm.send_transaction(tx).unwrap();

// Manually deserialize with discriminator skip
let account_data = svm.get_account(&pda).unwrap().data;
let account: MyAccount = MyAccount::try_deserialize(
    &mut &account_data[8..]
).unwrap();
```

### 之后（anchor-litesvm）

```rust
use anchor_lang::prelude::*;
use anchor_litesvm::{AnchorLiteSVM, Signer, TestHelpers};

anchor_lang::declare_program!(my_program);

let mut ctx = AnchorLiteSVM::build_with_program(my_program::ID, program_bytes);
let user = ctx.svm.create_funded_account(10_000_000_000).unwrap();

let ix = ctx.program()
    .accounts(my_program::client::accounts::Initialize {
        user: user.pubkey(),
        user_account: user_pda,
        system_program: anchor_lang::system_program::ID,
    })
    .args(my_program::client::args::Initialize { seed, name: "test".to_string() })
    .instruction()
    .unwrap();

ctx.execute_instruction(ix, &[&user]).unwrap().assert_success();

let account: my_program::accounts::MyAccount = ctx.get_account(&user_pda).unwrap();
```

## 关键组件

### AnchorLiteSVM Builder

| 方法                          | 描述                    |
| ------------------------------- | ------------------------------ |
| `new()`                         | 创建新的 builder 实例 |
| `with_payer(keypair)`           | 设置自定义付款方 keypair    |
| `deploy_program(id, bytes)`     | 添加要部署的程序       |
| `build()`                       | 构建 AnchorContext       |
| `build_with_program(id, bytes)` | 针对单个程序的便捷方法 |
| `build_with_programs(programs)` | 部署多个程序       |

### AnchorContext

| 方法                               | 描述                                                       |
| ------------------------------------ | ----------------------------------------------------------------- |
| `svm`                                | 直接访问底层的 `LiteSVM` 实例（公共字段） |
| `program_id`                         | 程序 ID（公共字段）                                     |
| `program()`                          | 返回用于构建指令的 `Program`                        |
| `payer()`                            | 获取付款方 `Keypair`                                           |
| `execute_instruction(ix, signers)`   | 执行单条指令                                      |
| `execute_instructions(ixs, signers)` | 在一笔交易中执行多条指令                           |
| `send_and_confirm_transaction(&tx)`  | 发送原始交易                                            |
| `get_account<T>(pubkey)`             | 获取并反序列化 Anchor 账户                           |
| `get_account_unchecked<T>(pubkey)`   | 获取账户但不检查 discriminator                                 |
| `create_funded_account(lamports)`    | 创建并充值一个新的 keypair                                     |
| `airdrop(pubkey, lamports)`          | 向地址空投 SOL                                         |
| `latest_blockhash()`                 | 获取当前 blockhash                                         |
| `account_exists(pubkey)`             | 检查账户是否存在                                        |
| `deploy_program(id, bytes)`          | 部署额外的程序（通过 `ProgramTestExt`）               |

### Program

| 方法               | 描述                                            |
| -------------------- | ------------------------------------------------------ |
| `accounts(accounts)` | 设置指令账户（任何 `ToAccountMetas` 类型）   |
| `args(args)`         | 设置指令参数（任何 `InstructionData` 类型） |
| `instruction()`      | 构建最终的 `Instruction`                          |
| `id()`               | 获取程序 ID                                     |

### ctx.svm — TestHelpers 与 AssertionHelpers

`ctx.svm` 是一个公共的 `LiteSVM` 字段，通过 `litesvm-utils` 可使用
`TestHelpers` 和 `AssertionHelpers` trait：

| 方法                                                    | 描述               |
| --------------------------------------------------------- | ------------------------- |
| `ctx.svm.create_funded_account(lamports)`                 | 创建并充值一个 keypair |
| `ctx.svm.create_token_mint(authority, decimals)`          | 创建 SPL 代币 mint  |
| `ctx.svm.create_associated_token_account(mint, owner)`    | 创建 ATA             |
| `ctx.svm.mint_to(mint, token_account, authority, amount)` | 铸造代币               |
| `ctx.svm.get_pda(seeds, program_id)`                      | 派生 PDA 地址      |
| `ctx.svm.get_pda_with_bump(seeds, program_id)`            | 连同 bump seed 一起派生 PDA |
| `ctx.svm.assert_token_balance(token_account, expected)`   | 断言代币余额      |
| `ctx.svm.assert_account_closed(pubkey)`                   | 断言账户已关闭 |
| `ctx.svm.assert_sol_balance(pubkey, expected)`            | 断言 SOL 余额        |

## 故障排除

### 常见错误

| 错误                                                    | 原因                                       | 解决方案                                                                 |
| -------------------------------------------------------- | ------------------------------------------- | ------------------------------------------------------------------------ |
| `Failed to add program: Instruction(InvalidAccountData)` | 程序被构建为 SBPF v3            | 按照[安装](#installation)部分的说明，构建为 SBPF v0      |
| `AccountNotFound`                                        | 账户不存在                       | 确保在获取之前已创建账户                                |
| `DiscriminatorMismatch`                                  | 账户类型错误                          | 确认你使用的是正确的账户结构体                           |
| `DeserializationError`                                   | 账户数据无效                        | 检查账户是否已正确初始化                                  |
| 未添加程序                                        | 在未调用 `deploy_program()` 的情况下调用了 `build()` | 在构建之前至少添加一个程序                                 |
| 缺少客户端类型                                     | 未调用 `declare_program!`               | 将 IDL 从 `target/idl/` 复制到 `idls/`，然后调用 `declare_program!` |
