Skip to main content

Crate simulator_client

Crate simulator_client 

Source
Expand description

Rust client for the Termina simulator.

A session replays a slot range of Solana mainnet on the server. You step it forward slot by slot, read and change its state through the session’s RPC endpoint, and stream what it executes. This crate drives sessions over the session control channel and calls the server’s HTTP endpoints. It re-exports the wire types as simulator_api, so you never add that crate yourself.

Use ManagedBacktestSession, or managed::ManagedParallelSession for a parallel run. Both reconnect and reattach on their own, so a dropped connection does not end your session. BacktestClient calls the server’s HTTP endpoints: ranges, usage, bundles, depth and dataset credentials.

Runnable programs live in the examples repository. Start with hello_session.

§Install

[dependencies]
simulator-client = "0.29.0" # x-release-please-version
tokio = { version = "1", features = ["macros", "rt-multi-thread"] }
rustls = { version = "0.23", default-features = false, features = ["ring"] }
tracing-subscriber = { version = "0.3", features = ["env-filter"] }

Needs Rust 1.97 or newer. Add Solana crates only at these versions, so that their types are the ones this crate uses:

CrateVersion
solana-address2.6 or newer, below 3
solana-pubkey4.x
solana-account, solana-client, solana-rpc-client, solana-rpc-client-api, solana-transaction, solana-transaction-status4.3 or newer, below 5
solana-hash, solana-message4.x
solana-commitment-config, solana-system-interface3.x
solana-keypair, solana-signature3.1 or newer, below 4
solana-loader-v3-interface7.x
solana-signer3.0.1 or newer, below 4

Every account address is an Address (re-exported from solana-address). A Pubkey from solana-pubkey 4 is the same type, so pass it as is. A Pubkey from an older Solana crate is a different type; convert it with Address::new_from_array(pubkey.to_bytes()).

§TLS

Install a rustls crypto provider at the top of main, before you connect:

let _ = rustls::crypto::ring::default_provider().install_default();

This crate builds rustls with the ring provider. If anything else in your program enables rustls’s aws-lc-rs provider (rustls’s default features, reqwest 0.13, the AWS SDK), rustls cannot pick one and the first connection panics. Installing one up front always works. The call fails only when a provider is already installed, so ignoring its result is safe.

§Connecting

  • URL. Pass the server’s host, such as simulator.termina.technology; it becomes wss://simulator.termina.technology/backtest. A full ws:// or wss:// URL is kept, and gains /backtest if it lacks it.
  • API key. Every request sends it as the X-API-Key header. Read it from the SIMULATOR_API_KEY environment variable, as sim does.
  • Slot ranges. BacktestClient::available_ranges lists the ranges the server can replay, oldest first. Start a session at a range’s bundle_start_slot and end it at or before its max_bundle_end_slot. filter_ranges narrows the list by slot or date.

§Quickstart

Start a session, read an account just before the start slot executes, then run it to the end:

use simulator_client::{
    Address, BacktestClient, Continue, CreateSession, ManagedBacktestSession, ManagedEvent,
};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let _ = rustls::crypto::ring::default_provider().install_default();
    tracing_subscriber::fmt()
        .with_env_filter(tracing_subscriber::EnvFilter::from_default_env())
        .init();

    let host = "simulator.termina.technology";
    let api_key = std::env::var("SIMULATOR_API_KEY")?;

    // 1. Pick the newest slot range the server can replay.
    let client = BacktestClient::builder().url(host).api_key(&api_key).build();
    let ranges = client.available_ranges().await?;
    let range = ranges
        .iter()
        .max_by_key(|range| range.bundle_start_slot)
        .ok_or("the server lists no slot ranges")?;

    // 2. Start a session at the range's first slot. `slot_count` counts the slots after it.
    let create = CreateSession::builder()
        .start_slot(range.bundle_start_slot)
        .slot_count(10)
        .capacity_wait_timeout_secs(300)
        .build()
        .into_request()?;
    let mut session = ManagedBacktestSession::start(host.to_string(), api_key, create).await?;

    // 3. Read state just before the start slot executes (the end of the slot before it)
    //    through the session's RPC endpoint.
    session.wait_until_ready().await?;
    let usdc: Address = "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v".parse()?;
    let mint = session.rpc().get_account(&usdc).await?;
    println!("USDC mint: {} bytes, owned by {}", mint.data.len(), mint.owner);

    // 4. Step one block at a time until the session completes, then close it.
    let step = Continue::builder().advance_count(1).build().into_params();
    session.send_continue(step.clone()).await?;
    let summary = session
        .run_to_completion(step, |event| {
            if let ManagedEvent::Slot(slot) = event {
                println!("executed slot {slot}");
            }
        })
        .await?;
    println!("{summary:?}");
    Ok(())
}

§Session lifecycle

  1. ManagedBacktestSession::start returns once the server has created the session. Its session_info holds the session ID and the session’s RPC endpoint.
  2. Call the subscribe_* methods you need, before the first continue.
  3. Read events with next_event. Status updates come first while the session starts.
  4. On ManagedEvent::ReadyForContinue the session is paused. Read or change state through rpc, then call send_continue with a Continue: how many blocks to execute (skipped slots are not counted), user transactions to run first, account overrides to write. Or call send_continue_to to stop at a slot: the session sends ManagedEvent::Paused there, then ReadyForContinue. Answer only the ReadyForContinue.
  5. ManagedEvent::Completed comes after the last slot and after every subscription’s last notification. The session’s RPC endpoint stops serving (HTTP 502).
  6. shutdown closes the session on the server. Dropping the session cancels it without waiting.

wait_until_ready and run_to_completion wrap steps 3 to 6. For a run split across concurrent sessions, use managed::ManagedParallelSession.

§Subscriptions

Managed subscribe_* methodsFunctions in subscriptionsYour own WebSocket
DeliveryManagedEvents from next_eventYour callback, on a background taskYours
ReconnectYes. Resends the last slot it delivered: dedupe transactions by signature, account diffs by (signature, account, slot)No. The stream ends with SubscriptionRuntimeError::ClosedYours
End of runEvery notification arrives before CompletedCall SubscriptionHandle::shutdown before you close the sessionYours
Stopshutdown on the sessionhandle.shutdown().await?; dropping the handle does not stop itYours
CoversTransactions (with program logs) and account changes by program; pre-scheduled action results; reroutes; diagnosticsAlso single accounts (subscribe_account_diffs) and program logs alone (subscribe_program_logs)Any subscribe method

Subscribe before the continue you want notifications for. Connect your own WebSocket to the session’s RPC endpoint (convert it with http_to_ws_url) and merge SubscribeConfig into a subscribe’s params with SubscribeConfig::apply_to. balances::balance_changes reads the SOL and token balance changes from a transaction notification; decode_transaction decodes the binary transactions in discovery, action and reroute notifications.

§Errors and recovery

The managed session has already retried what it could. Each ManagedSessionError says what to do. ManagedSessionError::is_retryable answers the last column in code:

ErrorCauseWhat to doRetry with a new session?
ApiKeyRejectedThe server refused the API key (HTTP 401 or 403)Fix the keyNo
CreateThe server refused the create request (CreateError::Rejected), could not be reached (CreateError::Connection), or sent a reply this client does not understand (CreateError::Protocol)Retry later, fix the request, or upgrade this crateWhen CreateError::is_retryable
RemoteThe server reported an error, terminal or not, during wait_until_ready or run_to_completionFix what it namesWhen BacktestError::is_retryable
ControlFailed, SubscriptionFailedA connection ran out of retriesStart a new sessionYes
ControlClosed, ContinueSendThe session is overStopNo
CancelledYour cancellation token fired, or the parallel run was shut downStopNo
CompletedBeforeReadyThe session finished before its first pauseCheck the range and the create requestNo

ManagedEvent::Error from next_event is terminal when BacktestError::is_terminal is true: stop. Any other error leaves the session running. A BacktestClient call fails with a BacktestClientError; BacktestClientError::is_retryable says whether to retry it.

§Connection drops

The session runs on the server and outlives its connections, unless disconnect_timeout_secs is 0. A managed session retries a dropped connection up to managed::RECONNECT_MAX_ATTEMPTS times within managed::RECONNECT_MAX_TOTAL, reattaches, and the server replays the responses you missed.

§Timeouts

WhatDefaultChange it with
Waiting for server capacity at createNone: fails at once when the server is busyCreateSession::capacity_wait_timeout_secs
Server keeps an unattached session360 s managed single session (managed::DEFAULT_DISCONNECT_TIMEOUT_SECS); 900 s for a parallel run. At most 900 sCreateSession::disconnect_timeout_secs
Managed reconnect budget per connection20 attempts within 5 minutesFixed
Managed connect / handshake30 s / 120 sFixed
Wait for notifications after Completed60 s without oneManagedBacktestSession::set_completion_drain_timeout

§Logging

The crate logs through tracing. Install a subscriber, as in the quickstart (tracing-subscriber with its env-filter feature), and set RUST_LOG:

  • RUST_LOG=simulator_client=info shows session creation, reconnects and retries.
  • RUST_LOG=simulator_client=debug adds reattaches.

§Troubleshooting

SymptomCauseFix
API key rejected: HTTP 401 (or 403); 401 Unauthorized from a BacktestClient callMissing, mistyped or expired keyCheck SIMULATOR_API_KEY; sim usage confirms a key works
session create failed: ... block bundle not found, invalid request or no produced blocks in requested rangeThe range is not availablePick a range from available_ranges; start at its bundle_start_slot
session create failed: ... insufficient capacityThe server is busySet capacity_wait_timeout_secs (sim run uses 900), or retry later
ControlFailed from a managed sessionThe session ended, or its disconnect_timeout_secs passedStart a new session; raise disconnect_timeout_secs
clerk error when creating a sessionThe server could not load the range’s historical dataRetry later
Panic: Could not automatically determine the process-level CryptoProviderTwo rustls providers are linkedInstall one: see TLS
Compile error: expected Address, found Pubkey, or two versions of solana_addressA Solana crate from another major versionUse the versions in Install; cargo tree -i solana-address@2 -e normal shows which crates use the 2.x copy. Other major versions, pulled in by spl-* crates, are harmless
No log outputNo tracing subscriber installedSee Logging

Re-exports§

pub use geyser::SessionGeyserChannel;
pub use injection::ProgramModError;
pub use injection::build_program_injection;
pub use injection::modify_program_via_rpc;
pub use managed::ControlEvent;
pub use managed::CreateError;
pub use managed::ManagedBacktestSession;
pub use managed::ManagedEvent;
pub use managed::ManagedSessionError;
pub use subscriptions::AccountDiffContext;
pub use subscriptions::AccountDiffNotification;
pub use subscriptions::AccountDiffSubscriptionHandle;
pub use subscriptions::ActionResultContext;
pub use subscriptions::ActionResultNotification;
pub use subscriptions::ActionSubscriptionHandle;
pub use subscriptions::ActionTransactionOutcome;
pub use subscriptions::DiagnosticContext;
pub use subscriptions::DiagnosticNotification;
pub use subscriptions::DiagnosticSubscriptionHandle;
pub use subscriptions::LogSubscriptionHandle;
pub use subscriptions::RoutedAccountDiffNotification;
pub use subscriptions::SubscriptionError;
pub use subscriptions::SubscriptionHandle;
pub use subscriptions::SubscriptionRuntimeError;
pub use subscriptions::UiAccountConversionError;
pub use subscriptions::account_data_from_ui;
pub use subscriptions::subscribe_account_diffs;
pub use subscriptions::subscribe_account_diffs_many;
pub use subscriptions::subscribe_actions;
pub use subscriptions::subscribe_diagnostics;
pub use subscriptions::subscribe_program_diffs;
pub use subscriptions::subscribe_program_logs;
pub use subscriptions::subscribe_replacements;
pub use urls::UrlError;
pub use urls::backtest_ws_url;
pub use urls::http_base_from_ws_url;
pub use urls::http_to_ws_url;
pub use simulator_api;

Modules§

balances
Lamport and token balance changes read from an encoded transaction’s metadata.
geyser
Reaching a session’s Yellowstone endpoint through the server.
injection
Program overrides: swap a program’s binary for your own ELF in a running session.
managed
Sessions that reconnect on their own.
recipes
Venue templates for rerouting swaps directly to a venue.
reroute_report
The reroute-report core fed from replacementSubscribe notifications. The computation — records, pricing, the reports themselves — lives in simulator_api::reroute_report; this module only maps the wire shape onto it.
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.
rpc
Calls to the session’s RPC endpoint that solana_client does not cover.
subscriptions
Standalone subscriptions to a session’s RPC endpoint.
urls
Converting between the URL forms the server and the session’s RPC endpoint use.

Structs§

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.
AvailableRange
One contiguous range of slots you can replay: an entry of GET /available-ranges.
BacktestClient
Client for the server’s HTTP endpoints, authenticated with an API key.
ComputeTotals
A session contributes wholly to the window — or UsageBucket — it ended in, even when it ran across the boundary.
Continue
Builder for a continue request.
ContinueToParams
The params of continueTo: execute up to a point, then pause there.
CreateSession
Builder for the request that creates a session.
DatasetCredentialsResponse
Response of POST /datasets/credentials: temporary, read-only credentials plus a path, so a caller doesn’t need to reconstruct the S3 layout.
DepthCoverageResponse
What a depth request will sample, per source. Response body of GET /generate-depth/coverage.
DepthRequest
Request body of POST /generate-depth.
DepthStatusResponse
Response body of POST /generate-depth and GET /generate-depth/{request_id}.
L1Score
What the original swap filled, and how the stand-in scored against it. Flattened into the notification’s top level. l1 in a name means the original (onchain) swap.
NonEmptyAccounts
Deserializes from a non-empty list of base58 addresses.
OriginalNotification
The original swap replayed as the baseline (kind: "original"): the historical transaction re-run against the state it was quoted at, so the other kinds can be scored against a number produced the same way rather than against the chain’s.
ParseRangeBoundError
A string that is not a slot number, an RFC 3339 timestamp or a YYYY-MM-DD date.
ProbedHop
The hop a venue probe re-priced, as the original swap ran it onchain and as the replay ran it.
ReplacementContext
The slot the payload was produced at, in the shape every other subscription’s context takes.
ReplacementCore
The identity and outcome every notification carries, whatever its kind. Flattened into the notification’s top level.
RequoteNotification
A transaction rerouted through the router (kind: "requote"): the original swap’s transaction re-quoted and simulated. The original still executed onchain; this result is never committed.
RerouteLegNotification
One swap of a transaction rerouted through the router.
RouteHop
One hop of a route: a swap through one venue. Wire keys are camelCase.
RoutePlan
A whole route in the order its hops run. Deserialization bypasses RoutePlan::new, so a plan read off the wire can still be empty.
SessionCounts
Point counts by outcome, not session-deduplicated, so the three need not balance: a pre-start failure has no started, a session moving between server instances re-emits it. Billing uses the compute totals, which derive only from the terminal points.
SessionUsage
One session that ran under the key, as its terminal event reported it.
SessionUsagePage
Response body of GET /usage/sessions.
SnapshotSlotResponse
Response of the server’s /snapshot-slot endpoint. The chosen source and import state are internal, so only the resolved slot is exposed.
SubscribeConfig
Cross-cutting subscribe options the client sets in the config object.
TakerSlots
The account slots a probe rewrites, as indices into instruction.accounts.
TemplateAccount
One account meta of a TemplateInstruction.
TemplateInstruction
The template’s single instruction, sent verbatim except the role slots’ addresses and the amount bytes.
UsageBucket
One UTC day of a UsageReport, covering (start, end]. end is the following midnight, except for a last bucket that ends at the report’s until.
UsageReport
Response body of GET /usage.
VenueNotification
A venue probe (kind: "directFill"): one hop rerouted directly to a venue through your template, simulated against the state it would have traded on.
VenueTemplate
One instruction the caller serialized, with the slots the server rewrites per probe and the offset it writes the amount at. Matches hops of mode originals trading inputMint → outputMint and is priced against each such hop’s realized fill.

Enums§

BacktestClientError
Error from crate::BacktestClient and the helpers built on it.
BundleBuildStatus
Where a bundle build or depth job is. snake_case on the wire: "in_progress".
BundleKind
What a bundle build produces.
Compression
Compression negotiated for notification frames. lowercase so the variant matches the on-wire token ("zstd").
DepthGranularity
How often a depth job samples its source; each publishes its own dataset under the source.
DepthSource
Which side of a venue a depth job measures.
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.
ParseAddressError
Why a string is not a valid Address; carried by this API’s parse errors.
RangeBound
A slot number or a UTC timestamp, used to filter available ranges.
ReplacementNotification
One reroute result for an original swap, streamed over replacementSubscribe: through the router, directly to a venue, or the original swap replayed as the baseline. Nothing stands in for the original. Tagged by kind, with the variant’s fields at the top level beside it.
SerializeEncodeError
Error serializing a transaction for injection.
SwapMode
Whether the swap fixes the input amount (ExactIn) or the output amount (ExactOut).
TxDecodeError
Why a server-encoded transaction could not be decoded.

Constants§

FULL_PERCENT
The whole trade through one hop; anything less is a split.

Functions§

decode_transaction
Decodes one server-encoded transaction from DiscoveryBatchEvent::transactions, ActionResultNotification::matched or RequoteNotification::routed_transaction; trailing bytes are a TxDecodeError::Wincode.
encode_transaction
Encodes a transaction the way ScheduledAction::transactions and ContinueParams::transactions carry it: the standard base64 of its wire bytes, the bytes sendTransaction takes, for a legacy, v0 or v1 transaction.
filter_ranges
Filter ranges to those bookended by [after, before]:
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.

Type Aliases§

BacktestClientResult
Result type returned by crate::BacktestClient.