services
Get a key

library / AI and blockchain / General agent frameworks / SI0086

Recorded RPC fixtures for agent tests

A test that waits on the network times out when the network is slow. Record each real answer once, keyed by method and params, then replay the file offline so agent tests run the same way every time.

By Carbium · General agent frameworks · SI0086 · updated 2026-11-22

01

Why live calls make tests slow and flaky

An agent test that calls a live endpoint depends on three things the test does not control: how long the node takes to answer, what the chain holds at that moment, and how much rate budget the account has left. A suite with a timeout turns any one of them into a red run. Even a call that returns in time gives a different slot, balance and newest signature than the run before, so an assertion on those values breaks on the next run.

Transaction lookups hurt most. getTransaction costs 50 cells a call, against 1 cell for a cached read such as getSlot, and a suite that fetches a few hundred transactions per run spends them quickly. Past its plan's rate limits a call gets 429 with a retry-after hint, and a test reads that as a failure.

An agent adds its own multiplier. One model turn can call several tools, each tool is an RPC call, and the test waits for the sum. With a tight timeout the suite fails on the runs where the network is slow and passes on the others, which is the pattern that makes a team stop trusting its tests.

The way out is to take the network out of the test. For a given slot the chain gives one answer to a given question, so an answer recorded once is a fair stand-in for the call. The fixture is that answer, stored in a file next to the test.

02

Record mode

The wrapper sits at the transport, the innermost layer of the kit client, so every method passes through it and no method needs its own mock. recording takes the live transport, passes each call through and files the answer under a key built from the method and its params. The live transport is the only place that holds the x-api-key header. The wrapper sees the payload and the response, so the key has no path into the file, and the script still searches the text for the key before it writes.

The script runs four calls: getSlot, getAccountInfo on the USDC mint, getSignaturesForAddress for the newest signature of a busy program (Jupiter's router by default, or any program id as the first argument), and getTransaction on that signature. Each of the three checks settles on its own, so one failure prints its error and leaves the others intact. A failed signature lookup also fails the getTransaction line, since that line needs the signature.

main.ts
// SI0086 · Recorded RPC fixtures for agent tests// https://carbium.sh/library/si/recorded-rpc-fixtures-for-agent-tests// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.// SPDX-License-Identifier: MIT// Record RPC answers once, replay them with no network. Run: CARBIUM_KEY=... node main.ts [program]import { readFileSync, writeFileSync } from "node:fs";import { address, createDefaultRpcTransport, createSolanaRpcFromTransport, type RpcTransport } from "@solana/kit";const key = process.env.CARBIUM_KEY;if (!key) {  console.error("Set CARBIUM_KEY to your Carbium API key.");  process.exit(1);}const url = process.env.CARBIUM_RPC_URL ?? "https://services.carbium.sh";const FILE = "fixtures.json";type Store = Record<string, unknown>;type Req = Parameters<RpcTransport>[0];// kit returns large integers as bigint and JSON.stringify throws on them, so tag them.const dump = (v: unknown): string =>  JSON.stringify(v, (_k, x) => (typeof x === "bigint" ? { $bigint: x.toString() } : x));const load = (s: string): Store =>  JSON.parse(s, (_k, x) => (x && typeof x === "object" && "$bigint" in x ? BigInt(x.$bigint) : x));// The key is the method plus its params; the request id and every header stay out.const keyOf = (req: Req): string => {  const { method, params } = req.payload as { method: string; params?: unknown };  return `${method} ${dump(params)}`;};const recording = (live: RpcTransport, store: Store): RpcTransport =>  async <T>(req: Req): Promise<T> => {    const res = await live<T>(req);    store[keyOf(req)] = res;    return res;  };const replaying = (store: Store): RpcTransport =>  async <T>(req: Req): Promise<T> => {    const k = keyOf(req);    if (!(k in store)) throw new Error(`no fixture for ${k}`);    return store[k] as T;  };type Rpc = ReturnType<typeof createSolanaRpcFromTransport>;const USDC = address("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v");async function scenario(rpc: Rpc, program: string) {  const calls: Record<string, () => Promise<unknown>> = {    getSlot: () => rpc.getSlot().send(),    getAccountInfo: () => rpc.getAccountInfo(USDC, { encoding: "base64" }).send(),    getTransaction: async () => {      const [newest] = await rpc.getSignaturesForAddress(address(program), { limit: 1 }).send();      if (!newest) return null;      return rpc.getTransaction(newest.signature, { encoding: "json", maxSupportedTransactionVersion: 1 }).send();    },  };  const entries = Object.entries(calls);  const started = performance.now();  const settled = await Promise.allSettled(entries.map(([, call]) => call()));  const out = Object.fromEntries(    entries.map(([name], i) => {      const s = settled[i]!;      return [name, s.status === "fulfilled" ? dump(s.value) : `failed: ${s.reason}`];    }),  ) as Record<string, string>;  return { ms: performance.now() - started, out };}if (import.meta.main) {  const program = process.argv[2] ?? "JUP6LkbZbjS1jKKwapdHNy74zcZ3tLUZoi5QNyVTaV4";  const store: Store = {};  const live = createDefaultRpcTransport({ url, headers: { "x-api-key": key } });  const first = await scenario(createSolanaRpcFromTransport(recording(live, store)), program);  const text = dump(store);  if (text.includes(key)) throw new Error("the key is in the fixtures");  writeFileSync(FILE, text);  const second = await scenario(createSolanaRpcFromTransport(replaying(load(readFileSync(FILE, "utf8")))), program);  for (const [name, recorded] of Object.entries(first.out)) {    const same = recorded === second.out[name];    if (!same) process.exitCode = 1;    console.log(`${name}: ${recorded.startsWith("failed") ? recorded : same ? "replay equals recording" : "MISMATCH"}`);  }  console.log(`recorded ${first.ms.toFixed(0)} ms, replay ${second.ms.toFixed(1)} ms, ${Object.keys(store).length} fixtures`);}

run: node main.ts

getTransaction passes maxSupportedTransactionVersion: 1, so a version 1 transaction comes back as data; leave the option out and the call answers -32015 for a v1 transaction, which Transaction version error -32015 explains. The answer can still be null. Signatures listed from the 30-day address index can reach below the validator's ledger floor, and the script files that null and replays it like any other answer. The newest signature of a busy program almost never hits it.

Run it in an empty directory: it writes fixtures.json to a relative path, replays from the file it just wrote, and prints one line per check, three in all, with the signature lookup and getTransaction on one line. Then it prints the recorded and replay milliseconds and the count of stored answers, four when every call succeeded.

03

Replay mode with no network

replaying takes the stored object and no live transport. It cannot reach the network because it holds nothing that could. A call with no matching fixture throws no fixture for followed by the method and params, which names the missing answer exactly. The error is the point: a replay that quietly fell back to the live endpoint would bring the slow, flaky suite straight back.

In a real test file, load fixtures.json once at the top, wrap it with replaying, build the client with createSolanaRpcFromTransport and hand that client to the agent's tools. The tools run the same code as in production, including kit's request and response transformers, so the test covers the parsing as well as your own logic.

With the answer frozen the test can assert exact values: the lamports of the mint, the number of instructions in the transaction, the fee. The account answer carries context.slot, so the test can also say which slot it is looking at. A kit call that leaves commitment out is sent at confirmed, and that value is part of the stored params.

The closing line prints recorded and replay times side by side. Read them as a check that replay touched no network: a replay time close to the recorded one would mean a call still goes out. They say nothing about how fast the endpoint answers, because one run of four calls is not a measurement.

04

Keying and bigint-safe storage

The key is the method followed by the params as JSON. Everything else in the request is left out on purpose.

Part of the requestIn the keyReason
methodyestwo methods never share an answer
params, with the commitment kit filled inyesa different address, option or commitment is a different question
request idnoit differs from run to run, so a key containing it would never match
x-api-key headernever storedit lives on the live transport and never reaches the wrapper

Large integers are the second trap. Kit returns values such as lamports and slots as bigint, and JSON.stringify throws Do not know how to serialize a BigInt on the first one. The dump function passes a replacer that writes each bigint as {"$bigint": "123"}, and load passes a reviver that turns the tag back into a BigInt. The same tagging covers a bigint inside params, such as a minContextSlot.

Because the key is JSON text, option order matters. A test that calls getAccountInfo with { encoding, commitment } in one order after recording in the other order misses the fixture. Keep the call in one helper that both the record script and the tests use.

05

Refreshing stale fixtures

A fixture is a snapshot, and it ages. Refresh it on purpose: delete fixtures.json, run the record script on its own, read the diff in git and commit the new file. Keep recording out of the test run. A suite that records whenever a fixture is missing hides the miss and goes back to waiting on the network.

The newest signature of a busy program changes every second, so each recording picks a different transaction. Tests should read the signature from the fixture, from the stored getSignaturesForAddress answer, and never hard-code one from an earlier recording.

For a transaction you want to keep as a permanent case, commit its file and leave it. A signature that has since aged out of the 30-day address index may come back null from a new recording, so the committed file can be the only copy of that answer.

06

Where it ends

  • A fixture holds the answers the chain gave. It cannot produce a 429, a slow reply or a dropped connection. Test timeout handling with a second transport that delays or never resolves.
  • Replay suits reads. An answer recorded for a sent transaction is true once, so keep sends out of the file.
  • The wrapper covers HTTP calls only. A WebSocket subscription needs its own list of recorded messages.
  • A recorded balance is the balance at that slot. A test that must see current state needs a live call, kept to a few and run outside the main suite.
  • Answers for large accounts or blocks make a large file. Record the few accounts the test needs.
07

When it goes wrong

what goes wrongwhat to do
JSON.stringify throws Do not know how to serialize a BigInt while saving the fixtures.Write bigint values as a tagged object with a replacer and rebuild them with a reviver on load, as dump and load do.
Replay throws no fixture for after a small code change.The key contains the params, so an added option or a different option order is a new question. Keep one helper for each call, and re-record after changing it.
The fixture file holds the key or a header.Wrap the transport and store only the method, params and response. Put the key on the live transport and search the text for it before writing.
A test hard-codes a signature and fails after the fixtures are refreshed.Read the signature from the recorded getSignaturesForAddress answer, so the test follows the file.
The recorded getTransaction answer is null and the test crashes on .transaction.Handle null in the code under test and keep one fixture that exercises that branch.
The suite is still slow after the switch to replay.Some call still goes through the live transport. Build every client in the tests from replaying, which holds no network client.
08

Questions

Why record at the transport and not mock getTransaction?

One wrapper covers every method, and kit's request and response transformers run as they do in production. A mocked method skips that parsing, so a test can pass while the real path breaks.

Is it safe to commit fixtures.json?

Yes, it holds public chain data plus method and params, and the key never reaches it. Read the diff before committing, because a recorded account or transaction can be large.

Does the recording run count against my limits?

Yes. It makes four calls: getSlot costs 1 cell, getAccountInfo 10, and getSignaturesForAddress and getTransaction 50 each. Replay costs nothing.

How do I test code that handles a timeout?

Write a transport that waits on the abort signal or never resolves and pass it to the same client. A recording only holds answers that arrived.