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

# Program 与 Context

> 使用 AnchorContext 和 Program 搭建测试环境并构建指令

## 使用 declare_program! 生成客户端类型

Anchor 1.0 引入了 `declare_program!`，它会在编译时读取程序的 IDL，并生成类型安全的 `client::accounts::*` 和 `client::args::*` 模块。这是在测试中构建指令的推荐方式。

```rust
// At the top of your test file, generate client modules from the IDL
use anchor_lang::prelude::*;

anchor_lang::declare_program!(my_program);

// Now use the generated types:
// my_program::ID (the program ID from the IDL)
// my_program::client::accounts::Initialize { ... }
// my_program::client::args::Initialize { ... }
// my_program::accounts::MyAccount (for account deserialization)
// my_program::events::MyEvent (for event parsing)
```

<Info>
  运行 `anchor build`，然后将 `target/idl/my_program.json` 复制到 `idls/my_program.json`。`declare_program!` 会在编译时从 crate 目录或其父目录中最近的 `idls` 目录读取 `idls/<name>.json`。宏名称必须与 IDL 文件名（即程序的 snake_case 名称）一致。调用该宏的位置必须已引入 `anchor_lang`，因此请在其上方添加 `use anchor_lang::prelude::*;`。测试和 IDL 的存放位置请参见 [快速入门](/developers/docs/tools/litesvm/additional-crates/testing-with-anchor-litesvm#project-setup)。
</Info>

<Warning>
  这些示例需要程序的 SBPF v0 构建版本。`anchor-litesvm` 0.4 使用 LiteSVM 0.11，而它无法加载 SBPF v3 程序，因此 `build_with_program` 会报错并显示 `Failed to add program: Instruction(InvalidAccountData)`。对于 Anchor 1.2 及更高版本，请使用 `anchor build --arch v0` 进行构建，并运行 `anchor test --skip-build`。对于 Anchor 1.1.x，请参见 [快速入门](/developers/docs/tools/litesvm/additional-crates/testing-with-anchor-litesvm#installation)。
</Warning>

## 设置测试环境

`AnchorLiteSVM` 构建器提供了流式 API，用于配置测试环境。

### 基本设置

```rust
use anchor_lang::prelude::*;
use anchor_litesvm::AnchorLiteSVM;

anchor_lang::declare_program!(my_program);

#[test]
fn test_basic_setup() {
    // declare_program! provides the program ID from the IDL
    let ctx = AnchorLiteSVM::new()
        .deploy_program(
            my_program::ID,
            include_bytes!("../../../target/deploy/my_program.so"),
        )
        .build();

    println!("Program deployed: {}", ctx.program().id());
}
```

### 单程序简写

```rust
use anchor_lang::prelude::*;
use anchor_litesvm::AnchorLiteSVM;

anchor_lang::declare_program!(my_program);

#[test]
fn test_single_program() {
    // Convenience method for single-program setups
    let ctx = AnchorLiteSVM::build_with_program(
        my_program::ID,
        include_bytes!("../../../target/deploy/my_program.so"),
    );
}
```

### 多个程序

```rust
use anchor_lang::prelude::*;
use anchor_litesvm::AnchorLiteSVM;

anchor_lang::declare_program!(program_a);
anchor_lang::declare_program!(program_b);

#[test]
fn test_multiple_programs() {
    // Deploy multiple programs — first one becomes the primary (ctx.program_id)
    let ctx = AnchorLiteSVM::build_with_programs(&[
        (program_a::ID, include_bytes!("../../../target/deploy/program_a.so") as &[u8]),
        (program_b::ID, include_bytes!("../../../target/deploy/program_b.so") as &[u8]),
    ]);

    // Primary program is program_a
    assert_eq!(ctx.program().id(), program_a::ID);
}
```

### 自定义付款方

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

anchor_lang::declare_program!(my_program);

#[test]
fn test_custom_payer() {
    let custom_payer = Keypair::new();

    let ctx = AnchorLiteSVM::new()
        .with_payer(custom_payer)
        .deploy_program(
            my_program::ID,
            include_bytes!("../../../target/deploy/my_program.so"),
        )
        .build();

    println!("Payer: {}", ctx.payer().pubkey());
}
```

<Info>
  如果未指定付款方，`AnchorLiteSVM` 会自动为你创建并充值一个付款账户。
</Info>

## AnchorContext

`AnchorContext` 是与测试环境交互的主要接口。

### 核心属性

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

anchor_lang::declare_program!(my_program);

#[test]
fn test_context_properties() {
    let ctx = AnchorLiteSVM::build_with_program(
        my_program::ID,
        include_bytes!("../../../target/deploy/my_program.so"),
    );

    // ctx.svm — direct access to the underlying LiteSVM instance (public field)
    let balance = ctx.svm.get_balance(&ctx.payer().pubkey());

    // ctx.payer() — the payer keypair
    let payer = ctx.payer();
    println!("Payer pubkey: {}", payer.pubkey());

    // ctx.program() — Program instance for instruction building
    let program = ctx.program();
    println!("Program ID: {}", program.id());

    // ctx.latest_blockhash()
    let blockhash = ctx.latest_blockhash();
}
```

### 创建已充值账户

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

anchor_lang::declare_program!(my_program);

#[test]
fn test_create_accounts() {
    let mut ctx = AnchorLiteSVM::build_with_program(
        my_program::ID,
        include_bytes!("../../../target/deploy/my_program.so"),
    );

    // Option 1: via AnchorContext (returns Result<Keypair>)
    let user = ctx.create_funded_account(10_000_000_000).unwrap();

    // Option 2: via ctx.svm with TestHelpers (same result)
    let user2 = ctx.svm.create_funded_account(10_000_000_000).unwrap();

    // Airdrop to an existing address
    let another_user = Keypair::new();
    ctx.airdrop(&another_user.pubkey(), 5_000_000_000).unwrap();
}
```

### 检查账户是否存在

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

anchor_lang::declare_program!(my_program);

#[test]
fn test_account_exists() {
    let ctx = AnchorLiteSVM::build_with_program(
        my_program::ID,
        include_bytes!("../../../target/deploy/my_program.so"),
    );

    let some_pda = ctx.svm.get_pda(&[b"vault"], &my_program::ID);

    if ctx.account_exists(&some_pda) {
        println!("Account exists!");
    } else {
        println!("Account not found");
    }
}
```

## 使用 Program 构建指令

`Program` 结构体提供了流式 API 来构建指令，其用法与 anchor-client 一致。请使用 `declare_program!` 生成的类型以确保类型安全。

### 基本指令构建

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

anchor_lang::declare_program!(my_program);

#[test]
fn test_build_instruction() {
    let mut ctx = AnchorLiteSVM::build_with_program(
        my_program::ID,
        include_bytes!("../../../target/deploy/my_program.so"),
    );

    let user = ctx.svm.create_funded_account(10_000_000_000).unwrap();
    let seed: u64 = 42;
    let user_pda = ctx.svm.get_pda(
        &[b"user", user.pubkey().as_ref(), &seed.to_le_bytes()],
        &my_program::ID,
    );

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

    println!("Instruction built successfully!");
}
```

<Info>
  `.accounts()` 方法接受任何实现了 `ToAccountMetas` 的类型，所有 Anchor 账户结构体都会自动实现该 trait。同样，`.args()` 接受任何实现了 `InstructionData` 的类型。
</Info>

### 执行指令

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

anchor_lang::declare_program!(my_program);

#[test]
fn test_execute_instruction() {
    let mut ctx = AnchorLiteSVM::build_with_program(
        my_program::ID,
        include_bytes!("../../../target/deploy/my_program.so"),
    );

    let user = ctx.svm.create_funded_account(10_000_000_000).unwrap();
    let seed: u64 = 42;
    let user_pda = ctx.svm.get_pda(
        &[b"user", user.pubkey().as_ref(), &seed.to_le_bytes()],
        &my_program::ID,
    );

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

    // Execute — returns TransactionResult
    ctx.execute_instruction(ix, &[&user])
        .unwrap()
        .assert_success();
}
```

### 执行多条指令

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

anchor_lang::declare_program!(my_program);

#[test]
fn test_execute_multiple_instructions() {
    let mut ctx = AnchorLiteSVM::build_with_program(
        my_program::ID,
        include_bytes!("../../../target/deploy/my_program.so"),
    );

    let user = ctx.svm.create_funded_account(10_000_000_000).unwrap();

    let ix1 = ctx.program()
        .accounts(my_program::client::accounts::Initialize { /* ... */ })
        .args(my_program::client::args::Initialize { seed: 42, name: "first".to_string() })
        .instruction()
        .unwrap();

    let ix2 = ctx.program()
        .accounts(my_program::client::accounts::Update { /* ... */ })
        .args(my_program::client::args::Update { name: "second".to_string() })
        .instruction()
        .unwrap();

    // Execute multiple instructions in one transaction
    ctx.execute_instructions(vec![ix1, ix2], &[&user])
        .unwrap()
        .assert_success();
}
```

### 使用 send_and_confirm_transaction

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

anchor_lang::declare_program!(my_program);

#[test]
fn test_send_transaction() {
    let mut ctx = AnchorLiteSVM::build_with_program(
        my_program::ID,
        include_bytes!("../../../target/deploy/my_program.so"),
    );

    let user = ctx.svm.create_funded_account(10_000_000_000).unwrap();

    let ix = ctx.program()
        .accounts(/* ... */)
        .args(/* ... */)
        .instruction()
        .unwrap();

    // Build transaction manually if needed
    let tx = Transaction::new_signed_with_payer(
        &[ix],
        Some(&ctx.payer().pubkey()),
        &[ctx.payer(), &user],
        ctx.latest_blockhash(),
    );

    // Note: takes &Transaction (reference)
    ctx.send_and_confirm_transaction(&tx).unwrap();
}
```

## 完整示例

下面是一个使用 `declare_program!` 和托管（escrow）模式的完整示例，适用于类似 [anchor-escrow-with-litesvm](https://github.com/brimigs/anchor-escrow-with-litesvm) 中的托管程序。它还会用到 Associated Token Account 和 SPL Token crate，因此请先添加它们（在 `programs/anchor_escrow` 目录下）：

```bash
cargo add --dev spl-associated-token-account@8 litesvm-token@0.11
```

```rust
use anchor_lang::prelude::*;
use anchor_lang::system_program;
use anchor_litesvm::{AnchorLiteSVM, AssertionHelpers, Signer, TestHelpers};
use litesvm_token::spl_token;
use spl_associated_token_account::get_associated_token_address;

anchor_lang::declare_program!(anchor_escrow);

#[test]
fn test_make_and_take() {
    // 1. One-line setup
    let program_id = anchor_escrow::ID;

    let mut ctx = AnchorLiteSVM::build_with_program(
        program_id,
        include_bytes!("../../../target/deploy/anchor_escrow.so"),
    );

    // 2. Create test accounts using TestHelpers on ctx.svm
    let maker = ctx.svm.create_funded_account(10_000_000_000).unwrap();
    let taker = ctx.svm.create_funded_account(10_000_000_000).unwrap();

    // 3. Create token mints and funded ATAs
    let mint_a = ctx.svm.create_token_mint(&maker, 9).unwrap();
    let mint_b = ctx.svm.create_token_mint(&maker, 9).unwrap();

    let maker_ata_a = ctx.svm
        .create_associated_token_account(&mint_a.pubkey(), &maker)
        .unwrap();
    ctx.svm.mint_to(&mint_a.pubkey(), &maker_ata_a, &maker, 1_000_000_000).unwrap();

    let taker_ata_b = ctx.svm
        .create_associated_token_account(&mint_b.pubkey(), &taker)
        .unwrap();
    ctx.svm.mint_to(&mint_b.pubkey(), &taker_ata_b, &maker, 500_000_000).unwrap();

    // 4. Derive PDAs
    let seed: u64 = 42;
    let escrow_pda = ctx.svm.get_pda(
        &[b"escrow", maker.pubkey().as_ref(), &seed.to_le_bytes()],
        &program_id,
    );
    let vault = get_associated_token_address(&escrow_pda, &mint_a.pubkey());

    // 5. Build and execute Make instruction using generated client types
    let make_ix = ctx.program()
        .accounts(anchor_escrow::client::accounts::Make {
            maker: maker.pubkey(),
            escrow: escrow_pda,
            mint_a: mint_a.pubkey(),
            mint_b: mint_b.pubkey(),
            maker_ata_a,
            vault,
            associated_token_program: spl_associated_token_account::id(),
            token_program: spl_token::id(),
            system_program: system_program::ID,
        })
        .args(anchor_escrow::client::args::Make {
            seed,
            receive: 500_000_000,
            amount: 1_000_000_000,
        })
        .instruction()
        .unwrap();

    ctx.execute_instruction(make_ix, &[&maker])
        .unwrap()
        .assert_success();

    // 6. Assert state using AssertionHelpers on ctx.svm
    assert!(ctx.account_exists(&escrow_pda));
    ctx.svm.assert_token_balance(&vault, 1_000_000_000);
    ctx.svm.assert_token_balance(&maker_ata_a, 0);

    // 7. Execute Take
    let taker_ata_a = get_associated_token_address(&taker.pubkey(), &mint_a.pubkey());
    let maker_ata_b = get_associated_token_address(&maker.pubkey(), &mint_b.pubkey());

    let take_ix = ctx.program()
        .accounts(anchor_escrow::client::accounts::Take {
            taker: taker.pubkey(),
            maker: maker.pubkey(),
            escrow: escrow_pda,
            mint_a: mint_a.pubkey(),
            mint_b: mint_b.pubkey(),
            vault,
            taker_ata_a,
            taker_ata_b,
            maker_ata_b,
            associated_token_program: spl_associated_token_account::id(),
            token_program: spl_token::id(),
            system_program: system_program::ID,
        })
        .args(anchor_escrow::client::args::Take {})
        .instruction()
        .unwrap();

    ctx.execute_instruction(take_ix, &[&taker])
        .unwrap()
        .assert_success();

    // 8. Final assertions
    ctx.svm.assert_account_closed(&escrow_pda);
    ctx.svm.assert_account_closed(&vault);
    ctx.svm.assert_token_balance(&taker_ata_a, 1_000_000_000);
    ctx.svm.assert_token_balance(&maker_ata_b, 500_000_000);
}
```
