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

# Bắt đầu nhanh

> Tìm hiểu cách sử dụng crate litesvm-utils để kiểm thử chương trình Solana hiệu quả hơn

[Xem `litesvm-utils` trên crates.io](https://crates.io/crates/litesvm-utils)

## Cài đặt

Hãy đảm bảo bạn đã có đầy đủ các dependency cần thiết:

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

<Warning>
  `litesvm-utils` ghim phiên bản `litesvm` riêng và re-export nó. Hãy import
  `LiteSVM` từ `litesvm_utils` (như các ví dụ bên dưới) và không thêm một
  dependency `litesvm` riêng, nếu không bạn sẽ có hai bản sao không tương thích
  của crate này.
</Warning>

## litesvm-utils là gì?

Crate `litesvm-utils` cung cấp các trait trợ giúp và tiện ích thiết yếu giúp
đơn giản hóa việc kiểm thử chương trình Solana. Crate này rút gọn đoạn mã boilerplate
kiểm thử thông thường từ hơn 30 dòng xuống còn mã tối giản, dễ đọc nhờ các API thân thiện.

<Steps>
<Step title="Trait TestHelpers">
- Tạo tài khoản đã nạp tiền chỉ với một lần gọi phương thức
- Dễ dàng thiết lập token mint và token account
- Dẫn xuất PDA mà không cần boilerplate
- Quản lý slot cho kiểm thử dựa trên thời gian
</Step>

<Step title="Trait AssertionHelpers">
- Khẳng định trạng thái tài khoản (tồn tại, đã đóng, chủ sở hữu)
- Xác minh số dư token và nguồn cung mint
- Kiểm tra số dư SOL
- Xác thực độ dài dữ liệu tài khoản
</Step>

<Step title="Trait TransactionHelpers">
- Thực thi instruction với khả năng xử lý kết quả phong phú
- Khẳng định giao dịch thành công hoặc thất bại
- Kiểm tra các lỗi cụ thể
- Kiểm tra log giao dịch và compute unit
</Step>

<Step title="LiteSVMBuilder">
- Mẫu fluent builder để thiết lập môi trường kiểm thử
- Triển khai chương trình bằng chuỗi phương thức (method chaining)
- Các phương thức factory tĩnh tiện lợi
</Step>
</Steps>

## Ví dụ nhanh

Đây là một ví dụ hoàn chỉnh cho thấy sức mạnh của 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);
}
```

## Lợi ích chính

### Trước khi dùng 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();
```

### Sau khi dùng litesvm-utils

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

## Tổng quan về Trait

### TestHelpers

| Phương thức                                         | Giá trị trả về                | Mô tả                         |
| ---------------------------------------------- | ---------------------- | ----------------------------------- |
| `create_funded_account(lamports)`              | `Result<Keypair>`      | Tạo một keypair và nạp tiền cho nó      |
| `create_funded_accounts(count, lamports)`      | `Result<Vec<Keypair>>` | Tạo nhiều keypair đã được nạp tiền    |
| `create_token_mint(authority, decimals)`       | `Result<Keypair>`      | Tạo một SPL token mint           |
| `create_token_account(mint, owner)`            | `Result<Keypair>`      | Tạo một token account thông thường     |
| `create_associated_token_account(mint, owner)` | `Result<Pubkey>`       | Tạo một ATA, trả về địa chỉ của nó |
| `mint_to(mint, account, authority, amount)`    | `Result<()>`           | Mint token vào một tài khoản          |
| `derive_pda(seeds, program_id)`                | `(Pubkey, u8)`         | Dẫn xuất một PDA cùng bump seed        |
| `get_pda(seeds, program_id)`                   | `Pubkey`               | Chỉ lấy địa chỉ PDA           |
| `get_pda_with_bump(seeds, program_id)`         | `(Pubkey, u8)`         | Bí danh của `derive_pda`              |
| `get_current_slot()`                           | `u64`                  | Trả về slot hiện tại                |
| `advance_slot(slots)`                          | `()`                   | Đẩy thời gian tiến lên N slot            |

### AssertionHelpers

| Phương thức                                  | Mô tả                                                            |
| --------------------------------------- | ---------------------------------------------------------------------- |
| `assert_account_exists(pubkey)`         | Panic nếu tài khoản không tồn tại                                       |
| `assert_account_closed(pubkey)`         | Panic trừ khi tài khoản không tồn tại, hoặc có số lamport bằng 0 và không có dữ liệu |
| `assert_token_balance(account, amount)` | Xác minh số dư token                                                 |
| `assert_sol_balance(pubkey, lamports)`  | Xác minh số dư SOL                                                   |
| `assert_mint_supply(mint, supply)`      | Xác minh tổng nguồn cung của mint                                             |
| `assert_account_owner(pubkey, owner)`   | Xác minh chủ sở hữu tài khoản                                                 |
| `assert_account_data_len(pubkey, len)`  | Xác minh độ dài dữ liệu                                                   |

### TransactionHelpers

| Phương thức                            | Giá trị trả về                                       | Mô tả                           |
| --------------------------------- | --------------------------------------------- | ------------------------------------- |
| `send_instruction(ix, signers)`   | `Result<TransactionResult, TransactionError>` | Gửi một instruction đơn            |
| `send_instructions(ixs, signers)` | `Result<TransactionResult, TransactionError>` | Gửi nhiều instruction trong một giao dịch |
| `send_transaction_result(tx)`     | `Result<TransactionResult, TransactionError>` | Gửi một `Transaction` thô             |

## Khắc phục sự cố

### Các lỗi thường gặp

| Lỗi               | Nguyên nhân                                       | Giải pháp                          |
| ------------------- | ------------------------------------------- | --------------------------------- |
| `AccountNotFound`   | Cố dùng một tài khoản không tồn tại | Hãy dùng `create_funded_account` trước |
| `InsufficientFunds` | Không đủ lamport cho giao dịch         | Tăng số tiền nạp ban đầu   |
| `OwnerMismatch`     | Tài khoản thuộc sở hữu của chương trình sai              | Xác minh đúng program ID         |
| `AssertionFailed`   | Số dư hoặc trạng thái không khớp với kỳ vọng     | Kiểm tra logic kiểm thử của bạn             |
