Expand description
Wire types for the Termina simulator’s backtest API.
This crate defines the JSON the server and its clients exchange: requests and responses on the session control channel, payloads on the session’s RPC endpoint, and the bodies of the HTTP endpoints. It does no I/O.
Most users want simulator-client instead. It sends these
types for you, reconnects and reattaches, and re-exports this crate as
simulator_client::simulator_api, so the versions always match. Depend on simulator-api
directly only to speak the protocol over your own transport.
§Message envelope
Every message on the session control channel (wss://<host>/backtest) is a JSON object with a
method and, when the variant carries data, params:
{"method": "continue", "params": {"advanceCount": 10}}
{"method": "readyForContinue"}- Requests are
BacktestRequestand responses areBacktestResponse. Themethodis the variant name in camelCase. - Unless
disconnectTimeoutSecsis 0, a single session wraps what the running session streams in aSequencedResponse(unset counts: it defaults to 30), which adds a top-level sequence number,seqId:{"seqId": 7, "method": "slotNotification", "params": 1234}. Keep the last one you received: you need it to reattach. - Startup
statusupdates,sessionCreated,sessionAttached,successand errors sent before the session runs carry noseqId. Parse aSequencedResponsefirst and fall back to a bareBacktestResponse. - Parallel sessions report through
sessionEventV2(BacktestResponse::SessionEventV2), which carries its own per-sessionseq_id.
§Session endpoints
- Send
createBacktestSessionV2(BacktestRequest::CreateBacktestSessionV2) to the server and skip thestatusframes. - The reply is
sessionGranted, orsessionsGrantedwhenparallelis set. EachSessionGrantholds the session’s endpoint and a token. Stop reading: the close frame after the grant is normal. Never sendcloseBacktestSessionto the server. A close with code 1012 before the reply means the server is draining and started no session: send the create again, to the same URL, after a backoff. - Open
SessionGrant::control_urlwith the token in thex-tokenheader. Within 30 seconds, sendattachBacktestSessionwith nolast_sequence. The answer issessionAttached. - Continue as in lifecycle steps 3 to 5 below:
continue, the streamed responses, andcloseBacktestSession.resumeAttachedSessionis not needed. - The session’s RPC endpoint is
SessionGrant::rpc_urlwith the token in a header, orSessionGrant::rpc_url_with_token. - An HTTP 401 from the session is final: the token is wrong.
The lifecycle below starts with createBacktestSession; use it without session endpoints.
§Session lifecycle
- Send
createBacktestSessionwithCreateSessionParams, or withCreateBacktestSessionRequestV1to name the session or split the range across parallel sessions. While the session starts, the server sendsstatusupdates. - The server replies
sessionCreatedwith thesession_idand the session’s RPC endpoint (rpc_endpoint, a path on the server’s host:/backtest/<session_id>), thenreadyForContinue. - Send
continue(ContinueParams) to execute the nextadvanceCountblocks, with any user transactions and account overrides, orcontinueTo(ContinueToParams) to pause at a slot or before a batch. The server streamsstatus,slotNotification,pausedanddiscoveryBatch, then sendsreadyForContinueagain. Answer onlyreadyForContinue: acontinueTogetspausedfirst, and answering both sends two continues. - Between steps, read and change state through the session’s RPC endpoint.
- After the last slot the server sends
completed, with aSessionSummarywhensendSummarywas set. SendcloseBacktestSessionto end the session; the server repliessuccess.
An error response carries a BacktestError. BacktestError::is_terminal tells you
whether the session is over, and BacktestError::is_retryable whether sending the request
again later can succeed.
A parallel create sends sessionCreated for each session, then sessionsCreatedV2 with a
control_session_id and one session_ids entry per session. Drive each session with
continueSessionV1, continueToSessionV1 and closeSessionV1, which name it by sessionId.
closeSessionV1 ends one session and sends no reply. closeBacktestSession ends the whole
parallel run and closes the connection without a reply.
Reattach. When the connection drops, the session waits disconnectTimeoutSecs for you to
come back: 30 seconds when unset (900 for a parallel run), at most
MAX_DISCONNECT_TIMEOUT_SECS. With 0, the session ends with the connection. To reattach:
- Open a new session control channel.
- Send
attachBacktestSessionwith thesession_idand the last sequence number you received aslast_sequence. A parallel run sendsattachParallelControlSessionV2with itscontrol_session_idandlast_sequences, one per session. - The server replies
sessionAttached(orparallelSessionAttachedV2) and replays every response after those sequence numbers. - For a single session, rebuild your subscriptions, then send
resumeAttachedSession; the server repliessuccess. A parallel run needs no resume.
§Wire casing
Casing depends on where a field sits. These names are the contract and do not change.
| Where | Casing | Examples |
|---|---|---|
method names and enum values on the session control channel | camelCase | createBacktestSession, readyForContinue, startingRuntime |
Fields declared on a BacktestRequest or BacktestResponse variant | snake_case | session_id, last_sequence, rpc_endpoint, control_session_id, last_sequences, seq_id (in sessionEventV2) |
Fields of a params struct, such as CreateSessionParams, ContinueParams or ScheduledAction | camelCase | startSlot, disconnectTimeoutSecs, advanceCount, modifyAccountStates, sessionId (in continueSessionV1) |
The SequencedResponse wrapper | camelCase | seqId |
BacktestError | camelCase variant name, snake_case fields | {"bundleNotFound": {"start_slot": 1, "end_slot": 2}} |
| HTTP request and response bodies and query parameters | snake_case, enum values too | start_slot, bundle_size, request_id, "in_progress" |
So sessionCreated arrives as:
{"method": "sessionCreated", "params": {"session_id": "backtest_…", "rpc_endpoint": "…"}}§Encoded fields
| Field | Encoding |
|---|---|
CreateSessionParams::actions, ScheduledAction::transactions, and slots in a beforeSlot or afterSlot ActionAnchor | One string: base64 (standard, padded) of the zstd-compressed JSON of the whole list. Each list decompresses to at most 256 MiB. actions nests: each action in it keeps its own encoded transactions and slots. |
Each transaction in ScheduledAction::transactions and ContinueParams::transactions | base64 of the transaction’s standard wire bytes, the bytes sendTransaction takes, for a legacy, v0 or v1 transaction. Build it with simulator_client::encode_transaction. wincode writes these bytes; bincode does not: it drops a v1 transaction’s version marker. |
AccountData::data | EncodedBinary of the raw account bytes: {"data": "<base64>", "encoding": "base64"} |
DiscoveryBatchEvent::transactions | EncodedBinary of a wincode-serialized VersionedTransaction. Decode with simulator_client::decode_transaction. |
ProgramOverride::elf | base64 of the program binary |
| Addresses, mints and program IDs | base58 strings |
AccountModifications | A JSON object keyed by base58 address |
SessionId and ControlSessionId | backtest_<uuid> and parallel_<uuid> |
§Modules
| Module | Contents |
|---|---|
| crate root | Requests, responses, session parameters, scheduled actions, account overrides, errors and HTTP bodies |
venue | Venue templates for rerouting directly to a venue |
replacement | replacementSubscribe notifications |
route_plan | Routes hop by hop, as the router quotes them and as transactions report them |
reroute_report | Reports built from reroute results |
mints | The stablecoins and major mints the reroute reports price against |
token | The SPL token-account layout, for building token account overrides |
subscribe_config | Options a subscription adds to its config object |
session_name | Session name rules |
usage | GET /usage bodies |
geyser_route | How a gRPC client names its session |
§Compatibility
- If you depend on both crates, use the
simulator-apiversion yoursimulator-clientdepends on, or reach this crate throughsimulator_client::simulator_api. - A new field is added with a default, so a message without it still parses. Unknown fields are ignored.
- An incompatible change to a message ships as a new versioned variant or type next to the old
one, such as
CreateBacktestSessionRequestV1orsessionsCreatedV2. - An unknown
methodor enum value is a parse error. A client older than the server can fail on a new response or status, so keep the client up to date. - Before 1.0, a minor release can break the Rust API. The changelog lists every break.
Re-exports§
pub use reroute_report::SwapMode;pub use venue::AMOUNT_WIDTH;pub use venue::DerivedAccount;pub use venue::ParseVenueTemplateError;pub use venue::Seed;pub use venue::TakerSlots;pub use venue::TemplateAccount;pub use venue::TemplateInstruction;pub use venue::TemplateResolver;pub use venue::VenueTemplate;
Modules§
- geyser_
route - How a gRPC caller names the session it wants.
- mints
- The major-mint universe shared by the reroute reports: tables of stables and priced majors, plus the helpers that classify, price, and label mints against them.
- replacement
- Notifications from
replacementSubscribe: one reroute result per original swap. Nothing stands in for the original; theoriginalkind is the original itself. - reroute_
report - Reports over a set of reroute results, from any source.
- route_
plan - One route, hop by hop: what the router quotes, what a decoded transaction reports, and what both are recorded and streamed as. Only the router names a pool; only a transaction’s route events name the program that ran a hop.
- session_
endpoint - The one mapping between a session id and the DNS name of its endpoint.
- session_
name - Session names, and the token that reclaims a name after a reconnect.
- subscribe_
config - Cross-cutting subscribe options shared by the client and server.
- token
- The SPL token-account layout shared by Token and Token-2022: build one, read its balance and mint, or re-balance an existing one.
- usage
- Usage and billing for an API key: the bodies of
GET /usageandGET /usage/sessions. - venue
- Caller-supplied venue templates: one instruction the server rewrites per probe.
Structs§
- Account
Data - An account’s full state, used as an account override.
- Account
Modifications - Account state modifications to apply.
- Action
Resolve Error - A
TxResolverErrorand the action it is in. - Address
- Solana account address used throughout this API; re-exported so callers need not pin a
matching
solana-addressversion. The address of a Solana account. - Array
KeyIndices - One or more distinct indices into a transaction’s static account keys. On the wire, a JSON
array of numbers; build one with
ArrayKeyIndices::try_from(vec![3, 4]). - Available
Range - One contiguous range of slots you can replay: an entry of
GET /available-ranges. - Batch
Position - A batch of a block, by its slot and its place among the block’s batches.
- Bundle
Build List Response - Response of
GET /build-bundle. - Bundle
Build Request - Request body of
POST /build-bundle. - Bundle
Build Status Response - Response of the server’s bundle-build endpoints.
- Bundle
Delete Request - Query of
DELETE /bundles: the bundle to delete, by kind and exact range. - Bundle
Delete Response - What
DELETE /bundlesremoved. - Close
Session Request V1 - The
paramsofcloseSessionV1. - Completed
Bundle - A bundle the caller owns and can use now. Ordered by slot range, then kind.
- Continue
Params - The
paramsofcontinue: execute the next blocks, after your own transactions and account overrides. Every field has a default, so{}advances one block. - Continue
Session Request V1 - The
paramsofcontinueSessionV1. - Continue
ToParams - The
paramsofcontinueTo: execute up to a point, then pause there. - Continue
ToSession Request V1 - The
paramsofcontinueToSessionV1. - Control
Session Id - Identifies the control session grouping the sessions of a parallel run.
- Create
Backtest Session Request V1 - The
paramsofcreateBacktestSessionwhen you name the session or split it into parallel sessions. TheCreateSessionParamsfields sit at the same level as these. - Create
Session Params - Parameters required to start a new session: the
paramsofcreateBacktestSession, or therequestof aCreateBacktestSessionRequestV1. Fields are camelCase on the wire. - Create
Session Params Builder - Use builder syntax to set the inputs and finish with
build(). - Dataset
Credentials Response - Response of
POST /datasets/credentials: temporary, read-only credentials plus a path, so a caller doesn’t need to reconstruct the S3 layout. - Dataset
Date - One UTC date.
- Dataset
Delete Request - Query of
DELETE /datasets. - Dataset
Delete Response - Anything reaching past either end of the range stays.
- Dataset
File - One file of a files dataset.
- Dataset
JobList Response - The caller’s jobs, as
GET /dataset-jobsanswers. - Dataset
JobRequest - Request body of
POST /dataset-jobs. Resubmitting it answers with the same job, re-running it if it failed or was cancelled. - Dataset
JobStatus Response - A job’s request, resolved range, phase and outputs, as
GET /dataset-jobs/{job_id}answers. - Dataset
List Query - With neither field, every one of the caller’s own datasets.
- Dataset
List Response - Response of
GET /datasets. - Dataset
Location - A dataset under the
user_s3_urithatPOST /datasets/credentialsreturns, at<name>/v<version>/. - Dataset
Partition - The parts under one value of the dataset’s partition key.
- Dataset
Parts - A count and extent of parquet parts.
- Dataset
Summary - One dataset in one scope.
- Dataset
Version - One version of a partitioned dataset.
- Depth
Selection - What a depth job measures over its slot range.
- Depth
Source Universe - What one
DepthSourcesamples. - Depth
Universe Response - What a depth job samples, per source.
- Diagnostic
Candidate - A pool the router may not hold, probed for
DiagnosticProbeParams::candidate_pairs. - Diagnostic
Market Pairs - The mint pairs one probed market is answered for.
- Diagnostic
Probe Params - Probe markets through the router’s
/diagnosticendpoint as the session runs, and stream the results overdiagnosticSubscribe. - Discovery
Batch Event - Payload emitted when the session has discovered an upcoming batch that
matches one or more registered
DiscoveryFilters from session creation (for example, a batch containing a transaction that invokes a program of interest). The(slot, batch_index)pair can be fed directly toBacktestRequest::ContinueToto pause immediately before the batch executes. After eachContinue/ContinueTo, the session emits the nextDiscoveryBatchEventahead of the next matching batch, enabling a reactive “pause on every discovery” driver loop. - Empty
Accounts - A
NonEmptyAccountsbuilt from no accounts. - Encoded
Binary - A blob paired with the encoding needed to decode it.
- Held
Slots - A slot range held by a job’s check.
- Inverted
Slot Range - Why a pair of bounds isn’t a valid range.
- Mint
Pair - The two mints a swap trades, without a direction: a maker quotes a pair both ways, so
(a, b)and(b, a)are the same pair. Normalized on construction and on deserialization, which is what makes the set lookup direction-agnostic. On the wire, an array of two base58 mints. - NoSlot
Windows - Slot windows were built from no range.
- NonEmpty
Accounts - Deserializes from a non-empty list of base58 addresses.
- Parse
Mint Pair Error - A
MintPairmint that is not a valid base58 address. - Paused
Event - Payload emitted when a session halts at a caller-specified point.
batch_indexisNonefor block-boundary pauses andSome(n)when the session stopped before batchnwithinslot(no transaction from batchnhas been applied). While paused, RPC reads against the session observe partial state up through batchn - 1. AreadyForContinuealways follows: answer that, not this. - Program
Override - A program the probes run in place of the deployed one:
program_idnames a deployed upgradeable (loader-v3) program, whose code becomeself. - Progress
- A count of finished units out of the total.
- Reroute
Aggregators - The aggregators a session reroutes. Jupiter alone by default: the router builds Jupiter replacements,
so other aggregators’ order flow is a cross-router counterfactual a session asks for
deliberately. On the wire, an array such as
["jupiter", "okx"]. Also parsed from one comma-separated string ("jupiter,okx") so a flag or an env var carries the set. - Reroute
Filter - Restricts which detected swaps are rerouted. A transaction is rerouted when at least one
of its swaps trades a listed pair; the rest replay unchanged, counted as
swaps_filtered. A filter with no pairs is rejected: omit the filter to reroute every pair. - Reroute
Params - Rerouting historical swaps through the router: each admitted swap is rerouted and the routed transaction is simulated just before the original executes — never committed, so the replay is unaffected. Each simulation reads the state of the batch its original belonged to; reroutes never observe one another.
- Reroute
Scopes - Which swaps a session reroutes, by where they ran. Top-level router instructions alone by default. Parsed from one comma-separated string so a flag or an env var carries the set.
- Reroute
Stats Report - Summary of a session run with
reroute_order_flow: how many detected swaps made it from rerouting through simulation to a non-reverting execution, and — for a session carrying aVenueTemplatelist — how many hops each template priced. Per-swap economics and latency land in the reroute tables, published todataset_uriwhen set. - Scheduled
Action - A sequence of transactions the server runs automatically during a backtest,
with results streamed over the
actionSubscribesubscription. - Sequenced
Response - Wire format wrapper for responses sent over the session control channel.
Sessions whose
disconnect_timeout_secsis not 0 (unset defaults to 30) use this to track client position. - Session
Id - Identifies one session.
- Session
Summary - Summary of transaction execution statistics for a completed session: how the replayed
transactions compare with what happened onchain. Sent with
completedwhen the session was created withsend_summary. Fields are camelCase on the wire (correctSimulation). - Slot
Range - An inclusive
[start, end]slot range. Construct viaSlotRange::new, which rejects an inverted range, orSlotRange::new_uncheckedwhere the ordering is already guaranteed by the caller. - Slot
Windows - The slots an action may fire at: one
SlotRangeobject or a list of them. - Snapshot
Slot Response - Response of the server’s
/snapshot-slotendpoint. The chosen source and import state are internal, so only the resolved slot is exposed. - Unmeasured
Depth - A source asked for at a granularity it cannot be measured at.
- Venue
Template Report - One template’s share of the venue probes; the flat
venue_*counters onRerouteStatsReportare the sums of these.
Enums§
- Action
Anchor - Where a
ScheduledActionfires. - Action
Kind - How an action’s transactions run. Only meaningful for an action that carries
transactions: one that carries none is a schedule entry for
account_overrides. - Array
KeyIndices Error - Why a list is not valid
ArrayKeyIndices. - Backtest
Error - Error variants surfaced to backtest RPC clients: the
paramsof anerrorresponse. - Backtest
Request - A request you send on the session control channel.
- Backtest
Response - A response the server sends on the session control channel.
- Backtest
Status - Progress reported in a
statusresponse, as a camelCase string such as"startingRuntime". Informational: you need not act on any of them. - Binary
Encoding - Supported binary encodings for account/transaction payloads.
- Bundle
Build Status - Where a bundle build or depth job is. snake_case on the wire:
"in_progress". - Bundle
Kind - What a bundle build produces.
- Create
Backtest Session Request - The
paramsofcreateBacktestSession, in either version. Untagged: the server tells them apart by shape. - Dataset
Contents - What a dataset holds, by how it is laid out.
- Dataset
JobPhase - Where a job is, tagged by
phaseon the wire. - Dataset
JobSpec - The dataset a job builds, tagged by
kindon the wire. - Dataset
Scope - Whose copy of a dataset a listing shows.
- Depth
Granularity - How often a depth job samples its source; each publishes its own dataset under the source.
- Depth
Kind - A depth dataset: a source at a granularity it can be measured at.
- Depth
Source - Which side of a venue a depth job measures.
- Diagnostic
Probe Error - Why a
DiagnosticProbeParamsis rejected at session creation. - Discovery
Filter - A filter registered at session creation describing which upcoming batches
the session should announce ahead of execution via
BacktestResponse::DiscoveryBatch(and its session-event twins). Each filter describes an event of interest (e.g. a specific program executing); the session “discovers” the batch in which that event will occur and emits aDiscoveryBatchso the client can pause immediately before it. - Fail
Fast Divergence Kind - What counts as a “non-benign” divergence for the session fail-fast behaviour.
- Invalid
Slot Windows - Why a set of ranges from the wire isn’t valid slot windows.
- Parse
Address Error - Why a string is not a valid
Address; carried by this API’s parse errors. - Parse
Aggregator Error - Why a string is not a
SwapAggregatoror aRerouteAggregatorslist. - Parse
Scope Error - Why a string is not a
SwapScopeor aRerouteScopeslist. - Predict
Table - A predict table a dataset job produces.
- Range
Scope - Who a listed range is available to.
- Session
Event Kind - What happened in one session of a parallel run: the
eventofsessionEventV2. Each variant means what theBacktestResponsevariant of the same name means, for that session alone. - Session
Type - How a session is being used, derived from its creation params.
- Swap
Aggregator - A router whose historical swaps a session can reroute. Lowercase on the wire; parsing ignores case and surrounding spaces.
- Swap
Scope - Where a rerouted swap ran in its transaction.
- TxResolver
- How a
ScheduledActionrewrites its transactions from live state each time it fires. Only valid forkind: simulateand withoutfeeds_reroute. - TxResolver
Error - Why a
ScheduledAction::resolvedoes not fit its action.
Constants§
- MAX_
ACCOUNT_ OVERRIDES - Server-side ceiling on
DepthSelection::account_overrides. - MAX_
ACCOUNT_ OVERRIDE_ BYTES - Ceiling on a request’s decoded account data together. The set repeats on every probe action inside one CreateSession message.
- MAX_
DIAGNOSTIC_ MARKETS - Most pools,
marketsandcandidatestogether, oneDiagnosticProbeParamscan name. - MAX_
DIAGNOSTIC_ MARKET_ PAIRS - Most pairs one
DiagnosticMarketPairscan name. - MAX_
DIAGNOSTIC_ USD_ VALUES - Most
usdValuesoneDiagnosticProbeParamscan name. - MAX_
DISCONNECT_ TIMEOUT_ SECS - Server-side ceiling on
CreateSessionParams::disconnect_timeout_secs: 900 seconds (15 minutes). A larger request is silently clamped to this, so clients must keep their reconnect budget under it to survive a detach. - MAX_
PROGRAM_ OVERRIDES - Server-side ceiling on
DepthSelection::program_overrides. - MAX_
RPC_ REQUEST_ BODY_ BYTES - Ceiling on a session JSON-RPC request’s body; fits
MAX_TOTAL_ELF_BYTESbase64-encoded. - MAX_
TOTAL_ ELF_ BYTES - Ceiling on a request’s ELFs together.
- MODIFIED_
PREFIX - The directory under which datasets measured under modifications publish.
- REPLAY_
RANGE_ ADVICE - Why a replayed range has to begin where a recording does. Shared so the splitter’s refusal and the service’s single-session refusal cannot drift apart.
- REROUTE_
DATASET_ RETENTION_ DAYS - How long a session’s published reroute tables stay in its owner’s datasets.
- RESOLVE_
FAILURE_ PREFIX - Opens a transaction outcome’s
errwhen the action’sTxResolverfailed, so nothing was simulated; the outcome’sunresolvedflag is what marks one.
Functions§
- depth_
dataset_ prefix - The key prefix a depth job’s dataset publishes under, e.g.
depth/onchain/slot. - modified_
dataset_ root - Where
datasetmeasured under the modifications withdigestpublishes: undermodified/, never indatasetitself. - split_
range - Split a user-requested
[start_slot, end_slot]range across the available bundle ranges, returning a list of contiguous, non-overlapping(start, end)pairs — one per bundle that the server can serve as its own session. - split_
range_ fewest split_range, choosing the gap-free split with the fewest sub-ranges instead of the most. Anchors, validates and errors exactly like it: an uncovered range names the first slot no bundle reaches.- validate_
resolvers - Checks each action’s
ScheduledAction::resolveagainst the rest of the action, as the server does when the session starts.