simulator-api 0.29.0

Wire-protocol types for the Solana simulator backtest WebSocket API
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
//! The reroute benchmark: how each rerouted route did against the historical one, as win/loss
//! counts, volume-weighted bps, and the venues both sides routed through.
//!
//! The caller selects the records — landed reroutes whose original also landed, with both
//! realized amounts present and the two mints distinct. [`collect`] adds only what needs every
//! record to decide: a signature seen twice is an ambiguous pairing and drops wholesale.
//! ExactOut legs are measured input-side (`amount` is output-token-denominated and outputs tie by
//! construction, so a win is paying less major input), which leaves a non-major-input ExactOut leg
//! unpriceable — those are skipped.
//!
//! Two deliberate differences from the pre-typed-plan reader, both forced by the typing. Hop
//! amounts arrive as strings, so a float-typed string like `"1.5e3"` truncates to an integer
//! instead of voiding the plan — the JSON number/string distinction died with the DOM parse;
//! genuinely unparseable text still voids. And an explicit `"inAmount": null` used to void the
//! whole plan where an absent key merely contributed zero — an `Option<String>` cannot tell the
//! two apart, so both now contribute zero.

use std::{
    cmp::Ordering,
    collections::{BTreeMap, HashMap, HashSet, hash_map::Entry},
};

use serde::Serialize;
use solana_address::Address;

use super::{
    fmt::{commas_u, median},
    prices::Prices,
    record::{LegRecord, SwapMode},
};
use crate::{mints, route_plan::RoutePlan};

/// Venues under this USD exposure on both sides are dust, hidden from the table.
pub const VENUE_DUST_USD: f64 = 1e4;
/// Legs whose change exceeds this many bps either way are treated as pricing artifacts, not
/// routing outcomes, and skipped.
pub const OUTLIER_BPS: f64 = 2000.0;

/// What [`collect`] dropped.
#[derive(Default, Debug)]
pub struct LoadStats {
    /// Signatures dropped because they had more than one row (multi-swap transactions).
    pub dropped_multi_row: usize,
}

/// Row order is preserved so float accumulation stays deterministic across runs. A signature seen
/// more than once is an ambiguous multi-swap transaction — pairing is by signature — so its rows
/// drop wholesale, and a skipped ExactOut row never claims a signature it could make ambiguous.
pub fn collect(rows: Vec<LegRecord>) -> (Vec<LegRecord>, LoadStats) {
    let mut kept: Vec<LegRecord> = Vec::new();
    let mut first_row: HashMap<String, usize> = HashMap::new();
    let mut dropped: HashSet<usize> = HashSet::new();
    for row in rows {
        if row.swap_mode == SwapMode::ExactOut && !mints::is_major(&row.input_mint) {
            continue;
        }
        match first_row.entry(row.original_signature.clone()) {
            Entry::Vacant(slot) => {
                slot.insert(kept.len());
                kept.push(row);
            }
            Entry::Occupied(slot) => {
                dropped.insert(*slot.get());
            }
        }
    }
    let stats = LoadStats {
        dropped_multi_row: dropped.len(),
    };
    (
        kept.into_iter()
            .enumerate()
            .filter(|(index, _)| !dropped.contains(index))
            .map(|(_, row)| row)
            .collect(),
        stats,
    )
}

/// Total `inAmount` for `mint` across the plan's hops. Amounts are strings on the wire; an integer
/// parse is preferred and a float truncates, matching how numeric JSON amounts were read before
/// plans were typed. A string that parses as neither voids the plan.
fn plan_input(plan: &RoutePlan, mint: &Address) -> Option<i64> {
    let mint = mint.to_string();
    let mut total = 0i64;
    for hop in plan.hops() {
        if hop.input_mint() != Some(mint.as_str()) {
            continue;
        }
        // An absent inAmount contributes zero; a present one that reads as no number at all voids
        // the whole plan.
        total += match hop.swap_info.in_amount.as_deref() {
            None => 0,
            Some(amount) => amount
                .parse::<i64>()
                .ok()
                .or_else(|| amount.parse::<f64>().ok().map(|float| float as i64))?,
        };
    }
    (total > 0).then_some(total)
}

/// `[(label, weight)]`; sequential hops each carry the full amount, splits weighted by percent.
/// Unlabeled hops keep their weight under `None` so dropped flow stays visible.
fn venue_weights(plan: &RoutePlan) -> Vec<(Option<&str>, f64)> {
    plan.hops()
        .iter()
        .map(|hop| (hop.label(), hop.percent as f64 / 100.0))
        .collect()
}

/// One measured leg: how the rerouted route compared and what it was worth.
pub struct Measurement {
    /// `Greater` when the reroute beat the original swap, `Equal` on a tie, `Less` when it lost.
    pub outcome: Ordering,
    /// The original swap's value, in USD.
    pub l1_usd: f64,
    /// The reroute's value on the same basis, in USD.
    pub rerouted_usd: f64,
}

/// ExactIn compares delivered output (buys valued at spend); ExactOut compares major input paid
/// for the identical output. `None` = unpriceable or a |bps| > [`OUTLIER_BPS`] dollar-outlier.
pub fn measure(record: &LegRecord, prices: &Prices) -> Option<Measurement> {
    match record.swap_mode {
        SwapMode::ExactOut => measure_exact_out(record, prices),
        SwapMode::ExactIn => measure_exact_in(record, prices),
    }
}

fn measure_exact_out(record: &LegRecord, prices: &Prices) -> Option<Measurement> {
    let mint = &record.input_mint;
    let rerouted = plan_input(record.route_plan.as_ref()?, mint)?;
    let l1 = plan_input(record.original_route_plan.as_ref()?, mint)?;
    let l1_usd = prices.usd(mint, l1 as f64)?;
    // Same output either way, so credit the input saved: l1 + (l1 - rerouted).
    let rerouted_usd = prices.usd(mint, (2 * l1 - rerouted) as f64)?;
    if l1_usd <= 0.0 || (rerouted_usd / l1_usd - 1.0).abs() * 1e4 > OUTLIER_BPS {
        return None;
    }
    Some(Measurement {
        outcome: l1.cmp(&rerouted),
        l1_usd,
        rerouted_usd,
    })
}

fn measure_exact_in(record: &LegRecord, prices: &Prices) -> Option<Measurement> {
    let rerouted = record.realized_output_amount.unwrap_or(0) as i64;
    let l1 = record.original_realized_output_amount.unwrap_or(0) as i64;
    let bps = (rerouted as f64 / l1 as f64 - 1.0) * 1e4;
    let scaled = |usd: f64| usd * (1.0 + bps / 1e4);
    // Majors first, so a leg with a priced side is valued on that side rather than through the
    // exotic map the last two arms fall back to.
    let (l1_usd, rerouted_usd) = if mints::is_major(&record.output_mint) {
        (
            prices.usd(&record.output_mint, l1 as f64),
            prices.usd(&record.output_mint, rerouted as f64),
        )
    } else if mints::is_major(&record.input_mint) {
        let spend = prices.usd(&record.input_mint, record.amount as f64);
        (spend, spend.map(scaled))
    } else if let Some(l1_usd) = prices.usd(&record.output_mint, l1 as f64) {
        (
            Some(l1_usd),
            prices.usd(&record.output_mint, rerouted as f64),
        )
    } else {
        let spend = prices.usd(&record.input_mint, record.amount as f64)?;
        (Some(spend), Some(scaled(spend)))
    };
    let (l1_usd, rerouted_usd) = (l1_usd?, rerouted_usd?);
    if l1_usd <= 0.0 || bps.abs() > OUTLIER_BPS {
        return None;
    }
    Some(Measurement {
        outcome: rerouted.cmp(&l1),
        l1_usd,
        rerouted_usd,
    })
}

/// USD totals for one side of the majors/exotic split.
#[derive(Default, Clone, Serialize)]
pub struct SideTotals {
    /// The original swaps' volume.
    pub vol: f64,
    /// Reroute minus original; positive means the reroutes did better.
    pub net: f64,
}

/// One venue's USD volume, each leg split across its route's venues by `percent`.
#[derive(Default, Clone, Serialize)]
pub struct VenueTotals {
    /// Volume the reroutes sent through it.
    pub rerouted: f64,
    /// Volume the original swaps sent through it.
    pub l1: f64,
    /// The reroutes' net gain, attributed by the venue's share of each reroute.
    pub net: f64,
}

/// How the reroutes did against the original swaps, for one range or a cross-range aggregate.
/// Dollar figures are USD; volumes are the original swaps' value.
#[derive(Default, Clone, Serialize)]
pub struct RangeReport {
    /// Measured legs.
    pub n: u64,
    /// Legs where the reroute did better.
    pub better: u64,
    /// Legs where the reroute tied.
    pub same: u64,
    /// Legs where the reroute did worse.
    pub worse: u64,
    /// Volume across measured legs.
    pub vol: f64,
    /// Reroute minus original across measured legs; positive means the reroutes did better.
    pub net: f64,
    /// Volume of the legs in [`Self::better`].
    pub vol_better: f64,
    /// Volume of the legs in [`Self::same`].
    pub vol_same: f64,
    /// Volume of the legs in [`Self::worse`].
    pub vol_worse: f64,
    /// Each measured leg's change, in bps.
    pub bps: Vec<f64>,
    /// Legs between two majors.
    pub majors: SideTotals,
    /// Legs with at least one non-major mint.
    pub exotic: SideTotals,
    /// By venue label; `(unlabeled)` collects hops without one.
    pub venues: BTreeMap<String, VenueTotals>,
}

impl RangeReport {
    /// [`measure`] each record and total the results; records it cannot measure are skipped.
    pub fn from_records(records: &[LegRecord], prices: &Prices) -> Self {
        let mut report = Self::default();
        for record in records {
            if let Some(measurement) = measure(record, prices) {
                report.record(record, &measurement);
            }
        }
        report
    }

    fn record(&mut self, leg: &LegRecord, measurement: &Measurement) {
        let delta = measurement.rerouted_usd - measurement.l1_usd;
        self.n += 1;
        let (count, vol) = match measurement.outcome {
            Ordering::Greater => (&mut self.better, &mut self.vol_better),
            Ordering::Equal => (&mut self.same, &mut self.vol_same),
            Ordering::Less => (&mut self.worse, &mut self.vol_worse),
        };
        *count += 1;
        *vol += measurement.l1_usd;
        self.vol += measurement.l1_usd;
        self.net += delta;
        if measurement.l1_usd > 0.0 {
            self.bps.push(delta / measurement.l1_usd * 1e4);
        }
        let side = if mints::trades_only_majors(&leg.input_mint, &leg.output_mint) {
            &mut self.majors
        } else {
            &mut self.exotic
        };
        side.vol += measurement.l1_usd;
        side.net += delta;
        self.attribute_venues(leg, measurement.l1_usd, delta);
    }

    /// Split the leg's USD across its route's venues, per-leg-normalized so every leg contributes
    /// its USD exactly once, for both the rerouted route and L1's landed one.
    fn attribute_venues(&mut self, leg: &LegRecord, l1_usd: f64, delta: f64) {
        for (rerouted, plan) in [(true, &leg.route_plan), (false, &leg.original_route_plan)] {
            let Some(plan) = plan else {
                continue;
            };
            let weights = venue_weights(plan);
            let total: f64 = weights.iter().map(|(_, weight)| weight).sum();
            let total = if total == 0.0 { 1.0 } else { total };
            for (label, weight) in weights {
                let label = label.unwrap_or("(unlabeled)");
                let entry = self.venues.entry(label.to_string()).or_default();
                let share = weight / total;
                if rerouted {
                    entry.rerouted += l1_usd * share;
                    entry.net += delta * share;
                } else {
                    entry.l1 += l1_usd * share;
                }
            }
        }
    }

    /// Add `other` into this report, for a cross-range aggregate.
    pub fn merge(&mut self, other: &Self) {
        self.n += other.n;
        self.better += other.better;
        self.same += other.same;
        self.worse += other.worse;
        self.vol += other.vol;
        self.net += other.net;
        self.vol_better += other.vol_better;
        self.vol_same += other.vol_same;
        self.vol_worse += other.vol_worse;
        self.bps.extend_from_slice(&other.bps);
        self.majors.vol += other.majors.vol;
        self.majors.net += other.majors.net;
        self.exotic.vol += other.exotic.vol;
        self.exotic.net += other.exotic.net;
        for (venue, totals) in &other.venues {
            let entry = self.venues.entry(venue.clone()).or_default();
            entry.rerouted += totals.rerouted;
            entry.l1 += totals.l1;
            entry.net += totals.net;
        }
    }

    /// The volume-weighted change in bps, `net / vol * 10_000`; 0 when nothing was measured.
    pub fn vw_bps(&self) -> f64 {
        if self.vol == 0.0 {
            0.0
        } else {
            self.net / self.vol * 1e4
        }
    }

    /// A Markdown section headed `name`: the summary lines, then the venue table without venues
    /// under [`VENUE_DUST_USD`] on both sides.
    pub fn render(&self, name: &str) -> String {
        if self.vol == 0.0 {
            return format!("### {name}: no measurable legs\n");
        }
        let mut lines = self.summary_lines(name);
        lines.push(String::new());
        lines.extend(self.venue_table());
        lines.push(String::new());
        lines.join("\n")
    }

    fn summary_lines(&self, name: &str) -> Vec<String> {
        let mut bps = self.bps.clone();
        let (q1_at, q3_at) = (bps.len() / 4, 3 * bps.len() / 4);
        let med = median(&mut bps);
        let mut lines = vec![
            format!("### {name}"),
            format!(
                "vw vs historical: **{:+.2} bps** (net {}$ on ${})",
                self.vw_bps(),
                commas_signed(self.net),
                commas(self.vol)
            ),
            format!(
                "b/s/w: {} / {} / {}  (by volume {:.1} / {:.1} / {:.1}%)",
                commas_u(self.better),
                commas_u(self.same),
                commas_u(self.worse),
                self.vol_better / self.vol * 100.0,
                self.vol_same / self.vol * 100.0,
                self.vol_worse / self.vol * 100.0
            ),
            format!(
                "per-leg bps: median {med:+.2}, IQR [{:+.2}, {:+.2}]",
                bps[q1_at], bps[q3_at]
            ),
        ];
        for (label, side) in [
            ("majors<->majors", &self.majors),
            ("exotic-involved", &self.exotic),
        ] {
            if side.vol > 0.0 {
                lines.push(format!(
                    "{label}: {:+.2} bps (net {}$ on ${})",
                    side.net / side.vol * 1e4,
                    commas_signed(side.net),
                    commas(side.vol)
                ));
            }
        }
        lines
    }

    fn venue_table(&self) -> Vec<String> {
        let mut lines = vec![
            "| Venue | rerouted share | historical share | vw bps (rerouted legs) |".to_string(),
            "|---|---|---|---|".to_string(),
        ];
        let total_rerouted: f64 = self
            .venues
            .values()
            .map(|e| e.rerouted)
            .sum::<f64>()
            .max(1.0);
        let total_l1: f64 = self.venues.values().map(|e| e.l1).sum::<f64>().max(1.0);
        let mut ranked: Vec<_> = self.venues.iter().collect();
        ranked.sort_by(|a, b| b.1.rerouted.total_cmp(&a.1.rerouted));
        for (venue, e) in ranked {
            if e.rerouted < VENUE_DUST_USD && e.l1 < VENUE_DUST_USD {
                continue;
            }
            let vw = if e.rerouted == 0.0 {
                0.0
            } else {
                e.net / e.rerouted * 1e4
            };
            lines.push(format!(
                "| {venue} | {:.1}% | {:.1}% | {vw:+.2} |",
                e.rerouted / total_rerouted * 100.0,
                e.l1 / total_l1 * 100.0
            ));
        }
        lines
    }
}

fn commas(x: f64) -> String {
    commas_u(x.round().abs() as u64)
}

fn commas_signed(x: f64) -> String {
    format!("{}{}", if x < 0.0 { "-" } else { "+" }, commas(x))
}

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

    use super::*;
    use crate::{
        reroute_report::{
            Samples,
            testing::{hop, plan, record_of},
        },
        route_plan::RouteHop,
    };

    #[rstest]
    #[case::rounds_up("+1,235", 1_234.6)]
    #[case::negative("-1,235", -1_234.6)]
    fn signed_commas_carry_the_sign(#[case] expected: &str, #[case] x: f64) {
        assert_eq!(commas_signed(x), expected);
    }

    fn hop_of(input_mint: &Address, in_amount: u64) -> RouteHop {
        hop(
            None,
            "Venue",
            &input_mint.to_string(),
            &mints::USDT.to_string(),
            in_amount,
        )
    }

    /// The wire carries amounts as text, which a fixture with a `u64` cannot express.
    fn amount_hop(in_amount: Option<&str>) -> RouteHop {
        let mut hop = hop_of(&mints::USDC, 0);
        hop.swap_info.in_amount = in_amount.map(str::to_string);
        hop
    }

    #[rstest]
    #[case::integer_amount(Some("1000"), Some(1_000))]
    #[case::float_amount_truncates(Some("1000.9"), Some(1_000))]
    #[case::float_string_truncates(Some("1.5e3"), Some(1_500))]
    #[case::unparseable_voids_the_plan(Some("abc"), None)]
    #[case::an_absent_amount_alone_sums_to_nothing(None, None)]
    fn plan_input_reads_integer_and_float_amounts(
        #[case] amount: Option<&str>,
        #[case] expected: Option<i64>,
    ) {
        let plan = plan(vec![amount_hop(amount)]).expect("a plan");
        assert_eq!(plan_input(&plan, &mints::USDC), expected);
    }

    #[test]
    fn plan_input_sums_only_the_asked_mints_hops() {
        let plan = plan(vec![
            hop_of(&mints::USDC, 300),
            hop_of(&Address::default(), 999),
            hop_of(&mints::USDC, 700),
        ])
        .expect("a plan");
        assert_eq!(plan_input(&plan, &mints::USDC), Some(1_000));

        // Deserialization bypasses `RoutePlan::new`, so a plan off the wire can still be empty.
        let empty: RoutePlan = serde_json::from_str("[]").expect("an empty plan");
        assert_eq!(plan_input(&empty, &mints::USDC), None);
    }

    #[test]
    fn an_absent_amount_contributes_zero_without_voiding() {
        let plan = plan(vec![amount_hop(None), hop_of(&mints::USDC, 700)]).expect("a plan");
        assert_eq!(plan_input(&plan, &mints::USDC), Some(700));
    }

    /// Fixes SOL at $100 from the stream's own swaps; the stable legs below price off decimals
    /// alone, so nothing else needs deriving.
    fn prices() -> Prices {
        let mut samples = Samples::default();
        for n in 1..=3u64 {
            samples.push(&LegRecord {
                original_realized_output_amount: Some(n * 100_000_000),
                ..record_of(mints::SOL, mints::USDC, n * 1_000_000_000, None, None, None)
            });
        }
        samples.prices().expect("anchored")
    }

    fn stable_record(mode: SwapMode, rerouted: u64, l1: u64) -> LegRecord {
        LegRecord {
            swap_mode: mode,
            realized_output_amount: Some(rerouted),
            original_realized_output_amount: Some(l1),
            route_plan: plan(vec![hop_of(&mints::USDC, rerouted)]),
            original_route_plan: plan(vec![hop_of(&mints::USDC, l1)]),
            ..record_of(mints::USDC, mints::USDT, 1_000_000, None, None, None)
        }
    }

    #[test]
    fn exact_out_credits_the_input_saved() {
        let m = measure(
            &stable_record(SwapMode::ExactOut, 999_000, 1_000_000),
            &prices(),
        )
        .expect("measurable");
        assert_eq!(m.outcome, Ordering::Greater);
        assert!((m.l1_usd - 1.0).abs() < 1e-9);
        assert!((m.rerouted_usd - 1.001).abs() < 1e-9);
    }

    #[rstest]
    #[case::win(1_010_000, 1_000_000, Some(Ordering::Greater))]
    #[case::tie(1_000_000, 1_000_000, Some(Ordering::Equal))]
    #[case::exactly_at_the_outlier_bound_stays(1_200_000, 1_000_000, Some(Ordering::Greater))]
    #[case::past_the_outlier_bound_drops(1_210_000, 1_000_000, None)]
    fn exact_in_measures_major_output_with_the_outlier_gate(
        #[case] rerouted: u64,
        #[case] l1: u64,
        #[case] expected: Option<Ordering>,
    ) {
        let m = measure(&stable_record(SwapMode::ExactIn, rerouted, l1), &prices());
        assert_eq!(m.map(|m| m.outcome), expected);
    }

    /// Pairing is by signature, so a signature seen twice is ambiguous and drops wholesale.
    #[test]
    fn collect_drops_multi_row_signatures_wholesale() {
        let mut a = stable_record(SwapMode::ExactIn, 1_000_000, 999_000);
        a.original_signature = "sigA".to_string();
        let mut a2 = a.clone();
        a2.amount = 2_000_000;
        let mut b = stable_record(SwapMode::ExactIn, 1_000_000, 999_000);
        b.original_signature = "sigB".to_string();

        let (kept, stats) = collect(vec![a, a2, b]);
        assert_eq!(kept.len(), 1);
        assert_eq!(kept[0].original_signature, "sigB");
        assert_eq!(stats.dropped_multi_row, 1);
    }

    /// An ExactOut leg is measured on its input, so a non-major input has no price to measure
    /// against — and dropping it before the signature bookkeeping keeps it from making a
    /// measurable row ambiguous.
    #[test]
    fn collect_skips_exact_out_legs_it_cannot_price() {
        let exotic = LegRecord {
            input_mint: Address::default(),
            ..stable_record(SwapMode::ExactOut, 1_000_000, 999_000)
        };
        let major = stable_record(SwapMode::ExactOut, 1_000_000, 999_000);

        let (kept, stats) = collect(vec![exotic, major]);
        assert_eq!(kept.len(), 1);
        assert_eq!(kept[0].input_mint, mints::USDC);
        assert_eq!(stats.dropped_multi_row, 0, "a skipped row is not a pairing");
    }
}