For complex scenarios where account state must persist between multiple instruction calls, use MolluskContext.
MolluskContext wraps a Mollusk instance and an AccountStore. It automatically manages accounts: when an instruction executes, the resulting account states are automatically stored in the context. This eliminates the need to manually pass the full account list for every subsequent instruction.
To use it, call mollusk.with_context(account_store) where account_store implements the AccountStore trait. Note that HashMap<Pubkey, Account> implements AccountStore directly for easy use.
use {
mollusk_svm::{Mollusk, account_store::AccountStore},
solana_account::Account,
solana_instruction::Instruction,
solana_pubkey::Pubkey,
solana_system_interface::instruction as system_instruction,
std::collections::HashMap,
};
// Simple in-memory account store implementation
#[derive(Default)]
struct InMemoryAccountStore {
accounts: HashMap<Pubkey, Account>,
}
impl AccountStore for InMemoryAccountStore {
fn get_account(&self, pubkey: &Pubkey) -> Option<Account> {
self.accounts.get(pubkey).cloned()
}
fn store_account(&mut self, pubkey: Pubkey, account: Account) {
self.accounts.insert(pubkey, account);
}
}
let mollusk = Mollusk::default();
let context = mollusk.with_context(InMemoryAccountStore::default());
let alice = Pubkey::new_unique();
let bob = Pubkey::new_unique();
// Execute instructions without managing accounts manually
let instruction1 = system_instruction::transfer(&alice, &bob, 1_000_000);
let result1 = context.process_instruction(&instruction1);
let instruction2 = system_instruction::transfer(&bob, &alice, 500_000);
let result2 = context.process_instruction(&instruction2);
// Account state is automatically preserved between calls