simulator-client 0.31.0

Async WebSocket client for the Solana simulator backtest API
Documentation
use std::collections::{BTreeMap, BTreeSet};

use base64::{Engine as _, engine::general_purpose::STANDARD as BASE64};
use bon::Builder;
use simulator_api::{
    AccountData, AccountModifications, ActionAnchor, ActionKind, BinaryEncoding, ContinueParams,
    CreateBacktestSessionRequest, CreateBacktestSessionRequestV1, CreateSessionParams,
    DiagnosticProbeParams, DiscoveryFilter, RerouteAggregators, RerouteFilter, RerouteParams,
    RerouteScopes, ScheduledAction, VenueTemplate, replay_support,
    session_name::{CreateToken, SessionName},
};
use solana_address::Address;
use solana_client::rpc_client::SerializableTransaction;
use thiserror::Error;

use crate::BacktestClientError;

/// Error serializing a transaction for injection.
#[derive(Debug, Error)]
pub enum SerializeEncodeError {
    /// wincode could not serialize the transaction.
    #[error("wincode serialization error: {0}")]
    Wincode(#[from] wincode::WriteError),
}

/// 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.
///
/// It serializes with wincode, which writes those bytes. bincode does not: it drops a v1
/// transaction's version marker, so the server cannot read it back. Errors only if wincode cannot
/// serialize the transaction.
pub fn encode_transaction(
    transaction: &impl SerializableTransaction,
) -> Result<String, SerializeEncodeError> {
    Ok(BASE64.encode(wincode::serialize(transaction)?))
}

/// Builder for the request that creates a session.
///
/// Set `start_slot` and exactly one of `end_slot` or `slot_count`; every other field has a
/// default. Pass the result to [`crate::ManagedBacktestSession`], or turn it into wire params
/// with [`Self::into_params`].
#[derive(Debug, Clone, Builder)]
pub struct CreateSession {
    #[expect(missing_docs, reason = "self-explanatory builder field")]
    pub start_slot: u64,

    /// Last slot of the range to replay, inclusive. Set this or `slot_count`, not both.
    pub end_slot: Option<u64>,

    /// Slots to advance past `start_slot` (alternative to `end_slot`); the
    /// session replays the inclusive range `[start_slot, start_slot + slot_count]`.
    /// `slot_count = 0` replays just the start slot.
    pub slot_count: Option<u64>,

    /// When true, include a session summary with transaction statistics in the Completed response.
    #[builder(default)]
    pub send_summary: bool,

    /// When true, reroute historical swaps: through the router (see
    /// `reroute_requote`), directly to a venue (see `reroute_venue_templates`), or both.
    ///
    /// Each original swap is priced at its pricing point: `quote_lag_blocks` blocks before the
    /// block it executed in.
    /// - Through the router: it quotes at the pricing point, and the new transaction is
    ///   simulated just before the original swap, in its block.
    /// - Directly to a venue: each probe is simulated at the pricing point.
    /// - Both: the original swap is replayed at the pricing point.
    ///
    /// Every simulation is discarded. The original transactions still run, so the replay is
    /// unchanged. Every other `reroute_*` field needs this.
    #[builder(default)]
    pub reroute_order_flow: bool,

    /// When true, also reroute swaps whose original transaction failed on slippage or after the
    /// swap ran. They are reported apart from the other reroutes. `l1` in the name means the
    /// original (onchain) swap.
    #[builder(default)]
    pub detect_failed_l1_swaps: bool,

    /// Which aggregators' historical swaps to reroute; Jupiter alone by default.
    #[builder(default)]
    pub reroute_aggregators: RerouteAggregators,

    /// Where a swap may have run to be rerouted; top-level router instructions alone by default.
    #[builder(default)]
    pub reroute_scopes: RerouteScopes,

    /// When true, also reroute atomic arbitrage (same input and output mint).
    #[builder(default)]
    pub reroute_circular_arbs: bool,

    /// Restrict rerouting to swaps trading these mint pairs. `sim run` has no flag for this.
    pub reroute_filter: Option<RerouteFilter>,

    /// Templates for rerouting directly to a venue, probed against the hops the session detects.
    #[builder(default)]
    pub reroute_venue_templates: Vec<VenueTemplate>,

    /// When true (the default), reroute through the router. Set it to false to
    /// reroute only directly to a venue, with `reroute_venue_templates`.
    #[builder(default = true)]
    pub reroute_requote: bool,

    /// Pools for the router to consider on top of the markets it already knows. Each must hold
    /// an account at the start of the range; give a pool that exists nowhere onchain its
    /// accounts with [`Self::add_override`] at `start_slot`.
    #[builder(default)]
    pub reroute_extra_markets: BTreeSet<Address>,

    /// Price swaps at their quote slot's end, or just before their own batch in their land slot.
    #[builder(default)]
    pub reroute_quote_late_in_slot: bool,

    /// When true, split the range across concurrent sessions: a parallel run. Start it with
    /// [`crate::managed::ManagedParallelSession`].
    #[builder(default)]
    pub parallel: bool,

    /// Name for the session, or for the whole run when `parallel` is set; the server assigns
    /// one when unset. A name is never reused: one an earlier session already took fails with
    /// [`simulator_api::BacktestError::SessionNameTaken`].
    pub name: Option<SessionName>,

    /// Seconds the server keeps trying to start the session while it has no capacity, before
    /// it fails the create. Unset or 0 fails at once when the server is busy, so set it for any
    /// unattended run; `sim run` uses 900.
    pub capacity_wait_timeout_secs: Option<u16>,

    /// Seconds the server keeps the session alive with no client attached —
    /// the window a reconnecting client has to reattach and resume. Must cover
    /// your retry policy. Unset, the server uses 30 (900 for a parallel run),
    /// and it caps this at 900; 0 ends the session with the connection. For a
    /// single session left unset, [`crate::ManagedBacktestSession`] substitutes
    /// [`crate::managed::DEFAULT_DISCONNECT_TIMEOUT_SECS`] (360).
    pub disconnect_timeout_secs: Option<u16>,

    /// Extra compute units to add to each transaction's SetComputeUnitLimit budget.
    pub extra_compute_units: Option<u32>,

    /// Batch discovery filters registered at session creation. For each
    /// filter, the server emits [`simulator_api::BacktestResponse::DiscoveryBatch`] ahead
    /// of every matching batch.
    #[builder(default)]
    pub discoveries: Vec<DiscoveryFilter>,

    /// Transactions the server runs automatically during the session, with
    /// results streamed over `actionSubscribe`.
    #[builder(default)]
    pub actions: Vec<ScheduledAction>,

    /// When true, apply the account states recorded for this range instead of executing its
    /// transactions, which is faster. The range needs an account-state bundle.
    #[builder(default)]
    pub replay_account_state: bool,

    /// Markets the server probes through the router's `/diagnostic` endpoint, streamed over
    /// `diagnosticSubscribe`. Only `afterSlot` and `afterEverySlot` anchors are supported.
    #[builder(default)]
    pub diagnostic_probes: Vec<DiagnosticProbeParams>,
}

impl CreateSession {
    /// Schedule counterfactual account overrides from `slot` onward, per account until a later
    /// override names that account. Rerouted swaps, account reads by address and the geyser
    /// account stream see them; the replay never does. Requires `reroute_order_flow`.
    #[must_use]
    pub fn add_override(mut self, slot: u64, overrides: AccountModifications) -> Self {
        self.actions.push(ScheduledAction {
            anchor: ActionAnchor::BeforeSlot { slots: vec![slot] },
            kind: ActionKind::default(),
            feeds_reroute: true,
            transactions: Vec::new(),
            account_overrides: overrides,
            return_accounts: Vec::new(),
            label: None,
            resolve: None,
            within: None,
        });
        self
    }

    /// Convert the builder into API parameters.
    ///
    /// # Errors
    ///
    /// [`BacktestClientError::InvalidParams`], before anything is sent, when:
    ///
    /// - both or neither of `end_slot` and `slot_count` are set;
    /// - `start_slot + slot_count` overflows, or `end_slot` is before `start_slot`;
    /// - a diagnostic probe or an action's resolver is invalid;
    /// - a `send` action is scheduled with `replay_account_state` set.
    pub fn into_params(self) -> Result<CreateSessionParams, BacktestClientError> {
        let end_slot = match (self.end_slot, self.slot_count) {
            (Some(_), Some(_)) => {
                return Err(BacktestClientError::InvalidParams {
                    message: "CreateSession: set only one of end_slot or slot_count".to_string(),
                });
            }
            (Some(end_slot), None) => end_slot,
            (None, Some(slot_count)) => {
                self.start_slot.checked_add(slot_count).ok_or_else(|| {
                    BacktestClientError::InvalidParams {
                        message: "CreateSession: start_slot + slot_count overflow".to_string(),
                    }
                })?
            }
            (None, None) => {
                return Err(BacktestClientError::InvalidParams {
                    message: "CreateSession: must set end_slot or slot_count".to_string(),
                });
            }
        };

        if end_slot < self.start_slot {
            return Err(BacktestClientError::InvalidParams {
                message: format!(
                    "CreateSession: end_slot ({end_slot}) must be >= start_slot ({})",
                    self.start_slot
                ),
            });
        }

        let params = CreateSessionParams::builder()
            .start_slot(self.start_slot)
            .end_slot(end_slot)
            .send_summary(self.send_summary)
            .maybe_reroute(self.reroute_order_flow.then_some(RerouteParams {
                aggregators: self.reroute_aggregators,
                scopes: self.reroute_scopes,
                filter: self.reroute_filter,
                detect_failed_l1_swaps: self.detect_failed_l1_swaps,
                circular_arbs: self.reroute_circular_arbs,
                requote: self.reroute_requote,
                venue_templates: self.reroute_venue_templates,
                extra_markets: self.reroute_extra_markets,
                quote_late_in_slot: self.reroute_quote_late_in_slot,
            }))
            .maybe_capacity_wait_timeout_secs(self.capacity_wait_timeout_secs)
            .maybe_disconnect_timeout_secs(self.disconnect_timeout_secs)
            .maybe_extra_compute_units(self.extra_compute_units)
            .discoveries(self.discoveries)
            .actions(self.actions)
            .replay_account_state(self.replay_account_state)
            .diagnostic_probes(self.diagnostic_probes)
            .build();

        // Same reason as the send-action check below: caught here to save the round trip, and
        // enforced again by the session itself.
        if let Err(error) = params.validate_diagnostic_probes() {
            return Err(BacktestClientError::InvalidParams {
                message: error.to_string(),
            });
        }
        params
            .validate_action_resolvers()
            .map_err(|error| BacktestClientError::InvalidParams {
                message: error.to_string(),
            })?;

        // Caught here purely to save the round trip; the manager and the session
        // enforce the same rule through the same wording.
        match replay_support::send_action_conflict(&params) {
            Some(message) => Err(BacktestClientError::InvalidParams { message }),
            None => Ok(params),
        }
    }

    /// Convert the builder into a versioned create request.
    ///
    /// Emits the V1 request when `parallel` or `name` is set, and V0 otherwise. With a `name`,
    /// each call generates a new create token, which marks a resent request as the same create.
    /// To retry, resend the returned request: a rebuilt one fails with
    /// [`simulator_api::BacktestError::SessionNameTaken`] once the first has taken the name.
    ///
    /// # Errors
    ///
    /// As [`Self::into_params`].
    pub fn into_request(mut self) -> Result<CreateBacktestSessionRequest, BacktestClientError> {
        let parallel = self.parallel;
        let (name, create_token) = self
            .name
            .take()
            .map(|name| (name.to_string(), CreateToken::random()))
            .unzip();
        let request = self.into_params()?;
        if parallel || name.is_some() {
            Ok(CreateBacktestSessionRequestV1 {
                request,
                parallel,
                name,
                create_token,
            }
            .into())
        } else {
            Ok(request.into())
        }
    }
}

/// Builder for a `continue` request.
///
/// Use it to advance the session, run user transactions, or apply account overrides. The server
/// runs the user transactions first, then writes the overrides, then executes the blocks.
#[derive(Debug, Builder)]
pub struct Continue {
    /// Blocks to execute before the session waits again. Default 1. A skipped slot has no
    /// block and is not counted.
    #[builder(default = ContinueParams::default_advance_count())]
    pub advance_count: u64,

    /// User transactions to run before advancing, each the standard base64 of the transaction's
    /// wire bytes. Add them with [`Self::push_transaction`], which encodes for you.
    #[builder(default)]
    pub transactions: Vec<String>,

    /// Account overrides, written after the user transactions and before the first block.
    #[builder(default)]
    pub modify_accounts: BTreeMap<Address, AccountData>,
}

impl Continue {
    /// Append a transaction that is already encoded as [`encode_transaction`] does.
    #[must_use]
    pub fn push_transaction_base64(mut self, data: impl Into<String>) -> Self {
        self.transactions.push(data.into());
        self
    }

    /// Append a transaction's wire bytes, encoding them as base64.
    #[must_use]
    pub fn push_transaction_bytes(mut self, bytes: &[u8]) -> Self {
        self.transactions.push(BinaryEncoding::Base64.encode(bytes));
        self
    }

    /// Append a transaction, encoded with [`encode_transaction`].
    ///
    /// # Errors
    ///
    /// [`SerializeEncodeError`] if wincode cannot serialize the transaction.
    pub fn push_transaction(
        mut self,
        transaction: &impl SerializableTransaction,
    ) -> Result<Self, SerializeEncodeError> {
        self.transactions.push(encode_transaction(transaction)?);
        Ok(self)
    }

    /// Override one account's state, as an entry of `modify_accounts`.
    #[must_use]
    pub fn modify_account(mut self, address: Address, account: AccountData) -> Self {
        self.modify_accounts.insert(address, account);
        self
    }

    /// Convert the builder into API parameters.
    pub fn into_params(self) -> ContinueParams {
        ContinueParams {
            advance_count: self.advance_count,
            transactions: self.transactions,
            modify_account_states: AccountModifications(self.modify_accounts),
        }
    }
}