> ## 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 程序可以发出(emit)事件,这些事件会在交易执行期间被记录到日志中。
这些事件在交易日志中以 Base64 编码,并带有前缀
`Program data:`。`anchor-litesvm` crate 提供了用于解析和
断言这些事件的工具。

```
┌─────────────────────────────────────────────────┐
│ Anchor Event Structure                          │
├────────────────┬────────────────────────────────┤
│ Discriminator  │ Event Data                     │
│ (8 bytes)      │ (serialized fields)            │
└────────────────┴────────────────────────────────┘
```

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

## 定义事件

首先,在您的 Anchor 程序中定义事件:

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

#[event]
pub struct TransferEvent {
    pub from: Pubkey,
    pub to: Pubkey,
    pub amount: u64,
    pub timestamp: i64,
}

#[event]
pub struct InitializeEvent {
    pub authority: Pubkey,
    pub name: String,
}
```

## 解析事件

在测试中,`declare_program!(your_program)` 会根据程序的 IDL 在 `your_program::events` 模块中生成事件结构体。

### 解析指定类型的所有事件

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

anchor_lang::declare_program!(your_program);

use your_program::events::TransferEvent;

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

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

    // Execute instruction that emits events
    let ix = ctx.program()
        .accounts(your_program::client::accounts::Transfer { /* ... */ })
        .args(your_program::client::args::Transfer { amount: 1000 })
        .instruction()
        .unwrap();

    let result = ctx.execute_instruction(ix, &[&user]).unwrap();

    // Parse all TransferEvent events from the transaction
    let events: Vec<TransferEvent> = result.parse_events().unwrap();

    assert_eq!(events.len(), 1);
    assert_eq!(events[0].amount, 1000);
}
```

### 解析单个事件

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

anchor_lang::declare_program!(your_program);

use your_program::events::TransferEvent;

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

    // ... execute instruction ...

    // Get the first event of the type
    let event: TransferEvent = result.parse_event().unwrap();

    println!("Transfer: {} -> {} ({})", event.from, event.to, event.amount);
}
```

## 断言事件

### 断言事件已被发出

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

anchor_lang::declare_program!(your_program);

use your_program::events::InitializeEvent;

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

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

    let ix = ctx.program()
        .accounts(your_program::client::accounts::Initialize { /* ... */ })
        .args(your_program::client::args::Initialize { name: "test".to_string() })
        .instruction()
        .unwrap();

    let result = ctx.execute_instruction(ix, &[&user]).unwrap();

    // Assert that at least one InitializeEvent was emitted
    result.assert_event_emitted::<InitializeEvent>();
}
```

<Info>
  如果在交易日志中未找到指定类型的事件,`assert_event_emitted` 将会触发 panic。
</Info>

### 断言事件数量

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

anchor_lang::declare_program!(your_program);

use your_program::events::TransferEvent;

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

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

    // Execute instruction that emits multiple events
    let ix = ctx.program()
        .accounts(your_program::client::accounts::BatchTransfer { /* ... */ })
        .args(your_program::client::args::BatchTransfer { recipients: vec![...], amounts: vec![...] })
        .instruction()
        .unwrap();

    let result = ctx.execute_instruction(ix, &[&user]).unwrap();

    // Assert exactly 3 TransferEvent events were emitted
    result.assert_event_count::<TransferEvent>(3);
}
```

### 检查事件是否存在

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

anchor_lang::declare_program!(your_program);

use your_program::events::TransferEvent;

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

    // ... execute instruction ...

    // Check without panicking
    if result.has_event::<TransferEvent>() {
        let event: TransferEvent = result.parse_event().unwrap();
        println!("Transfer occurred: {}", event.amount);
    } else {
        println!("No transfer in this transaction");
    }
}
```

## 手动解析事件

对于高级用例,您可以直接解析事件数据:

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

anchor_lang::declare_program!(your_program);

use your_program::events::TransferEvent;

#[test]
fn test_manual_parse() {
    // If you have the base64-encoded event data
    let base64_data = "SGVsbG8gV29ybGQ="; // Example

    let event: TransferEvent = parse_event_data(base64_data).unwrap();
}
```

## 事件错误

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

```rust
use anchor_litesvm::{EventError, EventHelpers};

match result.parse_event::<TransferEvent>() {
    Ok(event) => println!("Amount: {}", event.amount),
    Err(EventError::EventNotFound) => println!("No event found"),
    Err(EventError::ParseError(msg)) => println!("Parse error: {}", msg),
    Err(EventError::Base64Error(e)) => println!("Invalid Base64 encoding: {e}"),
    Err(EventError::InvalidFormat) => println!("Malformed event data"),
    Err(EventError::AnchorError(msg)) => println!("Anchor error: {}", msg),
}
```

| 错误                      | 描述                            |
| -------------------------- | -------------------------------------- |
| `EventNotFound`            | 日志中没有指定类型的事件 |
| `ParseError(String)`       | 解析事件数据失败             |
| `Base64Error(DecodeError)` | Base64 解码失败                |
| `InvalidFormat`            | 事件数据结构无效       |
| `AnchorError(String)`      | Anchor 反序列化失败          |

## 完整示例

下面是一个综合示例,演示如何在 vault 程序中处理事件。该程序的 `create_vault`、`deposit` 和 `withdraw` 指令会分别发出
`VaultCreated`、`Deposit` 和 `Withdrawal` 事件:

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

// declare_program! generates the client types and an `events` module with
// the program's event structs
anchor_lang::declare_program!(vault);

use vault::events::{Deposit, VaultCreated, Withdrawal};

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

    let authority = ctx.svm.create_funded_account(100_000_000_000).unwrap();
    let depositor = ctx.svm.create_funded_account(50_000_000_000).unwrap();

    let vault_pda = ctx.svm.get_pda(
        &[b"vault", authority.pubkey().as_ref()],
        &vault::ID,
    );

    // Create vault
    let create_ix = ctx.program()
        .accounts(vault::client::accounts::CreateVault {
            authority: authority.pubkey(),
            vault: vault_pda,
            system_program: system_program::ID,
        })
        .args(vault::client::args::CreateVault {})
        .instruction()
        .unwrap();

    let result = ctx.execute_instruction(create_ix, &[&authority]).unwrap();

    // Assert VaultCreated event
    result.assert_event_emitted::<VaultCreated>();
    let created_event: VaultCreated = result.parse_event().unwrap();
    assert_eq!(created_event.vault, vault_pda);
    assert_eq!(created_event.authority, authority.pubkey());

    // Deposit. The client accounts struct is named after the instruction
    // (`deposit`), whatever the program calls its Accounts struct.
    let deposit_ix = ctx.program()
        .accounts(vault::client::accounts::Deposit {
            vault: vault_pda,
            depositor: depositor.pubkey(),
            system_program: system_program::ID,
        })
        .args(vault::client::args::Deposit { amount: 10_000_000_000 })
        .instruction()
        .unwrap();

    let result = ctx.execute_instruction(deposit_ix, &[&depositor]).unwrap();

    // Assert Deposit event
    result.assert_event_emitted::<Deposit>();
    let deposit_event: Deposit = result.parse_event().unwrap();
    assert_eq!(deposit_event.amount, 10_000_000_000);
    assert_eq!(deposit_event.depositor, depositor.pubkey());

    // Withdrawal
    let withdraw_ix = ctx.program()
        .accounts(vault::client::accounts::Withdraw {
            vault: vault_pda,
            authority: authority.pubkey(),
            recipient: authority.pubkey(),
        })
        .args(vault::client::args::Withdraw { amount: 5_000_000_000 })
        .instruction()
        .unwrap();

    let result = ctx.execute_instruction(withdraw_ix, &[&authority]).unwrap();

    // Check withdrawal event
    assert!(result.has_event::<Withdrawal>());
    let withdraw_event: Withdrawal = result.parse_event().unwrap();
    assert_eq!(withdraw_event.amount, 5_000_000_000);

    println!("All event tests passed!");
}
```

<Info>
  事件是验证程序是否正确执行的绝佳方式,无需获取账户并对其进行反序列化。它们在
  追踪状态随时间的变化时尤其有用。
</Info>
