sim-cli 0.24.0

CLI tool for running and comparing Solana simulator backtests
Documentation
use clap::Parser;
use eyre::Result;
use sim_cli::args::{JsonOutputArgs, KindFilter, ScopeFilter};
use simulator_api::RangeScope;
use simulator_client::{RangeBound, filter_ranges};

const SIZE_TOLERANCE: f64 = 0.1;

const RANGES_EXAMPLES: &str = "\
Examples:
  sim ranges
  sim ranges --after 2026-09-01 --before 2026-09-30

  # Ranges `sim run --replay-account-state` can replay: it applies each slot's
  # account deltas instead of executing its transactions, about 20x faster.
  sim ranges --kind account-state

  # Ranges built for your API key, as JSON.
  sim ranges --scope user --json

Columns:
  Start Slot   pass it to `sim run --start-slot` as printed
  End Slot     the last slot a run starting at Start Slot can reach
  Bundle Size  the range's length in slots
  unbounded    the server reported no end slot for the range";

#[derive(Parser, Debug, Clone)]
#[command(after_help = RANGES_EXAMPLES)]
pub struct RangesArgs {
    /// Only show ranges that start at or after this point.
    /// Accepts a slot number or a timestamp (RFC 3339 or YYYY-MM-DD).
    #[arg(long)]
    pub after: Option<String>,

    /// Your simulator API key; needed to list the ranges built for it.
    #[arg(long, env = "SIMULATOR_API_KEY", hide_env_values = true)]
    pub api_key: Option<String>,

    /// Only show ranges that end at or before this point.
    /// Accepts a slot number or a timestamp (RFC 3339 or YYYY-MM-DD).
    #[arg(long)]
    pub before: Option<String>,

    /// Only show ranges of this kind.
    #[arg(long, value_enum)]
    pub kind: Option<KindFilter>,

    /// Only show ranges with this availability.
    #[arg(long, value_enum)]
    pub scope: Option<ScopeFilter>,

    /// Only show ranges whose bundle size is within 10% of this value.
    #[arg(long)]
    pub size: Option<u64>,

    #[command(flatten)]
    pub output: JsonOutputArgs,
}

pub async fn ranges(args: RangesArgs, url: String) -> Result<()> {
    let after: Option<RangeBound> = args.after.as_deref().map(str::parse).transpose()?;
    let before: Option<RangeBound> = args.before.as_deref().map(str::parse).transpose()?;

    let client = sim_cli::client::new(&url, args.api_key.as_deref().unwrap_or_default());
    // Skip the extra owner listing when a filter already excludes its rows.
    let all = match args.kind {
        Some(KindFilter::Transactions) => client.available_ranges().await?,
        _ => client.available_ranges_with_account_state().await?,
    };
    let time_bound = filter_ranges(&all, after.as_ref(), before.as_ref());
    let matched: Vec<_> = time_bound
        .into_iter()
        .filter(|r| {
            args.size.is_none_or(|target| {
                r.max_bundle_size.is_some_and(|size| {
                    let delta = (size as f64 - target as f64).abs();
                    delta / target as f64 <= SIZE_TOLERANCE
                })
            })
        })
        // An unlabelled range (older server) matches no explicit filter.
        .filter(|r| args.kind.is_none_or(|kind| r.kind == Some(kind.into())))
        .filter(|r| args.scope.is_none_or(|scope| r.scope == Some(scope.into())))
        .collect();

    if matched.is_empty() {
        if args.output.json {
            println!("[]");
        } else {
            println!("No available ranges matching the given filters.");
        }
        return Ok(());
    }

    if args.output.json {
        println!("{}", serde_json::to_string_pretty(&matched)?);
        return Ok(());
    }

    println!(
        "\n{:<30} {:<30} {:<15} {:<15} {:<15} {:<15} Scope",
        "Start Time (UTC)", "End Time (UTC)", "Start Slot", "End Slot", "Bundle Size", "Kind"
    );
    println!("{}", "-".repeat(130));
    for range in &matched {
        let start_time = range.bundle_start_slot_utc.as_deref().unwrap_or("-");
        let end_time = range.max_bundle_end_slot_utc.as_deref().unwrap_or("-");
        let start_slot = range.bundle_start_slot;
        let end_slot = range
            .max_bundle_end_slot
            .map_or_else(|| "unbounded".to_string(), |slot| slot.to_string());
        let bundle_size = range
            .max_bundle_size
            .map_or_else(|| "unbounded".to_string(), |size| size.to_string());
        let kind = range
            .kind
            .map_or_else(|| "-".to_string(), |kind| kind.to_string());
        let scope = range.scope.map_or("-", RangeScope::as_str);
        println!(
            "{start_time:<30} {end_time:<30} {start_slot:<15} {end_slot:<15} {bundle_size:<15} {kind:<15} {scope}"
        );
    }

    Ok(())
}

#[cfg(test)]
mod tests {
    use simulator_api::BundleKind;

    use super::*;

    #[test]
    fn api_key_is_optional_and_flows_when_given() {
        let args = RangesArgs::try_parse_from(["ranges", "--api-key", "k"]).unwrap();
        assert_eq!(args.api_key, Some("k".to_string()));
    }

    #[test]
    fn api_key_can_be_omitted() {
        let args = RangesArgs::try_parse_from(["ranges", "--json"]).unwrap();
        assert_eq!(args.api_key, None);
    }

    #[test]
    fn kind_and_scope_filters_parse_and_default_to_unset() {
        let args = RangesArgs::try_parse_from(["ranges"]).unwrap();
        assert_eq!(args.kind, None);
        assert_eq!(args.scope, None);

        let args =
            RangesArgs::try_parse_from(["ranges", "--kind", "account-state", "--scope", "user"])
                .unwrap();
        assert_eq!(args.kind, Some(KindFilter::AccountState));
        assert_eq!(args.scope, Some(ScopeFilter::User));
    }

    #[test]
    fn kind_filter_accepts_the_spelling_the_table_prints() {
        // The Kind column and `sim bundle status` both print `account_state`;
        // typing back what you read has to work.
        let args = RangesArgs::try_parse_from(["ranges", "--kind", "account_state"]).unwrap();
        assert_eq!(args.kind, Some(KindFilter::AccountState));
    }

    #[test]
    fn kind_filter_rejects_the_wire_spelling_of_blocks() {
        assert!(RangesArgs::try_parse_from(["ranges", "--kind", "blocks"]).is_err());
    }

    #[test]
    fn filters_map_onto_the_wire_kinds_the_table_labels() {
        assert_eq!(
            BundleKind::from(KindFilter::Transactions).to_string(),
            "transactions"
        );
        assert_eq!(
            BundleKind::from(KindFilter::AccountState).to_string(),
            "account_state"
        );
        assert_eq!(RangeScope::from(ScopeFilter::Global).as_str(), "global");
        assert_eq!(RangeScope::from(ScopeFilter::User).as_str(), "user");
    }
}