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:
| Crate | Version |
|---|---|
solana-address | 2.6 or newer, below 3 |
solana-pubkey | 4.x |
solana-account, solana-client, solana-rpc-client, solana-rpc-client-api, solana-transaction, solana-transaction-status | 4.3 or newer, below 5 |
solana-hash, solana-message | 4.x |
solana-commitment-config, solana-system-interface | 3.x |
solana-keypair, solana-signature | 3.1 or newer, below 4 |
solana-loader-v3-interface | 7.x |
solana-signer | 3.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 becomeswss://simulator.termina.technology/backtest. A fullws://orwss://URL is kept, and gains/backtestif it lacks it. - API key. Every request sends it as the
X-API-Keyheader. Read it from theSIMULATOR_API_KEYenvironment variable, assimdoes. - Slot ranges.
BacktestClient::available_rangeslists the ranges the server can replay, oldest first. Start a session at a range’sbundle_start_slotand end it at or before itsmax_bundle_end_slot.filter_rangesnarrows 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
ManagedBacktestSession::startreturns once the server has created the session. Itssession_infoholds the session ID and the session’s RPC endpoint.- Call the
subscribe_*methods you need, before the first continue. - Read events with
next_event.Statusupdates come first while the session starts. - On
ManagedEvent::ReadyForContinuethe session is paused. Read or change state throughrpc, then callsend_continuewith aContinue: how many blocks to execute (skipped slots are not counted), user transactions to run first, account overrides to write. Or callsend_continue_toto stop at a slot: the session sendsManagedEvent::Pausedthere, thenReadyForContinue. Answer only theReadyForContinue. ManagedEvent::Completedcomes after the last slot and after every subscription’s last notification. The session’s RPC endpoint stops serving (HTTP 502).shutdowncloses 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_* methods | Functions in subscriptions | Your own WebSocket | |
|---|---|---|---|
| Delivery | ManagedEvents from next_event | Your callback, on a background task | Yours |
| Reconnect | Yes. Resends the last slot it delivered: dedupe transactions by signature, account diffs by (signature, account, slot) | No. The stream ends with SubscriptionRuntimeError::Closed | Yours |
| End of run | Every notification arrives before Completed | Call SubscriptionHandle::shutdown before you close the session | Yours |
| Stop | shutdown on the session | handle.shutdown().await?; dropping the handle does not stop it | Yours |
| Covers | Transactions (with program logs) and account changes by program; pre-scheduled action results; reroutes; diagnostics | Also 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:
| Error | Cause | What to do | Retry with a new session? |
|---|---|---|---|
ApiKeyRejected | The server refused the API key (HTTP 401 or 403) | Fix the key | No |
Create | The 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 crate | When CreateError::is_retryable |
Remote | The server reported an error, terminal or not, during wait_until_ready or run_to_completion | Fix what it names | When BacktestError::is_retryable |
ControlFailed, SubscriptionFailed | A connection ran out of retries | Start a new session | Yes |
ControlClosed, ContinueSend | The session is over | Stop | No |
Cancelled | Your cancellation token fired, or the parallel run was shut down | Stop | No |
CompletedBeforeReady | The session finished before its first pause | Check the range and the create request | No |
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
| What | Default | Change it with |
|---|---|---|
| Waiting for server capacity at create | None: fails at once when the server is busy | CreateSession::capacity_wait_timeout_secs |
| Server keeps an unattached session | 360 s managed single session (managed::DEFAULT_DISCONNECT_TIMEOUT_SECS); 900 s for a parallel run. At most 900 s | CreateSession::disconnect_timeout_secs |
| Managed reconnect budget per connection | 20 attempts within 5 minutes | Fixed |
| Managed connect / handshake | 30 s / 120 s | Fixed |
Wait for notifications after Completed | 60 s without one | ManagedBacktestSession::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=infoshows session creation, reconnects and retries.RUST_LOG=simulator_client=debugadds reattaches.
§Troubleshooting
| Symptom | Cause | Fix |
|---|---|---|
API key rejected: HTTP 401 (or 403); 401 Unauthorized from a BacktestClient call | Missing, mistyped or expired key | Check SIMULATOR_API_KEY; sim usage confirms a key works |
session create failed: ... block bundle not found, invalid request or no produced blocks in requested range | The range is not available | Pick a range from available_ranges; start at its bundle_start_slot |
session create failed: ... insufficient capacity | The server is busy | Set capacity_wait_timeout_secs (sim run uses 900), or retry later |
ControlFailed from a managed session | The session ended, or its disconnect_timeout_secs passed | Start a new session; raise disconnect_timeout_secs |
clerk error when creating a session | The server could not load the range’s historical data | Retry later |
Panic: Could not automatically determine the process-level CryptoProvider | Two rustls providers are linked | Install one: see TLS |
Compile error: expected Address, found Pubkey, or two versions of solana_address | A Solana crate from another major version | Use 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 output | No tracing subscriber installed | See 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
replacementSubscribenotifications. The computation — records, pricing, the reports themselves — lives insimulator_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_clientdoes 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-addressversion. The address of a Solana account. - Available
Range - One contiguous range of slots you can replay: an entry of
GET /available-ranges. - Backtest
Client - Client for the server’s HTTP endpoints, authenticated with an API key.
- Compute
Totals - A session contributes wholly to the window — or
UsageBucket— it ended in, even when it ran across the boundary. - Continue
- Builder for a
continuerequest. - Continue
ToParams - The
paramsofcontinueTo: execute up to a point, then pause there. - Create
Session - Builder for the request that creates a session.
- 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. - Depth
Coverage Response - What a depth request will sample, per source. Response body of
GET /generate-depth/coverage. - Depth
Request - Request body of
POST /generate-depth. - Depth
Status Response - Response body of
POST /generate-depthandGET /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.
l1in a name means the original (onchain) swap. - NonEmpty
Accounts - Deserializes from a non-empty list of base58 addresses.
- Original
Notification - 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. - Parse
Range Bound Error - A string that is not a slot number, an RFC 3339 timestamp or a
YYYY-MM-DDdate. - Probed
Hop - The hop a venue probe re-priced, as the original swap ran it onchain and as the replay ran it.
- Replacement
Context - The slot the payload was produced at, in the shape every other subscription’s context takes.
- Replacement
Core - The identity and outcome every notification carries, whatever its kind. Flattened into the notification’s top level.
- Requote
Notification - 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. - Reroute
LegNotification - One swap of a transaction rerouted through the router.
- Route
Hop - One hop of a route: a swap through one venue. Wire keys are camelCase.
- Route
Plan - A whole route in the order its hops run. Deserialization bypasses
RoutePlan::new, so a plan read off the wire can still be empty. - Session
Counts - 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. - Session
Usage - One session that ran under the key, as its terminal event reported it.
- Session
Usage Page - Response body of
GET /usage/sessions. - 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. - Subscribe
Config - Cross-cutting subscribe options the client sets in the config object.
- Taker
Slots - The account slots a probe rewrites, as indices into
instruction.accounts. - Template
Account - One account meta of a
TemplateInstruction. - Template
Instruction - The template’s single instruction, sent verbatim except the role slots’ addresses and the amount bytes.
- Usage
Bucket - One UTC day of a
UsageReport, covering(start, end].endis the following midnight, except for a last bucket that ends at the report’suntil. - Usage
Report - Response body of
GET /usage. - Venue
Notification - A venue probe (
kind: "directFill"): one hop rerouted directly to a venue through your template, simulated against the state it would have traded on. - Venue
Template - One instruction the caller serialized, with the slots the server rewrites per probe and the
offset it writes the amount at. Matches hops of
modeoriginals tradinginputMint→outputMintand is priced against each such hop’s realized fill.
Enums§
- Backtest
Client Error - Error from
crate::BacktestClientand the helpers built on it. - 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.
- Compression
- Compression negotiated for notification frames.
lowercaseso the variant matches the on-wire token ("zstd"). - Depth
Granularity - How often a depth job samples its source; each publishes its own dataset under the source.
- Depth
Source - Which side of a venue a depth job measures.
- 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. - Parse
Address Error - Why a string is not a valid
Address; carried by this API’s parse errors. - Range
Bound - A slot number or a UTC timestamp, used to filter available ranges.
- Replacement
Notification - 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 bykind, with the variant’s fields at the top level beside it. - Serialize
Encode Error - Error serializing a transaction for injection.
- Swap
Mode - Whether the swap fixes the input amount (
ExactIn) or the output amount (ExactOut). - TxDecode
Error - 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::matchedorRequoteNotification::routed_transaction; trailing bytes are aTxDecodeError::Wincode. - encode_
transaction - Encodes a transaction the way
ScheduledAction::transactionsandContinueParams::transactionscarry it: the standard base64 of its wire bytes, the bytessendTransactiontakes, for a legacy, v0 or v1 transaction. - filter_
ranges - Filter
rangesto 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§
- Backtest
Client Result - Result type returned by
crate::BacktestClient.