Tìm hiểu về discriminator của tài khoản Anchor
Các chương trình Anchor thêm một discriminator 8 byte vào đầu tất cả dữ liệu tài khoản. Discriminator
này là giá trị băm của tên kiểu tài khoản và được dùng để xác minh rằng
dữ liệu tài khoản khớp với kiểu mong đợi.
┌─────────────────────────────────────────────────┐
│ Account Data Layout │
├────────────────┬────────────────────────────────┤
│ Discriminator │ Account Fields │
│ (8 bytes) │ (variable size) │
└────────────────┴────────────────────────────────┘
Các tiện ích tài khoản của anchor-litesvm tự động xử lý discriminator này.
Các ví dụ này cần bản build SBPF v0 của chương trình. anchor-litesvm 0.4
sử dụng LiteSVM 0.11, vốn không thể tải các chương trình SBPF v3, nên build_with_program
sẽ panic với lỗi Failed to add program: Instruction(InvalidAccountData). Với
Anchor 1.2 trở lên, hãy build bằng anchor build --arch v0 và chạy
anchor test --skip-build. Với Anchor 1.1.x, cũng như vị trí đặt bài kiểm thử
và IDL, hãy xem
Hướng dẫn bắt đầu nhanh.
Các kiểu tài khoản được lấy từ declare_program!(your_program), macro này tạo ra
chúng từ IDL của chương trình: các struct tài khoản nằm trong your_program::accounts
còn các kiểu khác, chẳng hạn enum, nằm trong your_program::types. Đừng khai báo
các struct #[account] trong chính tệp kiểm thử: macro mong đợi ID của chương trình
nằm ở gốc crate, mà crate kiểm thử thì không có.
Truy xuất tài khoản Anchor
Truy xuất tài khoản cơ bản
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>() tự động xác thực discriminator 8 byte để đảm bảo dữ liệu tài khoản khớp với kiểu mong đợi.
Giải tuần tự hóa không kiểm tra
Đối với PDA hoặc các bố cục tài khoản tùy chỉnh mà việc xác thực discriminator có thể thất bại,
hãy dùng 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();
}
Hãy dùng get_account_unchecked cẩn thận. Nếu không xác thực discriminator, bạn
có thể giải tuần tự hóa dữ liệu không hợp lệ. Chỉ dùng hàm này khi bạn chắc chắn về
kiểu tài khoản.
Sử dụng trực tiếp module tài khoản
Bạn cũng có thể sử dụng trực tiếp các hàm giải tuần tự hóa tài khoản:
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();
}
Lỗi tài khoản
Enum AccountError cung cấp thông tin lỗi chi tiết:
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);
}
}
}
Làm việc với nhiều kiểu tài khoản
Truy xuất các kiểu tài khoản khác nhau
Ở đây your_program định nghĩa các tài khoản Config, UserProfile và Order, cùng
enum OrderStatus (Pending, Completed, Cancelled) mà Order lưu trữ:
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));
}
Kiểm tra sự tồn tại của tài khoản trước khi truy xuất
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");
}
}
Ví dụ hoàn chỉnh
Dưới đây là một ví dụ toàn diện minh họa việc quản lý tài khoản với chương trình
bộ đếm, trong đó initialize tạo một PDA Counter (count, authority,
bump) và increment cộng thêm một vào 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() chỉ unwrap chính lệnh gọi đó. Một
giao dịch bị runtime từ chối vẫn trả về Ok, vì vậy hãy nối thêm
.assert_success() để bài kiểm thử thất bại khi giao dịch thất bại.