### Using expect with environment variable retrieval Source: https://docs.rs/litesvm/latest/litesvm/types/type.TransactionResult.html Example of using expect for retrieving environment variables, providing a clear message about expected setup. ```rust let path = std::env::var("IMPORTANT_PATH") .expect("env variable `IMPORTANT_PATH` should be set by `wrapper_script.sh`"); ``` -------------------------------- ### Create LiteSVM Instance Source: https://docs.rs/litesvm/latest/litesvm/struct.LiteSVM.html Creates a basic test environment for LiteSVM. This is the simplest way to get started. ```rust pub struct LiteSVM { /* private fields */ } ``` -------------------------------- ### Inspect Accounts Database Example Source: https://docs.rs/litesvm/latest/litesvm/struct.LiteSVM.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Demonstrates how to obtain read-only access to the internal accounts database for inspection purposes. ```rust use litesvm::LiteSVM; let svm = LiteSVM::new(); // Read-only access to accounts database let accounts_db = svm.accounts_db(); // ... inspect internal state if needed ``` -------------------------------- ### Deploying and Testing a Logging Program Source: https://docs.rs/litesvm/latest/litesvm/index.html Shows how to add a compiled Solana program to the test environment and execute an instruction that triggers program logs. This example uses a pre-compiled SPL logging program. ```rust use { litesvm::LiteSVM, solana_address::{address, Address}, solana_instruction::{account_meta::AccountMeta, Instruction}, solana_keypair::Keypair, solana_message::{Message, VersionedMessage}, solana_signer::Signer, solana_transaction::versioned::VersionedTransaction, }; fn test_logging() { let program_id = address!("Logging111111111111111111111111111111111111"); let account_meta = AccountMeta { pubkey: Address::new_unique(), is_signer: false, is_writable: true, }; let ix = Instruction { program_id, accounts: vec![account_meta], data: vec![5, 10, 11, 12, 13, 14], }; let mut svm = LiteSVM::new(); let payer = Keypair::new(); let bytes = include_bytes!("../../node-litesvm/program_bytes/spl_example_logging.so"); svm.add_program(program_id, bytes); svm.airdrop(&payer.pubkey(), 1_000_000_000).unwrap(); let blockhash = svm.latest_blockhash(); let msg = Message::new_with_blockhash(&[ix], Some(&payer.pubkey()), &blockhash); let tx = VersionedTransaction::try_new(VersionedMessage::Legacy(msg), &[payer]).unwrap(); // let's sim it first let sim_res = svm.simulate_transaction(tx.clone()).unwrap(); let meta = svm.send_transaction(tx).unwrap(); assert_eq!(sim_res.meta, meta); assert_eq!(meta.logs[1], "Program log: static string"); assert!(meta.compute_units_consumed < 10_000) // not being precise here in case it changes } ``` -------------------------------- ### Minimal Example: Transferring SOL Source: https://docs.rs/litesvm/latest/litesvm/index.html Demonstrates a basic transaction involving SOL transfer between two accounts. Ensure accounts have sufficient lamports before initiating the transfer. ```rust use litesvm::LiteSVM; use solana_address::Address; use solana_message::Message; use solana_system_interface::instruction::transfer; use solana_keypair::Keypair; use solana_signer::Signer; use solana_transaction::Transaction; let from_keypair = Keypair::new(); let from = from_keypair.pubkey(); let to = Address::new_unique(); let mut svm = LiteSVM::new(); svm.airdrop(&from, 1_000_000_000).unwrap(); svm.airdrop(&to, 1_000_000_000).unwrap(); let instruction = transfer(&from, &to, 64); let tx = Transaction::new( &[&from_keypair], Message::new(&[instruction], Some(&from)), svm.latest_blockhash(), ); let tx_res = svm.send_transaction(tx).unwrap(); let from_account = svm.get_account(&from); let to_account = svm.get_account(&to); assert_eq!(from_account.unwrap().lamports, 999994936); assert_eq!(to_account.unwrap().lamports, 1000000064); ``` -------------------------------- ### Create LiteSVM with Initial Lamports Source: https://docs.rs/litesvm/latest/litesvm/struct.LiteSVM.html?search= Configures the initial lamports in LiteSVM's airdrop account using a builder pattern. This sets the starting balance for the VM. ```rust pub fn with_lamports(self, lamports: u64) -> Self ``` -------------------------------- ### Create LiteSVM with Default Sysvars Source: https://docs.rs/litesvm/latest/litesvm/struct.LiteSVM.html?search= Initializes a LiteSVM instance with the default system variables included. This is a convenient builder method for common setups. ```rust pub fn with_sysvars(self) -> Self ``` -------------------------------- ### Writing Arbitrary Accounts with LiteSVM Source: https://docs.rs/litesvm/latest/litesvm/index.html?search=std%3A%3Avec This example demonstrates how to use LiteSVM to write arbitrary account data, such as giving an account a large amount of USDC without needing the actual USDC mint. This is useful for testing scenarios where you need specific account states. ```rust use { litesvm::LiteSVM, solana_account::Account, solana_address::{address, Address}, solana_program_option::COption, solana_program_pack::Pack, spl_associated_token_account_interface::address::get_associated_token_address, spl_token_interface::{ state::{Account as TokenAccount, AccountState}, ID as TOKEN_PROGRAM_ID, }, }; fn test_infinite_usdc_mint() { let owner = Address::new_unique(); let usdc_mint = address!("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"); let ata = get_associated_token_address(&owner, &usdc_mint); let usdc_to_own = 1_000_000_000_000; let token_acc = TokenAccount { mint: usdc_mint, owner: owner, amount: usdc_to_own, delegate: COption::None, state: AccountState::Initialized, is_native: COption::None, delegated_amount: 0, close_authority: COption::None, }; let mut svm = LiteSVM::new(); let mut token_acc_bytes = [0u8; TokenAccount::LEN]; TokenAccount::pack(token_acc, &mut token_acc_bytes).unwrap(); svm.set_account( ata, Account { lamports: 1_000_000_000, data: token_acc_bytes.to_vec(), owner: TOKEN_PROGRAM_ID, executable: false, rent_epoch: 0, }, ) .unwrap(); let raw_account = svm.get_account(&ata).unwrap(); assert_eq!( TokenAccount::unpack(&raw_account.data).unwrap().amount, usdc_to_own ) } ``` -------------------------------- ### Get Account Information Source: https://docs.rs/litesvm/latest/litesvm/struct.LiteSVM.html Retrieves all information associated with an account given its public key. ```rust pub fn get_account(&self, address: &Address) -> Option ``` -------------------------------- ### Set Initial Lamports Source: https://docs.rs/litesvm/latest/litesvm/struct.LiteSVM.html?search= Sets the initial amount of lamports in LiteSVM's airdrop account. This affects the starting balance for testing. ```rust pub fn set_lamports(&mut self, lamports: u64) ``` -------------------------------- ### Undefined Behavior Example: Unwrapping Ok as Err Source: https://docs.rs/litesvm/latest/litesvm/types/type.TransactionResult.html This example demonstrates undefined behavior when calling unwrap_err_unchecked on an Ok variant. ```rust let x: Result = Ok(2); unsafe { x.unwrap_err_unchecked() }; // Undefined behavior! ``` -------------------------------- ### Get Account Balance Source: https://docs.rs/litesvm/latest/litesvm/struct.LiteSVM.html Retrieves the balance of an account given its public key. ```rust pub fn get_balance(&self, address: &Address) -> Option ``` -------------------------------- ### Using unwrap to retrieve Ok value or panic Source: https://docs.rs/litesvm/latest/litesvm/types/type.TransactionResult.html Use unwrap to get the Ok value, but it will panic if the Result is Err. Prefer pattern matching or other methods for robust error handling. ```rust let x: Result = Ok(2); assert_eq!(x.unwrap(), 2); ``` ```rust let x: Result = Err("emergency failure"); x.unwrap(); // panics with `emergency failure` ``` -------------------------------- ### Write Arbitrary Account Data Source: https://docs.rs/litesvm/latest/litesvm/index.html Use `svm.set_account()` to write any account data, regardless of its state validity. This is convenient for testing scenarios without needing to manage complex account setups, like providing fake USDC. ```rust use { litesvm::LiteSVM, solana_account::Account, solana_address::{address, Address}, solana_program_option::COption, solana_program_pack::Pack, spl_associated_token_account_interface::address::get_associated_token_address, spl_token_interface::{ state::{Account as TokenAccount, AccountState}, ID as TOKEN_PROGRAM_ID, }, }; fn test_infinite_usdc_mint() { let owner = Address::new_unique(); let usdc_mint = address!("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"); let ata = get_associated_token_address(&owner, &usdc_mint); let usdc_to_own = 1_000_000_000_000; let token_acc = TokenAccount { mint: usdc_mint, owner: owner, amount: usdc_to_own, delegate: COption::None, state: AccountState::Initialized, is_native: COption::None, delegated_amount: 0, close_authority: COption::None, }; let mut svm = LiteSVM::new(); let mut token_acc_bytes = [0u8; TokenAccount::LEN]; TokenAccount::pack(token_acc, &mut token_acc_bytes).unwrap(); svm.set_account( ata, Account { lamports: 1_000_000_000, data: token_acc_bytes.to_vec(), owner: TOKEN_PROGRAM_ID, executable: false, rent_epoch: 0, }, ) .unwrap(); let raw_account = svm.get_account(&ata).unwrap(); assert_eq!( TokenAccount::unpack(&raw_account.data).unwrap().amount, usdc_to_own ) } ``` -------------------------------- ### LiteSVM::new Source: https://docs.rs/litesvm/latest/litesvm/struct.LiteSVM.html Creates a basic test environment for LiteSVM. This is the simplest way to initialize the VM for testing purposes. ```APIDOC ## LiteSVM::new ### Description Creates the basic test environment. ### Method `new()` ### Returns - `Self`: An instance of the LiteSVM struct. ``` -------------------------------- ### Undefined Behavior Example: Unwrapping Err Source: https://docs.rs/litesvm/latest/litesvm/types/type.TransactionResult.html This example demonstrates undefined behavior when calling unwrap_unchecked on an Err variant. ```rust let x: Result = Err("emergency failure"); unsafe { x.unwrap_unchecked() }; // Undefined behavior! ``` -------------------------------- ### Get Borsh declaration for Result Source: https://docs.rs/litesvm/latest/litesvm/types/type.TransactionResult.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Get the name of the type without brackets. Requires T and E to implement BorshSchema. ```rust fn declaration() -> String where T: BorshSchema, E: BorshSchema, ``` -------------------------------- ### type_id Source: https://docs.rs/litesvm/latest/litesvm/struct.LiteSVM.html?search=u32+-%3E+bool Gets the `TypeId` of the current value. ```APIDOC ## fn type_id(&self) -> TypeId ### Description Gets the `TypeId` of `self`. ### Method `&self` ### Returns `TypeId` - The type identifier of the value. ``` -------------------------------- ### transaction_history_capacity Source: https://docs.rs/litesvm/latest/litesvm/struct.LiteSVM.html Gets the capacity of the transaction history. Available only with the `persistence-internal` feature. ```APIDOC ## transaction_history_capacity ### Description Gets the capacity of the transaction history. Available on **crate feature`persistence-internal`** only. ### Method `GET` (Conceptual) ### Parameters None ### Response - **usize**: The capacity of the transaction history. ``` -------------------------------- ### get_feature_set_ref Source: https://docs.rs/litesvm/latest/litesvm/struct.LiteSVM.html Gets a reference to the feature set. Available only with the `persistence-internal` feature. ```APIDOC ## get_feature_set_ref ### Description Gets a reference to the feature set. Available on **crate feature`persistence-internal`** only. ### Method `GET` (Conceptual) ### Parameters None ### Response - **&FeatureSet**: A reference to the `FeatureSet`. ``` -------------------------------- ### Get Latest Blockhash Source: https://docs.rs/litesvm/latest/litesvm/struct.LiteSVM.html Retrieves the latest blockhash from the simulated environment. ```rust pub fn latest_blockhash(&self) -> Hash ``` -------------------------------- ### Deploying and Testing a Logging Program with LiteSVM Source: https://docs.rs/litesvm/latest/litesvm/index.html?search=std%3A%3Avec Shows how to add a compiled Solana program to LiteSVM and test its functionality, including simulating transactions and checking logs. The program bytes are loaded using `include_bytes!`. Ensure the program ID and data match the expected program. ```rust use { litesvm::LiteSVM, solana_address::{address, Address}, solana_instruction::{account_meta::AccountMeta, Instruction}, solana_keypair::Keypair, solana_message::{Message, VersionedMessage}, solana_signer::Signer, solana_transaction::versioned::VersionedTransaction, }; fn test_logging() { let program_id = address!("Logging111111111111111111111111111111111111"); let account_meta = AccountMeta { pubkey: Address::new_unique(), is_signer: false, is_writable: true, }; let ix = Instruction { program_id, accounts: vec![account_meta], data: vec![5, 10, 11, 12, 13, 14], }; let mut svm = LiteSVM::new(); let payer = Keypair::new(); let bytes = include_bytes!("../../node-litesvm/program_bytes/spl_example_logging.so"); svm.add_program(program_id, bytes); svm.airdrop(&payer.pubkey(), 1_000_000_000).unwrap(); let blockhash = svm.latest_blockhash(); let msg = Message::new_with_blockhash(&[ix], Some(&payer.pubkey()), &blockhash); let tx = VersionedTransaction::try_new(VersionedMessage::Legacy(msg), &[payer]).unwrap(); // let's sim it first let sim_res = svm.simulate_transaction(tx.clone()).unwrap(); let meta = svm.send_transaction(tx).unwrap(); assert_eq!(sim_res.meta, meta); assert_eq!(meta.logs[1], "Program log: static string"); assert!(meta.compute_units_consumed < 10_000) // not being precise here in case it changes } ``` -------------------------------- ### add_program_from_file Source: https://docs.rs/litesvm/latest/litesvm/struct.LiteSVM.html Adds an SBF program to the test environment by loading its bytecode from a specified file path. Returns an error if the file cannot be read or the program cannot be added. ```APIDOC ## add_program_from_file ### Description Adds an SBF program to the test environment from the file specified. ### Method `POST` (Conceptual) ### Parameters #### Request Body - **program_id** (`impl Into
`): The address for the program. - **path** (`impl AsRef`): The file path to the SBF program bytecode. ### Response - **Result<(), LiteSVMError>**: Ok if the program was added successfully, or an error if it failed. ``` -------------------------------- ### get_log_bytes_limit Source: https://docs.rs/litesvm/latest/litesvm/struct.LiteSVM.html Gets the configured limit for log bytes. Available only with the `persistence-internal` feature. ```APIDOC ## get_log_bytes_limit ### Description Gets the configured limit for log bytes. Available on **crate feature`persistence-internal`** only. ### Method `GET` (Conceptual) ### Parameters None ### Response - **Option**: The log bytes limit, or `None` if not set. ``` -------------------------------- ### add_program Source: https://docs.rs/litesvm/latest/litesvm/struct.LiteSVM.html Adds an SBF program to the test environment using provided program bytecode. It defaults to using the `BPFLoaderUpgradeable` for loading. ```APIDOC ## add_program ### Description Adds an SBF program to the test environment. Uses `BPFLoaderUpgradeable` by default for the loader. ### Method `POST` (Conceptual) ### Parameters #### Request Body - **program_id** (`impl Into
`): The address for the program. - **program_bytes** (`&[u8]`): The SBF program bytecode. ### Response - **Result<(), LiteSVMError>**: Ok if the program was added successfully, or an error if it failed. ``` -------------------------------- ### LiteSVM::with_precompiles Source: https://docs.rs/litesvm/latest/litesvm/struct.LiteSVM.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Adds the standard precompiles to the VM and returns the modified instance. Available on `precompiles` crate feature only. ```APIDOC ## LiteSVM::with_precompiles ### Description Adds the standard precompiles to the VM and returns the modified instance. Available on **crate feature`precompiles`** only. ### Method `with_precompiles(self) -> Self` ### Returns - `Self`: The modified LiteSVM instance with precompiles. ``` -------------------------------- ### Type ID Implementation Source: https://docs.rs/litesvm/latest/litesvm/error/enum.InvalidSysvarDataError.html?search= Gets the TypeId of a given type, part of the Any trait implementation. ```rust fn type_id(&self) -> TypeId ``` -------------------------------- ### LiteSVM::set_default_programs / LiteSVM::with_default_programs Source: https://docs.rs/litesvm/latest/litesvm/struct.LiteSVM.html?search= Includes the standard SPL programs in the VM environment. Use `set_default_programs` for mutable configuration or `with_default_programs` for fluent configuration. ```APIDOC ## LiteSVM::set_default_programs / LiteSVM::with_default_programs ### Description Includes the standard SPL programs. ### Methods * `set_default_programs(&mut self)` * `with_default_programs(self) -> Self` ### Returns `Self` - The LiteSVM instance with default SPL programs included. ``` -------------------------------- ### Add Standard Precompiles Source: https://docs.rs/litesvm/latest/litesvm/struct.LiteSVM.html Adds the standard precompiles to the VM. Available only with the 'precompiles' crate feature. ```rust pub fn set_precompiles(&mut self) ``` ```rust pub fn with_precompiles(self) -> Self ``` -------------------------------- ### Deprecated Cause Method for InvalidSysvarDataError Source: https://docs.rs/litesvm/latest/litesvm/error/enum.InvalidSysvarDataError.html?search= A deprecated method for getting the cause of the error. Replaced by Error::source. ```rust fn cause(&self) -> Option<&dyn Error> ``` -------------------------------- ### LiteSVM::set_precompiles Source: https://docs.rs/litesvm/latest/litesvm/struct.LiteSVM.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Adds the standard precompiles to the VM. Available on `precompiles` crate feature only. ```APIDOC ## LiteSVM::set_precompiles ### Description Adds the standard precompiles to the VM. Available on **crate feature`precompiles`** only. ### Method `set_precompiles(&mut self)` ``` -------------------------------- ### Iterate Over Ok Value Source: https://docs.rs/litesvm/latest/litesvm/types/type.TransactionResult.html?search=std%3A%3Avec Use iter to get an iterator that yields the Ok value if present, otherwise yields nothing. ```rust let x: Result = Ok(7); assert_eq!(x.iter().next(), Some(&7)); ``` ```rust let x: Result = Err("nothing!"); assert_eq!(x.iter().next(), None); ``` -------------------------------- ### Get Borsh Declaration for Result Source: https://docs.rs/litesvm/latest/litesvm/types/type.TransactionResult.html?search= Returns the type name string for `Result` used in Borsh schema generation. ```rust fn declaration() -> String ``` -------------------------------- ### Create LiteSVM with Compute Budget Source: https://docs.rs/litesvm/latest/litesvm/struct.LiteSVM.html?search= Creates a new LiteSVM instance with a specified compute budget. This is a builder-style method for configuring the VM. ```rust pub fn with_compute_budget(self, compute_budget: ComputeBudget) -> Self ``` -------------------------------- ### Create Debuggable LiteSVM Instance Source: https://docs.rs/litesvm/latest/litesvm/struct.LiteSVM.html Creates a test environment with debugging features enabled, such as register tracing. Requires the 'register-tracing' crate feature. ```rust pub fn new_debuggable(enable_register_tracing: bool) -> Self ``` -------------------------------- ### Using unwrap_err to retrieve Err value Source: https://docs.rs/litesvm/latest/litesvm/types/type.TransactionResult.html?search= Use unwrap_err to get the contained Err value. It will panic if the Result is Ok. ```rust let x: Result = Err("emergency failure"); assert_eq!(x.unwrap_err(), "emergency failure"); ``` -------------------------------- ### Using unwrap to retrieve Ok value Source: https://docs.rs/litesvm/latest/litesvm/types/type.TransactionResult.html?search= Use unwrap to get the contained Ok value. It will panic if the Result is Err. ```rust let x: Result = Ok(2); assert_eq!(x.unwrap(), 2); ``` -------------------------------- ### Create LiteSVM with Default SPL Programs Source: https://docs.rs/litesvm/latest/litesvm/struct.LiteSVM.html?search= Initializes a LiteSVM instance with the standard SPL programs included. This builder method simplifies testing of programs that interact with SPL. ```rust pub fn with_default_programs(self) -> Self ``` -------------------------------- ### LiteSVM::set_default_programs / with_default_programs Source: https://docs.rs/litesvm/latest/litesvm/struct.LiteSVM.html Includes the standard SPL programs in the VM environment. `set_default_programs` modifies the current VM, while `with_default_programs` returns a new VM with these programs included. ```APIDOC ## LiteSVM::set_default_programs / with_default_programs ### Description Includes the standard SPL programs. ### Methods - `set_default_programs(&mut self)` - `with_default_programs(self) -> Self` ### Returns - `&mut self` for `set_default_programs`. - `Self` for `with_default_programs`. ``` -------------------------------- ### get_sysvar Source: https://docs.rs/litesvm/latest/litesvm/struct.LiteSVM.html Gets a sysvar from the test environment. This method is generic and requires the type `T` to implement `Sysvar`, `SysvarId`, and `DeserializeOwned` traits. ```APIDOC ## get_sysvar ### Description Gets a sysvar from the test environment. ### Method `GET` (Conceptual) ### Parameters None ### Type Parameters - **T**: Must implement `Sysvar`, `SysvarId`, and `DeserializeOwned` traits. ### Response - **T**: The retrieved sysvar value. ``` -------------------------------- ### Create LiteSVM with Precompiles Source: https://docs.rs/litesvm/latest/litesvm/struct.LiteSVM.html?search= Initializes a LiteSVM instance with standard precompiled programs. This builder method is available when the 'precompiles' feature is enabled. ```rust pub fn with_precompiles(self) -> Self ``` -------------------------------- ### Get Minimum Balance for Rent Exemption Source: https://docs.rs/litesvm/latest/litesvm/struct.LiteSVM.html Calculates the minimum balance required to make an account with a specified data length rent-exempt. ```rust pub fn minimum_balance_for_rent_exemption(&self, data_len: usize) -> u64 ``` -------------------------------- ### Deprecated Description Method for InvalidSysvarDataError Source: https://docs.rs/litesvm/latest/litesvm/error/enum.InvalidSysvarDataError.html?search= A deprecated method for getting a string description of the error. Use the Display impl or to_string() instead. ```rust fn description(&self) -> &str ``` -------------------------------- ### with_custom_syscall Source: https://docs.rs/litesvm/latest/litesvm/struct.LiteSVM.html Registers a custom syscall for both program runtime environments (v1 and v2). This must be called after `with_builtins()` and before `with_default_programs()`. Panics if registration fails. ```APIDOC ## with_custom_syscall ### Description Registers a custom syscall in both program runtime environments (v1 and v2). **Must be called after `with_builtins()`** (which recreates the environments from scratch) and **before `with_default_programs()`** (which clones the environment Arcs into program cache entries, preventing further mutation). Panics if the runtime environments cannot be mutated or if registration fails. This is intentional — a misconfigured syscall should fail loudly rather than silently. ### Method `POST` (Conceptual) ### Parameters #### Request Body - **name** (`&str`): The name of the syscall. - **syscall** (`BuiltinFunction>`): The function implementing the syscall. ### Returns - **Self**: The modified `LiteSVM` instance. ``` -------------------------------- ### LiteSVM::set_compute_budget / LiteSVM::with_compute_budget Source: https://docs.rs/litesvm/latest/litesvm/struct.LiteSVM.html?search= Configures the compute budget for the VM. This can be done mutably using `set_compute_budget` or fluently using `with_compute_budget`. ```APIDOC ## LiteSVM::set_compute_budget / LiteSVM::with_compute_budget ### Description Sets the compute budget for the VM instance. ### Methods * `set_compute_budget(&mut self, compute_budget: ComputeBudget)` * `with_compute_budget(self, compute_budget: ComputeBudget) -> Self` ### Parameters * `compute_budget` (ComputeBudget) - The desired compute budget configuration. ``` -------------------------------- ### LiteSVM::with_default_programs Source: https://docs.rs/litesvm/latest/litesvm/struct.LiteSVM.html?search=u32+-%3E+bool Includes the standard SPL programs and returns the modified instance. This is a builder-style method. ```APIDOC ## LiteSVM::with_default_programs ### Description Includes the standard SPL programs. ### Method ``` pub fn with_default_programs(self) -> Self ``` ### Returns The modified `LiteSVM` instance with default SPL programs included. ``` -------------------------------- ### Get Mainnet Feature Set Source: https://docs.rs/litesvm/latest/litesvm/struct.LiteSVM.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Retrieves a FeatureSet containing features active on Solana mainnet-beta as of a specific date. This is useful for testing against mainnet conditions. ```rust pub fn mainnet_feature_set() -> FeatureSet ``` -------------------------------- ### LiteSVM::with_default_programs Source: https://docs.rs/litesvm/latest/litesvm/struct.LiteSVM.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Includes the standard SPL programs and returns the modified instance. ```APIDOC ## LiteSVM::with_default_programs ### Description Includes the standard SPL programs and returns the modified instance. ### Method `with_default_programs(self) -> Self` ### Returns - `Self`: The modified LiteSVM instance with default programs. ``` -------------------------------- ### Unsafe Unwrap of Err Value Source: https://docs.rs/litesvm/latest/litesvm/types/type.TransactionResult.html Use this method to get the contained Err value without checking if it's an Ok. Calling on an Ok is undefined behavior. ```rust let x: Result = Err("emergency failure"); assert_eq!(unsafe { x.unwrap_err_unchecked() }, "emergency failure"); ``` -------------------------------- ### Create LiteSVM with Feature Accounts Source: https://docs.rs/litesvm/latest/litesvm/struct.LiteSVM.html?search= Initializes a LiteSVM instance with on-chain feature gate accounts. This builder method ensures that feature gates are properly set up. ```rust pub fn with_feature_accounts(self) -> Self ``` -------------------------------- ### Set Compute Budget Source: https://docs.rs/litesvm/latest/litesvm/struct.LiteSVM.html Configures the compute budget for the LiteSVM environment. Use the mutable or builder pattern. ```rust pub fn set_compute_budget(&mut self, compute_budget: ComputeBudget) ``` ```rust pub fn with_compute_budget(self, compute_budget: ComputeBudget) -> Self ``` -------------------------------- ### Unsafe Unwrap of Ok Value Source: https://docs.rs/litesvm/latest/litesvm/types/type.TransactionResult.html Use this method to get the contained Ok value without checking if it's an Err. Calling on an Err is undefined behavior. ```rust let x: Result = Ok(2); assert_eq!(unsafe { x.unwrap_unchecked() }, 2); ``` -------------------------------- ### add_builtin Source: https://docs.rs/litesvm/latest/litesvm/struct.LiteSVM.html Adds a builtin program to the test environment, associating it with a program ID and an entrypoint function. ```APIDOC ## add_builtin ### Description Adds a builtin program to the test environment. ### Method `POST` (Conceptual) ### Parameters #### Request Body - **program_id** (`Address`): The address of the builtin program. - **entrypoint** (`BuiltinFunctionWithContext`): The entrypoint function for the builtin program. ``` -------------------------------- ### Mutable Iterator Over Ok Value Source: https://docs.rs/litesvm/latest/litesvm/types/type.TransactionResult.html?search=std%3A%3Avec Use iter_mut to get a mutable iterator that yields a mutable reference to the Ok value if present, otherwise yields nothing. ```rust let mut x: Result = Ok(7); assert_eq!(x.iter_mut().next(), Some(&mut 7)); ``` ```rust let mut x: Result = Err("nothing!"); assert_eq!(x.iter_mut().next(), None); ``` -------------------------------- ### LiteSVM::set_compute_budget / with_compute_budget Source: https://docs.rs/litesvm/latest/litesvm/struct.LiteSVM.html Configures the compute budget for the VM. `set_compute_budget` modifies the existing instance, while `with_compute_budget` returns a new instance with the updated budget. ```APIDOC ## LiteSVM::set_compute_budget / with_compute_budget ### Description Sets the compute budget for the VM instance. ### Methods - `set_compute_budget(&mut self, compute_budget: ComputeBudget)` - `with_compute_budget(self, compute_budget: ComputeBudget) -> Self` ### Parameters #### `set_compute_budget` - **compute_budget** (ComputeBudget) - Required - The compute budget to set. #### `with_compute_budget` - **compute_budget** (ComputeBudget) - Required - The compute budget to set. ### Returns - `&mut self` for `set_compute_budget`. - `Self` for `with_compute_budget`. ``` -------------------------------- ### Using unwrap_or_default to get Ok value or default Source: https://docs.rs/litesvm/latest/litesvm/types/type.TransactionResult.html Returns the contained Ok value or the default value for the type if the Result is Err. Useful for providing fallback values. ```rust let good_year_from_input = "1909"; let bad_year_from_input = "190blarg"; let good_year = good_year_from_input.parse().unwrap_or_default(); let bad_year = bad_year_from_input.parse().unwrap_or_default(); assert_eq!(1909, good_year); assert_eq!(0, bad_year); ``` -------------------------------- ### LiteSVM::set_default_programs / with_default_programs Source: https://docs.rs/litesvm/latest/litesvm/struct.LiteSVM.html?search=std%3A%3Avec Includes the standard SPL programs in the test environment. Use `set_default_programs` for mutable configuration or `with_default_programs` for immutable configuration. ```APIDOC ## LiteSVM::set_default_programs / with_default_programs ### Description Includes the standard SPL programs. ### Methods - `set_default_programs(&mut self)` - `with_default_programs(self) -> Self` ### Returns - `set_default_programs`: `()` - `with_default_programs`: `Self` ``` -------------------------------- ### LiteSVM::with_precompiles Source: https://docs.rs/litesvm/latest/litesvm/struct.LiteSVM.html?search=u32+-%3E+bool Adds the standard precompiles and returns the modified instance. This is a builder-style method. Available on `crate feature`precompiles` only. ```APIDOC ## LiteSVM::with_precompiles ### Description Adds the standard precompiles to the VM. Available on **crate feature`precompiles`** only. ### Method ``` pub fn with_precompiles(self) -> Self ``` ### Returns The modified `LiteSVM` instance with standard precompiles added. ``` -------------------------------- ### LiteSVM::set_sigverify / with_sigverify Source: https://docs.rs/litesvm/latest/litesvm/struct.LiteSVM.html Enables or disables the signature verification process. Use `set_sigverify` to modify the current instance or `with_sigverify` to get a new instance with the setting applied. ```APIDOC ## LiteSVM::set_sigverify / with_sigverify ### Description Enables or disables signature verification. ### Methods - `set_sigverify(&mut self, sigverify: bool)` - `with_sigverify(self, sigverify: bool) -> Self` ### Parameters #### `set_sigverify` - **sigverify** (bool) - Required - `true` to enable, `false` to disable. #### `with_sigverify` - **sigverify** (bool) - Required - `true` to enable, `false` to disable. ### Returns - `&mut self` for `set_sigverify`. - `Self` for `with_sigverify`. ``` -------------------------------- ### Get Mutable References to Result Contents Source: https://docs.rs/litesvm/latest/litesvm/types/type.TransactionResult.html Creates a new Result containing mutable references to the original Ok or Err values. Allows in-place modification of the contained value. ```rust fn mutate(r: &mut Result) { match r.as_mut() { Ok(v) => *v = 42, Err(e) => *e = 0, } } let mut x: Result = Ok(2); mutate(&mut x); assert_eq!(x.unwrap(), 42); let mut x: Result = Err(13); mutate(&mut x); assert_eq!(x.unwrap_err(), 0); ``` -------------------------------- ### LiteSVM::set_precompiles Source: https://docs.rs/litesvm/latest/litesvm/struct.LiteSVM.html?search=u32+-%3E+bool Adds the standard precompiles to the VM. This method modifies the existing VM instance. Available on `crate feature`precompiles` only. ```APIDOC ## LiteSVM::set_precompiles ### Description Adds the standard precompiles to the VM. Available on **crate feature`precompiles`** only. ### Method ``` pub fn set_precompiles(&mut self) ``` ``` -------------------------------- ### LiteSVM::set_precompiles / LiteSVM::with_precompiles Source: https://docs.rs/litesvm/latest/litesvm/struct.LiteSVM.html?search= Adds the standard precompile programs to the VM. This feature is available only when the `precompiles` crate feature is enabled. Use `set_precompiles` for mutable configuration or `with_precompiles` for fluent configuration. ```APIDOC ## LiteSVM::set_precompiles / LiteSVM::with_precompiles ### Description Available on **crate feature`precompiles`** only. Adds the standard precompiles to the VM. ### Methods * `set_precompiles(&mut self)` * `with_precompiles(self) -> Self` ### Returns `Self` - The LiteSVM instance with standard precompiles added. ``` -------------------------------- ### LiteSVM::set_precompiles / with_precompiles Source: https://docs.rs/litesvm/latest/litesvm/struct.LiteSVM.html Adds the standard precompile programs to the VM. This feature is available when the `precompiles` crate feature is enabled. `set_precompiles` modifies the current VM, while `with_precompiles` returns a new VM with precompiles added. ```APIDOC ## LiteSVM::set_precompiles / with_precompiles ### Description Adds the standard precompiles to the VM. Available on **crate feature`precompiles`** only. ### Methods - `set_precompiles(&mut self)` - `with_precompiles(self) -> Self` ### Returns - `&mut self` for `set_precompiles`. - `Self` for `with_precompiles`. ``` -------------------------------- ### Get Immutable References to Result Contents Source: https://docs.rs/litesvm/latest/litesvm/types/type.TransactionResult.html Creates a new Result containing immutable references to the original Ok or Err values. Useful for inspecting values without consuming the Result. ```rust let x: Result = Ok(2); assert_eq!(x.as_ref(), Ok(&2)); let x: Result = Err("Error"); assert_eq!(x.as_ref(), Err(&"Error")); ``` -------------------------------- ### into_ok Source: https://docs.rs/litesvm/latest/litesvm/types/type.TransactionResult.html Returns the contained `Ok` value, but never panics. This is an experimental API. ```APIDOC ## pub const fn into_ok(self) -> T ### Description Returns the contained `Ok` value, but never panics. Unlike `unwrap`, this method is known to never panic on the result types it is implemented for. Therefore, it can be used instead of `unwrap` as a maintainability safeguard that will fail to compile if the error type of the `Result` is later changed to an error that can actually occur. ### Examples ``` fn only_good_news() -> Result { Ok("this is fine".into()) } let s: String = only_good_news().into_ok(); println!("{s}"); ``` ``` -------------------------------- ### Set Feature Set Source: https://docs.rs/litesvm/latest/litesvm/struct.LiteSVM.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Configures the FeatureSet used by the VM instance. Use the builder pattern for a fluent API. ```rust pub fn with_feature_set(self, feature_set: FeatureSet) -> Self ``` ```rust pub fn set_feature_set(&mut self, feature_set: FeatureSet) ``` -------------------------------- ### Sum of Results from Iterator Source: https://docs.rs/litesvm/latest/litesvm/types/type.TransactionResult.html Calculates the sum of elements in an iterator where each element is a Result. If any element is an Err, it's returned immediately. Otherwise, the sum of all Ok values is returned. This example demonstrates rejecting negative numbers. ```rust let f = |&x: &i32| if x < 0 { Err("Negative element found") } else { Ok(x) }; let v = vec![1, 2]; let res: Result = v.iter().map(f).sum(); assert_eq!(res, Ok(3)); let v = vec![1, -2]; let res: Result = v.iter().map(f).sum(); assert_eq!(res, Err("Negative element found")); ``` -------------------------------- ### LiteSVM::with_feature_set Source: https://docs.rs/litesvm/latest/litesvm/struct.LiteSVM.html?search=u32+-%3E+bool Sets a custom `FeatureSet` for the VM instance. This is a builder-style method. ```APIDOC ## LiteSVM::with_feature_set ### Description Set the FeatureSet used by the VM instance. ### Method ``` pub fn with_feature_set(self, feature_set: FeatureSet) -> Self ``` ### Parameters #### Path Parameters - **feature_set** (FeatureSet) - Required - The `FeatureSet` to use for the VM instance. ``` -------------------------------- ### Iterate Mutably Over Ok Value (iter_mut) Source: https://docs.rs/litesvm/latest/litesvm/types/type.TransactionResult.html?search= Use iter_mut to get a mutable iterator that yields a mutable reference to the Ok value if present, otherwise yields nothing. Allows modification of the Ok value through iteration. ```rust let mut x: Result = Ok(7); for val in x.iter_mut() { *val = 10; } assert_eq!(x, Ok(10)); let mut x: Result = Err("nothing!"); for val in x.iter_mut() { *val = 10; } assert_eq!(x, Err("nothing!")); ``` -------------------------------- ### Use Mainnet Features Source: https://docs.rs/litesvm/latest/litesvm/struct.LiteSVM.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Replaces the current feature set with one matching Solana mainnet-beta features. This is a convenience method that uses `mainnet_feature_set()`. ```rust pub fn with_mainnet_features(self) -> Self ``` -------------------------------- ### Include Standard SPL Programs Source: https://docs.rs/litesvm/latest/litesvm/struct.LiteSVM.html Configures the LiteSVM environment to include the standard SPL programs. Use the mutable or builder pattern. ```rust pub fn set_default_programs(&mut self) ``` ```rust pub fn with_default_programs(self) -> Self ``` -------------------------------- ### Simulating Time Travel with LiteSVM Clock Source: https://docs.rs/litesvm/latest/litesvm/index.html?search=std%3A%3Avec This example demonstrates how to dynamically overwrite the Clock sysvar in LiteSVM to test time-dependent program logic. It shows setting the clock to a future date, causing a transaction to fail, and then setting it back to an earlier date for the transaction to succeed. ```rust use { litesvm::LiteSVM, solana_address::Address, solana_clock::Clock, solana_instruction::Instruction, solana_keypair::Keypair, solana_message::{Message, VersionedMessage}, solana_signer::Signer, solana_transaction::versioned::VersionedTransaction, }; fn test_set_clock() { let program_id = Address::new_unique(); let mut svm = LiteSVM::new(); let bytes = include_bytes!("../../node-litesvm/program_bytes/litesvm_clock_example.so"); svm.add_program(program_id, bytes); let payer = Keypair::new(); let payer_address = payer.pubkey(); svm.airdrop(&payer.pubkey(), 1_000_000_000).unwrap(); let blockhash = svm.latest_blockhash(); let ixs = [Instruction { program_id, data: vec![], accounts: vec![], }]; let msg = Message::new_with_blockhash(&ixs, Some(&payer_address), &blockhash); let versioned_msg = VersionedMessage::Legacy(msg); let tx = VersionedTransaction::try_new(versioned_msg, &[&payer]).unwrap(); // set the time to January 1st 2000 let mut initial_clock = svm.get_sysvar::(); initial_clock.unix_timestamp = 1735689600; svm.set_sysvar::(&initial_clock); // this will fail because it's not January 1970 anymore svm.send_transaction(tx).unwrap_err(); // so let's turn back time let mut clock = svm.get_sysvar::(); clock.unix_timestamp = 50; svm.set_sysvar::(&clock); let ixs2 = [Instruction { program_id, data: vec![1], // unused, this is just to dedup the transaction accounts: vec![], }]; let msg2 = Message::new_with_blockhash(&ixs2, Some(&payer_address), &blockhash); let versioned_msg2 = VersionedMessage::Legacy(msg2); let tx2 = VersionedTransaction::try_new(versioned_msg2, &[&payer]).unwrap(); // now the transaction goes through svm.send_transaction(tx2).unwrap(); } ``` -------------------------------- ### Create LiteSVM with Custom Builtins Source: https://docs.rs/litesvm/latest/litesvm/struct.LiteSVM.html?search= Initializes a LiteSVM instance with a modified set of default built-in programs. This builder method is useful for testing custom program interactions. ```rust pub fn with_builtins(self) -> Self ``` -------------------------------- ### LiteSVM::set_sysvars / LiteSVM::with_sysvars Source: https://docs.rs/litesvm/latest/litesvm/struct.LiteSVM.html?search= Configures the VM to include default system variables (sysvars). Use `set_sysvars` for mutable configuration or `with_sysvars` for fluent configuration. ```APIDOC ## LiteSVM::set_sysvars / LiteSVM::with_sysvars ### Description Includes the default sysvars. ### Methods * `set_sysvars(&mut self)` * `with_sysvars(self) -> Self` ### Returns `Self` - The LiteSVM instance with default sysvars included. ``` -------------------------------- ### Converting Result to Iterator (Ok Case) Source: https://docs.rs/litesvm/latest/litesvm/types/type.TransactionResult.html?search= Shows how an `Ok` Result can be converted into an iterator that yields a single value. ```rust let x: Result = Ok(5); let v: Vec = x.into_iter().collect(); assert_eq!(v, [5]); ``` -------------------------------- ### LiteSVM::set_lamports / LiteSVM::with_lamports Source: https://docs.rs/litesvm/latest/litesvm/struct.LiteSVM.html?search= Sets the initial amount of lamports in LiteSVM's airdrop account. Use `set_lamports` for mutable configuration or `with_lamports` for fluent configuration. ```APIDOC ## LiteSVM::set_lamports / LiteSVM::with_lamports ### Description Changes the initial lamports in LiteSVM’s airdrop account. ### Methods * `set_lamports(&mut self, lamports: u64)` * `with_lamports(self, lamports: u64) -> Self` ### Parameters * `lamports` (u64) - The number of lamports to set. ``` -------------------------------- ### get_compute_budget Source: https://docs.rs/litesvm/latest/litesvm/struct.LiteSVM.html Retrieves the current compute budget configuration of the test environment. ```APIDOC ## get_compute_budget ### Description Gets the current compute budget. ### Method `GET` (Conceptual) ### Parameters None ### Response - **Option**: The current compute budget, or `None` if not set. ``` -------------------------------- ### Set Default Programs Source: https://docs.rs/litesvm/latest/litesvm/struct.LiteSVM.html?search= Includes the standard SPL (Solana Program Library) programs in the LiteSVM environment. This ensures common SPL functionalities are available for testing. ```rust pub fn set_default_programs(&mut self) ``` -------------------------------- ### Nightly-Only Experimental API: Provide Method Source: https://docs.rs/litesvm/latest/litesvm/error/enum.InvalidSysvarDataError.html?search= Provides type-based access to context for error reports. This is an experimental API available only on nightly Rust. ```rust fn provide<'a>(&'a self, request: &mut Request<'a>) ``` -------------------------------- ### LiteSVM::with_lamports Source: https://docs.rs/litesvm/latest/litesvm/struct.LiteSVM.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Changes the initial lamports in LiteSVM's airdrop account and returns the modified instance. ```APIDOC ## LiteSVM::with_lamports ### Description Changes the initial lamports in LiteSVM's airdrop account and returns the modified instance. ### Method `with_lamports(self, lamports: u64) -> Self` ### Parameters #### Path Parameters - `lamports` (u64) - Required - The number of lamports for the airdrop account. ### Returns - `Self`: The modified LiteSVM instance. ``` -------------------------------- ### LiteSVM::with_mainnet_features Source: https://docs.rs/litesvm/latest/litesvm/struct.LiteSVM.html Configures the VM to use a `FeatureSet` matching the features active on Solana mainnet-beta. This is a convenience method that uses `mainnet_feature_set`. ```APIDOC ## LiteSVM::with_mainnet_features ### Description Replace the feature set with one matching the features active on Solana mainnet-beta. ### Method `with_mainnet_features(self) -> Self` ### Returns - `Self`: A new VM instance configured with mainnet features. ``` -------------------------------- ### LiteSVM::new_debuggable Source: https://docs.rs/litesvm/latest/litesvm/struct.LiteSVM.html Creates a test environment with debugging features enabled, specifically register tracing. This is useful for in-depth analysis of program execution. ```APIDOC ## LiteSVM::new_debuggable ### Description Create a test environment with debugging features. This constructor allows enabling low-level VM debugging capabilities, such as register tracing. ### Method `new_debuggable(enable_register_tracing: bool) -> Self` ### Parameters #### Query Parameters - **enable_register_tracing** (bool) - Required - If `true`, programs are loaded with register tracing support and a default `DefaultRegisterTracingCallback` is installed. Trace data is written to `SBF_TRACE_DIR`. ### Returns - `Self`: An instance of the LiteSVM struct with debugging enabled. ``` -------------------------------- ### LiteSVM::set_precompiles / with_precompiles Source: https://docs.rs/litesvm/latest/litesvm/struct.LiteSVM.html?search=std%3A%3Avec Adds the standard precompiles to the VM. This feature is available when the `precompiles` crate feature is enabled. Use `set_precompiles` for mutable configuration or `with_precompiles` for immutable configuration. ```APIDOC ## LiteSVM::set_precompiles / with_precompiles ### Description Adds the standard precompiles to the VM. Available on **crate feature`precompiles`** only. ### Methods - `set_precompiles(&mut self)` - `with_precompiles(self) -> Self` ### Returns - `set_precompiles`: `()` - `with_precompiles`: `Self` ``` -------------------------------- ### PartialEq Implementation for SimulatedTransactionInfo Source: https://docs.rs/litesvm/latest/litesvm/types/struct.SimulatedTransactionInfo.html?search=u32+-%3E+bool Defines equality comparison for SimulatedTransactionInfo instances. ```rust fn eq(&self, other: &SimulatedTransactionInfo) -> bool ``` ```rust fn ne(&self, other: &Rhs) -> bool ``` -------------------------------- ### PartialEq Implementation for SimulatedTransactionInfo Source: https://docs.rs/litesvm/latest/litesvm/types/struct.SimulatedTransactionInfo.html Defines equality comparison for SimulatedTransactionInfo instances. ```rust fn eq(&self, other: &SimulatedTransactionInfo) -> bool ``` ```rust fn ne(&self, other: &Rhs) -> bool ``` -------------------------------- ### Set Account Information Source: https://docs.rs/litesvm/latest/litesvm/struct.LiteSVM.html Sets all information associated with an account for a given public key. Returns an error if the operation fails. ```rust pub fn set_account( &mut self, address: Address, data: Account, ) -> Result<(), LiteSVMError> ```