> ## 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 账户,自动处理鉴别器

## 了解 Anchor 账户鉴别器

Anchor 程序会在所有账户数据前添加一个 8 字节的鉴别器。该
鉴别器是账户类型名称的哈希值,用于验证
账户数据是否与预期类型相匹配。

```
┌─────────────────────────────────────────────────┐
│ Account Data Layout                             │
├────────────────┬────────────────────────────────┤
│ Discriminator  │ Account Fields                 │
│ (8 bytes)      │ (variable size)                │
└────────────────┴────────────────────────────────┘
```

`anchor-litesvm` 账户工具会自动处理该鉴别器。

<Warning>
  这些示例需要使用 SBPF v0 构建你的程序。`anchor-litesvm` 0.4
  使用 LiteSVM 0.11,而该版本无法加载 SBPF v3 程序,因此 `build_with_program`
  会触发 panic,并报错 `Failed to add program: Instruction(InvalidAccountData)`。在
  Anchor 1.2 及更高版本中,请使用 `anchor build --arch v0` 构建,并运行
  `anchor test --skip-build`。对于 Anchor 1.1.x,以及测试文件和 IDL 的存放位置,请参阅
  [快速入门](/developers/docs/tools/litesvm/additional-crates/testing-with-anchor-litesvm#installation)。
</Warning>

账户类型来自 `declare_program!(your_program)`,它会根据你程序的 IDL 生成这些类型:账户结构体位于 `your_program::accounts` 下,
其他类型(例如枚举)位于 `your_program::types` 下。请勿在测试文件中直接声明
`#[account]` 结构体:该宏要求程序的 `ID` 位于 crate 根目录,而测试 crate 中并没有。

## 获取 Anchor 账户

### 基本账户获取

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

anchor_lang::declare_program!(your_program);

use your_program::accounts::UserAccount;

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

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

    // ... initialize the account ...

    let (user_pda, _) = Pubkey::find_program_address(
        &[b"user", user.pubkey().as_ref()],
        &your_program::ID,
    );

    // Fetch and deserialize the account
    let account: UserAccount = ctx.get_account(&user_pda).unwrap();

    assert_eq!(account.name, "Alice");
    assert_eq!(account.authority, user.pubkey());
}
```

<Info>
  `get_account<T>()` 会自动校验 8 字节的鉴别器,以确保账户数据与预期类型相匹配。
</Info>

### 不检查的反序列化

对于 PDA 或鉴别器校验可能失败的自定义账户布局,
请使用 `get_account_unchecked`:

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

anchor_lang::declare_program!(your_program);

use your_program::accounts::UserAccount;

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

    // Fetch without discriminator validation
    let account: UserAccount = ctx.get_account_unchecked(&some_pda).unwrap();
}
```

<Warning>
  请谨慎使用 `get_account_unchecked`。如果不进行鉴别器校验,
  可能会反序列化无效数据。仅在你确定账户类型时才使用。
</Warning>

## 直接使用账户模块

你也可以直接使用账户反序列化函数:

```rust
use anchor_lang::prelude::*;
use anchor_litesvm::{get_anchor_account, get_anchor_account_unchecked, LiteSVM};

anchor_lang::declare_program!(your_program);

use your_program::accounts::UserAccount;

#[test]
fn test_direct_account_fetch() {
    let mut svm = LiteSVM::new();
    // ... setup ...

    // Fetch with discriminator check
    let account: UserAccount = get_anchor_account(&svm, &account_pubkey).unwrap();

    // Fetch without discriminator check
    let account: UserAccount = get_anchor_account_unchecked(&svm, &account_pubkey).unwrap();
}
```

## 账户错误

`AccountError` 枚举提供了详细的错误信息:

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

anchor_lang::declare_program!(your_program);

use your_program::accounts::UserAccount;

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

    let result = ctx.get_account::<UserAccount>(&nonexistent_pubkey);

    match result {
        Ok(account) => println!("Found account: {}", account.name),
        Err(AccountError::AccountNotFound(pubkey)) => {
            println!("Account not found: {}", pubkey);
        }
        Err(AccountError::DiscriminatorMismatch) => {
            println!("Wrong account type!");
        }
        Err(AccountError::DeserializationError(msg)) => {
            println!("Failed to deserialize: {}", msg);
        }
    }
}
```

| 错误                          | 描述                                       |
| ------------------------------ | ------------------------------------------------- |
| `AccountNotFound(Pubkey)`      | 给定地址上不存在账户            |
| `DiscriminatorMismatch`        | 账户鉴别器与预期类型不匹配 |
| `DeserializationError(String)` | 反序列化账户数据失败                |

## 处理多种账户类型

### 获取不同的账户类型

这里的 `your_program` 定义了 `Config`、`UserProfile` 和 `Order` 账户,以及
`Order` 所存储的 `OrderStatus` 枚举(`Pending`、`Completed`、`Cancelled`):

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

anchor_lang::declare_program!(your_program);

use your_program::accounts::{Config, Order, UserProfile};
use your_program::types::OrderStatus;

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

    // Each account type is deserialized correctly
    let config: Config = ctx.get_account(&config_pda).unwrap();
    let profile: UserProfile = ctx.get_account(&profile_pda).unwrap();
    let order: Order = ctx.get_account(&order_pda).unwrap();

    assert_eq!(config.fee_bps, 100);
    assert_eq!(profile.username, "alice");
    assert!(matches!(order.status, OrderStatus::Pending));
}
```

### 获取前检查账户是否存在

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

anchor_lang::declare_program!(your_program);

use your_program::accounts::UserAccount;

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

    let user_pda = Pubkey::new_unique();

    // Check existence first
    if ctx.account_exists(&user_pda) {
        let account: UserAccount = ctx.get_account(&user_pda).unwrap();
        println!("Found: {}", account.name);
    } else {
        println!("Account not initialized yet");
    }
}
```

## 完整示例

下面是一个演示账户管理的完整示例,使用一个计数器
程序,其 `initialize` 会创建一个 `Counter` PDA(包含 `count`、`authority`、
`bump`),其 `increment` 会将 `count` 加一:

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

anchor_lang::declare_program!(counter);

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

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

    // Derive the counter PDA
    let (counter_pda, bump) = Pubkey::find_program_address(
        &[b"counter", authority.pubkey().as_ref()],
        &counter::ID,
    );

    // Verify counter doesn't exist yet
    assert!(!ctx.account_exists(&counter_pda));

    // Initialize using generated client types
    let init_ix = ctx.program()
        .accounts(counter::client::accounts::Initialize {
            authority: authority.pubkey(),
            counter: counter_pda,
            system_program: anchor_lang::system_program::ID,
        })
        .args(counter::client::args::Initialize {})
        .instruction()
        .unwrap();

    ctx.execute_instruction(init_ix, &[&authority])
        .unwrap()
        .assert_success();

    // Verify counter exists and has correct initial state
    assert!(ctx.account_exists(&counter_pda));
    let counter: counter::accounts::Counter = ctx.get_account(&counter_pda).unwrap();
    assert_eq!(counter.count, 0);
    assert_eq!(counter.authority, authority.pubkey());
    assert_eq!(counter.bump, bump);

    // Increment using generated client types
    let increment_ix = ctx.program()
        .accounts(counter::client::accounts::Increment {
            authority: authority.pubkey(),
            counter: counter_pda,
        })
        .args(counter::client::args::Increment {})
        .instruction()
        .unwrap();

    ctx.execute_instruction(increment_ix.clone(), &[&authority])
        .unwrap()
        .assert_success();

    // Verify incremented
    let counter: counter::accounts::Counter = ctx.get_account(&counter_pda).unwrap();
    assert_eq!(counter.count, 1);

    // An identical transaction with the same blockhash is rejected as
    // AlreadyProcessed, so move to a new blockhash before repeating it
    ctx.svm.expire_blockhash();

    // Increment again
    ctx.execute_instruction(increment_ix, &[&authority])
        .unwrap()
        .assert_success();

    let counter: counter::accounts::Counter = ctx.get_account(&counter_pda).unwrap();
    assert_eq!(counter.count, 2);

    println!("Counter test passed! Final count: {}", counter.count);
}
```

<Info>
  `execute_instruction(...).unwrap()` 只会解包调用本身。
  运行时拒绝的交易仍然会返回 `Ok`,因此请链式调用
  `.assert_success()`,以便在交易失败时让测试失败。
</Info>
