simulator-client 0.31.0

Async WebSocket client for the Solana simulator backtest API
Documentation
//! 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 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](https://github.com/nitro-svm/examples).
//! Start with [`hello_session`](https://github.com/nitro-svm/examples/tree/main/src/bin/hello_session).
//!
//! # Install
//!
//! ```toml
//! [dependencies]
//! simulator-client = "0.31.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:
//!
//! ```no_run
//! 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:
//!
//! ```no_run
//! 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 session is created and ready. Its
//!    [`session_info`](ManagedBacktestSession::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`](ManagedBacktestSession::next_event). `Status` updates come
//!    first while the session starts.
//! 4. On [`ManagedEvent::ReadyForContinue`] the session is paused. Read or change state through
//!    [`rpc`](ManagedBacktestSession::rpc), then call
//!    [`send_continue`](ManagedBacktestSession::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`](ManagedBacktestSession::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`](ManagedBacktestSession::shutdown) closes the session on the server. Dropping
//!    the session cancels it without waiting.
//!
//! [`wait_until_ready`](ManagedBacktestSession::wait_until_ready) and
//! [`run_to_completion`](ManagedBacktestSession::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 | [`ManagedEvent`]s from `next_event` | Your callback, on a background task | Yours |
//! | Reconnect | Yes. See [Connection drops](managed#connection-drops) for the duplicates | 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 create failed. See [`CreateError`] | Retry later, fix the request, or upgrade this crate | When [`CreateError::is_retryable`] |
//! | `SessionTokenRejected` | The session's endpoint refused the token, at the first attach or later | Start a new session | Yes |
//! | `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) |
//! | `ControlFailed` | The control channel used up its reconnect budget, or the session ended | Start a new session | Yes |
//! | `SubscriptionFailed` | A subscription ran out of retries | Start a new session | Yes |
//! | `ControlClosed`, `ContinueSend` | The session is over: it completed, or the server sent a terminal error (that error comes first from `next_event`) | 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`](simulator_api::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.
//!
//! # 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`] |
//! | Wait for notifications after `Completed` | 60 s without one | [`ManagedBacktestSession::set_completion_drain_timeout`] |
//!
//! # Logging
//!
//! The crate logs through [`tracing`](https://docs.rs/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 each reconnect attempt.
//!
//! # 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 |
//! | `clerk error` when creating a session | The server could not load the range's historical data | Retry later |
//! | `ControlFailed` from a managed session | The session ended, or its `disconnect_timeout_secs` passed | Start a new session; raise `disconnect_timeout_secs` |
//! | Panic: `Could not automatically determine the process-level CryptoProvider` | Two rustls providers are linked | Install one: see [TLS](#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](#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 |

#![forbid(unsafe_code)]
#![warn(missing_docs)]

pub mod balances;
mod builders;
mod client;
mod endpoint;
mod error;
pub mod geyser;
pub mod injection;
pub mod managed;
mod ranges;
pub mod recipes;
pub mod reroute_report;
pub mod rpc;
mod session;
pub mod subscriptions;
mod transaction_step;
mod tx;
pub mod urls;

pub use builders::{Continue, CreateSession, SerializeEncodeError, encode_transaction};
pub use client::BacktestClient;
pub use error::{BacktestClientError, BacktestClientResult};
pub use geyser::SessionGeyserChannel;
pub use injection::{ProgramModError, build_program_injection, modify_program_via_rpc};
pub use managed::{
    ControlEvent, CreateError, ManagedBacktestSession, ManagedEvent, ManagedSessionError,
};
pub use ranges::{ParseRangeBoundError, RangeBound, filter_ranges};
#[doc(hidden)]
pub use session::{
    AdvanceState, BacktestSession, ContinueResult, CoverageError, ReadyOutcome, SessionCoverage,
};
pub use simulator_api::{
    self, Address, AvailableRange, BundleBuildStatus, BundleKind, ContinueToParams,
    DatasetCredentialsResponse, DepthGranularity, DepthSource, DepthUniverseResponse,
    DiscoveryFilter, NonEmptyAccounts, ParseAddressError, SnapshotSlotResponse, SwapMode,
    TakerSlots, TemplateAccount, TemplateInstruction, VenueTemplate,
    route_plan::{self, FULL_PERCENT, RouteHop, RoutePlan},
    split_range,
    subscribe_config::{Compression, SubscribeConfig},
    usage::{
        ComputeTotals, SessionCounts, SessionUsage, SessionUsagePage, UsageBucket, UsageReport,
    },
};
pub use subscriptions::{
    AccountDiffContext, AccountDiffNotification, AccountDiffSubscriptionHandle,
    ActionResultContext, ActionResultNotification, ActionSubscriptionHandle,
    ActionTransactionOutcome, DiagnosticContext, DiagnosticNotification,
    DiagnosticSubscriptionHandle, L1Score, LogSubscriptionHandle, OriginalNotification, ProbedHop,
    ReplacementContext, ReplacementCore, ReplacementNotification, RequoteNotification,
    RerouteLegNotification, RoutedAccountDiffNotification, SubscriptionError, SubscriptionHandle,
    SubscriptionRuntimeError, UiAccountConversionError, VenueNotification, account_data_from_ui,
    subscribe_account_diffs, subscribe_account_diffs_many, subscribe_actions,
    subscribe_diagnostics, subscribe_program_diffs, subscribe_program_logs, subscribe_replacements,
};
#[doc(hidden)]
pub use transaction_step::{DiscoveryPause, DiscoveryStepResult};
pub use tx::{TxDecodeError, decode_transaction};
pub use urls::{UrlError, backtest_ws_url, http_base_from_ws_url, http_to_ws_url};