simulator-client 0.23.0

Async WebSocket client for the Solana simulator backtest 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
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
//! The reroute-report core fed from `replacementSubscribe` notifications. The computation —
//! records, pricing, the reports themselves — lives in [`simulator_api::reroute_report`]; this
//! module only maps the wire shape onto it.
//!
//! `ReplacementNotification` carries two shapes down one stream: `Requote` feeds the venue-flow
//! [`Report`], `DirectFill` the per-template [`ProbeReport`]. Each routing function reads only its
//! own variant and silently skips the other.
//!
//! ```no_run
//! # use simulator_client::{ReplacementNotification, reroute_report::{self, Target}};
//! # fn example(notifications: &[ReplacementNotification]) -> 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));
//! let probes = reroute_report::probes_from_notifications(notifications);
//! println!("{}", probes.render("R1"));
//! # Ok(()) }
//! ```

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

use crate::{
    DirectFillNotification, ReplacementNotification, RequoteNotification, RerouteLegNotification,
};

/// One record per leg of a requote. 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: &RequoteNotification) -> 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: &RequoteNotification,
    leg: &RerouteLegNotification,
    sole_leg: bool,
) -> LegRecord {
    LegRecord {
        original_signature: notification.core.original_signature.to_string(),
        input_mint: leg.input_mint,
        output_mint: leg.output_mint,
        amount: leg.amount,
        swap_mode: SwapMode::parse(&leg.swap_mode),
        failed: notification.core.error.is_some(),
        original_failed: notification.core.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(),
        // The original's quote, not the replacement's — see `LegRecord::quoted_output_amount`.
        quoted_output_amount: Some(leg.original_quoted_out).filter(|&quoted| quoted > 0),
        // DB-shaped columns the stream does not carry; `realized_output_amount` covers the fill
        // on the notification path.
        template: None,
        new_output_amount: None,
        error_category: None,
        output_bps: None,
    }
}

/// One record for a direct-fill probe: one hop, re-priced against a direct-fill template. Feeds
/// [`ProbeReport`] only, so the flow-report fields are left at inert defaults.
///
/// `error_category` is [`bucket`]ed, not `category` verbatim: `category` narrows to the revert
/// reason alone, so an `unattributed`/`unsimulatable` probe carries none of its own.
pub fn probe_record(notification: &DirectFillNotification) -> LegRecord {
    LegRecord {
        original_signature: notification.core.original_signature.to_string(),
        input_mint: notification.input_mint,
        output_mint: notification.output_mint,
        amount: notification.amount,
        swap_mode: SwapMode::parse(&notification.swap_mode),
        failed: false,
        original_failed: notification.core.original_failed,
        realized_output_amount: None,
        original_realized_output_amount: None,
        route_plan: None,
        original_route_plan: None,
        realized_route_plan: None,
        template: Some(notification.template.clone()),
        quoted_output_amount: notification.comparison.l1_fill,
        new_output_amount: notification.template_fill,
        error_category: bucket(
            &notification.core.outcome,
            notification.core.category.as_deref(),
        ),
        output_bps: notification.comparison.change_vs_l1_bps,
    }
}

/// Build the venue-flow report from anything that yields replacement notifications — a slice, a
/// `Vec`, a lazily-parsed file. `DirectFill` and `Original` variants are skipped.
pub fn from_notifications<'a>(
    target: Target,
    notifications: impl IntoIterator<Item = &'a ReplacementNotification>,
) -> Result<Report, RerouteReportError> {
    let mut builder = ReportBuilder::new(target);
    notifications
        .into_iter()
        .filter_map(|notification| match notification {
            ReplacementNotification::Requote(requote) => Some(requote),
            ReplacementNotification::DirectFill(_) | ReplacementNotification::Original(_) => None,
        })
        .flat_map(leg_records)
        .for_each(|record| builder.push(&record));
    builder.finish()
}

/// Build the venue-flow report from a live stream, holding no more than [`ReportBuilder`] does.
/// `DirectFill` and `Original` variants are skipped.
pub async fn from_stream(
    target: Target,
    stream: impl Stream<Item = ReplacementNotification>,
) -> Result<Report, RerouteReportError> {
    let mut builder = ReportBuilder::new(target);
    let mut stream = std::pin::pin!(stream);
    while let Some(notification) = stream.next().await {
        if let ReplacementNotification::Requote(requote) = notification {
            for record in leg_records(&requote) {
                builder.push(&record);
            }
        }
    }
    builder.finish()
}

/// Build the per-template probe report from anything that yields replacement notifications.
/// `Requote` and `Original` variants are skipped.
pub fn probes_from_notifications<'a>(
    notifications: impl IntoIterator<Item = &'a ReplacementNotification>,
) -> ProbeReport {
    let records: Vec<LegRecord> = notifications
        .into_iter()
        .filter_map(|notification| match notification {
            ReplacementNotification::DirectFill(probe) => Some(probe_record(probe)),
            ReplacementNotification::Requote(_) | ReplacementNotification::Original(_) => None,
        })
        .collect();
    ProbeReport::from_records(&records, None)
}

/// Build the per-template probe report from a live stream, holding no more than one merge's worth
/// of state at a time. `Requote` and `Original` variants are skipped.
pub async fn probes_from_stream(
    stream: impl Stream<Item = ReplacementNotification>,
) -> ProbeReport {
    let mut report = ProbeReport::default();
    let mut stream = std::pin::pin!(stream);
    while let Some(notification) = stream.next().await {
        if let ReplacementNotification::DirectFill(probe) = notification {
            report.merge(&ProbeReport::from_records(&[probe_record(&probe)], None));
        }
    }
    report
}

#[cfg(test)]
mod tests {

    /// Typed on the shared core, so a fixture needs real base58 rather than a placeholder.
    fn fixture_signature() -> String {
        simulator_api::replacement::Signature::default().to_string()
    }

    use rstest::rstest;
    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) -> RequoteNotification {
            serde_json::from_value(serde_json::json!({
                "context": {"slot": 1},
                "slot": 1,
                "batchIndex": 0,
                "originalSignature": fixture_signature(),
                "originalFailed": self.original_failed,
                // Drives `failed` on the record; the outcome word tracks it so the fixture
                // cannot claim a fill it also reports an error for.
                "outcome": if self.err.is_some() { "reverted" } else { "filled" },
                "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,
            }))
            .expect("a notification fixture decodes")
        }

        /// Wrapped in the enum, as it arrives off the wire.
        fn build_replacement(self) -> ReplacementNotification {
            ReplacementNotification::Requote(self.build())
        }
    }

    // ── 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<ReplacementNotification> {
        (1..=3)
            .map(|n| {
                Notification::swap(SOL, USDC, n * 1_000_000_000, n * 100_000_000)
                    .build_replacement()
            })
            .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: &[ReplacementNotification]) -> 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<ReplacementNotification> {
        let mut notifications = anchors();
        notifications.extend(extra.into_iter().map(Notification::build_replacement));
        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())
        );
    }

    // ── Direct-fill probe fixtures ──────────────────────────────────────────

    /// A probe notification wrapping one hop's outcome through a direct-fill template.
    fn probe(
        template: &str,
        template_fill: Option<u64>,
        l1_fill: Option<u64>,
        change_vs_l1_bps: Option<i64>,
        outcome: &str,
        category: Option<&str>,
    ) -> DirectFillNotification {
        serde_json::from_value(serde_json::json!({
            "context": {"slot": 1},
            "slot": 1,
            "batchIndex": 0,
            "originalSignature": fixture_signature(),
            "originalFailed": false,
            "template": template,
            "inputMint": SOL,
            "outputMint": USDC,
            "amount": 1_000_000_000u64,
            "swapMode": "ExactIn",
            "templateFill": template_fill,
            "l1Fill": l1_fill,
            "changeVsL1Bps": change_vs_l1_bps,
            "outcome": outcome,
            "category": category,
        }))
        .expect("a probe fixture decodes")
    }

    // ── Direct-fill probe tests ─────────────────────────────────────────────

    #[test]
    fn probe_record_maps_template_fields_onto_the_shared_record() {
        let notification = probe(
            "Tempest",
            Some(1_010_000_000),
            Some(1_000_000_000),
            Some(100),
            "filled",
            None,
        );
        let record = probe_record(&notification);

        assert_eq!(record.template.as_deref(), Some("Tempest"));
        assert_eq!(record.new_output_amount, Some(1_010_000_000));
        assert_eq!(record.quoted_output_amount, Some(1_000_000_000));
        assert_eq!(record.output_bps, Some(100));
        assert_eq!(record.error_category, None);
    }

    /// `unattributed` and `unsimulatable` carry no `category`, so they must be named by
    /// `outcome` rather than silently rebucketing as `"filled"`.
    #[rstest]
    #[case::filled("filled", None, "filled")]
    #[case::reverted("reverted", Some("slippage"), "reverted_slippage")]
    #[case::unattributed("unattributed", None, "unattributed")]
    #[case::unsimulatable("unsimulatable", None, "unsimulatable")]
    fn probe_record_reconstructs_the_pre_split_bucket_vocabulary(
        #[case] outcome: &str,
        #[case] category: Option<&str>,
        #[case] expected_bucket: &str,
    ) {
        let notification = probe("Tempest", None, None, None, outcome, category);
        let record = probe_record(&notification);
        let report = ProbeReport::from_records(&[record], None);
        assert_eq!(
            report.by_template["Tempest"].outcomes.get(expected_bucket),
            Some(&1)
        );
    }

    #[test]
    fn from_notifications_ignores_direct_fill_variants() {
        let mut notifications = priced([won_leg(2_000_000_000)]);
        notifications.push(ReplacementNotification::DirectFill(probe(
            "Tempest",
            Some(1_010_000_000),
            Some(1_000_000_000),
            Some(100),
            "filled",
            None,
        )));

        let total = report_of(&notifications).total();
        assert_eq!(total.requoted.legs, 1, "the probe contributed no leg");
    }

    #[test]
    fn probes_from_notifications_ignores_requote_variants() {
        let mut notifications = priced([won_leg(2_000_000_000)]);
        notifications.push(ReplacementNotification::DirectFill(probe(
            "Tempest",
            Some(1_010_000_000),
            Some(1_000_000_000),
            Some(100),
            "filled",
            None,
        )));

        let probes = probes_from_notifications(&notifications);
        assert_eq!(probes.by_template.len(), 1);
        assert_eq!(
            probes.by_template["Tempest"].outcomes.get("filled"),
            Some(&1)
        );
    }

    /// Unskipped, the probe would corrupt the flow totals: a phantom leg, dollars priced off a
    /// probe fill.
    #[tokio::test]
    async fn from_stream_ignores_direct_fill_variants_in_a_mixed_stream() {
        let mut notifications = priced([won_leg(2_000_000_000)]);
        notifications.push(ReplacementNotification::DirectFill(probe(
            "Tempest",
            Some(1_010_000_000),
            Some(1_000_000_000),
            Some(100),
            "filled",
            None,
        )));

        let from_slice = report_of(&notifications);
        let from_stream = from_stream(venue(), futures::stream::iter(notifications))
            .await
            .expect("the template appears");

        assert_eq!(
            from_stream.total().requoted.legs,
            1,
            "the probe contributed no leg"
        );
        assert_eq!(from_slice.render(None), from_stream.render(None));
    }

    /// Compares every `TemplateProbes` field, not just `.outcomes`, so the merge-carried ones are
    /// covered too.
    #[tokio::test]
    async fn probes_from_stream_matches_probes_from_notifications_on_a_mixed_stream() {
        let mut notifications = priced([won_leg(2_000_000_000)]);
        notifications.push(ReplacementNotification::DirectFill(probe(
            "Tempest",
            Some(1_010_000_000),
            Some(1_000_000_000),
            Some(100),
            "filled",
            None,
        )));
        notifications.push(ReplacementNotification::DirectFill(probe(
            "Tempest",
            None,
            None,
            None,
            "unattributed",
            None,
        )));

        let from_slice = probes_from_notifications(&notifications);
        let from_stream = probes_from_stream(futures::stream::iter(notifications)).await;

        assert_eq!(
            from_slice.by_template.len(),
            1,
            "the Requote notification contributed no template"
        );
        let slice_template = &from_slice.by_template["Tempest"];
        let stream_template = &from_stream.by_template["Tempest"];
        assert_eq!(slice_template.outcomes, stream_template.outcomes);
        assert_eq!(
            slice_template.scored_vs_historical,
            stream_template.scored_vs_historical
        );
        assert_eq!(
            slice_template.bps_vs_historical_total,
            stream_template.bps_vs_historical_total
        );
        assert_eq!(
            slice_template.pairs_vs_same_state,
            stream_template.pairs_vs_same_state
        );
        assert!(
            (slice_template.bps_vs_same_state_total - stream_template.bps_vs_same_state_total)
                .abs()
                < 1e-9
        );
    }
}