Anchor Olaylarını Anlamak
Anchor programları, işlem yürütülürken günlüğe kaydedilen olaylar yayınlayabilir.
Bu olaylar, işlem günlüklerinde Program data: önekiyle Base64 olarak
kodlanır. anchor-litesvm crate’i, bu olayları ayrıştırmak ve doğrulamak için
yardımcı araçlar sunar.
┌─────────────────────────────────────────────────┐
│ Anchor Event Structure │
├────────────────┬────────────────────────────────┤
│ Discriminator │ Event Data │
│ (8 bytes) │ (serialized fields) │
└────────────────┴────────────────────────────────┘
Bu örnekler, programınızın SBPF v0 derlemesini gerektirir. anchor-litesvm 0.4,
SBPF v3 programlarını yükleyemeyen LiteSVM 0.11 sürümünü kullanır; bu nedenle
build_with_program şu hatayla panic verir: Failed to add program: Instruction(InvalidAccountData).
Anchor 1.2 ve sonraki sürümlerde anchor build --arch v0 ile derleyin ve
anchor test --skip-build komutunu çalıştırın. Anchor 1.1.x için ve testin
ile IDL’in nereye konulacağı hakkında bilgi almak için
Hızlı Başlangıç bölümüne bakın.
Olayları Tanımlama
Önce olaylarınızı Anchor programınızda tanımlayın:
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,
}
Olayları Ayrıştırma
Testlerinizde declare_program!(your_program), olay yapılarını (struct) programın
IDL’inden your_program::events modülünde oluşturur.
Bir Türdeki Tüm Olayları Ayrıştırma
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);
}
Tek Bir Olayı Ayrıştırma
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);
}
Olayları Doğrulama
Olayın Yayınlandığını Doğrulama
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, işlem günlüklerinde belirtilen türde hiçbir olay
bulunamazsa panic verir.
Olay Sayısını Doğrulama
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);
}
Olayın Varlığını Kontrol Etme
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");
}
}
Manuel Olay Ayrıştırma
Gelişmiş kullanım senaryolarında olay verilerini doğrudan ayrıştırabilirsiniz:
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();
}
Olay Hataları
EventError enum’ı ayrıntılı hata bilgisi sağlar:
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),
}
Tam Örnek
Aşağıda, bir kasa (vault) programıyla olay yönetimini gösteren kapsamlı bir örnek
yer alıyor. Programın create_vault, deposit ve withdraw talimatları
VaultCreated, Deposit ve Withdrawal olaylarını yayınlar:
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!");
}
Olaylar, hesapları getirip seri durumundan çıkarmak zorunda kalmadan programınızın
doğru çalıştığını doğrulamanın harika bir yoludur. Özellikle durum
değişikliklerini zaman içinde izlemek için çok kullanışlıdırlar.