> ## 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.

# 快速开始

> 了解如何使用 litesvm-utils crate 简化 Solana 程序测试

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

## 安装

请确保已安装所有必需的依赖项:

```bash
cargo add --dev litesvm-utils solana-sdk@3 spl-token
cargo add --dev solana-system-interface@2 --features bincode
```

<Warning>
  `litesvm-utils` 固定了自己的 `litesvm` 版本,并将其重新导出。请从 `litesvm_utils` 中导入
  `LiteSVM`(如下方示例所示),不要再单独添加
  `litesvm` 依赖,否则最终会出现两个互不兼容的
  crate 副本。
</Warning>

## 什么是 litesvm-utils?

`litesvm-utils` crate 提供了一系列重要的辅助 trait 和工具,用于简化 Solana 程序测试。它通过简洁易用的 API,将常见的测试样板代码从 30 多行精简为极少量、易读的代码。

<Steps>
<Step title="TestHelpers Trait">
- 通过一次方法调用即可创建已充值的账户
- 轻松设置代币 mint 和 token account
- 无需样板代码即可派生 PDA
- 管理 slot,用于基于时间的测试
</Step>

<Step title="AssertionHelpers Trait">
- 断言账户状态(是否存在、是否已关闭、所有者)
- 验证代币余额和 mint 供应量
- 检查 SOL 余额
- 校验账户数据长度
</Step>

<Step title="TransactionHelpers Trait">
- 执行指令并获得丰富的结果处理
- 断言交易成功或失败
- 检查特定错误
- 查看交易日志和计算单元
</Step>

<Step title="LiteSVMBuilder">
- 采用流式构建器模式搭建测试环境
- 通过方法链式调用部署程序
- 便捷的静态工厂方法
</Step>
</Steps>

## 快速示例

下面是一个完整的示例,展示了 litesvm-utils 的强大功能:

```rust
use litesvm_utils::{AssertionHelpers, LiteSVM, Signer, TestHelpers, TransactionHelpers};
use solana_sdk::native_token::LAMPORTS_PER_SOL;
use solana_system_interface::instruction as system_instruction;

#[test]
fn test_with_utils() {
    let mut svm = LiteSVM::new();

    // Create funded accounts in one line
    let alice = svm.create_funded_account(10 * LAMPORTS_PER_SOL).unwrap();
    let bob = svm.create_funded_account(0).unwrap();

    // Create a token mint easily
    let mint = svm.create_token_mint(&alice, 9).unwrap();

    // Create an associated token account (returns Pubkey)
    let alice_ata = svm.create_associated_token_account(&mint.pubkey(), &alice).unwrap();

    // Mint tokens
    svm.mint_to(&mint.pubkey(), &alice_ata, &alice, 1000).unwrap();

    // Assert balances
    svm.assert_token_balance(&alice_ata, 1000);

    // Execute a SOL transfer with rich result handling
    let transfer_ix = system_instruction::transfer(
        &alice.pubkey(),
        &bob.pubkey(),
        LAMPORTS_PER_SOL,
    );

    let result = svm.send_instruction(transfer_ix, &[&alice]).unwrap();
    result.assert_success();

    // Verify the transfer
    svm.assert_sol_balance(&bob.pubkey(), LAMPORTS_PER_SOL);

    // Bob now has SOL, so he can pay for his own associated token account
    let bob_ata = svm.create_associated_token_account(&mint.pubkey(), &bob).unwrap();
    svm.assert_token_balance(&bob_ata, 0);
}
```

## 主要优势

### 使用 litesvm-utils 之前

```rust
// Creating a funded account manually
let keypair = Keypair::new();
let airdrop_tx = Transaction::new_signed_with_payer(
    &[system_instruction::transfer(
        &payer.pubkey(),
        &keypair.pubkey(),
        lamports,
    )],
    Some(&payer.pubkey()),
    &[&payer],
    svm.latest_blockhash(),
);
svm.send_transaction(airdrop_tx).unwrap();
```

### 使用 litesvm-utils 之后

```rust
// One line to create a funded account
let keypair = svm.create_funded_account(lamports).unwrap();
```

## Trait 概览

### TestHelpers

| 方法                                         | 返回值                | 描述                         |
| ---------------------------------------------- | ---------------------- | ----------------------------------- |
| `create_funded_account(lamports)`              | `Result<Keypair>`      | 创建 keypair 并为其充值      |
| `create_funded_accounts(count, lamports)`      | `Result<Vec<Keypair>>` | 创建多个已充值的 keypair    |
| `create_token_mint(authority, decimals)`       | `Result<Keypair>`      | 创建 SPL 代币 mint           |
| `create_token_account(mint, owner)`            | `Result<Keypair>`      | 创建普通 token account     |
| `create_associated_token_account(mint, owner)` | `Result<Pubkey>`       | 创建 ATA 并返回其地址 |
| `mint_to(mint, account, authority, amount)`    | `Result<()>`           | 向账户铸造代币          |
| `derive_pda(seeds, program_id)`                | `(Pubkey, u8)`         | 派生 PDA 并返回 bump seed        |
| `get_pda(seeds, program_id)`                   | `Pubkey`               | 仅获取 PDA 地址           |
| `get_pda_with_bump(seeds, program_id)`         | `(Pubkey, u8)`         | `derive_pda` 的别名              |
| `get_current_slot()`                           | `u64`                  | 返回当前 slot                |
| `advance_slot(slots)`                          | `()`                   | 将时间推进 N 个 slot            |

### AssertionHelpers

| 方法                                  | 描述                                                            |
| --------------------------------------- | ---------------------------------------------------------------------- |
| `assert_account_exists(pubkey)`         | 如果账户不存在则 panic                                       |
| `assert_account_closed(pubkey)`         | 除非账户不存在,或 lamport 为零且无数据,否则 panic |
| `assert_token_balance(account, amount)` | 验证代币余额                                                 |
| `assert_sol_balance(pubkey, lamports)`  | 验证 SOL 余额                                                   |
| `assert_mint_supply(mint, supply)`      | 验证 mint 的总供应量                                             |
| `assert_account_owner(pubkey, owner)`   | 验证账户所有者                                                 |
| `assert_account_data_len(pubkey, len)`  | 验证数据长度                                                   |

### TransactionHelpers

| 方法                            | 返回值                                       | 描述                           |
| --------------------------------- | --------------------------------------------- | ------------------------------------- |
| `send_instruction(ix, signers)`   | `Result<TransactionResult, TransactionError>` | 发送单条指令            |
| `send_instructions(ixs, signers)` | `Result<TransactionResult, TransactionError>` | 在一笔交易中发送多条指令 |
| `send_transaction_result(tx)`     | `Result<TransactionResult, TransactionError>` | 发送原始的 `Transaction`             |

## 故障排查

### 常见错误

| 错误               | 原因                                       | 解决方案                          |
| ------------------- | ------------------------------------------- | --------------------------------- |
| `AccountNotFound`   | 尝试使用不存在的账户 | 请先使用 `create_funded_account` |
| `InsufficientFunds` | lamport 不足以支付交易         | 增加初始充值金额   |
| `OwnerMismatch`     | 账户由错误的程序所有              | 请核实程序 ID 是否正确         |
| `AssertionFailed`   | 余额或状态与预期不符     | 请检查您的测试逻辑             |
