svmscope
Start from a real transaction. Decode it, replay it locally in an embedded SVM, mutate state and time-travel, freeze it into a fixture, and assert on it forever.
π¦ Full working example: github.com/alizeeshan1234/svmscope_example β an Anchor program plus a Rust project that consumes the published crate end-to-end.
The Solana testing stack has unit testing (LiteSVM), instruction testing (Mollusk), and integration testing from current mainnet state (Surfpool). svmscope covers the fourth quadrant: post-mortem and regression testing from a historical transaction β a real signature already encodes its entire world (accounts, programs, state), so one signature replaces a hundred lines of test setup.
Add it to a Rust project
svmscope is a testing tool, so add it as a dev-dependency:
[]
= "0.4"
Then point it at a real transaction and replay it locally β no validator, no setup:
use ;
#
That's the whole loop: reconstruct once, replay and mutate forever. The rest of this README goes deeper β building and submitting transactions, freezing offline fixtures, and the full assertion DSL.
The library has no features to configure β the HTTP API server lives in its
own workspace crate (server/), so library consumers never
compile axum/tokio.
Library quickstart
use ;
let scope = new;
let signature = "a mainnet transaction signature";
let = ;
// Decode: the full CPI tree, every instruction named from its on-chain IDL.
let analysis = scope.analyze?;
// Reconstruct the transaction's world once β every account, every program ELF.
// All RPC happens here; every run below is local, instant, and free.
let mut replay = scope.replay?;
assert!;
// What-if, with declarative checks (a reverting replay is data, not an Err):
let outcome = replay.verify?;
assert!;
// Time is just the Clock sysvar β warp it. A vesting claim that reverts
// today succeeds at +30 days.
replay.advance_seconds;
let future = replay.run?;
// Freeze the whole world into one JSON file: accounts, ELFs, IDLs, and the
// recorded on-chain outcome. It replays identically forever, offline.
write?;
# Ok::
The main API is available directly from the crate root. Import
Scope, Replay, Mutation, Check, Cmp, Scenario, Fixture, and result
types as svmscope::Type; implementation modules are intentionally private.
The idl, report, and spec modules are public for IDL inspection, HTML
reports, and the JSON scenario format respectively.
Four ways to mutate state
A what-if is one or more Mutations applied before the replay. Named-field
mutations are the headline β flip an oracle price, a token balance, a vesting
cliff by name, with no byte offsets, resolved through the same SPL-layout/IDL
decoding the assertion DSL uses:
use ;
#
The JSON scenario suites below express the same
mutations declaratively: {"kind":"field","field":"reserve_a","value":β¦},
{"kind":"lamports",β¦}, and {"kind":"data","offset":β¦,"bytes_hex":β¦}.
Build and send the transaction inside the Rust test
You can also start from scratch instead of an existing signature. A Rust test can
build an Anchor instruction from the program IDL, sign it, send it to a local
solana-test-validator, wait for it to land, and immediately receive a replay of
the exact pre-transaction state β no copying signatures out of a separate test
suite.
1. Build and deploy the Anchor program
Terminal 1 (leave it running):
Terminal 2:
Keep the generated target/idl/<program>.json. The local validator must already
have the program deployed before svmscope constructs the replay because the
replay captures the deployed ELF and all input accounts. Put the address printed
by anchor keys list in YOUR_PROGRAM_ID. If the instruction updates state,
initialize that state/PDA first and put its address in
YOUR_EXISTING_STATE_ACCOUNT.
2. Add the test dependencies
[]
= "0.4"
= "1"
= "2.6"
= "3.1"
= "3.0"
3. Construct, submit, capture, mutate, and time-travel
use FromStr;
use json;
use Address;
use read_keypair_file;
use Signer;
use ;
Use .account_signer("accountName", &keypair) when an IDL account must sign,
or .signer(&keypair) when its address was supplied separately. Fixed-address
accounts in modern Anchor IDLs, such as the System Program, are filled
automatically. PDAs are addresses, not signers: derive them in the test and pass
the result with .account(...).
Argument values are JSON and are Borsh-encoded in IDL order. Supported values
include booleans; signed and unsigned integers through 128 bits; floats; strings;
public keys; bytes; vectors; options; fixed arrays; and IDL-defined structs and
enums. Pass integers larger than JSON's exact numeric range as decimal strings,
and bytes either as [0, 1, 255] or a "0x..." string.
send_and_capture waits up to 20 seconds. A program revert is still a landed
transaction and returns Ok(CapturedTransaction) with
captured.replay.recorded().unwrap().success == false. Err is reserved for an
RPC failure, timeout, malformed IDL/accounts/arguments, or transaction-building
failure.
If you already construct a VersionedTransaction yourself, use the lower-level
path directly:
let captured = scope.send_and_capture?;
Offline fixture use
Capture a transaction once while connected to RPC, then load it without any network access in tests or CI:
use ;
let fixture = from_json?;
let replay = from_fixture?;
let outcomes = replay.run_suite?;
assert!;
# Ok::
The three things it does
1. Post-mortem a transaction. Paste a failed mainnet signature: the CPI tree arrives with instructions, arguments, and accounts named (resolved from the on-chain Anchor IDL or known native layouts), balance and token diffs, per-program compute units, and β on replay β the failure explained in plain language ("SlippageToleranceExceeded", not Custom(6001)). Then change one thing and run it again.
2. Test against reality. scope.replay(sig) rebuilds the transaction's world inside LiteSVM β no validator, no ports, no devnet dance. Mutate lamports or bytes, flip runtime feature gates, warp the clock by slots/epochs/seconds or to an absolute point, and assert on outcomes and resulting state with a mollusk-style Check DSL, including named fields: Check::account(pool).field("reserve_a", Cmp::gt(0)).
3. Regression-test it in CI, offline. scope.capture(sig) freezes everything β transaction, accounts, program binaries, IDLs, and the actual on-chain outcome β into one portable JSON fixture. Replay::from_fixture rebuilds the world with zero RPC: deterministic suites in CI with no key, no drift, no flakes, and Check::matches_onchain() as the "does it still behave like mainnet" primitive.
4. Profile the compute. replay.profile(&[]) traces every BPF instruction the transaction executes β every program frame, every CPI β and attributes them to functions, syscalls and call stacks: a flamegraph of where the compute units went. Nothing else on Solana shows this. Mainnet programs are stripped, so their functions read as function_<pc> with exact boundaries and shape; pass the .debug file cargo build-sbf --debug writes next to your own .so and every function gets its Rust name.
Errors are typed and self-explanatory: a typo'd mutation address is a hard Error::MutationTargetMissing, never a fake "revert" your test happily accepts; an unknown field name errors listing the available fields.
Run the examples against any transaction:
For a full real-world consumer β an Anchor program (counter + SOL vesting) plus a standalone Rust project that depends on the published crate and drives the entire build β submit β capture β replay β mutate β time-travel β freeze workflow, with a 129-test offline suite and validator-gated online tests β see the svmscope_example repo.
The CLI
The same engine, on the command line:
Every command takes --cluster <mainnet|devnet|testnet|localnet> or --rpc <url>.
$ cargo run -- <SIGNATURE>
#0 Route V2 (JUP6LkbZbjS1jKKwapdHNy74zcZ3tLUZoi5QNyVTaV4)
ββ [2] Swap (BiSoNHVpsVZW2F7rx2eQ59yQwKxzU5NvBcmKshCSUypi)
ββ [3] Transfer (TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA)
-- compute units per program --
JUP6LkbZbjS1jKKwapdHNy74zcZ3tLUZoi5QNyVTaV4 178113 CU
-- replay --
REPLAY: failed β error: InstructionError(4, Custom(6024))
That's the real Jupiter program executing locally. Swaps often fail on replay with a slippage error β not a bug, but the honest consequence of state drift: replays run against current reconstructed state, and pool prices have moved since the original slot. That's exactly why fixtures exist: freeze once, and the replay is pinned forever.
Profile the compute
Every Solana developer has stared at consumed 187,342 of 200,000 compute units with no idea which function ate it. The profiler answers that for any transaction, mainnet or local:
$ cargo run -- profile <SIGNATURE>
replay: ok β
Β· 58,501 CU charged Β· 34,556 BPF instructions across 9 program frames
-- compute per program --
37487 pAMMBay6oceH9fJKBRHGP5D4bD4sWpmSwMn52FMfXEA
12968 ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL
5660 pfeeUxB6jkeY1Hxd7CsFCAjcbHA9rWtchMGdZ6VojVZ
...
== frame 9 Β· pAMMBay6oceH9fJKBRHGP5D4bD4sWpmSwMn52FMfXEA Β· 22051 instructions Β· 37487 CU Β· 15436 CU beyond instructions ==
self total calls ~CU function
4492 5525 1 7636 function_105164
2612 2612 2 4440 function_7339
1319 1319 60 2242 function_93342
syscalls:
86 sol_memcmp_
75 sol_memcpy_
Hosted: svmscope.vercel.app has a Profile tab β paste a signature and the flamegraph is the first thing on screen; /flame/<signature> is a shareable link to one.
How it works: LiteSVM records every BPF instruction each program frame executes; the profiler folds that trace into call stacks (function boundaries come from the program's own call graph, so they are exact), counts syscalls by name, and attaches the runtime's measured compute per frame β exclusive of the CPIs it made β from the consumed log lines. The folded stacks are flamegraph input; the hosted debugger draws them.
Names: every mainnet program is stripped, so its functions have no symbol names. Two things fill that in automatically. A bundled shape corpus names library functions β core, alloc, borsh, Anchor, Solana, SPL β by matching their code shape against open-source builds with symbols (Phoenix profiles with its real Rust names this way). And the trace says what each remaining function did, so the profiler labels them from that evidence: Buy handler, instruction dispatch, CPI β Token Program: Transfer, PDA derivation, emits event, hashing, error: SlippageExceeded. Functions that only compute stay fn@<pc>. For your own program, build with cargo build-sbf --debug, deploy that .so, keep the .debug beside it, and pass --symbols <program>=<path>.debug (or upload it in the debugger UI): every function gets its Rust name. If the build you have is not the one on chain (a plain release deploy, symbols from a --debug build), pass both files β --symbols <program>=<path>.debug,<path>.so β and functions are matched by code shape instead of address; the same-build case still maps by address and refuses a mismatched entrypoint.
Library: let (result, mut profile) = replay.profile(&[])?; profile.symbolize(program, &std::fs::read("my.debug")?)?; β Profile is frames: Vec<FrameProfile> with functions, syscalls, stacks (folded, a;b;c β count) and compute_units per frame. The profiler feature is on by default; default-features = false drops it.
Scenario suites (JSON)
Suites also exist as a JSON format β the same one the web UI exports and svmscope test runs. Reference a fixture for the deterministic, offline path:
$ cargo run -- test suite.json
svmscope test β fixture 4RHXβ¦oJWt (16 accounts, 5 programs) [deterministic, offline]
PASS baseline replays faithfully (expect: succeeds; got: succeeded)
PASS draining the pool reverts (expect: reverts; got: reverted (Custom(6004)))
2/2 passed
Assert kinds: lamports, u64 (at an offset), token_amount, lamports_delta, token_delta, and named fields β "field": "pool.reserveA" resolved through SPL layouts or the program's IDL (field_delta for changes). v2 fixtures carry their IDLs, so named-field asserts work fully offline.
How it works
- Decode β walks
getTransaction: the CPI tree frominnerInstructions+stackHeight, diffs frompre/postBalances, compute from the logs, Address Lookup Table resolution, instruction/account/field naming from on-chain IDLs (Anchor and the Program Metadata program) or built-in native layouts. - Reconstruct β
getMultipleAccountsfor every touched account; programs resolve through the upgradeable loader's programdata pointer to the raw ELF; closed accounts (drained fee payers, closed token accounts) are rebuilt from the transaction's own metadata; pre-transaction SPL balances are rewound so swaps replay faithfully. - Replay β everything loads into a pristine LiteSVM per run (sigverify/blockhash checks off β the original blockhash can't be valid in a fresh SVM), the clock anchored to the transaction's real slot and block time. There is no validator to wait for, so runs are microseconds and trivially parallel.
- Time travel β programs read time from the Clock sysvar; we own it. Warps move slot, epoch, and timestamp coherently (432k slots/epoch, ~400ms/slot), so a program checking all three sees a consistent world.
Live demo
A hosted web UI over this same library β paste a signature, click through the CPI tree, edit named account fields, run suites, freeze fixtures β is at svmscope.vercel.app.
Optional HTTP server
A small HTTP API over the engine lives in the server/ workspace
crate (svmscope-server β deployment infrastructure, not published to
crates.io). It reads HOST, PORT, and SVMSCOPE_RPC_URL from the
environment:
A typed TypeScript client lives in sdk/. Point it at your own RPC
endpoint β the public mainnet RPC is heavily rate-limited.
Roadmap
- Decode, reconstruct, replay, mutate, time-travel, feature gates
- Hermetic fixtures (v2: IDLs + recorded outcome captured β offline named-field asserts and
matches_onchain) - Typed errors; mutations validated up front (no silently-passing revert tests)
-
Scope/Replaylibrary API β fetch once, replay forever - Mollusk-style
CheckDSL with named-field assertions - Codama/Shank IDL support (named fields for native & Pinocchio programs)
- Named-field mutations β
Mutation::field(addr, "count", 99) - Async/trait RPC abstraction
- Anchor event decoding; archival state at the exact slot; cross-account invariants
See VISION.md for the full architecture.
Built with
Rust Β· litesvm Β· solana-client Β· thiserror Β· serde_json
License
MIT β see LICENSE.