> ## 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 dùng anchor-litesvm để kiểm thử chương trình Anchor với cú pháp đơn giản hóa

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

## Cài đặt

`anchor init` tạo một bài kiểm thử LiteSVM, `programs/<program-name>/tests/test_initialize.rs`,
kèm `litesvm` dev-dependency riêng. `anchor-litesvm` đi kèm phiên bản `litesvm` của riêng nó,
và các kiểu dữ liệu từ hai bản sao của crate này không thể dùng lẫn nhau (với Anchor 1.2.2,
hai bộ dependency thậm chí không thể biên dịch cùng nhau). Từ thư mục của chương trình,
`programs/<program-name>`, hãy xóa bài kiểm thử được tạo sẵn cùng các dependency của nó,
sau đó thêm `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
```

Hãy import `LiteSVM`, `Keypair`, `Pubkey` và `Signer` từ `anchor_litesvm`
thay vì thêm một dependency `litesvm` riêng.

<Warning>
**`build_with_program` bị panic với lỗi `Failed to add program: Instruction(InvalidAccountData)`?**
`anchor-litesvm` 0.4 và `litesvm-utils` 0.4 sử dụng LiteSVM 0.11, phiên bản này không thể tải
các chương trình SBPF v3. Anchor 1.2 trở lên, và Solana CLI 4.3 trở lên, mặc định build SBPF
v3. Cho đến khi các crate này chuyển sang LiteSVM mới hơn, hãy build chương trình của bạn
cho SBPF v0 và chạy các bài kiểm thử mà không build lại:

- **Anchor 1.2 trở lên:**

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

- **Anchor 1.1.x trên Solana CLI 4.3 trở lên**, nơi lệnh `anchor build` thông thường
  thất bại với lỗi `Platform tools v1.52 is incompatible with SBPFv3`: hãy build
  chương trình mà không có IDL, sau đó build IDL riêng.

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

Anchor 1.1.2 được cài đặt bằng AVM, theo cách trình cài đặt Solana thiết lập, sử dụng Solana
CLI 3.1.10, phiên bản build SBPF v0, nên không cần giải pháp tạm thời nào.
</Warning>

## Thiết lập dự án

1. Build chương trình (cho SBPF v0, như mô tả ở trên), sau đó sao chép IDL của chương trình từ
   `target/idl/` vào thư mục `idls/` ở gốc workspace.
   `declare_program!(my_program)` đọc `idls/my_program.json` tại thời điểm biên dịch
   và tạo ra các kiểu dữ liệu client cùng program ID, `my_program::ID`.

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

   Hãy thực hiện bước này trước khi viết các bài kiểm thử gọi `declare_program!`: `anchor build`
   biên dịch các bài kiểm thử của bạn trong khi build IDL, nên một bài kiểm thử không tìm thấy
   IDL sẽ làm hỏng quá trình build. Hãy sao chép lại IDL sau khi bạn thay đổi các
   instruction, account hoặc event của chương trình.

2. Đặt các bài kiểm thử của bạn trong `programs/my_program/tests/`. Các ví dụ trên những trang này
   tải chương trình từ đó, lên ba cấp thư mục:
   `include_bytes!("../../../target/deploy/my_program.so")`. Nếu các bài kiểm thử của bạn
   nằm trong một crate khác, hãy dùng đường dẫn hoạt động được từ bất kỳ crate nào trong workspace:
   `include_bytes!(concat!(env!("CARGO_TARGET_TMPDIR"), "/../deploy/my_program.so"))`.

## anchor-litesvm là gì?

Crate `anchor-litesvm` cung cấp **cú pháp đơn giản hóa tương tự
anchor-client** nhưng không có chi phí RPC. Crate này giúp **giảm 78% lượng mã**
so với LiteSVM thuần, đồng thời vẫn đảm bảo an toàn kiểu dữ liệu với các kiểu của Anchor.

<Steps>
<Step title="AnchorContext">
- Ngữ cảnh kiểm thử tương thích với môi trường production
- Cùng mẫu API như anchor-client
- Quản lý instance LiteSVM, payer và chương trình
- Thực thi instruction mà không có chi phí RPC
</Step>

<Step title="Program API">
- Xây dựng instruction theo kiểu fluent
- Xử lý account và đối số an toàn về kiểu dữ liệu
- Cú pháp anchor-client quen thuộc
</Step>

<Step title="Giải tuần tự hóa tài khoản">
- Lấy và giải tuần tự hóa các account của Anchor
- Tự động xử lý discriminator
- Hỗ trợ PDA và bố cục tùy chỉnh
</Step>

<Step title="Phân tích sự kiện">
- Phân tích các event từ log giao dịch
- Xác nhận event được phát ra
- Giải tuần tự hóa event an toàn về kiểu dữ liệu
</Step>
</Steps>

## Ví dụ nhanh

Với Anchor 1.0, hãy dùng `declare_program!` để tạo các kiểu dữ liệu client từ IDL của
chương trình. Macro này tạo ra các module `client::accounts::*` và `client::args::*`
để xây dựng instruction an toàn về kiểu dữ liệu, cùng với program 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)` đọc IDL từ `idls/my_program.json` tại thời điểm
  biên dịch (macro tìm thư mục `idls` trong thư mục của crate và
  các thư mục cha của nó). `my_program::ID` là địa chỉ trong IDL, giống với
  `declare_id!` của chương trình. `anchor_lang` cũng phải nằm trong phạm vi nơi bạn gọi
  macro, vì vậy hãy thêm `use anchor_lang::prelude::*;` phía trên nó.
</Info>

## So sánh: LiteSVM thuần và anchor-litesvm

### Trước (LiteSVM thuần)

```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();
```

### Sau (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();
```

## Các thành phần chính

### AnchorLiteSVM Builder

| Phương thức                          | Mô tả                    |
| ------------------------------- | ------------------------------ |
| `new()`                         | Tạo một instance builder mới |
| `with_payer(keypair)`           | Đặt keypair payer tùy chỉnh    |
| `deploy_program(id, bytes)`     | Thêm một chương trình để triển khai       |
| `build()`                       | Build AnchorContext       |
| `build_with_program(id, bytes)` | Tiện ích cho trường hợp một chương trình |
| `build_with_programs(programs)` | Triển khai nhiều chương trình       |

### AnchorContext

| Phương thức                               | Mô tả                                                       |
| ------------------------------------ | ----------------------------------------------------------------- |
| `svm`                                | Truy cập trực tiếp vào instance `LiteSVM` bên dưới (trường public) |
| `program_id`                         | Program ID (trường public)                                     |
| `program()`                          | Trả về `Program` để xây dựng instruction                        |
| `payer()`                            | Lấy `Keypair` của payer                                           |
| `execute_instruction(ix, signers)`   | Thực thi một instruction đơn lẻ                                      |
| `execute_instructions(ixs, signers)` | Thực thi nhiều instruction trong một giao dịch                           |
| `send_and_confirm_transaction(&tx)`  | Gửi một giao dịch thô                                            |
| `get_account<T>(pubkey)`             | Lấy và giải tuần tự hóa một account của Anchor                           |
| `get_account_unchecked<T>(pubkey)`   | Lấy mà không kiểm tra discriminator                                 |
| `create_funded_account(lamports)`    | Tạo và nạp tiền cho một keypair mới                                     |
| `airdrop(pubkey, lamports)`          | Airdrop SOL đến một địa chỉ                                         |
| `latest_blockhash()`                 | Lấy blockhash hiện tại                                         |
| `account_exists(pubkey)`             | Kiểm tra xem một account có tồn tại hay không                                        |
| `deploy_program(id, bytes)`          | Triển khai thêm một chương trình (qua `ProgramTestExt`)               |

### Program

| Phương thức               | Mô tả                                            |
| -------------------- | ------------------------------------------------------ |
| `accounts(accounts)` | Đặt các account cho instruction (bất kỳ kiểu `ToAccountMetas` nào)   |
| `args(args)`         | Đặt các đối số cho instruction (bất kỳ kiểu `InstructionData` nào) |
| `instruction()`      | Xây dựng `Instruction` cuối cùng                          |
| `id()`               | Lấy program ID                                     |

### ctx.svm — TestHelpers & AssertionHelpers

`ctx.svm` là một trường `LiteSVM` public với các trait `TestHelpers` và `AssertionHelpers`
có sẵn thông qua `litesvm-utils`:

| Phương thức                                                    | Mô tả               |
| --------------------------------------------------------- | ------------------------- |
| `ctx.svm.create_funded_account(lamports)`                 | Tạo và nạp tiền cho một keypair |
| `ctx.svm.create_token_mint(authority, decimals)`          | Tạo một SPL token mint  |
| `ctx.svm.create_associated_token_account(mint, owner)`    | Tạo một ATA             |
| `ctx.svm.mint_to(mint, token_account, authority, amount)` | Mint token               |
| `ctx.svm.get_pda(seeds, program_id)`                      | Suy ra một địa chỉ PDA      |
| `ctx.svm.get_pda_with_bump(seeds, program_id)`            | Suy ra PDA cùng với bump seed |
| `ctx.svm.assert_token_balance(token_account, expected)`   | Xác nhận số dư token      |
| `ctx.svm.assert_account_closed(pubkey)`                   | Xác nhận account đã bị đóng |
| `ctx.svm.assert_sol_balance(pubkey, expected)`            | Xác nhận số dư SOL        |

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

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

| Lỗi                                                    | Nguyên nhân                                       | Giải pháp                                                                 |
| -------------------------------------------------------- | ------------------------------------------- | ------------------------------------------------------------------------ |
| `Failed to add program: Instruction(InvalidAccountData)` | Chương trình được build dưới dạng SBPF v3            | Build cho SBPF v0, như mô tả trong phần [Cài đặt](#installation)      |
| `AccountNotFound`                                        | Account không tồn tại                       | Đảm bảo account đã được tạo trước khi lấy                                |
| `DiscriminatorMismatch`                                  | Sai loại account                          | Xác minh rằng bạn đang dùng đúng struct account                           |
| `DeserializationError`                                   | Dữ liệu account không hợp lệ                        | Kiểm tra account đã được khởi tạo đúng cách                                  |
| Chưa thêm chương trình nào                                        | Đã gọi `build()` mà không có `deploy_program()` | Thêm ít nhất một chương trình trước khi build                                 |
| Thiếu các kiểu dữ liệu client                                     | Chưa gọi `declare_program!`               | Sao chép IDL từ `target/idl/` sang `idls/`, rồi gọi `declare_program!` |
