Skip to main content

simulator_client/
lib.rs

1//! Rust client for the Termina simulator.
2//!
3//! A session replays a slot range of Solana mainnet on the server. You step it forward slot by
4//! slot, read and change its state through the session's RPC endpoint, and stream what it
5//! executes. This crate drives sessions over the session control channel and calls the server's
6//! HTTP endpoints. It re-exports the wire types as [`simulator_api`], so you never add that crate
7//! yourself.
8//!
9//! Use [`ManagedBacktestSession`], or [`managed::ManagedParallelSession`] for a parallel run.
10//! Both reconnect on their own, so a dropped connection does not end your session.
11//! [`BacktestClient`] calls the server's HTTP endpoints: ranges, usage, bundles, depth and
12//! dataset credentials.
13//!
14//! Runnable programs live in the [examples repository](https://github.com/nitro-svm/examples).
15//! Start with [`hello_session`](https://github.com/nitro-svm/examples/tree/main/src/bin/hello_session).
16//!
17//! # Install
18//!
19//! ```toml
20//! [dependencies]
21//! simulator-client = "0.31.0" # x-release-please-version
22//! tokio = { version = "1", features = ["macros", "rt-multi-thread"] }
23//! rustls = { version = "0.23", default-features = false, features = ["ring"] }
24//! tracing-subscriber = { version = "0.3", features = ["env-filter"] }
25//! ```
26//!
27//! Needs Rust 1.97 or newer. Add Solana crates only at these versions, so that their types are
28//! the ones this crate uses:
29//!
30//! | Crate | Version |
31//! |---|---|
32//! | `solana-address` | 2.6 or newer, below 3 |
33//! | `solana-pubkey` | 4.x |
34//! | `solana-account`, `solana-client`, `solana-rpc-client`, `solana-rpc-client-api`, `solana-transaction`, `solana-transaction-status` | 4.3 or newer, below 5 |
35//! | `solana-hash`, `solana-message` | 4.x |
36//! | `solana-commitment-config`, `solana-system-interface` | 3.x |
37//! | `solana-keypair`, `solana-signature` | 3.1 or newer, below 4 |
38//! | `solana-loader-v3-interface` | 7.x |
39//! | `solana-signer` | 3.0.1 or newer, below 4 |
40//!
41//! Every account address is an [`Address`] (re-exported from `solana-address`). A `Pubkey` from
42//! `solana-pubkey` 4 is the same type, so pass it as is. A `Pubkey` from an older Solana crate
43//! is a different type; convert it with `Address::new_from_array(pubkey.to_bytes())`.
44//!
45//! # TLS
46//!
47//! Install a rustls crypto provider at the top of `main`, before you connect:
48//!
49//! ```no_run
50//! let _ = rustls::crypto::ring::default_provider().install_default();
51//! ```
52//!
53//! This crate builds rustls with the `ring` provider. If anything else in your program enables
54//! rustls's `aws-lc-rs` provider (rustls's default features, `reqwest` 0.13, the AWS SDK), rustls
55//! cannot pick one and the first connection panics. Installing one up front always works. The
56//! call fails only when a provider is already installed, so ignoring its result is safe.
57//!
58//! # Connecting
59//!
60//! - **URL.** Pass the server's host, such as `simulator.termina.technology`; it becomes
61//!   `wss://simulator.termina.technology/backtest`. A full `ws://` or `wss://` URL is kept, and
62//!   gains `/backtest` if it lacks it.
63//! - **API key.** Every request sends it as the `X-API-Key` header. Read it from the
64//!   `SIMULATOR_API_KEY` environment variable, as `sim` does.
65//! - **Slot ranges.** [`BacktestClient::available_ranges`] lists the ranges the server can
66//!   replay, oldest first. Start a session at a range's `bundle_start_slot` and end it at or
67//!   before its `max_bundle_end_slot`. [`filter_ranges`] narrows the list by slot or date.
68//!
69//! # Quickstart
70//!
71//! Start a session, read an account just before the start slot executes, then run it to the end:
72//!
73//! ```no_run
74//! use simulator_client::{
75//!     Address, BacktestClient, Continue, CreateSession, ManagedBacktestSession, ManagedEvent,
76//! };
77//!
78//! #[tokio::main]
79//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
80//!     let _ = rustls::crypto::ring::default_provider().install_default();
81//!     tracing_subscriber::fmt()
82//!         .with_env_filter(tracing_subscriber::EnvFilter::from_default_env())
83//!         .init();
84//!
85//!     let host = "simulator.termina.technology";
86//!     let api_key = std::env::var("SIMULATOR_API_KEY")?;
87//!
88//!     // 1. Pick the newest slot range the server can replay.
89//!     let client = BacktestClient::builder().url(host).api_key(&api_key).build();
90//!     let ranges = client.available_ranges().await?;
91//!     let range = ranges
92//!         .iter()
93//!         .max_by_key(|range| range.bundle_start_slot)
94//!         .ok_or("the server lists no slot ranges")?;
95//!
96//!     // 2. Start a session at the range's first slot. `slot_count` counts the slots after it.
97//!     let create = CreateSession::builder()
98//!         .start_slot(range.bundle_start_slot)
99//!         .slot_count(10)
100//!         .capacity_wait_timeout_secs(300)
101//!         .build()
102//!         .into_request()?;
103//!     let mut session = ManagedBacktestSession::start(host.to_string(), api_key, create).await?;
104//!
105//!     // 3. Read state just before the start slot executes (the end of the slot before it)
106//!     //    through the session's RPC endpoint.
107//!     session.wait_until_ready().await?;
108//!     let usdc: Address = "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v".parse()?;
109//!     let mint = session.rpc().get_account(&usdc).await?;
110//!     println!("USDC mint: {} bytes, owned by {}", mint.data.len(), mint.owner);
111//!
112//!     // 4. Step one block at a time until the session completes, then close it.
113//!     let step = Continue::builder().advance_count(1).build().into_params();
114//!     session.send_continue(step.clone()).await?;
115//!     let summary = session
116//!         .run_to_completion(step, |event| {
117//!             if let ManagedEvent::Slot(slot) = event {
118//!                 println!("executed slot {slot}");
119//!             }
120//!         })
121//!         .await?;
122//!     println!("{summary:?}");
123//!     Ok(())
124//! }
125//! ```
126//!
127//! # Session lifecycle
128//!
129//! 1. [`ManagedBacktestSession::start`] returns once the session is created and ready. Its
130//!    [`session_info`](ManagedBacktestSession::session_info) holds the session ID and the
131//!    session's RPC endpoint.
132//! 2. Call the `subscribe_*` methods you need, before the first continue.
133//! 3. Read events with [`next_event`](ManagedBacktestSession::next_event). `Status` updates come
134//!    first while the session starts.
135//! 4. On [`ManagedEvent::ReadyForContinue`] the session is paused. Read or change state through
136//!    [`rpc`](ManagedBacktestSession::rpc), then call
137//!    [`send_continue`](ManagedBacktestSession::send_continue) with a [`Continue`]: how many
138//!    blocks to execute (skipped slots are not counted), user transactions to run first, account
139//!    overrides to write. Or call
140//!    [`send_continue_to`](ManagedBacktestSession::send_continue_to) to stop at a slot: the
141//!    session sends [`ManagedEvent::Paused`] there, then `ReadyForContinue`. Answer only the
142//!    `ReadyForContinue`.
143//! 5. [`ManagedEvent::Completed`] comes after the last slot and after every subscription's last
144//!    notification. The session's RPC endpoint stops serving (HTTP 502).
145//! 6. [`shutdown`](ManagedBacktestSession::shutdown) closes the session on the server. Dropping
146//!    the session cancels it without waiting.
147//!
148//! [`wait_until_ready`](ManagedBacktestSession::wait_until_ready) and
149//! [`run_to_completion`](ManagedBacktestSession::run_to_completion) wrap steps 3 to 6. For a run
150//! split across concurrent sessions, use [`managed::ManagedParallelSession`].
151//!
152//! # Subscriptions
153//!
154//! | | Managed `subscribe_*` methods | Functions in [`subscriptions`] | Your own WebSocket |
155//! |---|---|---|---|
156//! | Delivery | [`ManagedEvent`]s from `next_event` | Your callback, on a background task | Yours |
157//! | Reconnect | Yes. See [Connection drops](managed#connection-drops) for the duplicates | No. The stream ends with [`SubscriptionRuntimeError::Closed`] | Yours |
158//! | End of run | Every notification arrives before `Completed` | Call [`SubscriptionHandle::shutdown`] before you close the session | Yours |
159//! | Stop | `shutdown` on the session | `handle.shutdown().await?`; dropping the handle does not stop it | Yours |
160//! | 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 |
161//!
162//! Subscribe before the continue you want notifications for. Connect your own WebSocket to the
163//! session's RPC endpoint (convert it with [`http_to_ws_url`]) and merge [`SubscribeConfig`]
164//! into a subscribe's params with [`SubscribeConfig::apply_to`].
165//! [`balances::balance_changes`] reads the SOL and token balance changes from a transaction
166//! notification; [`decode_transaction`] decodes the binary transactions in discovery, action and
167//! reroute notifications.
168//!
169//! # Errors and recovery
170//!
171//! The managed session has already retried what it could. Each [`ManagedSessionError`] says what
172//! to do. [`ManagedSessionError::is_retryable`] answers the last column in code:
173//!
174//! | Error | Cause | What to do | Retry with a new session? |
175//! |---|---|---|---|
176//! | `ApiKeyRejected` | The server refused the API key (HTTP 401 or 403) | Fix the key | No |
177//! | `Create` | The create failed. See [`CreateError`] | Retry later, fix the request, or upgrade this crate | When [`CreateError::is_retryable`] |
178//! | `SessionTokenRejected` | The session's endpoint refused the token, at the first attach or later | Start a new session | Yes |
179//! | `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`](simulator_api::BacktestError::is_retryable) |
180//! | `ControlFailed` | The control channel used up its reconnect budget, or the session ended | Start a new session | Yes |
181//! | `SubscriptionFailed` | A subscription ran out of retries | Start a new session | Yes |
182//! | `ControlClosed`, `ContinueSend` | The session is over: it completed, or the server sent a terminal error (that error comes first from `next_event`) | Stop | No |
183//! | `Cancelled` | Your cancellation token fired, or the parallel run was shut down | Stop | No |
184//! | `CompletedBeforeReady` | The session finished before its first pause | Check the range and the create request | No |
185//!
186//! [`ManagedEvent::Error`] from `next_event` is terminal when
187//! [`BacktestError::is_terminal`](simulator_api::BacktestError::is_terminal) is true: stop. Any
188//! other error leaves the session running. A [`BacktestClient`] call fails with a
189//! [`BacktestClientError`]; [`BacktestClientError::is_retryable`] says whether to retry it.
190//!
191//! # Timeouts
192//!
193//! | What | Default | Change it with |
194//! |---|---|---|
195//! | Waiting for server capacity at create | None: fails at once when the server is busy | [`CreateSession::capacity_wait_timeout_secs`] |
196//! | 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`] |
197//! | Wait for notifications after `Completed` | 60 s without one | [`ManagedBacktestSession::set_completion_drain_timeout`] |
198//!
199//! # Logging
200//!
201//! The crate logs through [`tracing`](https://docs.rs/tracing). Install a subscriber, as in the
202//! quickstart (`tracing-subscriber` with its `env-filter` feature), and set `RUST_LOG`:
203//!
204//! - `RUST_LOG=simulator_client=info` shows session creation, reconnects and retries.
205//! - `RUST_LOG=simulator_client=debug` adds each reconnect attempt.
206//!
207//! # Troubleshooting
208//!
209//! | Symptom | Cause | Fix |
210//! |---|---|---|
211//! | `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 |
212//! | `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` |
213//! | `session create failed: ... insufficient capacity` | The server is busy | Set `capacity_wait_timeout_secs` (`sim run` uses 900), or retry later |
214//! | `clerk error` when creating a session | The server could not load the range's historical data | Retry later |
215//! | `ControlFailed` from a managed session | The session ended, or its `disconnect_timeout_secs` passed | Start a new session; raise `disconnect_timeout_secs` |
216//! | Panic: `Could not automatically determine the process-level CryptoProvider` | Two rustls providers are linked | Install one: see [TLS](#tls) |
217//! | Compile error: expected `Address`, found `Pubkey`, or two versions of `solana_address` | A Solana crate from another major version | Use the versions in [Install](#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 |
218
219#![forbid(unsafe_code)]
220#![warn(missing_docs)]
221
222pub mod balances;
223mod builders;
224mod client;
225mod endpoint;
226mod error;
227pub mod geyser;
228pub mod injection;
229pub mod managed;
230mod ranges;
231pub mod recipes;
232pub mod reroute_report;
233pub mod rpc;
234mod session;
235pub mod subscriptions;
236mod transaction_step;
237mod tx;
238pub mod urls;
239
240pub use builders::{Continue, CreateSession, SerializeEncodeError, encode_transaction};
241pub use client::BacktestClient;
242pub use error::{BacktestClientError, BacktestClientResult};
243pub use geyser::SessionGeyserChannel;
244pub use injection::{ProgramModError, build_program_injection, modify_program_via_rpc};
245pub use managed::{
246    ControlEvent, CreateError, ManagedBacktestSession, ManagedEvent, ManagedSessionError,
247};
248pub use ranges::{ParseRangeBoundError, RangeBound, filter_ranges};
249#[doc(hidden)]
250pub use session::{
251    AdvanceState, BacktestSession, ContinueResult, CoverageError, ReadyOutcome, SessionCoverage,
252};
253pub use simulator_api::{
254    self, Address, AvailableRange, BundleBuildStatus, BundleKind, ContinueToParams,
255    DatasetCredentialsResponse, DepthGranularity, DepthSource, DepthUniverseResponse,
256    DiscoveryFilter, NonEmptyAccounts, ParseAddressError, SnapshotSlotResponse, SwapMode,
257    TakerSlots, TemplateAccount, TemplateInstruction, VenueTemplate,
258    route_plan::{self, FULL_PERCENT, RouteHop, RoutePlan},
259    split_range,
260    subscribe_config::{Compression, SubscribeConfig},
261    usage::{
262        ComputeTotals, SessionCounts, SessionUsage, SessionUsagePage, UsageBucket, UsageReport,
263    },
264};
265pub use subscriptions::{
266    AccountDiffContext, AccountDiffNotification, AccountDiffSubscriptionHandle,
267    ActionResultContext, ActionResultNotification, ActionSubscriptionHandle,
268    ActionTransactionOutcome, DiagnosticContext, DiagnosticNotification,
269    DiagnosticSubscriptionHandle, L1Score, LogSubscriptionHandle, OriginalNotification, ProbedHop,
270    ReplacementContext, ReplacementCore, ReplacementNotification, RequoteNotification,
271    RerouteLegNotification, RoutedAccountDiffNotification, SubscriptionError, SubscriptionHandle,
272    SubscriptionRuntimeError, UiAccountConversionError, VenueNotification, account_data_from_ui,
273    subscribe_account_diffs, subscribe_account_diffs_many, subscribe_actions,
274    subscribe_diagnostics, subscribe_program_diffs, subscribe_program_logs, subscribe_replacements,
275};
276#[doc(hidden)]
277pub use transaction_step::{DiscoveryPause, DiscoveryStepResult};
278pub use tx::{TxDecodeError, decode_transaction};
279pub use urls::{UrlError, backtest_ws_url, http_base_from_ws_url, http_to_ws_url};