Skip to content
alizeeshan1234Public

About

Transaction autopsy for Solana — decode any transaction, replay it locally in an embedded SVM, mutate state, time-travel, and freeze it into offline test fixtures

Topics

Resources

Contributing

Stars

8 stars

Watchers

0 watching

Forks

Latest commit

 

History

389 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

svmscope

crates.io docs.rs CI license: MIT

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:

cargo add --dev svmscope
[dev-dependencies]
svmscope = "0.6"

Then point it at a real transaction and replay it locally — no validator, no setup:

use svmscope::{Check, Mutation, Scope};

# fn main() -> Result<(), Box<dyn std::error::Error>> {
let scope = Scope::new("https://api.mainnet-beta.solana.com");

// Reconstruct the transaction's world once — every account, every program ELF.
let mut replay = scope.replay("<signature>")?;
assert!(replay.run()?.result.success);

// Then ask "what if?" — a reverting replay is data, not an error.
let out = replay.verify(
    "draining the vault makes the claim revert",
    &[Mutation::lamports("<vault-address>", 0)],
    &[Check::revert_contains("InsufficientFunds")],
)?;
assert!(out.pass);
# Ok(())
# }

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.

Two feature flags: profiler (default; default-features = false drops it) and single-run-trace (the step debugger's single-execution mode, which depends on a runtime hook not yet upstream and therefore builds only from a checkout — see Cargo.toml). The HTTP API server lives in its own workspace crate (server/), so library consumers never compile axum/tokio.

Library quickstart

use svmscope::{Check, Cmp, Mutation, Scope};

let scope = Scope::new("https://api.mainnet-beta.solana.com");
let signature = "a mainnet transaction signature";
let (vault, user) = ("the vault's address", "the user's address");

// Decode: the full CPI tree, every instruction named from its on-chain IDL.
let analysis = scope.analyze(signature)?;

// 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(signature)?;
assert!(replay.run()?.result.success);

// What-if, with declarative checks (a reverting replay is data, not an Err):
let outcome = replay.verify(
    "draining the vault makes the claim revert",
    &[Mutation::lamports(vault, 0)],
    &[
        Check::revert_contains("InsufficientFunds"),
        Check::account(user).token_delta(Cmp::eq(0)).build(),
    ],
)?;
assert!(outcome.pass);

// Time is just the Clock sysvar — warp it. A vesting claim that reverts
// today succeeds at +30 days.
replay.advance_seconds(30 * 86_400);
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.
std::fs::write("fixtures/claim.json", scope.capture(signature)?.to_json()?)?;
# Ok::<(), Box<dyn std::error::Error>>(())

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 svmscope::{Mutation, Scope};
# fn main() -> Result<(), Box<dyn std::error::Error>> {
# let scope = Scope::new("https://api.mainnet-beta.solana.com");
# let mut replay = scope.replay("<signature>")?;
# let (pool, vault, oracle, config) = ("<pool>", "<vault>", "<oracle>", "<config>");
let out = replay.simulate(&[
    // 1. Set a NAMED field — the mutation-side twin of
    //    Check::account(pool).field("reserve_a", …). A typo'd name errors
    //    listing the real fields; an out-of-range value is a hard error.
    Mutation::field(pool, "reserve_a", 1_000_000),

    // 2. Set an account's SOL balance.
    Mutation::lamports(vault, 0),

    // 3. Patch a slice at a raw byte offset (when no layout is known).
    Mutation::patch(oracle, 8, 1_000_000_u64.to_le_bytes().to_vec()),

    // 4. Replace an account's data wholesale.
    Mutation::data(config, vec![0u8; 128]),
])?;
assert!(out.result.success || out.result.error.is_some());
# Ok(())
# }

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

solana-test-validator --reset

Terminal 2:

anchor build
anchor deploy --provider.cluster localnet
mkdir -p tests/fixtures
solana-keygen new --no-bip39-passphrase -o tests/fixtures/payer.json
solana airdrop 10 "$(solana address -k tests/fixtures/payer.json)" --url localhost
anchor keys list

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

[dev-dependencies]
svmscope = "0.6"
serde_json = "1"
solana-address = "2.6"
solana-keypair = "3.1"
solana-signer = "3.0"

3. Construct, submit, capture, mutate, and time-travel

use std::str::FromStr;

use serde_json::json;
use solana_address::Address;
use solana_keypair::read_keypair_file;
use solana_signer::Signer;
use svmscope::{Mutation, Scope};

fn invokes_program_and_replays_it() -> Result<(), Box<dyn std::error::Error>> {
    let scope = Scope::new("http://127.0.0.1:8899");
    let program_id = Address::from_str("YOUR_PROGRAM_ID")?;
    let state = Address::from_str("YOUR_EXISTING_STATE_ACCOUNT")?;
    let payer = read_keypair_file("tests/fixtures/payer.json")?;
    let idl = serde_json::from_str(&std::fs::read_to_string(
        "target/idl/your_program.json",
    )?)?;

    let mut captured = scope
        .program_with_idl(program_id, idl)
        .method("setValue")?
        .payer(&payer)
        // Names must match the IDL. Nested accounts may use "group.account".
        .account("authority", payer.pubkey())
        .account("state", state)
        .args(json!({ "value": 42 }))?
        .send_and_capture()?;

    // This signature was created here; nothing is copied from a TS test.
    println!("landed transaction: {}", captured.signature);
    assert!(captured.replay.recorded().is_some());

    // Re-execute locally from the state captured immediately before submission.
    let baseline = captured.replay.run()?;
    assert!(baseline.result.success);

    // Mutations and time travel now reuse that in-memory replay with no RPC.
    let changed = captured
        .replay
        .simulate(&[Mutation::lamports(state.to_string(), 0)])?;
    println!("after mutation: {:?}", changed.result.error);

    captured.replay.advance_seconds(30 * 86_400);
    let future = captured.replay.run()?;
    println!("after 30 days: {}", future.result.success);

    // Optional: freeze this newly created transaction for offline CI.
    let fixture = captured.replay.to_fixture()?;
    std::fs::write("fixtures/set_value.json", fixture.to_json()?)?;

    Ok(())
}

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(signed_versioned_transaction)?;

Offline fixture use

Capture a transaction once while connected to RPC, then load it without any network access in tests or CI:

use svmscope::{Check, Fixture, Replay, Scenario};

let fixture = Fixture::from_json(&std::fs::read_to_string("fixtures/claim.json")?)?;
let replay = Replay::from_fixture(&fixture)?;
let outcomes = replay.run_suite(&[
    Scenario::new("matches mainnet").check(Check::matches_onchain()),
    Scenario::new("still succeeds").check(Check::success()),
])?;

assert!(outcomes.iter().all(|outcome| outcome.pass));
# Ok::<(), Box<dyn std::error::Error>>(())

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.

5. Replay a whole bundle, not one transaction. Some transactions only make sense together: a bot buys in one and sells in the next, a liquidator moves a price and then seizes the position. scope.bundle(input)?.run(&[]) takes a Jito bundle id, any signature that landed inside one, or your own ordered list, and replays every transaction in sequence on one SVM, each starting from what the ones before it left behind. Every step is checked against what the chain recorded, the accounts that carry state between steps are reported as edges, and Bundle::trace(step, ..) steps through any one of them with all its predecessors already run. Edit a step and every step after it re-runs on the result.

Replaying one slot back to back is more faithful than replaying one transaction historically. On a pinned five-transaction bundle every step matched the chain's outcome and its exact compute units; a single historical replay matches compute exactly about a third of the time. Nothing is reconstructed between steps of one slot, which is the whole reason.

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:

cargo run --example post_mortem -- <signature>
cargo run --example what_if    -- <signature> <account>
cargo run --example fixture_ci -- <signature>

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:

cargo run -- <SIGNATURE>                          # decode + replay
cargo run -- <SIGNATURE> --mutate <ADDR>:<LAMPORTS>  # + a what-if
cargo run -- freeze <SIGNATURE> -o fixture.json   # capture a fixture
cargo run -- test suite.json                      # run a scenario suite (CI-ready)
cargo run -- report suite.json -o report.html     # shareable HTML report
cargo run -- upgrade fixture.json                 # re-capture an old fixture as v2
cargo run -- debug <SIGNATURE>                    # step debugger: every instruction and CPI, state diffs, failing step
cargo run -- profile <SIGNATURE>                  # compute profiler: instructions per function, per frame, per syscall
cargo run -- profile <SIGNATURE> --symbols <PROGRAM>=target/deploy/my_program.debug   # …with Rust function names
cargo run -- bundle <BUNDLE-ID>                   # replay a Jito bundle in order, every step checked against the chain
cargo run -- bundle <SIG>,<SIG>,<SIG>             # …or your own ordered list
cargo run -- bundle <BUNDLE-ID> --step 2          # step through one transaction of the sequence
cargo run -- bundle <BUNDLE-ID> --mutate 0:<ADDR>:0            # edit a step; every later step re-runs on the result
cargo run -- bundle <BUNDLE-ID> --mutations edits.json         # …any mutation, in the shape the HTTP API takes

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:

{
  "fixture": "fixture.json",
  "scenarios": [
    { "name": "baseline replays faithfully", "expect": "success" },
    {
      "name": "draining the pool reverts",
      "expect": "revert",
      "mutations": [{ "kind": "data", "address": "<POOL>", "offset": 64, "bytes_hex": "0000000000000000" }],
      "asserts": [{ "address": "<POOL>", "kind": "field", "field": "amount", "op": "==", "value": 0 }]
    }
  ]
}
$ 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 from innerInstructions + stackHeight, diffs from pre/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 — getMultipleAccounts for 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:

cargo run -p svmscope-server   # → http://127.0.0.1:3000, GET /api lists the surface

A typed TypeScript client lives in sdk/. Point it at your own RPC endpoint — the public mainnet RPC is heavily rate-limited.

Who is using it

The server counts every work-doing request and every page load per anonymous client (a hash of the address, never the address). Set SVMSCOPE_STATS_TOKEN and open the private analytics site (analytics/, deployed apart from the UI) with that token to see people per day, what they used, where they came from, and each client's activity; GET /stats?token=… is the same as JSON. The counters live in SVMSCOPE_STATS_FILE (default svmscope-stats.json) and, on a host whose disk does not survive a restart, are also kept as a release asset when SVMSCOPE_STATS_GITHUB=owner/repo (falling back to SVMSCOPE_RECORD_GITHUB) and SVMSCOPE_GITHUB_TOKEN are set: restored at boot, pushed every ten minutes while they change, and on shutdown.

Recording state for historical replay

replay_at_slot needs no archive. For every account the server has been recording since before the transaction landed, it serves the version observed across the target slot; what it cannot establish, the certificate names. Recording is off unless SVMSCOPE_RECORD_DIR is set:

Variable Meaning
SVMSCOPE_RECORD_DIR Directory for the record store (per-account logs of compressed diffs). Turns the recorder on.
SVMSCOPE_RECORD_SEEDS Extra comma-separated addresses to watch from the start. The bundled list in seeds/mainnet.txt (the accounts the busiest programs' transactions share, most-shared first, regenerated with cargo run --example seed_list) is watched by default up to SVMSCOPE_RECORD_MAX_SEEDS (default 400, 0 for none); each hot account costs about 1 MB a day of dense recording. Every account a replay had to rebuild is added automatically.
SVMSCOPE_RECORD_RPC_URL Node the recorder polls, default the public mainnet RPC (one getMultipleAccounts per 100 accounts per round; never a paid key).
SVMSCOPE_RECORD_INTERVAL_MS Polling interval, default 2000.
SVMSCOPE_RECORD_GITHUB + SVMSCOPE_GITHUB_TOKEN owner/repo and a token with releases write scope: the durable 30-day queue. On every hour boundary and on shutdown, the versions recorded since the previous push are uploaded as an asset of that UTC day's release; releases older than 30 days are deleted; the window is restored from the releases after a redeploy, so a redeploy loses nothing. Without it the window lives on local disk only.
SVMSCOPE_RECONSTRUCT_BUDGET Old transactions the free tier may re-execute per drifting account that no recording covers, default 0.
SVMSCOPE_REPLAY_WINDOW_DAYS How far back a replay at slot reaches, by block time (default 30, the recorder's retention). Older slots are refused with a plain message, so the product promises only what its own archive keeps, whatever a third-party stream still holds.
SUBSTREAMS_API_KEY One or more keys, comma-separated, from The Graph Market (free tier, no card; the two-stream limit is per account, so keys from different accounts add capacity and a key that hits the limit is skipped for five minutes): turns on the account-changes stream, which supplies any account's bytes at any slot in roughly the last three months for slots the recordings don't cover. The engine speaks to it natively over gRPC (the package is bundled; nothing to install) and bytes arrive as bytes, so there is no account size limit: a 1.7 MB order book is one message. Each version fetched is written into the record store, so it is fetched once. SVMSCOPE_HISTORY_LOOKBACK (5000) is the first search window and SVMSCOPE_HISTORY_DEEP_LOOKBACK (100000, about eleven hours) the furthest it looks back, in windows that widen fourfold and stop at the first hit (the three default windows take seconds; a 400,000-slot window took about 100 s in testing, so raising the depth trades replay time for accounts written more than half a day before the slot); an account the range misses is then looked for through its own mention history, one block per mention, a few steps at most; accounts of 64 KB or more start at a 16-slot window, since the stream sends every change in a range and a busy order book changes every slot. SVMSCOPE_SUBSTREAMS_PACKAGE names a local .spkg to use instead of the bundled one, SVMSCOPE_SUBSTREAMS_ENDPOINT another endpoint.

The window keeps every change for 24 hours and one version per 30 seconds for 30 days; with the account-changes stream attached, slots before the window are served from the stream on demand and cached into the window. Address lookup tables are rebuilt from the transaction's own record, so a table closed or extended since never blocks a replay. The fidelity certificate names the slot coverage begins at and labels every account: Recorded (a version observed before the slot with continuous coverage across it — polling rounds are at most MAX_COVERAGE_GAP (300) slots apart, so a change reverted between two rounds is the one thing coverage cannot see; a version taken from the account-changes stream carries exact bytes but no balance, and the balance is then only as good as the transaction's own record), MetadataRewind (balances from the transaction's own metadata), MetadataEstimate (a balance the transaction's own record only bounds, for a replay away from the landing slot: counted as drift), Unchanged (verified not written since the slot), Reconstructed (re-executed write history, exact or not), BlockPrefix (written by earlier transactions in the same block, which were replayed first, in order, on the block's opening state, so the bytes are what the transaction saw; exact is false, and it counts as drift, when one of those transactions' inputs had to come from today's data), SameBlock (the same situation when that replay was not possible: the chain of earlier transactions was longer than SVMSCOPE_PREFIX_MAX_TXS (160) or touched more than SVMSCOPE_PREFIX_MAX_ACCOUNTS (600) data accounts, none of them succeeded here, or the block itself could not be read (writes is then 0): counted as drift; a single predecessor that does not succeed here is skipped and only the accounts it would have written are marked inexact; the accounts those transactions write are searched SVMSCOPE_PREFIX_LOOKBACK (1024) slots back in the stream, the ones they only read SVMSCOPE_PREFIX_READ_LOOKBACK (256), with today's bytes beyond that), Absent (the transaction names it but it held nothing at the slot, with proven false, counted as drift, when that rests on it being empty today), Instruction and account names come from the IDL the program had at that slot, not the one it has today: a replay reaches for the version whose live range covers the target (the Solana Foundation's IDL history service, overridable with SVMSCOPE_IDL_HISTORY_URL, empty to disable), falling back to the current IDL when there is no history. Provenance labels are Program (the current ELF, with whether it was upgraded after the slot; a program upgraded since runs the bytecode deployed before the slot when the stream has it, and is then labelled Recorded at its deploy slot), HistoricalArchive, or CurrentRpc (current bytes, may differ: the only label the certificate counts as drift, along with SameBlock, an unproven Absent, an inexact reconstruction or an upgraded program).

Dependency watch

Your program calls programs you do not control. When one of them is upgraded, svmscope replays your recent transactions against the new binary and reports what changed: which transactions now fail, which errors are new, where the compute moved. The hosted engine shows it under Watch.

The on-chain half is programs/dependency_registry, an Anchor program on devnet at 4nH59dWUJ5rgTZJTybPbfGY1sgBDwKgrKMBXpRtdxhhg. A protocol registers its program, lists the programs it depends on, and gives a URL to alert. If the program is deployed on the registry's cluster the signer must hold its upgrade authority, proven through the program data account; a program that lives only on mainnet registers without proof, and the engine verifies the entry against its mainnet upgrade authority before it is ever checked or alerted. Entries are keyed by program and authority, so nobody can squat a program id, and an entry with no dependencies can be closed with unregister:

cd programs/dependency_registry && yarn install
ANCHOR_PROVIDER_URL=https://api.devnet.solana.com ANCHOR_WALLET=~/.config/solana/id.json \
  yarn ts-node scripts/register-devnet.ts <your program id> <alert url> <dependency id>...

The engine half is svmscope::dependency_watch. The server's watcher reads the registry, verifies each entry against the program's upgrade authority on the cluster it is checked on, keeps the current binary of every watched dependency, and when a deploy slot moves it replays each dependent protocol's most recent transactions (corpus_size of them, the number set at registration) twice on the same state, once with the held binary and once with the new one, so only the binary change shows. The report goes to the alert URL as JSON, signed by the engine's reporter key (x-svmscope-reporter, x-svmscope-signature over the body), and is kept at /dependency_reports/{id}. GET /dependency_check/{program}?dependency=… runs a check on demand.

Variable Meaning
SVMSCOPE_DEPWATCH 0 turns the watcher off.
SVMSCOPE_DEPWATCH_REGISTRY The registry program (default: the devnet one above).
SVMSCOPE_DEPWATCH_RPC The cluster the registry lives on (default: public devnet).
SVMSCOPE_DEPWATCH_CHECK_RPC Where checks run for programs that live there (default: SVMSCOPE_RPC_URL, else public mainnet). A protocol is checked on whichever of the two clusters its registered authority holds the program's upgrade authority, so a devnet registry can watch mainnet programs; an entry whose authority holds the program nowhere is shown as unverified and never alerted.
SVMSCOPE_DEPWATCH_INTERVAL_SECS Poll period (default 120).
SVMSCOPE_DEPWATCH_MAX_CORPUS Cap on transactions per check (default 50).
SVMSCOPE_REPORTER_KEYPAIR Keypair that signs alerts: a JSON array, a file path or base58. Without it alerts are unsigned.
SVMSCOPE_PUBLIC_URL This engine's public base URL, used for report links in alerts.

Anchor 1.0 starts Surfpool for anchor test; if it does not start on your machine, anchor test --validator legacy uses the Solana test validator.

Lift: composition in transaction construction, measured

A router such as Jupiter takes one instruction and calls the venues from inside its program. GET /lift/{signature} rebuilds a landed transaction with those inner calls as top-level instructions the client would send itself, runs the original and the rebuilt transaction on the state the original ran in, and reports: whether every token balance still moves the same, what the on-chain router cost in compute, whether the rebuilt transaction fits in a 1232-byte packet, and which inner calls cannot be lifted because only the router's program-derived address could sign them. A router's calls to itself (event emission) are dropped; token, associated token and system helpers are left in place unless named with ?router=. ?exact=true replays at the transaction's own slot, for swaps whose inputs have drifted since. The rebuilt transaction is returned unsigned as base64. From the library: Scope::lift(signature, router).

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/Replay library API — fetch once, replay forever
  • Mollusk-style Check DSL 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.

About

Transaction autopsy for Solana — decode any transaction, replay it locally in an embedded SVM, mutate state, time-travel, and freeze it into offline test fixtures

Topics

Resources

Contributing

Stars

8 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages