1use futures::{Stream, StreamExt};
21use simulator_api::reroute_report::probes::bucket;
22pub use simulator_api::{
23 mints::short_mint,
24 reroute_report::{
25 Direction, Flow, LegRecord, Pair, Report, ReportBuilder, RerouteReportError, SwapMode,
26 Target, probes::ProbeReport,
27 },
28};
29
30use crate::{
31 ReplacementNotification, RequoteNotification, RerouteLegNotification, VenueNotification,
32};
33
34pub fn leg_records(notification: &RequoteNotification) -> Vec<LegRecord> {
38 let sole_leg = notification.legs.len() == 1;
39 notification
40 .legs
41 .iter()
42 .map(|leg| leg_record(notification, leg, sole_leg))
43 .collect()
44}
45
46fn leg_record(
47 notification: &RequoteNotification,
48 leg: &RerouteLegNotification,
49 sole_leg: bool,
50) -> LegRecord {
51 LegRecord {
52 original_signature: notification.core.original_signature.to_string(),
53 input_mint: leg.input_mint,
54 output_mint: leg.output_mint,
55 amount: leg.amount,
56 swap_mode: SwapMode::parse(&leg.swap_mode),
57 failed: notification.core.error.is_some(),
58 original_failed: notification.core.original_failed,
59 realized_output_amount: notification.realized_output_amount,
60 original_realized_output_amount: sole_leg
61 .then_some(notification.original_realized_output_amount)
62 .flatten(),
63 route_plan: leg.route_plan.clone(),
64 original_route_plan: leg.original_route_plan.clone(),
65 realized_route_plan: leg.realized_route_plan.clone(),
66 quoted_output_amount: Some(leg.original_quoted_out).filter(|"ed| quoted > 0),
68 template: None,
71 new_output_amount: None,
72 error_category: None,
73 output_bps: None,
74 }
75}
76
77pub fn probe_record(notification: &VenueNotification) -> LegRecord {
92 let swap_mode = SwapMode::parse(¬ification.swap_mode);
93 LegRecord {
94 original_signature: notification.core.original_signature.to_string(),
95 input_mint: notification.input_mint,
96 output_mint: notification.output_mint,
97 amount: notification.amount,
98 swap_mode,
99 failed: false,
100 original_failed: notification.core.original_failed,
101 realized_output_amount: None,
102 original_realized_output_amount: None,
103 route_plan: None,
104 original_route_plan: None,
105 realized_route_plan: None,
106 template: Some(notification.template.clone()),
107 quoted_output_amount: same_state_fill(notification, swap_mode),
108 new_output_amount: notification.template_fill,
109 error_category: bucket(
110 ¬ification.core.outcome,
111 notification.core.category.as_deref(),
112 ),
113 output_bps: notification.comparison.change_vs_l1_bps,
114 }
115}
116
117fn same_state_fill(notification: &VenueNotification, swap_mode: SwapMode) -> Option<u64> {
122 let hop = ¬ification.hop;
123 let (fixed, measured) = match swap_mode {
124 SwapMode::ExactIn => (hop.replay_input_amount?, hop.replay_output_amount?),
125 SwapMode::ExactOut => (hop.replay_output_amount?, hop.replay_input_amount?),
126 };
127 let scaled =
128 (u128::from(measured) * u128::from(notification.amount)).checked_div(u128::from(fixed))?;
129 u64::try_from(scaled).ok()
130}
131
132pub fn from_notifications<'a>(
135 target: Target,
136 notifications: impl IntoIterator<Item = &'a ReplacementNotification>,
137) -> Result<Report, RerouteReportError> {
138 let mut builder = ReportBuilder::new(target);
139 notifications
140 .into_iter()
141 .filter_map(|notification| match notification {
142 ReplacementNotification::Requote(requote) => Some(requote),
143 ReplacementNotification::Venue(_) | ReplacementNotification::Original(_) => None,
144 })
145 .flat_map(leg_records)
146 .for_each(|record| builder.push(&record));
147 builder.finish()
148}
149
150pub async fn from_stream(
153 target: Target,
154 stream: impl Stream<Item = ReplacementNotification>,
155) -> Result<Report, RerouteReportError> {
156 let mut builder = ReportBuilder::new(target);
157 let mut stream = std::pin::pin!(stream);
158 while let Some(notification) = stream.next().await {
159 if let ReplacementNotification::Requote(requote) = notification {
160 for record in leg_records(&requote) {
161 builder.push(&record);
162 }
163 }
164 }
165 builder.finish()
166}
167
168pub fn probes_from_notifications<'a>(
171 notifications: impl IntoIterator<Item = &'a ReplacementNotification>,
172) -> ProbeReport {
173 let records: Vec<LegRecord> = notifications
174 .into_iter()
175 .filter_map(|notification| match notification {
176 ReplacementNotification::Venue(probe) => Some(probe_record(probe)),
177 ReplacementNotification::Requote(_) | ReplacementNotification::Original(_) => None,
178 })
179 .collect();
180 ProbeReport::from_records(&records, None)
181}
182
183pub async fn probes_from_stream(
186 stream: impl Stream<Item = ReplacementNotification>,
187) -> ProbeReport {
188 let mut report = ProbeReport::default();
189 let mut stream = std::pin::pin!(stream);
190 while let Some(notification) = stream.next().await {
191 if let ReplacementNotification::Venue(probe) = notification {
192 report.merge(&ProbeReport::from_records(&[probe_record(&probe)], None));
193 }
194 }
195 report
196}
197
198#[cfg(test)]
199mod tests {
200
201 fn fixture_signature() -> String {
203 simulator_api::replacement::Signature::default().to_string()
204 }
205
206 use rstest::rstest;
207 use simulator_api::route_plan::{RouteHop, RouteHopSwapInfo, RoutePlan};
208
209 use super::*;
210
211 const SOL: &str = "So11111111111111111111111111111111111111112";
212 const USDC: &str = "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v";
213 const VENUE_PROGRAM: &str = "BiSoNHVpsVZW2F7rx2eQ59yQwKxzU5NvBcmKshCSUypi";
214 const OTHER_PROGRAM: &str = "whirLbMiicVdio4qvUfM5KAg6Ct8VwpYzGff3uctyCc";
215
216 fn hop(
221 program: Option<&str>,
222 label: &str,
223 input_mint: &str,
224 output_mint: &str,
225 in_amount: u64,
226 ) -> RouteHop {
227 RouteHop {
228 program: program.map(str::to_string),
229 swap_info: RouteHopSwapInfo {
230 label: Some(label.to_string()),
231 amm_key: program.is_none().then(|| "pool".to_string()),
232 input_mint: Some(input_mint.to_string()),
233 in_amount: Some(in_amount.to_string()),
234 output_mint: Some(output_mint.to_string()),
235 out_amount: None,
236 },
237 ..RouteHop::default()
238 }
239 }
240
241 fn plan(hops: Vec<RouteHop>) -> Option<RoutePlan> {
242 RoutePlan::new(hops)
243 }
244
245 fn leg_of(
247 input_mint: &str,
248 output_mint: &str,
249 amount: u64,
250 quoted: Option<&RoutePlan>,
251 original: Option<&RoutePlan>,
252 realized: Option<&RoutePlan>,
253 ) -> RerouteLegNotification {
254 serde_json::from_value(serde_json::json!({
255 "inputMint": input_mint,
256 "outputMint": output_mint,
257 "amount": amount,
258 "swapMode": "ExactIn",
259 "originalQuotedOut": 0,
260 "metisQuotedOut": 0,
261 "routeSummary": "",
262 "routePlan": quoted,
263 "originalRoutePlan": original,
264 "realizedRoutePlan": realized,
265 }))
266 .expect("a leg fixture decodes")
267 }
268
269 struct Notification {
271 legs: Vec<RerouteLegNotification>,
272 err: Option<String>,
273 original_failed: bool,
274 original_realized_output_amount: Option<u64>,
275 }
276
277 impl Notification {
278 fn new(legs: Vec<RerouteLegNotification>) -> Self {
279 Self {
280 legs,
281 err: None,
282 original_failed: false,
283 original_realized_output_amount: None,
284 }
285 }
286
287 fn swap(input_mint: &str, output_mint: &str, amount: u64, output: u64) -> Self {
289 let leg = leg_of(input_mint, output_mint, amount, None, None, None);
290 Self {
291 original_realized_output_amount: Some(output),
292 ..Self::new(vec![leg])
293 }
294 }
295
296 fn reverted(mut self) -> Self {
298 self.err = Some("reverted".to_string());
299 self
300 }
301
302 fn original_failed(mut self) -> Self {
304 self.original_failed = true;
305 self
306 }
307
308 fn build(self) -> RequoteNotification {
309 serde_json::from_value(serde_json::json!({
310 "context": {"slot": 1},
311 "slot": 1,
312 "batchIndex": 0,
313 "originalSignature": fixture_signature(),
314 "originalFailed": self.original_failed,
315 "outcome": if self.err.is_some() { "reverted" } else { "filled" },
318 "legs": self.legs,
319 "routedTransaction": {"data": "AA==", "encoding": "base64"},
320 "err": self.err,
321 "logs": [],
322 "computeUnitsConsumed": 0,
323 "fee": 5_000,
324 "realizedOutputAmount": serde_json::Value::Null,
325 "originalRealizedOutputAmount": self.original_realized_output_amount,
326 }))
327 .expect("a notification fixture decodes")
328 }
329
330 fn build_replacement(self) -> ReplacementNotification {
332 ReplacementNotification::Requote(self.build())
333 }
334 }
335
336 fn anchors() -> Vec<ReplacementNotification> {
341 (1..=3)
342 .map(|n| {
343 Notification::swap(SOL, USDC, n * 1_000_000_000, n * 100_000_000)
344 .build_replacement()
345 })
346 .collect()
347 }
348
349 fn venue() -> Target {
350 Target::new(
351 Some("BisonFi".to_string()),
352 Some(VENUE_PROGRAM.parse().expect("a venue program")),
353 )
354 }
355
356 fn fill(
357 program: &str,
358 label: &str,
359 input: &str,
360 output: &str,
361 amount: u64,
362 ) -> Option<RoutePlan> {
363 plan(vec![hop(Some(program), label, input, output, amount)])
364 }
365
366 fn report_of(notifications: &[ReplacementNotification]) -> Report {
367 from_notifications(venue(), notifications).expect("the venue appears")
368 }
369
370 fn priced(extra: impl IntoIterator<Item = Notification>) -> Vec<ReplacementNotification> {
372 let mut notifications = anchors();
373 notifications.extend(extra.into_iter().map(Notification::build_replacement));
374 notifications
375 }
376
377 fn won_leg(amount: u64) -> Notification {
379 let realized = fill(VENUE_PROGRAM, "BisonFi", SOL, USDC, amount);
380 let l1 = fill(OTHER_PROGRAM, "Whirlpool", SOL, USDC, amount);
381 Notification::new(vec![leg_of(
382 SOL,
383 USDC,
384 amount,
385 None,
386 l1.as_ref(),
387 realized.as_ref(),
388 )])
389 }
390
391 #[test]
399 fn deferring_the_conversion_matches_pricing_each_hop_as_it_arrives() {
400 let report = report_of(&priced([won_leg(2_000_000_000), won_leg(3_000_000_000)]));
401 let total = report.total();
402
403 assert_eq!(report.sol_usd(), Some(100.0));
404 assert_eq!(total.requoted.legs, 2);
405 assert_eq!(total.requoted.usd, 500.0);
407 assert_eq!(total.l1.legs, 0, "L1 had these legs at another venue");
408 }
409
410 #[test]
414 fn the_result_does_not_depend_on_arrival_order() {
415 let forward = priced([won_leg(2_000_000_000), won_leg(3_000_000_000)]);
416 let mut backward = forward.clone();
417 backward.reverse();
418
419 let (forward, backward) = (report_of(&forward), report_of(&backward));
420 assert_eq!(forward.sol_usd(), backward.sol_usd());
421 assert_eq!(forward.total().requoted.usd, backward.total().requoted.usd);
422 assert_eq!(forward.render(None), backward.render(None));
423 }
424
425 #[test]
428 fn neither_side_counts_flow_that_never_landed() {
429 let notifications = priced([
430 won_leg(2_000_000_000),
431 won_leg(9_000_000_000).reverted(),
432 won_leg(9_000_000_000).original_failed(),
433 ]);
434
435 let total = report_of(¬ifications).total();
436 assert_eq!(total.requoted.legs, 1, "only the landed leg counts");
437 assert_eq!(total.requoted.usd, 200.0);
438 }
439
440 #[test]
443 fn a_multi_leg_notification_prices_nothing() {
444 let legs = vec![
445 leg_of(SOL, USDC, 1_000_000_000, None, None, None),
446 leg_of(USDC, SOL, 100_000_000, None, None, None),
447 ];
448 let mut notification = Notification::new(legs);
449 notification.original_realized_output_amount = Some(100_000_000);
450 let records = leg_records(¬ification.build());
451 assert_eq!(records.len(), 2);
452 assert!(
453 records
454 .iter()
455 .all(|r| r.original_realized_output_amount.is_none())
456 );
457 }
458
459 fn probe(
463 template: &str,
464 template_fill: Option<u64>,
465 l1_fill: Option<u64>,
466 change_vs_l1_bps: Option<i64>,
467 outcome: &str,
468 category: Option<&str>,
469 ) -> VenueNotification {
470 serde_json::from_value(serde_json::json!({
471 "context": {"slot": 1},
472 "slot": 1,
473 "batchIndex": 0,
474 "originalSignature": fixture_signature(),
475 "originalFailed": false,
476 "template": template,
477 "program": USDC,
478 "hop": {
479 "slot": 1,
480 "blockTime": 1_767_225_600i64,
481 "txIndex": 0,
482 "ixIndex": 0,
483 "legIndex": 0,
484 "inputAmount": 1_000_000_000u64,
485 "outputAmount": l1_fill.unwrap_or_default(),
486 },
487 "quoteTxIndex": 0,
488 "quoteLagBlocks": 0,
489 "inputMint": SOL,
490 "outputMint": USDC,
491 "amount": 1_000_000_000u64,
492 "swapMode": "ExactIn",
493 "templateFill": template_fill,
494 "l1Fill": l1_fill,
495 "changeVsL1Bps": change_vs_l1_bps,
496 "outcome": outcome,
497 "category": category,
498 }))
499 .expect("a probe fixture decodes")
500 }
501
502 #[test]
505 fn probe_record_maps_template_fields_onto_the_shared_record() {
506 let notification = probe(
507 "venue-a",
508 Some(1_010_000_000),
509 Some(1_000_000_000),
510 Some(100),
511 "filled",
512 None,
513 );
514 let record = probe_record(¬ification);
515
516 assert_eq!(record.template.as_deref(), Some("venue-a"));
517 assert_eq!(record.new_output_amount, Some(1_010_000_000));
518 assert_eq!(
519 record.quoted_output_amount, None,
520 "the onchain fill is not the same-state baseline"
521 );
522 assert_eq!(record.output_bps, Some(100));
523 assert_eq!(record.error_category, None);
524 }
525
526 #[rstest]
529 #[case::exact_in_as_replayed(
530 "ExactIn",
531 Some(1_000_000_000),
532 Some(990_000_000),
533 Some(990_000_000)
534 )]
535 #[case::exact_in_rescaled("ExactIn", Some(500_000_000), Some(495_000_000), Some(990_000_000))]
536 #[case::exact_out_rescaled("ExactOut", Some(400_000_000), Some(500_000_000), Some(800_000_000))]
537 #[case::not_replayed("ExactIn", None, None, None)]
538 #[case::replay_moved_nothing("ExactIn", Some(0), Some(0), None)]
539 fn probe_record_takes_the_same_state_baseline_from_the_replayed_hop(
540 #[case] swap_mode: &str,
541 #[case] replay_input_amount: Option<u64>,
542 #[case] replay_output_amount: Option<u64>,
543 #[case] expected: Option<u64>,
544 ) {
545 let mut notification = probe(
546 "venue-a",
547 Some(1_010_000_000),
548 Some(1_000_000_000),
549 Some(100),
550 "filled",
551 None,
552 );
553 notification.swap_mode = swap_mode.to_string();
554 notification.hop.replay_input_amount = replay_input_amount;
555 notification.hop.replay_output_amount = replay_output_amount;
556
557 assert_eq!(probe_record(¬ification).quoted_output_amount, expected);
558 }
559
560 #[rstest]
563 #[case::replayed(Some((1_000_000_000, 1_010_000_000)), "+0.00 (1 pairs)")]
564 #[case::not_replayed(None, "—")]
565 fn the_same_state_column_scores_against_the_replay_not_the_onchain_fill(
566 #[case] replay: Option<(u64, u64)>,
567 #[case] vs_same_state: &str,
568 ) {
569 let mut notification = probe(
570 "venue-a",
571 Some(1_010_000_000),
572 Some(1_000_000_000),
573 Some(100),
574 "filled",
575 None,
576 );
577 notification.hop.replay_input_amount = replay.map(|(input, _)| input);
578 notification.hop.replay_output_amount = replay.map(|(_, output)| output);
579
580 let rendered =
581 probes_from_notifications(&[ReplacementNotification::Venue(notification)]).render("R1");
582 assert!(
583 rendered.contains(&format!(
584 "| venue-a | 1 | 1 (100.0%) | +100.00 (1 scored) | — | {vs_same_state} |"
585 )),
586 "{rendered}"
587 );
588 }
589
590 #[rstest]
593 #[case::filled("filled", None, "filled")]
594 #[case::reverted("reverted", Some("slippage"), "reverted_slippage")]
595 #[case::unattributed("unattributed", None, "unattributed")]
596 #[case::unsimulatable("unsimulatable", None, "unsimulatable")]
597 fn probe_record_reconstructs_the_pre_split_bucket_vocabulary(
598 #[case] outcome: &str,
599 #[case] category: Option<&str>,
600 #[case] expected_bucket: &str,
601 ) {
602 let notification = probe("venue-a", None, None, None, outcome, category);
603 let record = probe_record(¬ification);
604 let report = ProbeReport::from_records(&[record], None);
605 assert_eq!(
606 report.by_template["venue-a"].outcomes.get(expected_bucket),
607 Some(&1)
608 );
609 }
610
611 #[test]
612 fn from_notifications_ignores_venue_variants() {
613 let mut notifications = priced([won_leg(2_000_000_000)]);
614 notifications.push(ReplacementNotification::Venue(probe(
615 "venue-a",
616 Some(1_010_000_000),
617 Some(1_000_000_000),
618 Some(100),
619 "filled",
620 None,
621 )));
622
623 let total = report_of(¬ifications).total();
624 assert_eq!(total.requoted.legs, 1, "the probe contributed no leg");
625 }
626
627 #[test]
628 fn probes_from_notifications_ignores_requote_variants() {
629 let mut notifications = priced([won_leg(2_000_000_000)]);
630 notifications.push(ReplacementNotification::Venue(probe(
631 "venue-a",
632 Some(1_010_000_000),
633 Some(1_000_000_000),
634 Some(100),
635 "filled",
636 None,
637 )));
638
639 let probes = probes_from_notifications(¬ifications);
640 assert_eq!(probes.by_template.len(), 1);
641 assert_eq!(
642 probes.by_template["venue-a"].outcomes.get("filled"),
643 Some(&1)
644 );
645 }
646
647 #[tokio::test]
650 async fn from_stream_ignores_venue_variants_in_a_mixed_stream() {
651 let mut notifications = priced([won_leg(2_000_000_000)]);
652 notifications.push(ReplacementNotification::Venue(probe(
653 "venue-a",
654 Some(1_010_000_000),
655 Some(1_000_000_000),
656 Some(100),
657 "filled",
658 None,
659 )));
660
661 let from_slice = report_of(¬ifications);
662 let from_stream = from_stream(venue(), futures::stream::iter(notifications))
663 .await
664 .expect("the template appears");
665
666 assert_eq!(
667 from_stream.total().requoted.legs,
668 1,
669 "the probe contributed no leg"
670 );
671 assert_eq!(from_slice.render(None), from_stream.render(None));
672 }
673
674 #[tokio::test]
677 async fn probes_from_stream_matches_probes_from_notifications_on_a_mixed_stream() {
678 let mut notifications = priced([won_leg(2_000_000_000)]);
679 notifications.push(ReplacementNotification::Venue(probe(
680 "venue-a",
681 Some(1_010_000_000),
682 Some(1_000_000_000),
683 Some(100),
684 "filled",
685 None,
686 )));
687 notifications.push(ReplacementNotification::Venue(probe(
688 "venue-a",
689 None,
690 None,
691 None,
692 "unattributed",
693 None,
694 )));
695
696 let from_slice = probes_from_notifications(¬ifications);
697 let from_stream = probes_from_stream(futures::stream::iter(notifications)).await;
698
699 assert_eq!(
700 from_slice.by_template.len(),
701 1,
702 "the Requote notification contributed no template"
703 );
704 let slice_template = &from_slice.by_template["venue-a"];
705 let stream_template = &from_stream.by_template["venue-a"];
706 assert_eq!(slice_template.outcomes, stream_template.outcomes);
707 assert_eq!(
708 slice_template.scored_vs_historical,
709 stream_template.scored_vs_historical
710 );
711 assert_eq!(
712 slice_template.bps_vs_historical_total,
713 stream_template.bps_vs_historical_total
714 );
715 assert_eq!(
716 slice_template.pairs_vs_same_state,
717 stream_template.pairs_vs_same_state
718 );
719 assert!(
720 (slice_template.bps_vs_same_state_total - stream_template.bps_vs_same_state_total)
721 .abs()
722 < 1e-9
723 );
724 }
725}