litesvm

package module
v0.3.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 4, 2026 License: Apache-2.0 Imports: 22 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README


litesvm-go

Go Reference

The Go take on LiteSVM: a fast, in-process Solana VM for testing programs and clients. Pure Go, no cgo; a fresh VM boots in milliseconds and runs in the same process as your tests. Core types (PublicKey, Hash, Signature) come from gagliardetto/solana-go, so values flow naturally to and from the rest of the Go Solana ecosystem.

Install

go get github.com/LiteSVM/litesvm-go

Requires Go 1.25.7 or newer; cross-compilation works with plain GOOS/GOARCH. Note: until the patched mithril and solana-go dependencies are published, go.mod carries two local-path replace directives that you must point at your own checkouts.

Quick start

package mytest

import (
    "testing"

    litesvm "github.com/LiteSVM/litesvm-go"
    solana "github.com/gagliardetto/solana-go"
    "github.com/gagliardetto/solana-go/programs/system"
)

func TestTransfer(t *testing.T) {
    svm, err := litesvm.New()
    if err != nil {
        t.Fatal(err)
    }
    defer svm.Close()

    priv, _ := solana.NewRandomPrivateKey()
    payer := priv.PublicKey()
    recipient := solana.NewWallet().PublicKey()

    if err := svm.Airdrop(payer, 2_000_000_000); err != nil {
        t.Fatal(err)
    }

    // Build, sign, and encode a transfer with solana-go.
    blockhash, _ := svm.LatestBlockhash()
    ix := system.NewTransferInstruction(1_000_000_000, payer, recipient).Build()
    tx, _ := solana.NewTransaction(
        []solana.Instruction{ix},
        blockhash,
        solana.TransactionPayer(payer),
    )
    tx.Sign(func(k solana.PublicKey) *solana.PrivateKey {
        if k.Equals(payer) {
            return &priv
        }
        return nil
    })
    txBytes, _ := tx.MarshalBinary()

    out, err := svm.SendLegacyTransaction(txBytes)
    if err != nil {
        t.Fatal(err)
    }
    if !out.IsOk() {
        t.Fatalf("tx failed: %s\nlogs: %v", out.Error(), out.Logs())
    }

    if lamports, _, _ := svm.Balance(recipient); lamports != 1_000_000_000 {
        t.Fatalf("recipient balance = %d, want 1_000_000_000", lamports)
    }
}

Features

  • Send and simulate transactions, legacy and versioned (v0, including address-table lookups). Every entry point returns (value, error), wrapped under a single sentinel detectable with errors.Is.
  • Accounts: airdrops, read/write any account, rent-exempt minimums.
  • Sysvars: read and overwrite Clock, Rent, EpochSchedule, EpochRewards, SlotHashes, StakeHistory, and more; WarpToSlot for time travel.
  • Feature gates: activate or deactivate any runtime feature per instance.
  • Compute budget configuration per instance.
  • Program loading from bytes or file, under any loader; a fresh instance ships the default program set (SPL Token, Token-2022, Memo, ATA, Address Lookup Table, Stake) preloaded.
  • Transaction history with duplicate detection (GetTransaction).
  • Instances are fully isolated from each other.

Notes

  • The engine is mithril's SVM, running as pure Go inside your test process. It is consumed from the sonicfromnewyoke/mithril fork, which carries the patches this package needs.
  • Transaction error strings (TxOutcome.Error) are Agave wire-format JSON, e.g. {"InstructionError":[0,{"Custom":1}]}.
  • SetComputeBudget honors ComputeUnitLimit and HeapSize only; every other field is a VM cost constant baked into the engine and must keep its default value.
  • A LiteSVM handle is not safe for concurrent use from multiple goroutines; confine it to one goroutine or guard it with a mutex.

Contributing

Everything is plain Go: clone and run go test -count=1 ./.... The root package is the entire public API; the engine internals live alongside it and the vendored program ELFs and feature-gate table live under internal/. New API goes in the root package with tests in litesvm_test.go. Benchmarks for the common workloads are in bench_test.go (go test -run '^$' -bench .).

License

Apache-2.0. See LICENSE.

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

Examples

Constants

This section is empty.

Variables

View Source
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.

func Version

func Version() string

Version reports the engine backing this package.

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.

func (*FeatureSet) IsActive

func (fs *FeatureSet) IsActive(featureID solana.PublicKey) bool

IsActive reports whether `featureID` is currently active.

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

func New() (*LiteSVM, error)

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

func (s *LiteSVM) AddProgram(programID solana.PublicKey, programBytes []byte) error

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

func (s *LiteSVM) AddProgramFromFile(programID solana.PublicKey, path string) error

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

func (s *LiteSVM) Airdrop(pubkey solana.PublicKey, lamports uint64) error

Airdrop credits lamports to pubkey by executing a real transfer transaction from the internal airdrop account, mirroring litesvm.

func (*LiteSVM) Balance

func (s *LiteSVM) Balance(pubkey solana.PublicKey) (uint64, bool, error)

Balance returns the lamport balance of pubkey. The bool reports whether the account exists.

func (*LiteSVM) Clock

func (s *LiteSVM) Clock() (*sysvar.Clock, error)

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

func (s *LiteSVM) ExpireBlockhash() error

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

func (s *LiteSVM) GetAccount(pubkey solana.PublicKey) *solana.Account

GetAccount returns the account at pubkey, or nil if it does not exist.

func (*LiteSVM) GetTransaction

func (s *LiteSVM) GetTransaction(signature solana.Signature) *TxOutcome

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

func (s *LiteSVM) LatestBlockhash() (solana.Hash, error)

LatestBlockhash returns the most recent registered blockhash.

func (*LiteSVM) MinimumBalanceForRentExemption

func (s *LiteSVM) MinimumBalanceForRentExemption(dataLen int) (uint64, error)

MinimumBalanceForRentExemption computes the rent-exempt minimum for an account of the given data length using the current Rent sysvar.

func (*LiteSVM) Rent

func (s *LiteSVM) Rent() (*sysvar.Rent, error)

func (*LiteSVM) SendLegacyTransaction

func (s *LiteSVM) SendLegacyTransaction(txBytes []byte) (*TxOutcome, error)

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

func (s *LiteSVM) SendVersionedTransaction(txBytes []byte) (*TxOutcome, error)

SendVersionedTransaction submits a bincode-encoded versioned transaction (legacy or v0 wire format).

func (*LiteSVM) SetAccount

func (s *LiteSVM) SetAccount(pubkey solana.PublicKey, acct *solana.Account) error

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

func (s *LiteSVM) SetBlockhashCheck(enabled bool) error

SetBlockhashCheck toggles transaction blockhash-age validation.

func (*LiteSVM) SetBuiltins

func (s *LiteSVM) SetBuiltins() error

SetBuiltins (re-)installs the default set of built-in program accounts.

func (*LiteSVM) SetClock

func (s *LiteSVM) SetClock(c *sysvar.Clock) error

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

func (s *LiteSVM) SetDefaultPrograms() error

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

func (s *LiteSVM) SetLamports(lamports uint64) error

SetLamports resets the airdrop pool balance.

func (*LiteSVM) SetLastRestartSlot

func (s *LiteSVM) SetLastRestartSlot(l *sysvar.LastRestartSlot) error

func (*LiteSVM) SetLogBytesLimit

func (s *LiteSVM) SetLogBytesLimit(limit int) error

SetLogBytesLimit caps the log bytes recorded per transaction. A negative limit removes the cap.

func (*LiteSVM) SetPrecompiles

func (s *LiteSVM) SetPrecompiles() error

SetPrecompiles (re-)installs the standard precompile accounts.

func (*LiteSVM) SetRent

func (s *LiteSVM) SetRent(r *sysvar.Rent) error

func (*LiteSVM) SetSigverify

func (s *LiteSVM) SetSigverify(enabled bool) error

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

func (s *LiteSVM) SetSysvars() error

SetSysvars re-initializes the built-in sysvars to their defaults. The recent-blockhash queue is left untouched.

func (*LiteSVM) SetTransactionHistory

func (s *LiteSVM) SetTransactionHistory(capacity int) error

SetTransactionHistory sets the transaction history capacity; 0 disables history and with it duplicate-transaction detection.

func (*LiteSVM) Sigverify

func (s *LiteSVM) Sigverify() (bool, error)

Sigverify reports whether signature verification is enabled.

func (*LiteSVM) SimulateLegacyTransaction

func (s *LiteSVM) SimulateLegacyTransaction(txBytes []byte) (*TxOutcome, error)

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

func (s *LiteSVM) SimulateVersionedTransaction(txBytes []byte) (*TxOutcome, error)

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

func (s *LiteSVM) WarpToSlot(slot uint64) error

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

func (s *LiteSVM) WithNativeMints() error

WithNativeMints seeds the wrapped-SOL mint (and the Token-2022 native mint) when the corresponding token program account is installed.

type PostAccount

type PostAccount struct {
	Address solana.PublicKey
	Account *solana.Account
}

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) Close

func (o *TxOutcome) Close()

Close is a no-op kept for API compatibility.

func (*TxOutcome) ComputeUnits

func (o *TxOutcome) ComputeUnits() uint64

ComputeUnits returns the compute units consumed.

func (*TxOutcome) Error

func (o *TxOutcome) Error() string

Error returns the failure rendering, or "" on success.

func (*TxOutcome) Fee

func (o *TxOutcome) Fee() uint64

Fee returns the fee charged in lamports.

func (*TxOutcome) InnerInstructions

func (o *TxOutcome) InnerInstructions() InnerInstructionsList

InnerInstructions returns recorded CPIs grouped by top-level instruction.

func (*TxOutcome) IsOk

func (o *TxOutcome) IsOk() bool

IsOk reports whether the transaction executed successfully. Returns false if the receiver is nil (treating an unusable outcome as "not ok").

func (*TxOutcome) Logs

func (o *TxOutcome) Logs() []string

Logs returns the program log messages.

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

func (o *TxOutcome) ReturnData() (solana.PublicKey, []byte, bool)

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.

func (*TxOutcome) Signature

func (o *TxOutcome) Signature() solana.Signature

Signature returns the transaction signature.

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).

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ 换网址