Documentation
¶
Overview ¶
Package litesvm provides an in-process Solana VM for fast testing of Solana programs and clients, intended as a drop-in alternative to solana-test-validator for Go unit and integration tests: a fresh handle boots in milliseconds and runs in the same process as the test.
The package is pure Go. The engine is mithril's SVM (github.com/sonicfromnewyoke/mithril): sealevel runtime, sbpf VM, and the pure transaction pipeline replay.LoadAndExecuteTransaction. That dependency is an implementation detail and never appears in this package's API.
It uses github.com/gagliardetto/solana-go for the core Solana types (PublicKey, Hash, Signature, Account) so that values returned from this package can be passed directly into solana-go helpers (transaction construction, signing, base58 encoding) and vice-versa.
A LiteSVM handle is not safe for concurrent use from multiple goroutines. Either confine it to a single goroutine, or serialize access with your own sync.Mutex.
Index ¶
- Variables
- func BuildTransferTx(payerSeed [32]byte, to solana.PublicKey, lamports uint64, ...) ([]byte, error)
- func NewAccount(lamports uint64, data []byte, owner solana.PublicKey, executable bool, ...) (*solana.Account, error)
- func Version() string
- type ComputeBudget
- type FeatureSet
- func (fs *FeatureSet) Activate(featureID solana.PublicKey, slot uint64) error
- func (fs *FeatureSet) ActivatedSlot(featureID solana.PublicKey) (uint64, bool)
- func (fs *FeatureSet) ActiveCount() int
- func (fs *FeatureSet) ActiveFeatures() []solana.PublicKey
- func (fs *FeatureSet) Close()deprecated
- func (fs *FeatureSet) Deactivate(featureID solana.PublicKey) error
- func (fs *FeatureSet) InactiveCount() int
- func (fs *FeatureSet) InactiveFeatures() []solana.PublicKey
- func (fs *FeatureSet) IsActive(featureID solana.PublicKey) bool
- type InnerInstruction
- type InnerInstructionsList
- type LiteSVM
- func (s *LiteSVM) AddProgram(programID solana.PublicKey, programBytes []byte) error
- func (s *LiteSVM) AddProgramFromFile(programID solana.PublicKey, path string) error
- func (s *LiteSVM) AddProgramWithLoader(programID solana.PublicKey, programBytes []byte, loader solana.PublicKey) error
- func (s *LiteSVM) Airdrop(pubkey solana.PublicKey, lamports uint64) error
- func (s *LiteSVM) Balance(pubkey solana.PublicKey) (uint64, bool, error)
- func (s *LiteSVM) Clock() (*sysvar.Clock, error)
- func (s *LiteSVM) Close()
- func (s *LiteSVM) ComputeBudget() (ComputeBudget, bool, error)
- func (s *LiteSVM) EpochRewards() (*sysvar.EpochRewards, error)
- func (s *LiteSVM) EpochSchedule() (*sysvar.EpochSchedule, error)
- func (s *LiteSVM) ExpireBlockhash() error
- func (s *LiteSVM) GetAccount(pubkey solana.PublicKey) *solana.Account
- func (s *LiteSVM) GetTransaction(signature solana.Signature) *TxOutcome
- func (s *LiteSVM) LastRestartSlot() (*sysvar.LastRestartSlot, error)
- func (s *LiteSVM) LatestBlockhash() (solana.Hash, error)
- func (s *LiteSVM) MinimumBalanceForRentExemption(dataLen int) (uint64, error)
- func (s *LiteSVM) Rent() (*sysvar.Rent, error)
- func (s *LiteSVM) SendLegacyTransaction(txBytes []byte) (*TxOutcome, error)
- func (s *LiteSVM) SendVersionedTransaction(txBytes []byte) (*TxOutcome, error)
- func (s *LiteSVM) SetAccount(pubkey solana.PublicKey, acct *solana.Account) error
- func (s *LiteSVM) SetBlockhashCheck(enabled bool) error
- func (s *LiteSVM) SetBuiltins() error
- func (s *LiteSVM) SetClock(c *sysvar.Clock) error
- func (s *LiteSVM) SetComputeBudget(b ComputeBudget) error
- func (s *LiteSVM) SetDefaultPrograms() error
- func (s *LiteSVM) SetEpochRewards(e *sysvar.EpochRewards) error
- func (s *LiteSVM) SetEpochSchedule(e *sysvar.EpochSchedule) error
- func (s *LiteSVM) SetFeatureSet(f *FeatureSet) error
- func (s *LiteSVM) SetLamports(lamports uint64) error
- func (s *LiteSVM) SetLastRestartSlot(l *sysvar.LastRestartSlot) error
- func (s *LiteSVM) SetLogBytesLimit(limit int) error
- func (s *LiteSVM) SetPrecompiles() error
- func (s *LiteSVM) SetRent(r *sysvar.Rent) error
- func (s *LiteSVM) SetSigverify(enabled bool) error
- func (s *LiteSVM) SetSlotHashes(items sysvar.SlotHashes) error
- func (s *LiteSVM) SetSlotHistory(sh *sysvar.SlotHistory) error
- func (s *LiteSVM) SetStakeHistory(items sysvar.StakeHistory) error
- func (s *LiteSVM) SetSysvars() error
- func (s *LiteSVM) SetTransactionHistory(capacity int) error
- func (s *LiteSVM) Sigverify() (bool, error)
- func (s *LiteSVM) SimulateLegacyTransaction(txBytes []byte) (*TxOutcome, error)
- func (s *LiteSVM) SimulateVersionedTransaction(txBytes []byte) (*TxOutcome, error)
- func (s *LiteSVM) SlotHashes() (sysvar.SlotHashes, error)
- func (s *LiteSVM) SlotHistory() (*sysvar.SlotHistory, error)
- func (s *LiteSVM) StakeHistory() (sysvar.StakeHistory, error)
- func (s *LiteSVM) WarpToSlot(slot uint64) error
- func (s *LiteSVM) WithNativeMints() error
- type PostAccount
- type TxOutcome
- func (o *TxOutcome) Close()
- func (o *TxOutcome) ComputeUnits() uint64
- func (o *TxOutcome) Error() string
- func (o *TxOutcome) Fee() uint64
- func (o *TxOutcome) InnerInstructions() InnerInstructionsList
- func (o *TxOutcome) IsOk() bool
- func (o *TxOutcome) Logs() []string
- func (o *TxOutcome) PostAccounts() ([]PostAccount, error)
- func (o *TxOutcome) ReturnData() (solana.PublicKey, []byte, bool)
- func (o *TxOutcome) Signature() solana.Signature
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ErrLiteSVM = errors.New("litesvm")
ErrLiteSVM is the sentinel wrapped by every error this package returns. It is the same value as the root package's ErrLiteSVM, and its message is "litesvm" so wrapped errors read "litesvm: ...".
Functions ¶
func BuildTransferTx ¶
func BuildTransferTx(payerSeed [32]byte, to solana.PublicKey, lamports uint64, blockhash solana.Hash) ([]byte, error)
BuildTransferTx produces a signed, wire-encoded legacy Transaction that transfers `lamports` from the keypair derived from `payerSeed` to `to`, using `blockhash`. It is a convenience for tests; application code can build the same transaction directly with solana-go.
func NewAccount ¶
func NewAccount(lamports uint64, data []byte, owner solana.PublicKey, executable bool, rentEpoch uint64) (*solana.Account, error)
NewAccount builds an account value for SetAccount. Accounts are plain solana.Account structs, so a composite literal does the same job and is usually clearer:
&solana.Account{Lamports: 1e9, Data: data, Owner: owner}
This constructor exists so the documented API surface can be used positionally. The error result is always nil; it is retained so callers written against it keep compiling.
Types ¶
type ComputeBudget ¶
type ComputeBudget struct {
ComputeUnitLimit uint64
Log64Units uint64
CreateProgramAddressUnits uint64
InvokeUnits uint64
MaxInstructionStackDepth uint64
MaxInstructionTraceLength uint64
Sha256BaseCost uint64
Sha256ByteCost uint64
Sha256MaxSlices uint64
MaxCallDepth uint64
StackFrameSize uint64
LogPubkeyUnits uint64
CpiBytesPerUnit uint64
SysvarBaseCost uint64
Secp256k1RecoverCost uint64
SyscallBaseCost uint64
Curve25519EdwardsValidatePointCost uint64
Curve25519EdwardsAddCost uint64
Curve25519EdwardsSubtractCost uint64
Curve25519EdwardsMultiplyCost uint64
Curve25519EdwardsMsmBaseCost uint64
Curve25519EdwardsMsmIncrementalCost uint64
Curve25519RistrettoValidatePointCost uint64
Curve25519RistrettoAddCost uint64
Curve25519RistrettoSubtractCost uint64
Curve25519RistrettoMultiplyCost uint64
Curve25519RistrettoMsmBaseCost uint64
Curve25519RistrettoMsmIncrementalCost uint64
HeapSize uint32
HeapCost uint64
MemOpBaseCost uint64
AltBn128AdditionCost uint64
AltBn128MultiplicationCost uint64
AltBn128PairingOnePairCostFirst uint64
AltBn128PairingOnePairCostOther uint64
BigModularExponentiationBaseCost uint64
BigModularExponentiationCostDivisor uint64
PoseidonCostCoefficientA uint64
PoseidonCostCoefficientC uint64
GetRemainingComputeUnitsCost uint64
AltBn128G1Compress uint64
AltBn128G1Decompress uint64
AltBn128G2Compress uint64
AltBn128G2Decompress uint64
}
ComputeBudget mirrors litesvm-go's ComputeBudget (itself a mirror of solana_compute_budget::compute_budget::ComputeBudget). Fields typed as `usize` on the Solana side are surfaced as uint64; HeapSize stays uint32.
func DefaultComputeBudget ¶ added in v0.3.0
func DefaultComputeBudget() ComputeBudget
DefaultComputeBudget returns the Agave runtime defaults (solana-compute-budget 4.0.0, ComputeBudget::new_with_defaults with SIMD-0268 and SIMD-0339 inactive). Mithril's cu package constants match these values. The AltBn128AdditionCost / AltBn128MultiplicationCost fields carry the G1 costs.
type FeatureSet ¶
type FeatureSet struct {
// contains filtered or unexported fields
}
FeatureSet describes which runtime features are enabled: active feature ids with their activation slot, plus the set of known-but-inactive feature ids. It is plain Go state backed by the gates catalog — use NewFeatureSet or NewFeatureSetAllEnabled to obtain the feature catalog, mutate it with Activate/Deactivate, then install it with (*LiteSVM).SetFeatureSet.
func NewFeatureSet ¶
func NewFeatureSet() (*FeatureSet, error)
NewFeatureSet returns the default feature set: every feature in the gates catalog, inactive.
func NewFeatureSetAllEnabled ¶
func NewFeatureSetAllEnabled() (*FeatureSet, error)
NewFeatureSetAllEnabled returns a FeatureSet with every known feature activated at slot 0.
func (*FeatureSet) Activate ¶
func (fs *FeatureSet) Activate(featureID solana.PublicKey, slot uint64) error
Activate marks `featureID` as active at `slot`. The error result is non-nil only for a nil receiver and is retained for backward compatibility.
func (*FeatureSet) ActivatedSlot ¶
func (fs *FeatureSet) ActivatedSlot(featureID solana.PublicKey) (uint64, bool)
ActivatedSlot returns the slot at which `featureID` was activated. The bool is false if the feature is not active.
func (*FeatureSet) ActiveCount ¶
func (fs *FeatureSet) ActiveCount() int
ActiveCount returns the number of active features.
func (*FeatureSet) ActiveFeatures ¶
func (fs *FeatureSet) ActiveFeatures() []solana.PublicKey
ActiveFeatures returns the full list of active feature pubkeys. Output is sorted for deterministic ordering.
func (*FeatureSet) Close
deprecated
func (fs *FeatureSet) Close()
Close is a no-op: FeatureSet is plain Go state and holds nothing to release.
Deprecated: there is nothing to release; calls can be removed.
func (*FeatureSet) Deactivate ¶
func (fs *FeatureSet) Deactivate(featureID solana.PublicKey) error
Deactivate marks `featureID` as inactive. The error result is non-nil only for a nil receiver and is retained for backward compatibility.
func (*FeatureSet) InactiveCount ¶
func (fs *FeatureSet) InactiveCount() int
InactiveCount returns the number of inactive features.
func (*FeatureSet) InactiveFeatures ¶
func (fs *FeatureSet) InactiveFeatures() []solana.PublicKey
InactiveFeatures returns the full list of inactive feature pubkeys. Output is sorted for deterministic ordering.
type InnerInstruction ¶
type InnerInstruction struct {
// Instruction is the compiled instruction that was invoked. Its account
// and program indices point into the enclosing transaction message's
// account-keys table.
Instruction solana.CompiledInstruction `json:"instruction"`
// StackHeight is the invocation stack height of this instruction: the
// runtime's TRANSACTION_LEVEL_STACK_HEIGHT (1) is a top-level
// instruction, 2 and deeper are CPIs.
// NOTE: it is actually a uint8, but using a uint16 for consistency with
// how solana-go widens u8 message indices.
StackHeight uint16 `json:"stackHeight"`
}
InnerInstruction is one cross-program invocation (CPI) recorded while a transaction executed, together with the depth at which it ran.
This is a port of the upstream anza-xyz/solana-sdk `message::inner_instruction::InnerInstruction` struct. It complements rpc.InnerInstruction (which is shaped for JSON-RPC responses) as the plain core-SDK representation, reusing solana-go's CompiledInstruction.
NOTE: this is a data-model port only; it is NOT bincode-layout-compatible with the Rust struct. Reflection-based bin encoding would write StackHeight as a little-endian u16 (Rust serializes a u8) and CompiledInstruction's widened uint16 indices instead of u8 indices with short-vec lengths.
type InnerInstructionsList ¶ added in v0.3.0
type InnerInstructionsList [][]InnerInstruction
InnerInstructionsList groups the recorded CPIs of one transaction: the outer slice is indexed by top-level instruction index, each inner slice holds the CPIs that instruction triggered, in execution order.
Port of solana-sdk `message::inner_instruction::InnerInstructionsList`.
type LiteSVM ¶
type LiteSVM struct {
// contains filtered or unexported fields
}
LiteSVM is a pure-Go, in-process Solana VM for testing. Instances are fully isolated from each other (per-instance accounts, sysvar cache, feature set, blockhash queue) and are NOT safe for concurrent use by multiple goroutines.
func New ¶
New creates a fresh LiteSVM with default settings, mirroring Rust LiteSVM::new(): default sysvars (including the deprecated Fees sysvar and stake-config accounts), builtin programs, precompile accounts, the default SPL/core-BPF program set (with_default_programs: SPL Token as p-token, Token-2022, Memo v1+v3, ATA, Address Lookup Table, Stake), on-chain feature-gate accounts for every mainnet-active feature, an airdrop pool of 1M SOL, and the deterministic genesis blockhash sha256("genesis"). Native mints stay opt-in via WithNativeMints, as in Rust.
Example ¶
Boot a fresh VM, fund an account, and read its balance. The whole round trip runs in-process: no validator, no RPC.
package main
import (
"crypto/ed25519"
"fmt"
litesvm "github.com/LiteSVM/litesvm-go"
"github.com/gagliardetto/solana-go"
)
// keypair derives a deterministic keypair for the examples below. Real
// code would use solana.NewRandomPrivateKey or load an existing key.
func keypair(b byte) ([32]byte, solana.PublicKey) {
var seed [32]byte
seed[0] = b
priv := solana.PrivateKey(ed25519.NewKeyFromSeed(seed[:]))
return seed, priv.PublicKey()
}
func main() {
svm, err := litesvm.New()
if err != nil {
panic(err)
}
defer svm.Close()
_, wallet := keypair(1)
if err := svm.Airdrop(wallet, 1_000_000_000); err != nil {
panic(err)
}
lamports, exists, err := svm.Balance(wallet)
if err != nil {
panic(err)
}
fmt.Println(exists, lamports)
}
Output: true 1000000000
func (*LiteSVM) AddProgram ¶
AddProgram installs an SBF program under the upgradeable loader, mirroring Rust litesvm's add_program default. Like the Rust engine (which loads and verifies the ELF while populating its program cache), invalid program bytes are rejected up front.
func (*LiteSVM) AddProgramFromFile ¶
AddProgramFromFile loads an SBF program ELF from disk and installs it.
func (*LiteSVM) AddProgramWithLoader ¶
func (s *LiteSVM) AddProgramWithLoader(programID solana.PublicKey, programBytes []byte, loader solana.PublicKey) error
AddProgramWithLoader installs an SBF program under a specific loader: the deprecated loader (v1), BPF loader v2, or the upgradeable loader (v3). Unknown loader ids are an error.
func (*LiteSVM) Airdrop ¶
Airdrop credits lamports to pubkey by executing a real transfer transaction from the internal airdrop account, mirroring litesvm.
func (*LiteSVM) Balance ¶
Balance returns the lamport balance of pubkey. The bool reports whether the account exists.
func (*LiteSVM) Close ¶
func (s *LiteSVM) Close()
Close is a no-op: the engine holds no resources that need releasing. It exists so `defer svm.Close()` remains valid.
func (*LiteSVM) ComputeBudget ¶
func (s *LiteSVM) ComputeBudget() (ComputeBudget, bool, error)
ComputeBudget returns the current custom compute budget. The bool is false (with a zero-value budget) when no custom budget has been configured and the runtime default is in effect.
func (*LiteSVM) EpochRewards ¶
func (s *LiteSVM) EpochRewards() (*sysvar.EpochRewards, error)
func (*LiteSVM) EpochSchedule ¶
func (s *LiteSVM) EpochSchedule() (*sysvar.EpochSchedule, error)
func (*LiteSVM) ExpireBlockhash ¶
ExpireBlockhash invalidates all current blockhashes and installs a fresh latest blockhash, mirroring litesvm's expire_blockhash: the new hash is create_blockhash(previous hash bytes) and the rewritten RecentBlockhashes entry carries fee_structure.lamports_per_signature (5000).
func (*LiteSVM) GetAccount ¶
GetAccount returns the account at pubkey, or nil if it does not exist.
func (*LiteSVM) GetTransaction ¶
GetTransaction returns the recorded outcome for signature, or nil. Mirroring Rust litesvm, both successful and executed-but-failed (fee charged) transactions are recorded; pre-execution rejections are not.
func (*LiteSVM) LastRestartSlot ¶
func (s *LiteSVM) LastRestartSlot() (*sysvar.LastRestartSlot, error)
func (*LiteSVM) LatestBlockhash ¶
LatestBlockhash returns the most recent registered blockhash.
func (*LiteSVM) MinimumBalanceForRentExemption ¶
MinimumBalanceForRentExemption computes the rent-exempt minimum for an account of the given data length using the current Rent sysvar.
func (*LiteSVM) SendLegacyTransaction ¶
SendLegacyTransaction submits a bincode-encoded legacy transaction. Version-prefixed (v0) bytes are rejected with a decode error.
Example ¶
Send a signed legacy transaction and inspect the outcome.
package main
import (
"crypto/ed25519"
"fmt"
litesvm "github.com/LiteSVM/litesvm-go"
"github.com/gagliardetto/solana-go"
)
// keypair derives a deterministic keypair for the examples below. Real
// code would use solana.NewRandomPrivateKey or load an existing key.
func keypair(b byte) ([32]byte, solana.PublicKey) {
var seed [32]byte
seed[0] = b
priv := solana.PrivateKey(ed25519.NewKeyFromSeed(seed[:]))
return seed, priv.PublicKey()
}
func main() {
svm, err := litesvm.New()
if err != nil {
panic(err)
}
defer svm.Close()
payerSeed, payer := keypair(2)
_, recipient := keypair(3)
if err := svm.Airdrop(payer, 1_000_000_000); err != nil {
panic(err)
}
blockhash, err := svm.LatestBlockhash()
if err != nil {
panic(err)
}
txBytes, err := litesvm.BuildTransferTx(payerSeed, recipient, 1_000_000, blockhash)
if err != nil {
panic(err)
}
out, err := svm.SendLegacyTransaction(txBytes)
if err != nil {
panic(err)
}
defer out.Close()
got, _, err := svm.Balance(recipient)
if err != nil {
panic(err)
}
fmt.Println(out.IsOk(), got)
}
Output: true 1000000
func (*LiteSVM) SendVersionedTransaction ¶
SendVersionedTransaction submits a bincode-encoded versioned transaction (legacy or v0 wire format).
func (*LiteSVM) SetAccount ¶
SetAccount installs acct at pubkey, overwriting any existing account, mirroring Rust litesvm's set_account (accounts_db.rs add_account):
- the compiled-program cache entry for pubkey is evicted, so overwriting a program (or programdata) account never serves stale program bytes;
- writing a known sysvar ADDRESS (regardless of the account's owner) refreshes the typed sysvar cache, and undecodable sysvar data is rejected without storing anything, keeping both views coherent;
- a zero-lamport account deletes the entry instead of storing it.
The account data is copied, so later mutation of acct.Data by the caller does not affect engine state.
Example ¶
Write an arbitrary account into the VM and read it back. This is how you inject fixtures (e.g. accounts dumped from mainnet) into a test.
package main
import (
"crypto/ed25519"
"fmt"
litesvm "github.com/LiteSVM/litesvm-go"
"github.com/gagliardetto/solana-go"
)
// keypair derives a deterministic keypair for the examples below. Real
// code would use solana.NewRandomPrivateKey or load an existing key.
func keypair(b byte) ([32]byte, solana.PublicKey) {
var seed [32]byte
seed[0] = b
priv := solana.PrivateKey(ed25519.NewKeyFromSeed(seed[:]))
return seed, priv.PublicKey()
}
func main() {
svm, err := litesvm.New()
if err != nil {
panic(err)
}
defer svm.Close()
_, owner := keypair(6)
_, address := keypair(7)
acct := &solana.Account{
Lamports: 1_000_000_000,
Data: []byte("hello"),
Owner: owner,
}
if err := svm.SetAccount(address, acct); err != nil {
panic(err)
}
got := svm.GetAccount(address)
if got == nil {
panic("account not found")
}
fmt.Printf("%s %d\n", got.Data, got.Lamports)
}
Output: hello 1000000000
func (*LiteSVM) SetBlockhashCheck ¶
SetBlockhashCheck toggles transaction blockhash-age validation.
func (*LiteSVM) SetBuiltins ¶
SetBuiltins (re-)installs the default set of built-in program accounts.
func (*LiteSVM) SetComputeBudget ¶
func (s *LiteSVM) SetComputeBudget(b ComputeBudget) error
SetComputeBudget replaces the compute budget used for subsequent txs.
Mithril's pure pipeline (replay.LoadAndExecuteTransaction) derives its compute budget solely from the transaction's compute-budget instructions, so only the knobs that can be expressed as such instructions are honored per-instance:
- ComputeUnitLimit and HeapSize are threaded into execution by appending synthetic compute-budget instructions to transactions that carry none of their own (see tx.go). Transactions with explicit compute-budget instructions keep their own budget, and the injected instructions consume the usual 150 CU each. ComputeUnitLimit must not exceed 1_400_000, and HeapSize must be a multiple of 1024 within [32KiB, 256KiB]: the runtime rejects other values.
- MaxInstructionStackDepth and MaxInstructionTraceLength are hardcoded by mithril's replay package (5 and 64, the Agave defaults) and can only be set to those values.
Every other field is a VM cost constant baked into mithril's cu package; setting it to anything but the default is an error naming the field.
func (*LiteSVM) SetDefaultPrograms ¶
SetDefaultPrograms installs the standard program set the Rust litesvm crate ships: SPL Token (p-token), Token-2022, Memo v1+v3, Associated Token Account, and the core-BPF Address Lookup Table and Stake programs.
func (*LiteSVM) SetEpochRewards ¶
func (s *LiteSVM) SetEpochRewards(e *sysvar.EpochRewards) error
func (*LiteSVM) SetEpochSchedule ¶
func (s *LiteSVM) SetEpochSchedule(e *sysvar.EpochSchedule) error
func (*LiteSVM) SetFeatureSet ¶
func (s *LiteSVM) SetFeatureSet(f *FeatureSet) error
SetFeatureSet installs `f` as the SVM's active feature set. The engine's runtime feature set is rebuilt from scratch, so feature ids missing from `f`'s active list become inactive.
Mithril keys its Features map on {Name, Address} pairs with its own gate names, so activation is mapped by address onto mithril's gate catalog (features.AllFeatureGates). Gates mithril does not know are silently ignored — mithril has no execution path keyed on them, which matches the Rust engine's behavior of ignoring feature accounts it never consults.
The on-chain feature-gate accounts written by New() are NOT rewritten: Rust's set_feature_set only swaps the runtime feature set (lib.rs:666-669) and leaves the accounts from with_feature_accounts untouched.
func (*LiteSVM) SetLamports ¶
SetLamports resets the airdrop pool balance.
func (*LiteSVM) SetLastRestartSlot ¶
func (s *LiteSVM) SetLastRestartSlot(l *sysvar.LastRestartSlot) error
func (*LiteSVM) SetLogBytesLimit ¶
SetLogBytesLimit caps the log bytes recorded per transaction. A negative limit removes the cap.
func (*LiteSVM) SetPrecompiles ¶
SetPrecompiles (re-)installs the standard precompile accounts.
func (*LiteSVM) SetSigverify ¶
SetSigverify toggles signature verification for submitted transactions.
func (*LiteSVM) SetSlotHashes ¶
func (s *LiteSVM) SetSlotHashes(items sysvar.SlotHashes) error
SetSlotHashes replaces the SlotHashes sysvar. Entries are canonicalized to the layout programs expect: descending slot order, deduplicated, and capped at sysvar.SlotHashesMaxEntries.
func (*LiteSVM) SetSlotHistory ¶
func (s *LiteSVM) SetSlotHistory(sh *sysvar.SlotHistory) error
SetSlotHistory replaces the SlotHistory sysvar.
func (*LiteSVM) SetStakeHistory ¶
func (s *LiteSVM) SetStakeHistory(items sysvar.StakeHistory) error
SetStakeHistory replaces the StakeHistory sysvar. Entries are canonicalized to descending epoch order, deduplicated, and capped at sysvar.StakeHistoryMaxEntries (newest kept).
func (*LiteSVM) SetSysvars ¶
SetSysvars re-initializes the built-in sysvars to their defaults. The recent-blockhash queue is left untouched.
func (*LiteSVM) SetTransactionHistory ¶
SetTransactionHistory sets the transaction history capacity; 0 disables history and with it duplicate-transaction detection.
func (*LiteSVM) SimulateLegacyTransaction ¶
SimulateLegacyTransaction simulates a bincode-encoded legacy transaction without committing state. Version-prefixed (v0) bytes are rejected with a decode error.
Example ¶
Simulate a transaction to preflight it: compute units and logs are reported, but no state is mutated.
package main
import (
"crypto/ed25519"
"fmt"
litesvm "github.com/LiteSVM/litesvm-go"
"github.com/gagliardetto/solana-go"
)
// keypair derives a deterministic keypair for the examples below. Real
// code would use solana.NewRandomPrivateKey or load an existing key.
func keypair(b byte) ([32]byte, solana.PublicKey) {
var seed [32]byte
seed[0] = b
priv := solana.PrivateKey(ed25519.NewKeyFromSeed(seed[:]))
return seed, priv.PublicKey()
}
func main() {
svm, err := litesvm.New()
if err != nil {
panic(err)
}
defer svm.Close()
payerSeed, payer := keypair(4)
_, recipient := keypair(5)
if err := svm.Airdrop(payer, 1_000_000_000); err != nil {
panic(err)
}
blockhash, err := svm.LatestBlockhash()
if err != nil {
panic(err)
}
txBytes, err := litesvm.BuildTransferTx(payerSeed, recipient, 1_000_000, blockhash)
if err != nil {
panic(err)
}
out, err := svm.SimulateLegacyTransaction(txBytes)
if err != nil {
panic(err)
}
defer out.Close()
// The simulation succeeded and consumed compute units...
fmt.Println(out.IsOk(), out.ComputeUnits() > 0)
// ...but the recipient was never credited.
_, exists, err := svm.Balance(recipient)
if err != nil {
panic(err)
}
fmt.Println(exists)
}
Output: true true false
func (*LiteSVM) SimulateVersionedTransaction ¶
SimulateVersionedTransaction simulates a bincode-encoded versioned transaction (legacy or v0 wire format) without committing state.
func (*LiteSVM) SlotHashes ¶
func (s *LiteSVM) SlotHashes() (sysvar.SlotHashes, error)
func (*LiteSVM) SlotHistory ¶
func (s *LiteSVM) SlotHistory() (*sysvar.SlotHistory, error)
SlotHistory returns the SlotHistory sysvar.
func (*LiteSVM) StakeHistory ¶
func (s *LiteSVM) StakeHistory() (sysvar.StakeHistory, error)
func (*LiteSVM) WarpToSlot ¶
WarpToSlot advances the bank to the given slot: it updates the Clock sysvar's Slot field (cache + account) and the internal slot counter.
Example ¶
Jump the VM to an arbitrary slot — handy for testing time-locked logic (vesting, auctions) without waiting on a real clock.
package main
import (
"fmt"
litesvm "github.com/LiteSVM/litesvm-go"
)
func main() {
svm, err := litesvm.New()
if err != nil {
panic(err)
}
defer svm.Close()
if err := svm.WarpToSlot(1_000); err != nil {
panic(err)
}
clock, err := svm.Clock()
if err != nil {
panic(err)
}
fmt.Println(clock.Slot)
}
Output: 1000
func (*LiteSVM) WithNativeMints ¶
WithNativeMints seeds the wrapped-SOL mint (and the Token-2022 native mint) when the corresponding token program account is installed.
type PostAccount ¶
PostAccount is a (address, account) pair returned by a successful simulation.
type TxOutcome ¶
type TxOutcome struct {
// contains filtered or unexported fields
}
TxOutcome holds the result of a transaction submission or simulation. It always carries metadata (signature, logs, compute units, fee) regardless of whether the transaction succeeded; if it failed, Error returns a non-empty string.
Error strings are Agave wire-format JSON, e.g. "BlockhashNotFound" or {"InstructionError":[0,{"Custom":1}]}.
func (*TxOutcome) ComputeUnits ¶
ComputeUnits returns the compute units consumed.
func (*TxOutcome) InnerInstructions ¶
func (o *TxOutcome) InnerInstructions() InnerInstructionsList
InnerInstructions returns recorded CPIs grouped by top-level instruction.
func (*TxOutcome) IsOk ¶
IsOk reports whether the transaction executed successfully. Returns false if the receiver is nil (treating an unusable outcome as "not ok").
func (*TxOutcome) PostAccounts ¶
func (o *TxOutcome) PostAccounts() ([]PostAccount, error)
PostAccounts returns the modified accounts after a successful execution. The error result is always nil and retained for backward compatibility.
func (*TxOutcome) ReturnData ¶
ReturnData returns the last instruction's return data. The bool reports whether return data was set. Empty return data is indistinguishable from never-set return data and reports false.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
examples
|
|
|
transfer
command
Command transfer is a minimal end-to-end example: spin up a fresh LiteSVM, fund a payer, send a system-program transfer, and print the resulting balances.
|
Command transfer is a minimal end-to-end example: spin up a fresh LiteSVM, fund a payer, send a system-program transfer, and print the resulting balances. |
|
internal
|
|
|
elf
Package elf vendors the Solana program ELF blobs that the Rust litesvm 0.13.0 crate ships and installs by default (mainnet feature set), mirroring litesvm-0.13.0/src/programs/mod.rs.
|
Package elf vendors the Solana program ELF blobs that the Rust litesvm 0.13.0 crate ships and installs by default (mainnet feature set), mirroring litesvm-0.13.0/src/programs/mod.rs. |
|
gates
Package gates catalogs the Agave runtime feature gates: every feature registered in agave-feature-set's FEATURE_NAMES map, with the pubkey that activates it and whether it was active on mainnet-beta per the litesvm 0.13 snapshot (2026-06-16).
|
Package gates catalogs the Agave runtime feature gates: every feature registered in agave-feature-set's FEATURE_NAMES map, with the pubkey that activates it and whether it was active on mainnet-beta per the litesvm 0.13 snapshot (2026-06-16). |