anchor-litesvm
This is a crate for writing LiteSVM tests when you are testing an Anchor program.
Overview
anchor-litesvm provides a minimal wrapper around LiteSVM that handles Anchor-specific patterns, reducing test code by 60-70% while maintaining full control and flexibility.
Quick Start
use AnchorLiteSVM;
let mut ctx = build_with_program;
// access helper methods from the Anchor Context
let account = ctx.create_funded_account?;
let mint = ctx.create_token_mint?;
Why Use anchor-litesvm?
1. Instruction Builder with Direct Execution
Eliminates ~15 lines of boilerplate per instruction:
// Before (manual approach):
let mut hasher = new;
hasher.update;
let hash = hasher.finalize;
let mut discriminator = ;
discriminator.copy_from_slice;
let mut instruction_data = discriminator.to_vec;
instruction_data.extend_from_slice;
instruction_data.extend_from_slice;
instruction_data.extend_from_slice;
let make_instruction = Instruction ;
let tx = new_signed_with_payer;
let result = svm.send_transaction;
// After (with anchor-litesvm):
// Build and execute in one call
let result = ctx.instruction_builder
.signer
.account_mut
.account
.system_program
.args // No struct needed!
.execute?;
2. Type-Safe Account Deserialization
Automatic Anchor account unpacking:
// Before:
let account_data = svm.get_account.unwrap;
let escrow: EscrowState = try_from_slice.unwrap;
// After:
let escrow: EscrowState = ctx.get_anchor_account?;
3. Transaction Execution Helpers
Simplified transaction execution:
// Execute single instruction
let result = ctx.send_instruction?;
result.assert_success;
// Execute multiple instructions
let result = ctx.send_instructions?;
// Build and execute in one call
let result = ctx.execute?;
// Transaction result helpers
assert!;
println!;
4. Test Account Helpers
Streamlined account creation for tests:
// Create funded account
let maker = ctx.create_funded_account?;
// Create multiple accounts
let accounts = ctx.create_funded_accounts?;
// Create token mint
let mint = ctx.create_token_mint?;
// Create token account and mint tokens
let ata = ctx.create_token_account?;
// Batch airdrop
ctx.batch_airdrop?;
5. Assertion Helpers
Clean test assertions:
// Account assertions
ctx.assert_account_exists;
ctx.assert_account_closed;
ctx.assert_accounts_closed;
// Token balance assertions
ctx.assert_token_balance;
ctx.assert_token_balance_with_msg;
// Lamports and owner assertions
ctx.assert_account_lamports;
ctx.assert_account_owner;
6. Simplified Test Setup
Multiple ways to initialize your test environment:
// Simplest - one line setup
let mut ctx = build_with_program;
// Builder pattern for multiple programs
let mut ctx = new
.deploy_program
.deploy_program
.build;
// Extension trait on Pubkey
use ProgramTestExt;
let mut ctx = PROGRAM_ID.test_with;
7. Direct LiteSVM Access
The AnchorContext provides full access to the underlying LiteSVM instance:
let mut ctx = new;
// Direct access for any LiteSVM operations
ctx.svm.airdrop;
ctx.svm.send_transaction;