Anchor 이벤트 이해하기
Anchor 프로그램은 트랜잭션 실행 중에 로그로 기록되는 이벤트를 발생시킬 수 있습니다. 이러한 이벤트는 트랜잭션 로그에Program data: 접두사와 함께 Base64로 인코딩되어 기록됩니다.
anchor-litesvm 크레이트는 이러한 이벤트를 파싱하고 검증하는 유틸리티를 제공합니다.
┌─────────────────────────────────────────────────┐
│ Anchor Event Structure │
├────────────────┬────────────────────────────────┤
│ Discriminator │ Event Data │
│ (8 bytes) │ (serialized fields) │
└────────────────┴────────────────────────────────┘
이 예제를 실행하려면 프로그램을 SBPF v0으로 빌드해야 합니다.
anchor-litesvm 0.4는
LiteSVM 0.11을 사용하며, 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의 경우와 테스트 및 IDL을 배치할 위치는
빠른 시작을 참고하세요.이벤트 정의하기
먼저 Anchor 프로그램에서 이벤트를 정의합니다.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 모듈에 이벤트 구조체를 생성합니다.
특정 유형의 모든 이벤트 파싱하기
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);
}
단일 이벤트 파싱하기
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);
}
이벤트 검증하기
이벤트 발생 여부 검증하기
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>();
}
지정한 유형의 이벤트가 트랜잭션 로그에서 발견되지 않으면
assert_event_emitted가
패닉을 일으킵니다.이벤트 개수 검증하기
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);
}
이벤트 존재 여부 확인하기
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");
}
}
수동 이벤트 파싱
고급 사용 사례에서는 이벤트 데이터를 직접 파싱할 수 있습니다.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 열거형은 상세한 오류 정보를 제공합니다.
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 역직렬화에 실패했습니다 |
전체 예제
다음은 볼트 프로그램을 사용하여 이벤트 처리를 보여 주는 종합 예제입니다. 이 프로그램의create_vault, deposit, withdraw 인스트럭션은 각각 VaultCreated, Deposit, Withdrawal 이벤트를 발생시킵니다.
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!");
}
이벤트는 계정을 가져와 역직렬화하지 않고도 프로그램이 올바르게 실행되었는지 확인할 수 있는 유용한 방법입니다. 특히 시간에 따른 상태 변화를 추적하는 데 유용합니다.