فهم مُميِّزات حسابات Anchor
تضيف برامج Anchor مُميِّزًا (discriminator) بحجم 8 بايت في بداية بيانات جميع الحسابات. هذا
المُميِّز هو تجزئة (hash) لاسم نوع الحساب، ويُستخدم للتحقق من أن
بيانات الحساب تطابق النوع المتوقع.
┌─────────────────────────────────────────────────┐
│ 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 الخاص ببرنامجك: هياكل الحسابات (structs) ضمن your_program::accounts
والأنواع الأخرى، مثل التعدادات (enums)، ضمن your_program::types. لا تصرّح بهياكل
#[account] في ملف الاختبار نفسه: فالماكرو يتوقع وجود ID الخاص بالبرنامج
في جذر الحزمة (crate)، وهو غير موجود في حزمة الاختبار.
جلب حسابات 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، والتعداد
OrderStatus (Pending وCompleted وCancelled) الذي يخزّنه 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));
}
التحقق من وجود الحساب قبل جلبه
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 حساب PDA من النوع Counter (count وauthority و
bump) وتضيف increment واحدًا إلى 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() غلاف الاستدعاء نفسه فقط. أما
المعاملة التي يرفضها وقت التشغيل فتُرجع Ok مع ذلك، لذا أضف
.assert_success() في السلسلة لكي يفشل الاختبار عندما تفشل المعاملة.