simulator-client 0.24.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, DirectFillTemplate, DiscoveryFilter, RerouteAggregators, RerouteFilter,
    RerouteParams, ScheduledAction, replay_support,
};
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 {
    #[error("wincode serialization error: {0}")]
    Wincode(#[from] wincode::WriteError),
}

// wincode is the serializer 4.2's transaction types carry; its bytes are the legacy short-vec
// bincode wire format, so the base64 payload is unchanged.
fn serialize_to_base64(
    transaction: &impl SerializableTransaction,
) -> Result<String, SerializeEncodeError> {
    Ok(BASE64.encode(wincode::serialize(transaction)?))
}

/// Builder for `CreateBacktestSession`.
///
/// Set either `end_slot` or `slot_count` (not both). Use the helper methods to
/// add account filters.
#[derive(Debug, Clone, Builder)]
pub struct CreateSession {
    pub start_slot: u64,

    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>,

    #[builder(default)]
    pub signer_filter: BTreeSet<Address>,

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

    /// When true, replace historical swaps with transactions re-quoted through the
    /// metis router against the current simulation state.
    #[builder(default)]
    pub reroute_order_flow: bool,

    /// When true, also re-quote swaps whose L1 transaction failed in a way re-quoting can
    /// answer. Tracked as a separate population from the headline reroute funnel.
    #[builder(default)]
    pub detect_failed_l1_swaps: bool,

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

    /// When true, also re-quote arbitrage cycles (same input and output mint).
    #[builder(default)]
    pub reroute_circular_arbs: bool,

    /// Restrict rerouting to swaps trading these mint pairs.
    pub reroute_filter: Option<RerouteFilter>,

    /// Direct-fill templates to probe against the hops the run detects.
    #[builder(default)]
    pub reroute_direct_fill: Vec<DirectFillTemplate>,

    /// Re-quote through metis. Off runs `reroute_direct_fill` alone, with no sidecar.
    #[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 on chain its
    /// accounts with [`Self::add_override`] at `start_slot`.
    #[builder(default)]
    pub reroute_extra_markets: BTreeSet<Address>,

    /// When true, ask manager to create all available sessions in the target epoch.
    #[builder(default)]
    pub parallel: bool,

    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: the server's own default is tens of seconds, and it
    /// caps this at 900. Left unset, [`crate::ManagedBacktestSession`]
    /// substitutes [`crate::managed::DEFAULT_DISCONNECT_TIMEOUT_SECS`].
    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 [`BacktestResponse::DiscoveryBatch`] ahead
    /// of every matching batch so the caller can pause via
    /// [`BacktestSession::advance_to_discovery`] before it executes.
    #[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, replay the account states for this range instead of
    /// executing transactions (state-only acceleration).
    #[builder(default)]
    pub replay_account_state: bool,

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

impl CreateSession {
    /// Add an account to the signer filter.
    pub fn add_signer_filter(mut self, address: Address) -> Self {
        self.signer_filter.insert(address);
        self
    }

    /// 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`.
    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,
        });
        self
    }

    /// Convert the builder into API parameters, validating slot options.
    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)
            .signer_filter(self.signer_filter)
            .send_summary(self.send_summary)
            .maybe_reroute(self.reroute_order_flow.then_some(RerouteParams {
                aggregators: self.reroute_aggregators,
                filter: self.reroute_filter,
                detect_failed_l1_swaps: self.detect_failed_l1_swaps,
                circular_arbs: self.reroute_circular_arbs,
                requote: self.reroute_requote,
                direct_fill: self.reroute_direct_fill,
                extra_markets: self.reroute_extra_markets,
            }))
            .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(),
            });
        }

        // 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 versioned create request payload.
    pub fn into_request(self) -> Result<CreateBacktestSessionRequest, BacktestClientError> {
        let parallel = self.parallel;
        let request = self.into_params()?;
        if parallel {
            Ok(CreateBacktestSessionRequestV1 { request, parallel }.into())
        } else {
            Ok(request.into())
        }
    }
}

/// Builder for `Continue` requests.
///
/// Use this to advance the simulation, inject transactions, or patch accounts.
#[derive(Debug, Builder)]
pub struct Continue {
    #[builder(default = ContinueParams::default_advance_count())]
    pub advance_count: u64,

    #[builder(default)]
    pub transactions: Vec<String>,

    #[builder(default)]
    pub modify_accounts: BTreeMap<Address, AccountData>,
}

impl Continue {
    /// Append a base64-encoded transaction payload.
    pub fn push_transaction_base64(mut self, data: impl Into<String>) -> Self {
        self.transactions.push(data.into());
        self
    }

    /// Append a raw transaction payload encoded as base64.
    pub fn push_transaction_bytes(mut self, bytes: &[u8]) -> Self {
        self.transactions.push(BinaryEncoding::Base64.encode(bytes));
        self
    }

    /// Append a serializable transaction encoded as base64.
    pub fn push_transaction(
        mut self,
        transaction: &impl SerializableTransaction,
    ) -> Result<Self, SerializeEncodeError> {
        self.transactions.push(serialize_to_base64(transaction)?);
        Ok(self)
    }

    /// Modify an account state prior to execution.
    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),
        }
    }
}