Anchor アカウントのディスクリミネーターについて
Anchor プログラムは、すべてのアカウントデータの先頭に8バイトのディスクリミネーターを付加します。このディスクリミネーターはアカウント型名のハッシュで、アカウントデータが期待される型と一致するかを検証するために使われます。
┌─────────────────────────────────────────────────┐
│ Account Data Layout │
├────────────────┬────────────────────────────────┤
│ Discriminator │ Account Fields │
│ (8 bytes) │ (variable size) │
└────────────────┴────────────────────────────────┘
anchor-litesvm のアカウントユーティリティは、このディスクリミネーターを自動的に処理します。
これらの例には、プログラムの SBPF v0 ビルドが必要です。anchor-litesvm 0.4 は 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 の配置場所については、クイックスタートを参照してください。
アカウント型は declare_program!(your_program) から取得します。このマクロはプログラムの IDL から型を生成し、アカウント構造体は your_program::accounts に、列挙型などその他の型は your_program::types に配置されます。テストファイル内で #[account] 構造体を宣言しないでください。このマクロはクレートルートにプログラムの ID があることを前提としていますが、テストクレートにはそれがありません。
Anchor アカウントの取得
基本的なアカウントの取得
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>() は8バイトのディスクリミネーターを自動的に検証し、アカウントデータが期待される型と一致することを確認します。
チェックなしのデシリアライズ
PDA やカスタムのアカウントレイアウトなど、ディスクリミネーターの検証が失敗する可能性がある場合は、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();
}
get_account_unchecked は慎重に使用してください。ディスクリミネーターの検証を行わないため、無効なデータをデシリアライズしてしまう可能性があります。アカウントの型が確実にわかっている場合にのみ使用してください。
アカウントモジュールを直接使用する
アカウントのデシリアライズ関数を直接使用することもできます。
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 列挙型は、詳細なエラー情報を提供します。
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);
}
}
}
複数のアカウント型を扱う
さまざまなアカウント型の取得
ここでは、your_program が Config、UserProfile、Order の各アカウントと、Order が保持する OrderStatus 列挙型(Pending、Completed、Cancelled)を定義しているものとします。
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));
}
取得前にアカウントの存在を確認する
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 に1を加算します。
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() が展開するのは呼び出し自体の結果だけです。ランタイムに拒否されたトランザクションでも Ok が返されるため、トランザクションが失敗したときにテストも失敗するよう、.assert_success() を連鎖させてください。