Memahami Discriminator Akun Anchor
Program Anchor menambahkan discriminator 8 byte di awal semua data akun. Discriminator ini merupakan hash dari nama tipe akun dan digunakan untuk memverifikasi bahwa data akun sesuai dengan tipe yang diharapkan.
┌─────────────────────────────────────────────────┐
│ Account Data Layout │
├────────────────┬────────────────────────────────┤
│ Discriminator │ Account Fields │
│ (8 bytes) │ (variable size) │
└────────────────┴────────────────────────────────┘
Utilitas akun anchor-litesvm menangani discriminator ini secara otomatis.
Contoh-contoh ini memerlukan build SBPF v0 dari program Anda. anchor-litesvm 0.4
menggunakan LiteSVM 0.11, yang tidak dapat memuat program SBPF v3, sehingga build_with_program
mengalami panic dengan pesan Failed to add program: Instruction(InvalidAccountData). Dengan
Anchor 1.2 dan yang lebih baru, lakukan build dengan anchor build --arch v0 dan jalankan
anchor test --skip-build. Untuk Anchor 1.1.x, serta untuk mengetahui letak penempatan test
dan IDL, lihat
Panduan Memulai.
Tipe akun berasal dari declare_program!(your_program), yang menghasilkannya dari IDL program Anda: struct akun berada di bawah your_program::accounts dan tipe lainnya, seperti enum, berada di bawah your_program::types. Jangan mendeklarasikan struct #[account] di dalam file test itu sendiri: makro tersebut mengharapkan ID program berada di crate root, yang tidak dimiliki oleh crate test.
Mengambil Akun Anchor
Pengambilan Akun Dasar
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());
}
get_account<T>() secara otomatis memvalidasi discriminator 8 byte untuk memastikan data akun sesuai dengan tipe yang diharapkan.
Deserialisasi Tanpa Pemeriksaan
Untuk PDA atau tata letak akun kustom yang validasi discriminator-nya mungkin gagal, gunakan get_account_unchecked:
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();
}
Gunakan get_account_unchecked dengan hati-hati. Tanpa validasi discriminator, Anda mungkin mendeserialisasi data yang tidak valid. Gunakan hanya jika Anda yakin dengan tipe akunnya.
Menggunakan Modul Akun Secara Langsung
Anda juga dapat menggunakan fungsi deserialisasi akun secara langsung:
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();
}
Error Akun
Enum AccountError menyediakan informasi error yang mendetail:
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);
}
}
}
Bekerja dengan Beberapa Tipe Akun
Mengambil Berbagai Tipe Akun
Di sini your_program mendefinisikan akun Config, UserProfile, dan Order, serta enum OrderStatus (Pending, Completed, Cancelled) yang disimpan oleh Order:
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));
}
Memeriksa Keberadaan Akun Sebelum Mengambil
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");
}
}
Contoh Lengkap
Berikut contoh komprehensif yang mendemonstrasikan manajemen akun dengan program counter, yang initialize-nya membuat PDA Counter (count, authority, bump) dan increment-nya menambahkan satu ke count:
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);
}
execute_instruction(...).unwrap() hanya membuka hasil dari pemanggilannya saja. Transaksi yang ditolak oleh runtime tetap mengembalikan Ok, jadi rangkaikan
.assert_success() agar test gagal ketika transaksinya gagal.