simulator-client 0.22.1

Async WebSocket client for the Solana simulator backtest API
Documentation
//! The reroute-report core fed from `rerouteSubscribe` notifications. The computation —
//! records, pricing, the report itself — lives in [`simulator_api::reroute_report`]; this
//! module only maps the wire shape onto it.
//!
//! ```no_run
//! # use simulator_client::{RerouteNotification, reroute_report::{self, Target}};
//! # fn example(notifications: &[RerouteNotification]) -> Result<(), Box<dyn std::error::Error>> {
//! let target = Target::new(Some("BisonFi".to_string()), None);
//! let report = reroute_report::from_notifications(target, notifications)?;
//! println!("{}", report.render(None));
//! # Ok(()) }
//! ```

use futures::{Stream, StreamExt};
use simulator_api::mints;
pub use simulator_api::{
    mints::short_mint,
    reroute_report::{
        Direction, Flow, LegRecord, Pair, Report, ReportBuilder, RerouteReportError, SwapMode,
        Target,
    },
};

use crate::{RerouteLegNotification, RerouteNotification};

/// One record per leg. Notification-level facts (error, signature, the original's realized
/// output) repeat onto each; the original's output attaches only when the notification has a
/// single leg, since a multi-swap total is nobody's single leg.
pub fn leg_records(notification: &RerouteNotification) -> Vec<LegRecord> {
    let sole_leg = notification.legs.len() == 1;
    notification
        .legs
        .iter()
        .map(|leg| leg_record(notification, leg, sole_leg))
        .collect()
}

fn leg_record(
    notification: &RerouteNotification,
    leg: &RerouteLegNotification,
    sole_leg: bool,
) -> LegRecord {
    LegRecord {
        original_signature: notification.original_signature.clone(),
        input_mint: mints::parse_mint(&leg.input_mint),
        output_mint: mints::parse_mint(&leg.output_mint),
        amount: leg.amount,
        swap_mode: SwapMode::parse(&leg.swap_mode),
        failed: notification.err.is_some(),
        original_failed: notification.original_failed,
        realized_output_amount: notification.realized_output_amount,
        original_realized_output_amount: sole_leg
            .then_some(notification.original_realized_output_amount)
            .flatten(),
        route_plan: leg.route_plan.clone(),
        original_route_plan: leg.original_route_plan.clone(),
        realized_route_plan: leg.realized_route_plan.clone(),
    }
}

/// Build from anything that yields notifications — a slice, a `Vec`, a lazily-parsed file.
pub fn from_notifications<'a>(
    target: Target,
    notifications: impl IntoIterator<Item = &'a RerouteNotification>,
) -> Result<Report, RerouteReportError> {
    let mut builder = ReportBuilder::new(target);
    for notification in notifications {
        for record in leg_records(notification) {
            builder.push(&record);
        }
    }
    builder.finish()
}

/// Build from a live stream, holding no more than [`ReportBuilder`] does.
pub async fn from_stream(
    target: Target,
    stream: impl Stream<Item = RerouteNotification>,
) -> Result<Report, RerouteReportError> {
    let mut builder = ReportBuilder::new(target);
    let mut stream = std::pin::pin!(stream);
    while let Some(notification) = stream.next().await {
        for record in leg_records(&notification) {
            builder.push(&record);
        }
    }
    builder.finish()
}

#[cfg(test)]
mod tests {
    use simulator_api::route_plan::{RouteHop, RouteHopSwapInfo, RoutePlan};

    use super::*;

    const SOL: &str = "So11111111111111111111111111111111111111112";
    const USDC: &str = "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v";
    const VENUE_PROGRAM: &str = "BiSoNHVpsVZW2F7rx2eQ59yQwKxzU5NvBcmKshCSUypi";
    const OTHER_PROGRAM: &str = "whirLbMiicVdio4qvUfM5KAg6Ct8VwpYzGff3uctyCc";

    // ── Fixtures ─────────────────────────────────────────────────────────────
    // The notification is deserialized from its own encoding, so a serde rename fails the test.

    /// A program makes it a fill; without one, a quote naming a pool.
    fn hop(
        program: Option<&str>,
        label: &str,
        input_mint: &str,
        output_mint: &str,
        in_amount: u64,
    ) -> RouteHop {
        RouteHop {
            program: program.map(str::to_string),
            swap_info: RouteHopSwapInfo {
                label: Some(label.to_string()),
                amm_key: program.is_none().then(|| "pool".to_string()),
                input_mint: Some(input_mint.to_string()),
                in_amount: Some(in_amount.to_string()),
                output_mint: Some(output_mint.to_string()),
                out_amount: None,
            },
            ..RouteHop::default()
        }
    }

    fn plan(hops: Vec<RouteHop>) -> Option<RoutePlan> {
        RoutePlan::new(hops)
    }

    /// The mints and amount decide which direction the leg lands in.
    fn leg_of(
        input_mint: &str,
        output_mint: &str,
        amount: u64,
        quoted: Option<RoutePlan>,
        original: Option<RoutePlan>,
        realized: Option<RoutePlan>,
    ) -> RerouteLegNotification {
        serde_json::from_value(serde_json::json!({
            "inputMint": input_mint,
            "outputMint": output_mint,
            "amount": amount,
            "swapMode": "ExactIn",
            "originalQuotedOut": 0,
            "metisQuotedOut": 0,
            "routeSummary": "",
            "routePlan": quoted,
            "originalRoutePlan": original,
            "realizedRoutePlan": realized,
        }))
        .expect("a leg fixture decodes")
    }

    /// A notification wrapping `legs`, landed on both sides unless told otherwise.
    struct Notification {
        legs: Vec<RerouteLegNotification>,
        err: Option<String>,
        original_failed: bool,
        original_realized_output_amount: Option<u64>,
    }

    impl Notification {
        fn new(legs: Vec<RerouteLegNotification>) -> Self {
            Self {
                legs,
                err: None,
                original_failed: false,
                original_realized_output_amount: None,
            }
        }

        /// A routeless swap, the shape pricing reads.
        fn swap(input_mint: &str, output_mint: &str, amount: u64, output: u64) -> Self {
            let leg = leg_of(input_mint, output_mint, amount, None, None, None);
            Self {
                original_realized_output_amount: Some(output),
                ..Self::new(vec![leg])
            }
        }

        /// The simulation reverted.
        fn reverted(mut self) -> Self {
            self.err = Some("reverted".to_string());
            self
        }

        /// The original failed on L1, so its route events are not flow the venue served.
        fn original_failed(mut self) -> Self {
            self.original_failed = true;
            self
        }

        fn build(self) -> RerouteNotification {
            serde_json::from_value(serde_json::json!({
                "context": {"slot": 1},
                "slot": 1,
                "batchIndex": 0,
                "originalSignature": "sig",
                "legs": self.legs,
                "routedTransaction": {"data": "AA==", "encoding": "base64"},
                "err": self.err,
                "logs": [],
                "computeUnitsConsumed": 0,
                "fee": 5_000,
                "realizedOutputAmount": serde_json::Value::Null,
                "originalRealizedOutputAmount": self.original_realized_output_amount,
                "originalFailed": self.original_failed,
            }))
            .expect("a notification fixture decodes")
        }
    }

    // ── Test helpers ─────────────────────────────────────────────────────────

    /// Fixes SOL at $100 from the stream's own swaps. Carries no route plan, so it prices the
    /// range without contributing a hop to anything.
    fn anchors() -> Vec<RerouteNotification> {
        (1..=3)
            .map(|n| Notification::swap(SOL, USDC, n * 1_000_000_000, n * 100_000_000).build())
            .collect()
    }

    fn venue() -> Target {
        Target::new(
            Some("BisonFi".to_string()),
            Some(VENUE_PROGRAM.parse().expect("a venue program")),
        )
    }

    fn fill(
        program: &str,
        label: &str,
        input: &str,
        output: &str,
        amount: u64,
    ) -> Option<RoutePlan> {
        plan(vec![hop(Some(program), label, input, output, amount)])
    }

    fn report_of(notifications: &[RerouteNotification]) -> Report {
        from_notifications(venue(), notifications).expect("the venue appears")
    }

    /// The anchors, plus whatever the test is actually about.
    fn priced(extra: impl IntoIterator<Item = Notification>) -> Vec<RerouteNotification> {
        let mut notifications = anchors();
        notifications.extend(extra.into_iter().map(Notification::build));
        notifications
    }

    /// A leg the venue won: the re-quote routed it through the venue, L1 had it elsewhere.
    fn won_leg(amount: u64) -> Notification {
        let realized = fill(VENUE_PROGRAM, "BisonFi", SOL, USDC, amount);
        let l1 = fill(OTHER_PROGRAM, "Whirlpool", SOL, USDC, amount);
        Notification::new(vec![leg_of(SOL, USDC, amount, None, l1, realized)])
    }

    // ── Tests ────────────────────────────────────────────────────────────────

    /// Prices are medians over the whole stream, so no dollar figure exists until it ends. The
    /// builder holds raw amounts and converts once — which only works because the conversion is
    /// linear, and this is the test of that. The single-leg gate on
    /// `original_realized_output_amount` survives the notification-to-record mapping, since the
    /// anchors are single-leg swaps and the anchor still prices to `$100`.
    #[test]
    fn deferring_the_conversion_matches_pricing_each_hop_as_it_arrives() {
        let report = report_of(&priced([won_leg(2_000_000_000), won_leg(3_000_000_000)]));
        let total = report.total();

        assert_eq!(report.sol_usd(), Some(100.0));
        assert_eq!(total.requoted.legs, 2);
        // 2 SOL and 3 SOL at $100, whether summed raw and converted once or converted twice.
        assert_eq!(total.requoted.usd, 500.0);
        assert_eq!(total.l1.legs, 0, "L1 had these legs at another venue");
    }

    /// The order notifications arrive in is the order the session produced them, which is not a
    /// property of the venue. Every figure must be a fold, not a sequence. This is the
    /// output-parity canary for the whole move onto the shared core.
    #[test]
    fn the_result_does_not_depend_on_arrival_order() {
        let forward = priced([won_leg(2_000_000_000), won_leg(3_000_000_000)]);
        let mut backward = forward.clone();
        backward.reverse();

        let (forward, backward) = (report_of(&forward), report_of(&backward));
        assert_eq!(forward.sol_usd(), backward.sol_usd());
        assert_eq!(forward.total().requoted.usd, backward.total().requoted.usd);
        assert_eq!(forward.render(None), backward.render(None));
    }

    /// Neither column counts flow that never landed, and the two must be filtered alike — a
    /// reverted simulation is not a leg the venue won, and a failed original is not one it held.
    #[test]
    fn neither_side_counts_flow_that_never_landed() {
        let notifications = priced([
            won_leg(2_000_000_000),
            won_leg(9_000_000_000).reverted(),
            won_leg(9_000_000_000).original_failed(),
        ]);

        let total = report_of(&notifications).total();
        assert_eq!(total.requoted.legs, 1, "only the landed leg counts");
        assert_eq!(total.requoted.usd, 200.0);
    }

    /// A multi-leg notification's original output total is nobody's single leg, so no record
    /// carries it into pricing.
    #[test]
    fn a_multi_leg_notification_prices_nothing() {
        let legs = vec![
            leg_of(SOL, USDC, 1_000_000_000, None, None, None),
            leg_of(USDC, SOL, 100_000_000, None, None, None),
        ];
        let mut notification = Notification::new(legs);
        notification.original_realized_output_amount = Some(100_000_000);
        let records = leg_records(&notification.build());
        assert_eq!(records.len(), 2);
        assert!(
            records
                .iter()
                .all(|r| r.original_realized_output_amount.is_none())
        );
    }
}