sim-cli 0.15.0

CLI tool for running and comparing Solana simulator backtests
Documentation
//! Clap argument groups shared across every simulator-driving command on both
//! CLI binaries (`sim`, `backtest-driver`, and its `benchmark` subcommand).
//!
//! Flattening these keeps the flag names, env vars, defaults, help text, and
//! validation identical wherever a command takes a slot range, opens a
//! WebSocket session, or toggles JSON output.

use std::fmt;

use clap::{Args, ValueEnum};
use simulator_api::{BundleKind, RangeScope};

/// Failure validating a slot range supplied on the command line.
#[derive(Debug)]
pub enum SlotRangeError {
    /// A command that requires an explicit range was given neither bound.
    MissingBounds,
    /// `start_slot` exceeded `end_slot`.
    OutOfOrder { start: u64, end: u64 },
}

impl fmt::Display for SlotRangeError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::MissingBounds => f.write_str("--start-slot and --end-slot are required"),
            Self::OutOfOrder { start, end } => {
                write!(
                    f,
                    "--start-slot ({start}) must not exceed --end-slot ({end})"
                )
            }
        }
    }
}

impl std::error::Error for SlotRangeError {}

/// Inclusive `[start, end]` slot bounds. Optional so each command can default
/// or require them while sharing one flag/env spelling and one ordering check.
#[derive(Debug, Clone, Args)]
pub struct SlotBoundsArgs {
    /// First slot (inclusive) to simulate.
    #[arg(long, env = "SIMULATOR_START_SLOT")]
    pub start_slot: Option<u64>,

    /// Last slot (inclusive) to simulate.
    #[arg(long, env = "SIMULATOR_END_SLOT")]
    pub end_slot: Option<u64>,
}

impl SlotBoundsArgs {
    /// Both bounds, validated `start <= end` — for commands that require an
    /// explicit range (no built-in defaults).
    pub fn require(&self) -> Result<(u64, u64), SlotRangeError> {
        match (self.start_slot, self.end_slot) {
            (Some(start), Some(end)) => Self::checked(start, end),
            _ => Err(SlotRangeError::MissingBounds),
        }
    }

    /// Resolve both bounds, falling back to the given defaults for any omitted,
    /// then validate `start <= end`.
    pub fn resolve_or(
        &self,
        default_start: u64,
        default_end: u64,
    ) -> Result<(u64, u64), SlotRangeError> {
        Self::checked(
            self.start_slot.unwrap_or(default_start),
            self.end_slot.unwrap_or(default_end),
        )
    }

    fn checked(start: u64, end: u64) -> Result<(u64, u64), SlotRangeError> {
        if start <= end {
            Ok((start, end))
        } else {
            Err(SlotRangeError::OutOfOrder { start, end })
        }
    }
}

/// Slot range and stepping granularity, shared by every range-driving command.
#[derive(Debug, Clone, Args)]
pub struct SimRangeArgs {
    #[command(flatten)]
    pub bounds: SlotBoundsArgs,

    /// Slots to advance per continue request. Defaults to the whole range — one
    /// request — so a run measures execution rather than per-slot control
    /// round-trips. Lower it only to test finer-grained session stepping.
    #[arg(long, env = "SIMULATOR_ADVANCE_COUNT", value_parser = clap::value_parser!(u64).range(1..))]
    pub advance_count: Option<u64>,
}

impl SimRangeArgs {
    /// Slots to advance per continue request, defaulting to the full `[start,
    /// end]` span so the whole range rides a single request.
    pub fn advance_count(&self, start: u64, end: u64) -> u64 {
        self.advance_count
            .unwrap_or_else(|| end.saturating_sub(start).saturating_add(1))
    }
}

/// What a bundle holds, and so what it can be used for.
#[derive(Copy, Clone, Debug, PartialEq, Eq, ValueEnum)]
pub enum KindFilter {
    /// The transactions a run executes.
    #[value(name = "transactions")]
    Transactions,
    /// The account state `run --replay-account-state` replays.
    #[value(name = "account-state", alias = "account_state")]
    AccountState,
}

impl From<KindFilter> for BundleKind {
    fn from(value: KindFilter) -> Self {
        match value {
            KindFilter::Transactions => Self::Blocks,
            KindFilter::AccountState => Self::AccountState,
        }
    }
}

/// Who a range is available to.
#[derive(Copy, Clone, Debug, PartialEq, Eq, ValueEnum)]
pub enum ScopeFilter {
    /// Ranges available to everyone.
    Global,
    /// Ranges built for your API key.
    User,
}

impl From<ScopeFilter> for RangeScope {
    fn from(value: ScopeFilter) -> Self {
        match value {
            ScopeFilter::Global => Self::Global,
            ScopeFilter::User => Self::User,
        }
    }
}

/// Deployment whose public WebSocket endpoint a session connects to.
#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
pub enum SimEnvironment {
    Local,
    Staging,
    Production,
}

impl SimEnvironment {
    /// Default backtest WebSocket URL for this deployment.
    pub fn websocket_url(self) -> &'static str {
        match self {
            Self::Local => "ws://localhost:8900/backtest",
            Self::Staging => "wss://staging.simulator.termina.technology/backtest",
            Self::Production => "wss://simulator.termina.technology/backtest",
        }
    }
}

impl fmt::Display for SimEnvironment {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            Self::Local => "local",
            Self::Staging => "staging",
            Self::Production => "production",
        })
    }
}

/// WebSocket connection settings shared by the session-driving commands
/// (`backtest-driver` and `benchmark remote`).
#[derive(Debug, Clone, Args)]
pub struct SimConnectionArgs {
    /// Deployment to connect to (ignored when `--websocket-url` is set).
    #[arg(long, env = "SIMULATOR_ENVIRONMENT", default_value_t = SimEnvironment::Staging)]
    pub environment: SimEnvironment,

    /// Explicit WebSocket URL, overriding the `--environment` default.
    #[arg(long, env = "SIMULATOR_WEBSOCKET_URL")]
    pub websocket_url: Option<String>,

    /// Max seconds to wait for runtime capacity to scale out before failing the
    /// create.
    #[arg(long, env = "SIMULATOR_CAPACITY_WAIT_TIMEOUT_SECS")]
    pub capacity_wait_timeout_secs: Option<u16>,
}

impl SimConnectionArgs {
    /// Resolve the WebSocket endpoint: explicit URL wins, else the deployment
    /// default.
    pub fn websocket_endpoint(&self) -> String {
        self.websocket_url
            .clone()
            .unwrap_or_else(|| self.environment.websocket_url().to_string())
    }
}

/// Shared `--json` output toggle. Formats a command's result on stdout and
/// means nothing else, so prompts belong on stderr.
#[derive(Debug, Clone, Copy, Args)]
pub struct JsonOutputArgs {
    /// Print output as JSON.
    #[arg(long)]
    pub json: bool,
}

#[cfg(test)]
mod tests {
    use clap::Parser;

    use super::*;

    #[derive(Parser)]
    struct Harness {
        #[command(flatten)]
        range: SimRangeArgs,
    }

    #[test]
    fn advance_count_rejects_zero() {
        assert!(Harness::try_parse_from(["x", "--advance-count", "0"]).is_err());
    }

    #[test]
    fn advance_count_defaults_to_full_span() {
        let h = Harness::try_parse_from(["x"]).unwrap();
        assert_eq!(h.range.advance_count, None);
        assert_eq!(h.range.advance_count(100, 109), 10);
    }

    #[test]
    fn resolve_or_defaults_then_validates() {
        let unset = Harness::try_parse_from(["x"]).unwrap().range.bounds;
        assert_eq!(unset.resolve_or(5, 10).unwrap(), (5, 10));

        let reversed = Harness::try_parse_from(["x", "--start-slot", "10", "--end-slot", "5"])
            .unwrap()
            .range
            .bounds;
        assert!(reversed.resolve_or(0, 100).is_err());
    }

    #[test]
    fn require_needs_both_bounds_in_order() {
        let only_start = Harness::try_parse_from(["x", "--start-slot", "5"]).unwrap();
        assert!(only_start.range.bounds.require().is_err());

        let reversed =
            Harness::try_parse_from(["x", "--start-slot", "10", "--end-slot", "5"]).unwrap();
        assert!(reversed.range.bounds.require().is_err());

        let ok = Harness::try_parse_from(["x", "--start-slot", "5", "--end-slot", "10"]).unwrap();
        assert_eq!(ok.range.bounds.require().unwrap(), (5, 10));
    }
}