Skip to main content

Crate simulator_api

Crate simulator_api 

Source
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 BacktestRequest and responses are BacktestResponse. The method is the variant name in camelCase.
  • Unless disconnectTimeoutSecs is 0, a single session wraps what the running session streams in a SequencedResponse (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 status updates, sessionCreated, sessionAttached, success and errors sent before the session runs carry no seqId. Parse a SequencedResponse first and fall back to a bare BacktestResponse.
  • Parallel sessions report through sessionEventV2 (BacktestResponse::SessionEventV2), which carries its own per-session seq_id.

§Session endpoints

  1. Send createBacktestSessionV2 (BacktestRequest::CreateBacktestSessionV2) to the server and skip the status frames.
  2. The reply is sessionGranted, or sessionsGranted when parallel is set. Each SessionGrant holds the session’s endpoint and a token. Stop reading: the close frame after the grant is normal. Never send closeBacktestSession to 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.
  3. Open SessionGrant::control_url with the token in the x-token header. Within 30 seconds, send attachBacktestSession with no last_sequence. The answer is sessionAttached.
  4. Continue as in lifecycle steps 3 to 5 below: continue, the streamed responses, and closeBacktestSession. resumeAttachedSession is not needed.
  5. The session’s RPC endpoint is SessionGrant::rpc_url with the token in a header, or SessionGrant::rpc_url_with_token.
  6. 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

  1. Send createBacktestSession with CreateSessionParams, or with CreateBacktestSessionRequestV1 to name the session or split the range across parallel sessions. While the session starts, the server sends status updates.
  2. The server replies sessionCreated with the session_id and the session’s RPC endpoint (rpc_endpoint, a path on the server’s host: /backtest/<session_id>), then readyForContinue.
  3. Send continue (ContinueParams) to execute the next advanceCount blocks, with any user transactions and account overrides, or continueTo (ContinueToParams) to pause at a slot or before a batch. The server streams status, slotNotification, paused and discoveryBatch, then sends readyForContinue again. Answer only readyForContinue: a continueTo gets paused first, and answering both sends two continues.
  4. Between steps, read and change state through the session’s RPC endpoint.
  5. After the last slot the server sends completed, with a SessionSummary when sendSummary was set. Send closeBacktestSession to end the session; the server replies success.

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:

  1. Open a new session control channel.
  2. Send attachBacktestSession with the session_id and the last sequence number you received as last_sequence. A parallel run sends attachParallelControlSessionV2 with its control_session_id and last_sequences, one per session.
  3. The server replies sessionAttached (or parallelSessionAttachedV2) and replays every response after those sequence numbers.
  4. For a single session, rebuild your subscriptions, then send resumeAttachedSession; the server replies success. A parallel run needs no resume.

§Wire casing

Casing depends on where a field sits. These names are the contract and do not change.

WhereCasingExamples
method names and enum values on the session control channelcamelCasecreateBacktestSession, readyForContinue, startingRuntime
Fields declared on a BacktestRequest or BacktestResponse variantsnake_casesession_id, last_sequence, rpc_endpoint, control_session_id, last_sequences, seq_id (in sessionEventV2)
Fields of a params struct, such as CreateSessionParams, ContinueParams or ScheduledActioncamelCasestartSlot, disconnectTimeoutSecs, advanceCount, modifyAccountStates, sessionId (in continueSessionV1)
The SequencedResponse wrappercamelCaseseqId
BacktestErrorcamelCase variant name, snake_case fields{"bundleNotFound": {"start_slot": 1, "end_slot": 2}}
HTTP request and response bodies and query parameterssnake_case, enum values toostart_slot, bundle_size, request_id, "in_progress"

So sessionCreated arrives as:

{"method": "sessionCreated", "params": {"session_id": "backtest_…", "rpc_endpoint": "…"}}

§Encoded fields

FieldEncoding
CreateSessionParams::actions, ScheduledAction::transactions, and slots in a beforeSlot or afterSlot ActionAnchorOne 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::transactionsbase64 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::dataEncodedBinary of the raw account bytes: {"data": "<base64>", "encoding": "base64"}
DiscoveryBatchEvent::transactionsEncodedBinary of a wincode-serialized VersionedTransaction. Decode with simulator_client::decode_transaction.
ProgramOverride::elfbase64 of the program binary
Addresses, mints and program IDsbase58 strings
AccountModificationsA JSON object keyed by base58 address
SessionId and ControlSessionIdbacktest_<uuid> and parallel_<uuid>

§Modules

ModuleContents
crate rootRequests, responses, session parameters, scheduled actions, account overrides, errors and HTTP bodies
venueVenue templates for rerouting directly to a venue
replacementreplacementSubscribe notifications
route_planRoutes hop by hop, as the router quotes them and as transactions report them
reroute_reportReports built from reroute results
mintsThe stablecoins and major mints the reroute reports price against
tokenThe SPL token-account layout, for building token account overrides
subscribe_configOptions a subscription adds to its config object
session_nameSession name rules
usageGET /usage bodies
geyser_routeHow a gRPC client names its session

§Compatibility

  • If you depend on both crates, use the simulator-api version your simulator-client depends on, or reach this crate through simulator_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 CreateBacktestSessionRequestV1 or sessionsCreatedV2.
  • An unknown method or 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::FrameField;
pub use venue::FramePatch;
pub use venue::FrameRead;
pub use venue::ParseVenueTemplateError;
pub use venue::Seed;
pub use venue::TakerSlots;
pub use venue::TemplateAccount;
pub use venue::TemplateFrame;
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; the original kind 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 /usage and GET /usage/sessions.
venue
Caller-supplied venue templates: one instruction the server rewrites per probe.

Structs§

AccountData
An account’s full state, used as an account override.
AccountModifications
Account state modifications to apply.
ActionResolveError
A TxResolverError and the action it is in.
Address
Solana account address used throughout this API; re-exported so callers need not pin a matching solana-address version. The address of a Solana account.
ArrayKeyIndices
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]).
AvailableRange
One contiguous range of slots you can replay: an entry of GET /available-ranges.
BatchPosition
A batch of a block, by its slot and its place among the block’s batches.
BundleBuildListResponse
Response of GET /build-bundle.
BundleBuildRequest
Request body of POST /build-bundle.
BundleBuildStatusResponse
Response of the server’s bundle-build endpoints.
BundleDeleteRequest
Query of DELETE /bundles: the bundle to delete, by kind and exact range.
BundleDeleteResponse
What DELETE /bundles removed.
CloseSessionRequestV1
The params of closeSessionV1.
CompletedBundle
A bundle the caller owns and can use now. Ordered by slot range, then kind.
ContinueParams
The params of continue: execute the next blocks, after your own transactions and account overrides. Every field has a default, so {} advances one block.
ContinueSessionRequestV1
The params of continueSessionV1.
ContinueToParams
The params of continueTo: execute up to a point, then pause there.
ContinueToSessionRequestV1
The params of continueToSessionV1.
ControlSessionId
Identifies the control session grouping the sessions of a parallel run.
CreateBacktestSessionRequestV1
The params of createBacktestSession when you name the session or split it into parallel sessions. The CreateSessionParams fields sit at the same level as these.
CreateSessionParams
Parameters required to start a new session: the params of createBacktestSession, or the request of a CreateBacktestSessionRequestV1. Fields are camelCase on the wire.
CreateSessionParamsBuilder
Use builder syntax to set the inputs and finish with build().
DatasetCredentialsResponse
Response of POST /datasets/credentials: temporary, read-only credentials plus a path, so a caller doesn’t need to reconstruct the S3 layout.
DatasetDate
One UTC date.
DatasetDeleteRequest
Query of DELETE /datasets.
DatasetDeleteResponse
Anything reaching past either end of the range stays.
DatasetFile
One file of a files dataset.
DatasetJobListResponse
The caller’s jobs, as GET /dataset-jobs answers.
DatasetJobRequest
Request body of POST /dataset-jobs. Resubmitting it answers with the same job, re-running it if it failed or was cancelled.
DatasetJobStatusResponse
A job’s request, resolved range, phase and outputs, as GET /dataset-jobs/{job_id} answers.
DatasetListQuery
With neither field, every one of the caller’s own datasets.
DatasetListResponse
Response of GET /datasets.
DatasetLocation
A dataset under the user_s3_uri that POST /datasets/credentials returns, at <name>/v<version>/.
DatasetPartition
The parts under one value of the dataset’s partition key.
DatasetParts
A count and extent of parquet parts.
DatasetSummary
One dataset in one scope.
DatasetVersion
One version of a partitioned dataset.
DepthSelection
What a depth job measures over its slot range.
DepthSourceUniverse
What one DepthSource samples.
DepthUniverseResponse
What a depth job samples, per source.
DiagnosticCandidate
A pool the router may not hold, probed for DiagnosticProbeParams::candidate_pairs.
DiagnosticMarketPairs
The mint pairs one probed market is answered for.
DiagnosticProbeParams
Probe markets through the router’s /diagnostic endpoint as the session runs, and stream the results over diagnosticSubscribe.
DiscoveryBatchEvent
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 to BacktestRequest::ContinueTo to pause immediately before the batch executes. After each Continue / ContinueTo, the session emits the next DiscoveryBatchEvent ahead of the next matching batch, enabling a reactive “pause on every discovery” driver loop.
EmptyAccounts
A NonEmptyAccounts built from no accounts.
EncodedBinary
A blob paired with the encoding needed to decode it.
HeldSlots
A slot range held by a job’s check.
InvertedSlotRange
Why a pair of bounds isn’t a valid range.
MintPair
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.
NoSlotWindows
Slot windows were built from no range.
NonEmptyAccounts
Deserializes from a non-empty list of base58 addresses.
ParseMintPairError
A MintPair mint that is not a valid base58 address.
PausedEvent
Payload emitted when a session halts at a caller-specified point. batch_index is None for block-boundary pauses and Some(n) when the session stopped before batch n within slot (no transaction from batch n has been applied). While paused, RPC reads against the session observe partial state up through batch n - 1. A readyForContinue always follows: answer that, not this.
ProgramOverride
A program the probes run in place of the deployed one: program_id names a deployed upgradeable (loader-v3) program, whose code becomes elf.
Progress
A count of finished units out of the total.
RerouteAggregators
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.
RerouteFilter
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.
RerouteParams
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.
RerouteScopes
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.
RerouteStatsReport
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 a VenueTemplate list — how many hops each template priced. Per-swap economics and latency land in the reroute tables, published to dataset_uri when set.
ScheduledAction
A sequence of transactions the server runs automatically during a backtest, with results streamed over the actionSubscribe subscription.
SequencedResponse
Wire format wrapper for responses sent over the session control channel. Sessions whose disconnect_timeout_secs is not 0 (unset defaults to 30) use this to track client position.
SessionId
Identifies one session.
SessionSummary
Summary of transaction execution statistics for a completed session: how the replayed transactions compare with what happened onchain. Sent with completed when the session was created with send_summary. Fields are camelCase on the wire (correctSimulation).
SlotProgress
Slots a running job’s sessions have replayed, out of the slots it owes.
SlotRange
An inclusive [start, end] slot range. Construct via SlotRange::new, which rejects an inverted range, or SlotRange::new_unchecked where the ordering is already guaranteed by the caller.
SlotWindows
The slots an action may fire at: one SlotRange object or a list of them.
SnapshotSlotResponse
Response of the server’s /snapshot-slot endpoint. The chosen source and import state are internal, so only the resolved slot is exposed.
UnmeasuredDepth
A source asked for at a granularity it cannot be measured at.
VenueTemplateReport
One template’s share of the venue probes; the flat venue_* counters on RerouteStatsReport are the sums of these.

Enums§

ActionAnchor
Where a ScheduledAction fires.
ActionKind
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.
ArrayKeyIndicesError
Why a list is not valid ArrayKeyIndices.
BacktestError
Error variants surfaced to backtest RPC clients: the params of an error response.
BacktestRequest
A request you send on the session control channel.
BacktestResponse
A response the server sends on the session control channel.
BacktestStatus
Progress reported in a status response, as a camelCase string such as "startingRuntime". Informational: you need not act on any of them.
BinaryEncoding
Supported binary encodings for account/transaction payloads.
BundleBuildStatus
Where a bundle build or depth job is. snake_case on the wire: "in_progress".
BundleKind
What a bundle build produces.
CreateBacktestSessionRequest
The params of createBacktestSession, in either version. Untagged: the server tells them apart by shape.
DatasetContents
What a dataset holds, by how it is laid out.
DatasetJobPhase
Where a job is, tagged by phase on the wire.
DatasetJobSpec
The dataset a job builds, tagged by kind on the wire.
DatasetScope
Whose copy of a dataset a listing shows.
DepthGranularity
How often a depth job samples its source; each publishes its own dataset under the source.
DepthKind
A depth dataset: a source at a granularity it can be measured at.
DepthSource
Which side of a venue a depth job measures.
DiagnosticProbeError
Why a DiagnosticProbeParams is rejected at session creation.
DiscoveryFilter
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 a DiscoveryBatch so the client can pause immediately before it.
FailFastDivergenceKind
What counts as a “non-benign” divergence for the session fail-fast behaviour.
InvalidSlotWindows
Why a set of ranges from the wire isn’t valid slot windows.
ParseAddressError
Why a string is not a valid Address; carried by this API’s parse errors.
ParseAggregatorError
Why a string is not a SwapAggregator or a RerouteAggregators list.
ParseScopeError
Why a string is not a SwapScope or a RerouteScopes list.
PredictTable
A predict table a dataset job produces.
RangeScope
Who a listed range is available to.
SessionEventKind
What happened in one session of a parallel run: the event of sessionEventV2. Each variant means what the BacktestResponse variant of the same name means, for that session alone.
SessionType
How a session is being used, derived from its creation params.
SwapAggregator
A router whose historical swaps a session can reroute. Lowercase on the wire; parsing ignores case and surrounding spaces.
SwapScope
Where a rerouted swap ran in its transaction.
TxResolver
How a ScheduledAction rewrites its transactions from live state each time it fires. Only valid for kind: simulate and without feeds_reroute.
TxResolverError
Why a ScheduledAction::resolve does 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, markets and candidates together, one DiagnosticProbeParams can name.
MAX_DIAGNOSTIC_MARKET_PAIRS
Most pairs one DiagnosticMarketPairs can name.
MAX_DIAGNOSTIC_USD_VALUES
Most usdValues one DiagnosticProbeParams can 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_BYTES base64-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 err when the action’s TxResolver failed, so nothing was simulated; the outcome’s unresolved flag 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 dataset measured under the modifications with digest publishes: under modified/, never in dataset itself.
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::resolve against the rest of the action, as the server does when the session starts.