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 and reattach 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.29.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 server has created the session. 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. Resends the last slot it delivered: dedupe transactions by signature, account diffs by (signature, account, slot) | 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 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`] |
178//! | `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) |
179//! | `ControlFailed`, `SubscriptionFailed` | A connection ran out of retries | Start a new session | Yes |
180//! | `ControlClosed`, `ContinueSend` | The session is over | Stop | No |
181//! | `Cancelled` | Your cancellation token fired, or the parallel run was shut down | Stop | No |
182//! | `CompletedBeforeReady` | The session finished before its first pause | Check the range and the create request | No |
183//!
184//! [`ManagedEvent::Error`] from `next_event` is terminal when
185//! [`BacktestError::is_terminal`](simulator_api::BacktestError::is_terminal) is true: stop. Any
186//! other error leaves the session running. A [`BacktestClient`] call fails with a
187//! [`BacktestClientError`]; [`BacktestClientError::is_retryable`] says whether to retry it.
188//!
189//! # Connection drops
190//!
191//! The session runs on the server and outlives its connections, unless `disconnect_timeout_secs`
192//! is 0. A managed session retries a dropped connection up to [`managed::RECONNECT_MAX_ATTEMPTS`]
193//! times within [`managed::RECONNECT_MAX_TOTAL`], reattaches, and the server replays the responses
194//! you missed.
195//!
196//! # Timeouts
197//!
198//! | What | Default | Change it with |
199//! |---|---|---|
200//! | Waiting for server capacity at create | None: fails at once when the server is busy | [`CreateSession::capacity_wait_timeout_secs`] |
201//! | 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`] |
202//! | Managed reconnect budget per connection | 20 attempts within 5 minutes | Fixed |
203//! | Managed connect / handshake | 30 s / 120 s | Fixed |
204//! | Wait for notifications after `Completed` | 60 s without one | [`ManagedBacktestSession::set_completion_drain_timeout`] |
205//!
206//! # Logging
207//!
208//! The crate logs through [`tracing`](https://docs.rs/tracing). Install a subscriber, as in the
209//! quickstart (`tracing-subscriber` with its `env-filter` feature), and set `RUST_LOG`:
210//!
211//! - `RUST_LOG=simulator_client=info` shows session creation, reconnects and retries.
212//! - `RUST_LOG=simulator_client=debug` adds reattaches.
213//!
214//! # Troubleshooting
215//!
216//! | Symptom | Cause | Fix |
217//! |---|---|---|
218//! | `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 |
219//! | `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` |
220//! | `session create failed: ... insufficient capacity` | The server is busy | Set `capacity_wait_timeout_secs` (`sim run` uses 900), or retry later |
221//! | `ControlFailed` from a managed session | The session ended, or its `disconnect_timeout_secs` passed | Start a new session; raise `disconnect_timeout_secs` |
222//! | `clerk error` when creating a session | The server could not load the range's historical data | Retry later |
223//! | Panic: `Could not automatically determine the process-level CryptoProvider` | Two rustls providers are linked | Install one: see [TLS](#tls) |
224//! | 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 |
225//! | No log output | No `tracing` subscriber installed | See [Logging](#logging) |
226
227#![forbid(unsafe_code)]
228#![warn(missing_docs)]
229
230pub mod balances;
231mod builders;
232mod client;
233mod error;
234pub mod geyser;
235pub mod injection;
236pub mod managed;
237mod ranges;
238pub mod recipes;
239pub mod reroute_report;
240pub mod rpc;
241mod session;
242pub mod subscriptions;
243mod transaction_step;
244mod tx;
245pub mod urls;
246
247pub use builders::{Continue, CreateSession, SerializeEncodeError, encode_transaction};
248pub use client::BacktestClient;
249pub use error::{BacktestClientError, BacktestClientResult};
250pub use geyser::SessionGeyserChannel;
251pub use injection::{ProgramModError, build_program_injection, modify_program_via_rpc};
252pub use managed::{
253    ControlEvent, CreateError, ManagedBacktestSession, ManagedEvent, ManagedSessionError,
254};
255pub use ranges::{ParseRangeBoundError, RangeBound, filter_ranges};
256#[doc(hidden)]
257pub use session::{
258    AdvanceState, BacktestSession, ContinueResult, CoverageError, ReadyOutcome, SessionCoverage,
259};
260pub use simulator_api::{
261    self, Address, AvailableRange, BundleBuildStatus, BundleKind, ContinueToParams,
262    DatasetCredentialsResponse, DepthCoverageResponse, DepthGranularity, DepthRequest, DepthSource,
263    DepthStatusResponse, DiscoveryFilter, NonEmptyAccounts, ParseAddressError,
264    SnapshotSlotResponse, SwapMode, TakerSlots, TemplateAccount, TemplateInstruction,
265    VenueTemplate,
266    route_plan::{self, FULL_PERCENT, RouteHop, RoutePlan},
267    split_range,
268    subscribe_config::{Compression, SubscribeConfig},
269    usage::{
270        ComputeTotals, SessionCounts, SessionUsage, SessionUsagePage, UsageBucket, UsageReport,
271    },
272};
273pub use subscriptions::{
274    AccountDiffContext, AccountDiffNotification, AccountDiffSubscriptionHandle,
275    ActionResultContext, ActionResultNotification, ActionSubscriptionHandle,
276    ActionTransactionOutcome, DiagnosticContext, DiagnosticNotification,
277    DiagnosticSubscriptionHandle, L1Score, LogSubscriptionHandle, OriginalNotification, ProbedHop,
278    ReplacementContext, ReplacementCore, ReplacementNotification, RequoteNotification,
279    RerouteLegNotification, RoutedAccountDiffNotification, SubscriptionError, SubscriptionHandle,
280    SubscriptionRuntimeError, UiAccountConversionError, VenueNotification, account_data_from_ui,
281    subscribe_account_diffs, subscribe_account_diffs_many, subscribe_actions,
282    subscribe_diagnostics, subscribe_program_diffs, subscribe_program_logs, subscribe_replacements,
283};
284#[doc(hidden)]
285pub use transaction_step::{DiscoveryPause, DiscoveryStepResult};
286pub use tx::{TxDecodeError, decode_transaction};
287pub use urls::{UrlError, backtest_ws_url, http_base_from_ws_url, http_to_ws_url};