sim-cli 0.13.0

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

const SIZE_TOLERANCE: f64 = 0.1;

#[derive(Parser, Debug, Clone)]
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>,

    /// API key for authentication
    #[arg(long, env = "SIMULATOR_API_KEY")]
    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_builder = BacktestClient::builder().url(url);
    let client = if let Some(api_key) = args.api_key.clone() {
        client_builder.api_key(api_key).build()
    } else {
        client_builder.build()
    };
    // 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 = format_slot(range.bundle_start_slot);
        let end_slot = range
            .max_bundle_end_slot
            .map(format_slot)
            .unwrap_or_else(|| "unbounded".to_string());
        let bundle_size = range
            .max_bundle_size
            .map(format_slot)
            .unwrap_or_else(|| "unbounded".to_string());
        let kind = range.kind.map_or("-", kind_label);
        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(())
}

/// Spelled for the reader, not the wire: `blocks` names the artifact rather
/// than what it holds.
fn kind_label(kind: BundleKind) -> &'static str {
    match kind {
        BundleKind::Blocks => "transactions",
        BundleKind::AccountState => "account_state",
    }
}

#[cfg(test)]
mod tests {
    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 build-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),
            BundleKind::Blocks
        );
        assert_eq!(kind_label(KindFilter::Transactions.into()), "transactions");
        assert_eq!(kind_label(KindFilter::AccountState.into()), "account_state");
        assert_eq!(RangeScope::from(ScopeFilter::Global).as_str(), "global");
        assert_eq!(RangeScope::from(ScopeFilter::User).as_str(), "user");
    }
}