Anchor 계정 디스크리미네이터 이해하기
Anchor 프로그램은 모든 계정 데이터 앞에 8바이트 디스크리미네이터를 붙입니다. 이
디스크리미네이터는 계정 타입 이름의 해시이며, 계정 데이터가 예상 타입과
일치하는지 검증하는 데 사용됩니다.
┌─────────────────────────────────────────────────┐
│ Account Data Layout │
├────────────────┬────────────────────────────────┤
│ Discriminator │ Account Fields │
│ (8 bytes) │ (variable size) │
└────────────────┴────────────────────────────────┘
anchor-litesvm 계정 유틸리티는 이 디스크리미네이터를 자동으로 처리합니다.
이 예제들을 실행하려면 프로그램의 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을 둘 위치는
빠른 시작을 참고하세요.
계정 타입은 declare_program!(your_program)에서 가져오며, 이 매크로가 프로그램의 IDL로부터 타입을 생성합니다. 계정 구조체는 your_program::accounts 아래에, enum 같은 기타 타입은 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 enum은 상세한 오류 정보를 제공합니다:
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 enum(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()은 호출 자체만 unwrap합니다. 런타임이 거부한
트랜잭션도 여전히 Ok를 반환하므로, 트랜잭션이 실패할 때 테스트도 실패하도록
.assert_success()를 체이닝하세요.