declare_program! によるクライアント型の生成
Anchor 1.0 ではdeclare_program! が導入されました。これはコンパイル時にプログラムの IDL を読み込み、
型安全な client::accounts::* モジュールと client::args::* モジュールを生成します。
テストで instructions を構築する際は、この方法を推奨します。
// At the top of your test file, generate client modules from the IDL
use anchor_lang::prelude::*;
anchor_lang::declare_program!(my_program);
// Now use the generated types:
// my_program::ID (the program ID from the IDL)
// my_program::client::accounts::Initialize { ... }
// my_program::client::args::Initialize { ... }
// my_program::accounts::MyAccount (for account deserialization)
// my_program::events::MyEvent (for event parsing)
anchor build を実行し、target/idl/my_program.json を
idls/my_program.json にコピーしてください。declare_program! は、クレートのディレクトリまたはその親ディレクトリにある最も近い idls ディレクトリから、コンパイル時に idls/<name>.json を読み込みます。
マクロ名は IDL ファイル名(プログラムのスネークケースの名前)と一致している必要があります。
マクロを呼び出す場所では anchor_lang がスコープ内にある必要があるため、
その上に use anchor_lang::prelude::*; を追加してください。テストと IDL の配置場所については、
クイックスタート
を参照してください。これらの例では、プログラムの 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 については、
クイックスタートを参照してください。テスト環境のセットアップ
AnchorLiteSVM ビルダーは、テスト環境を設定するためのフルエントな API を提供します。
基本的なセットアップ
use anchor_lang::prelude::*;
use anchor_litesvm::AnchorLiteSVM;
anchor_lang::declare_program!(my_program);
#[test]
fn test_basic_setup() {
// declare_program! provides the program ID from the IDL
let ctx = AnchorLiteSVM::new()
.deploy_program(
my_program::ID,
include_bytes!("../../../target/deploy/my_program.so"),
)
.build();
println!("Program deployed: {}", ctx.program().id());
}
単一プログラムの簡易記法
use anchor_lang::prelude::*;
use anchor_litesvm::AnchorLiteSVM;
anchor_lang::declare_program!(my_program);
#[test]
fn test_single_program() {
// Convenience method for single-program setups
let ctx = AnchorLiteSVM::build_with_program(
my_program::ID,
include_bytes!("../../../target/deploy/my_program.so"),
);
}
複数のプログラム
use anchor_lang::prelude::*;
use anchor_litesvm::AnchorLiteSVM;
anchor_lang::declare_program!(program_a);
anchor_lang::declare_program!(program_b);
#[test]
fn test_multiple_programs() {
// Deploy multiple programs — first one becomes the primary (ctx.program_id)
let ctx = AnchorLiteSVM::build_with_programs(&[
(program_a::ID, include_bytes!("../../../target/deploy/program_a.so") as &[u8]),
(program_b::ID, include_bytes!("../../../target/deploy/program_b.so") as &[u8]),
]);
// Primary program is program_a
assert_eq!(ctx.program().id(), program_a::ID);
}
カスタム Payer
use anchor_lang::prelude::*;
use anchor_litesvm::{AnchorLiteSVM, Keypair, Signer};
anchor_lang::declare_program!(my_program);
#[test]
fn test_custom_payer() {
let custom_payer = Keypair::new();
let ctx = AnchorLiteSVM::new()
.with_payer(custom_payer)
.deploy_program(
my_program::ID,
include_bytes!("../../../target/deploy/my_program.so"),
)
.build();
println!("Payer: {}", ctx.payer().pubkey());
}
payer を指定しない場合、
AnchorLiteSVM が自動的に payer を作成し、資金を付与します。AnchorContext
AnchorContext は、テスト環境を操作するためのメインのインターフェースです。
主要なプロパティ
use anchor_lang::prelude::*;
use anchor_litesvm::{AnchorLiteSVM, Signer};
anchor_lang::declare_program!(my_program);
#[test]
fn test_context_properties() {
let ctx = AnchorLiteSVM::build_with_program(
my_program::ID,
include_bytes!("../../../target/deploy/my_program.so"),
);
// ctx.svm — direct access to the underlying LiteSVM instance (public field)
let balance = ctx.svm.get_balance(&ctx.payer().pubkey());
// ctx.payer() — the payer keypair
let payer = ctx.payer();
println!("Payer pubkey: {}", payer.pubkey());
// ctx.program() — Program instance for instruction building
let program = ctx.program();
println!("Program ID: {}", program.id());
// ctx.latest_blockhash()
let blockhash = ctx.latest_blockhash();
}
資金付きアカウントの作成
use anchor_lang::prelude::*;
use anchor_litesvm::{AnchorLiteSVM, Keypair, Signer, TestHelpers};
anchor_lang::declare_program!(my_program);
#[test]
fn test_create_accounts() {
let mut ctx = AnchorLiteSVM::build_with_program(
my_program::ID,
include_bytes!("../../../target/deploy/my_program.so"),
);
// Option 1: via AnchorContext (returns Result<Keypair>)
let user = ctx.create_funded_account(10_000_000_000).unwrap();
// Option 2: via ctx.svm with TestHelpers (same result)
let user2 = ctx.svm.create_funded_account(10_000_000_000).unwrap();
// Airdrop to an existing address
let another_user = Keypair::new();
ctx.airdrop(&another_user.pubkey(), 5_000_000_000).unwrap();
}
アカウントの存在確認
use anchor_lang::prelude::*;
use anchor_litesvm::{AnchorLiteSVM, TestHelpers};
anchor_lang::declare_program!(my_program);
#[test]
fn test_account_exists() {
let ctx = AnchorLiteSVM::build_with_program(
my_program::ID,
include_bytes!("../../../target/deploy/my_program.so"),
);
let some_pda = ctx.svm.get_pda(&[b"vault"], &my_program::ID);
if ctx.account_exists(&some_pda) {
println!("Account exists!");
} else {
println!("Account not found");
}
}
Program を使った instructions の構築
Program 構造体は、anchor-client と同様に instructions を構築するためのフルエントな API を提供します。
型安全性を確保するため、declare_program! が生成する型を使用してください。
基本的な instruction の構築
use anchor_lang::prelude::*;
use anchor_lang::system_program;
use anchor_litesvm::{AnchorLiteSVM, Signer, TestHelpers};
anchor_lang::declare_program!(my_program);
#[test]
fn test_build_instruction() {
let mut ctx = AnchorLiteSVM::build_with_program(
my_program::ID,
include_bytes!("../../../target/deploy/my_program.so"),
);
let user = ctx.svm.create_funded_account(10_000_000_000).unwrap();
let seed: u64 = 42;
let user_pda = ctx.svm.get_pda(
&[b"user", user.pubkey().as_ref(), &seed.to_le_bytes()],
&my_program::ID,
);
// Build instruction using types generated by declare_program!
let ix = ctx.program()
.accounts(my_program::client::accounts::Initialize {
user: user.pubkey(),
user_account: user_pda,
system_program: system_program::ID,
})
.args(my_program::client::args::Initialize {
seed,
name: "test".to_string(),
})
.instruction()
.unwrap();
println!("Instruction built successfully!");
}
.accounts() メソッドは ToAccountMetas を実装する任意の型を受け付けます。
Anchor のアカウント構造体はすべて自動的にこれを実装しています。同様に、.args() は
InstructionData を実装する任意の型を受け付けます。instructions の実行
use anchor_lang::prelude::*;
use anchor_lang::system_program;
use anchor_litesvm::{AnchorLiteSVM, Signer, TestHelpers};
anchor_lang::declare_program!(my_program);
#[test]
fn test_execute_instruction() {
let mut ctx = AnchorLiteSVM::build_with_program(
my_program::ID,
include_bytes!("../../../target/deploy/my_program.so"),
);
let user = ctx.svm.create_funded_account(10_000_000_000).unwrap();
let seed: u64 = 42;
let user_pda = ctx.svm.get_pda(
&[b"user", user.pubkey().as_ref(), &seed.to_le_bytes()],
&my_program::ID,
);
let ix = ctx.program()
.accounts(my_program::client::accounts::Initialize {
user: user.pubkey(),
user_account: user_pda,
system_program: system_program::ID,
})
.args(my_program::client::args::Initialize { seed, name: "test".to_string() })
.instruction()
.unwrap();
// Execute — returns TransactionResult
ctx.execute_instruction(ix, &[&user])
.unwrap()
.assert_success();
}
複数の instructions の実行
use anchor_lang::prelude::*;
use anchor_litesvm::{AnchorLiteSVM, Signer, TestHelpers};
anchor_lang::declare_program!(my_program);
#[test]
fn test_execute_multiple_instructions() {
let mut ctx = AnchorLiteSVM::build_with_program(
my_program::ID,
include_bytes!("../../../target/deploy/my_program.so"),
);
let user = ctx.svm.create_funded_account(10_000_000_000).unwrap();
let ix1 = ctx.program()
.accounts(my_program::client::accounts::Initialize { /* ... */ })
.args(my_program::client::args::Initialize { seed: 42, name: "first".to_string() })
.instruction()
.unwrap();
let ix2 = ctx.program()
.accounts(my_program::client::accounts::Update { /* ... */ })
.args(my_program::client::args::Update { name: "second".to_string() })
.instruction()
.unwrap();
// Execute multiple instructions in one transaction
ctx.execute_instructions(vec![ix1, ix2], &[&user])
.unwrap()
.assert_success();
}
send_and_confirm_transaction の使用
use anchor_lang::prelude::*;
use anchor_litesvm::{AnchorLiteSVM, Signer, TestHelpers};
use solana_sdk::transaction::Transaction;
anchor_lang::declare_program!(my_program);
#[test]
fn test_send_transaction() {
let mut ctx = AnchorLiteSVM::build_with_program(
my_program::ID,
include_bytes!("../../../target/deploy/my_program.so"),
);
let user = ctx.svm.create_funded_account(10_000_000_000).unwrap();
let ix = ctx.program()
.accounts(/* ... */)
.args(/* ... */)
.instruction()
.unwrap();
// Build transaction manually if needed
let tx = Transaction::new_signed_with_payer(
&[ix],
Some(&ctx.payer().pubkey()),
&[ctx.payer(), &user],
ctx.latest_blockhash(),
);
// Note: takes &Transaction (reference)
ctx.send_and_confirm_transaction(&tx).unwrap();
}
完全なサンプル
ここでは、anchor-escrow-with-litesvm にあるようなエスクローのプログラムを対象に、declare_program! を使ったエスクローパターンの総合的なサンプルを紹介します。
このサンプルでは Associated Token Account と SPL Token のクレートも使用するため、
先にそれらを追加してください(programs/anchor_escrow から実行):
cargo add --dev spl-associated-token-account@8 litesvm-token@0.11
use anchor_lang::prelude::*;
use anchor_lang::system_program;
use anchor_litesvm::{AnchorLiteSVM, AssertionHelpers, Signer, TestHelpers};
use litesvm_token::spl_token;
use spl_associated_token_account::get_associated_token_address;
anchor_lang::declare_program!(anchor_escrow);
#[test]
fn test_make_and_take() {
// 1. One-line setup
let program_id = anchor_escrow::ID;
let mut ctx = AnchorLiteSVM::build_with_program(
program_id,
include_bytes!("../../../target/deploy/anchor_escrow.so"),
);
// 2. Create test accounts using TestHelpers on ctx.svm
let maker = ctx.svm.create_funded_account(10_000_000_000).unwrap();
let taker = ctx.svm.create_funded_account(10_000_000_000).unwrap();
// 3. Create token mints and funded ATAs
let mint_a = ctx.svm.create_token_mint(&maker, 9).unwrap();
let mint_b = ctx.svm.create_token_mint(&maker, 9).unwrap();
let maker_ata_a = ctx.svm
.create_associated_token_account(&mint_a.pubkey(), &maker)
.unwrap();
ctx.svm.mint_to(&mint_a.pubkey(), &maker_ata_a, &maker, 1_000_000_000).unwrap();
let taker_ata_b = ctx.svm
.create_associated_token_account(&mint_b.pubkey(), &taker)
.unwrap();
ctx.svm.mint_to(&mint_b.pubkey(), &taker_ata_b, &maker, 500_000_000).unwrap();
// 4. Derive PDAs
let seed: u64 = 42;
let escrow_pda = ctx.svm.get_pda(
&[b"escrow", maker.pubkey().as_ref(), &seed.to_le_bytes()],
&program_id,
);
let vault = get_associated_token_address(&escrow_pda, &mint_a.pubkey());
// 5. Build and execute Make instruction using generated client types
let make_ix = ctx.program()
.accounts(anchor_escrow::client::accounts::Make {
maker: maker.pubkey(),
escrow: escrow_pda,
mint_a: mint_a.pubkey(),
mint_b: mint_b.pubkey(),
maker_ata_a,
vault,
associated_token_program: spl_associated_token_account::id(),
token_program: spl_token::id(),
system_program: system_program::ID,
})
.args(anchor_escrow::client::args::Make {
seed,
receive: 500_000_000,
amount: 1_000_000_000,
})
.instruction()
.unwrap();
ctx.execute_instruction(make_ix, &[&maker])
.unwrap()
.assert_success();
// 6. Assert state using AssertionHelpers on ctx.svm
assert!(ctx.account_exists(&escrow_pda));
ctx.svm.assert_token_balance(&vault, 1_000_000_000);
ctx.svm.assert_token_balance(&maker_ata_a, 0);
// 7. Execute Take
let taker_ata_a = get_associated_token_address(&taker.pubkey(), &mint_a.pubkey());
let maker_ata_b = get_associated_token_address(&maker.pubkey(), &mint_b.pubkey());
let take_ix = ctx.program()
.accounts(anchor_escrow::client::accounts::Take {
taker: taker.pubkey(),
maker: maker.pubkey(),
escrow: escrow_pda,
mint_a: mint_a.pubkey(),
mint_b: mint_b.pubkey(),
vault,
taker_ata_a,
taker_ata_b,
maker_ata_b,
associated_token_program: spl_associated_token_account::id(),
token_program: spl_token::id(),
system_program: system_program::ID,
})
.args(anchor_escrow::client::args::Take {})
.instruction()
.unwrap();
ctx.execute_instruction(take_ix, &[&taker])
.unwrap()
.assert_success();
// 8. Final assertions
ctx.svm.assert_account_closed(&escrow_pda);
ctx.svm.assert_account_closed(&vault);
ctx.svm.assert_token_balance(&taker_ata_a, 1_000_000_000);
ctx.svm.assert_token_balance(&maker_ata_b, 500_000_000);
}