1use std::collections::BTreeMap;
14
15use solana_address::Address;
16
17use super::{LegRecord, Prices, Samples};
18use crate::route_plan::{RouteHop, RoutePlan};
19
20fn in_amount(hop: &RouteHop) -> Option<u128> {
21 hop.swap_info.in_amount.as_ref()?.parse().ok()
22}
23
24#[derive(Debug, thiserror::Error)]
27pub enum RerouteReportError {
28 #[error(
30 "{asked} never appears in this stream.\nIt names {} venues; the busiest are {}.",
31 .venues.len(),
32 busiest(.venues),
33 )]
34 NothingMatched {
35 asked: String,
37 venues: Vec<(String, u64)>,
39 },
40}
41
42const NAMED_IN_ERROR: usize = 8;
43
44fn busiest(venues: &[(String, u64)]) -> String {
45 let mut ranked: Vec<_> = venues.iter().collect();
46 ranked.sort_unstable_by(|(a_label, a_hops), (b_label, b_hops)| {
47 b_hops.cmp(a_hops).then_with(|| a_label.cmp(b_label))
48 });
49 ranked
50 .iter()
51 .take(NAMED_IN_ERROR)
52 .map(|(label, hops)| format!("{label} ({hops})"))
53 .collect::<Vec<_>>()
54 .join(", ")
55}
56
57#[derive(Clone, Default, Debug)]
62pub struct Target {
63 label: Option<String>,
64 program: Option<(Address, String)>,
66}
67
68impl Target {
69 pub fn new(label: Option<String>, program: Option<Address>) -> Self {
71 Self {
72 label,
73 program: program.map(|program| (program, program.to_string())),
74 }
75 }
76
77 #[allow(missing_docs)]
78 pub fn label(&self) -> Option<&str> {
79 self.label.as_deref()
80 }
81
82 #[allow(missing_docs)]
83 pub fn program(&self) -> Option<Address> {
84 self.program.as_ref().map(|(program, _)| *program)
85 }
86
87 pub fn claims_quoted(&self, hop: &RouteHop) -> bool {
90 match &self.label {
91 Some(label) => hop.label() == Some(label.as_str()),
92 None => false,
93 }
94 }
95
96 pub fn claims_fill(&self, hop: &RouteHop) -> bool {
99 if let Some((_, key)) = &self.program {
100 return hop.program.as_deref() == Some(key.as_str());
101 }
102 self.claims_quoted(hop)
103 }
104
105 fn describe(&self) -> String {
106 if let Some(label) = &self.label {
107 format!("label {label:?}")
108 } else if let Some((program, _)) = &self.program {
109 format!("program {program}")
110 } else {
111 "that venue".to_string()
112 }
113 }
114}
115
116#[derive(Default, Clone, Copy, Debug)]
118pub struct Flow {
119 pub legs: u64,
121 pub usd: f64,
123 pub without_amount: u64,
125 pub without_price: u64,
127 share_usd: f64,
129}
130
131impl Flow {
132 fn merge(&mut self, other: Self) {
133 self.legs += other.legs;
134 self.usd += other.usd;
135 self.without_amount += other.without_amount;
136 self.without_price += other.without_price;
137 self.share_usd += other.share_usd;
138 }
139}
140
141#[derive(Default, Clone, Copy, Debug)]
143pub struct Direction {
144 pub l1: Flow,
146 pub requoted: Flow,
148 l1_all: f64,
150 requoted_all: f64,
151}
152
153impl Direction {
154 fn merge(&mut self, other: Self) {
155 self.l1.merge(other.l1);
156 self.requoted.merge(other.requoted);
157 self.l1_all += other.l1_all;
158 self.requoted_all += other.requoted_all;
159 }
160
161 pub fn share(&self) -> Option<(f64, f64)> {
164 (self.l1_all > 0.0 && self.requoted_all > 0.0).then(|| {
165 (
166 self.l1.share_usd / self.l1_all * 100.0,
167 self.requoted.share_usd / self.requoted_all * 100.0,
168 )
169 })
170 }
171
172 pub const fn present(&self) -> bool {
174 self.l1.legs > 0 || self.requoted.legs > 0
175 }
176
177 pub const fn unpriced(&self) -> bool {
179 self.l1.without_price > 0 || self.requoted.without_price > 0
180 }
181
182 pub fn fully_unpriced(&self) -> bool {
184 self.unpriced() && self.l1.usd == 0.0 && self.requoted.usd == 0.0
185 }
186
187 pub(super) fn rank(&self) -> (u64, u64) {
189 let usd = self.l1.usd.max(self.requoted.usd);
190 (usd as u64, self.l1.legs.max(self.requoted.legs))
191 }
192}
193
194pub(super) fn fold(directions: impl IntoIterator<Item = Direction>) -> Direction {
195 directions
196 .into_iter()
197 .fold(Direction::default(), |mut total, direction| {
198 total.merge(direction);
199 total
200 })
201}
202
203pub type Pair = (String, String);
205
206#[derive(Clone, Copy)]
207enum Side {
208 L1,
209 Requoted,
210}
211
212#[derive(Debug)]
214pub struct Report {
215 by_direction: BTreeMap<Pair, Direction>,
216 target: Target,
217 sol_usd: Option<f64>,
219}
220
221impl Report {
222 pub fn from_records<'a>(
224 target: Target,
225 records: impl IntoIterator<Item = &'a LegRecord>,
226 ) -> Result<Self, RerouteReportError> {
227 let mut builder = ReportBuilder::new(target);
228 for record in records {
229 builder.push(record);
230 }
231 builder.finish()
232 }
233
234 pub const fn target(&self) -> &Target {
236 &self.target
237 }
238
239 pub const fn sol_usd(&self) -> Option<f64> {
242 self.sol_usd
243 }
244
245 pub fn by_direction(&self) -> impl Iterator<Item = (&Pair, &Direction)> {
248 self.by_direction.iter()
249 }
250
251 pub fn total(&self) -> Direction {
254 fold(self.by_direction.values().copied())
255 }
256}
257
258pub struct ReportBuilder {
265 target: Target,
266 samples: Samples,
267 by_direction: Directions,
268 labels: BTreeMap<String, u64>,
270}
271
272impl ReportBuilder {
273 pub fn new(target: Target) -> Self {
275 Self {
276 target,
277 samples: Samples::default(),
278 by_direction: Directions::default(),
279 labels: BTreeMap::new(),
280 }
281 }
282
283 pub fn push(&mut self, record: &LegRecord) {
285 self.samples.push(record);
286
287 if record.failed || record.original_failed {
289 return;
290 }
291 let Self {
292 target,
293 by_direction,
294 labels,
295 ..
296 } = self;
297 fn hops_of(plan: &Option<RoutePlan>) -> Option<&[RouteHop]> {
298 plan.as_ref().map(RoutePlan::hops)
299 }
300 let quoted = hops_of(&record.route_plan);
302 for label in quoted.iter().copied().flatten().filter_map(RouteHop::label) {
303 match labels.get_mut(label) {
304 Some(hops) => *hops += 1,
305 None => {
306 labels.insert(label.to_string(), 1);
307 }
308 }
309 }
310
311 let (requoted, from_quote) = match hops_of(&record.realized_route_plan) {
313 Some(filled) => (filled, false),
314 None => (quoted.unwrap_or_default(), true),
315 };
316 let claimed = |hop: &RouteHop| match from_quote {
317 true => target.claims_quoted(hop),
318 false => target.claims_fill(hop),
319 };
320 for hop in requoted.iter().filter(|hop| claimed(hop)) {
321 by_direction.record(Side::Requoted, hop);
322 }
323
324 let l1 = hops_of(&record.original_route_plan);
325 for hop in l1
326 .iter()
327 .copied()
328 .flatten()
329 .filter(|hop| target.claims_fill(hop))
330 {
331 by_direction.record(Side::L1, hop);
332 }
333
334 let leg_amount = u128::from(record.amount) as f64;
337 by_direction.accumulate_share(
338 Side::Requoted,
339 requoted,
340 record.input_mint,
341 leg_amount,
342 claimed,
343 );
344 if let Some(l1) = l1 {
345 by_direction.accumulate_share(Side::L1, l1, record.input_mint, leg_amount, |hop| {
346 target.claims_fill(hop)
347 });
348 }
349 }
350
351 pub fn finish(self) -> Result<Report, RerouteReportError> {
354 let prices = self.samples.prices();
355 let report = Report {
356 sol_usd: prices.as_ref().map(Prices::sol_usd),
357 by_direction: self.by_direction.price(prices.as_ref()),
358 target: self.target,
359 };
360 let total = report.total();
361 if total.l1.legs == 0 && total.requoted.legs == 0 {
362 return Err(RerouteReportError::NothingMatched {
363 asked: report.target.describe(),
364 venues: self.labels.into_iter().collect(),
365 });
366 }
367 Ok(report)
368 }
369}
370
371#[derive(Default)]
374struct Directions(BTreeMap<Pair, DirectionAccum>);
375
376impl Directions {
377 fn record(&mut self, side: Side, hop: &RouteHop) {
379 let Some(key) = key_of(hop) else {
380 return;
381 };
382 let flow = &mut self.0.entry(key).or_default().side_mut(side).flow;
383 flow.legs += 1;
384 match in_amount(hop) {
385 Some(amount) => flow.raw += amount,
386 None => flow.without_amount += 1,
387 }
388 }
389
390 fn accumulate_share(
396 &mut self,
397 side: Side,
398 hops: &[RouteHop],
399 leg_mint: Address,
400 leg_amount: f64,
401 claimed: impl Fn(&RouteHop) -> bool,
402 ) {
403 let total: u64 = hops.iter().map(|hop| hop.percent).sum();
404 if total == 0 {
405 return;
406 }
407 for hop in hops {
408 let Some(key) = key_of(hop) else {
409 continue;
410 };
411 let value = leg_amount * hop.percent as f64 / total as f64;
412 let share = &mut self.0.entry(key).or_default().side_mut(side).share;
413 credit(&mut share.all, leg_mint, value);
414 if claimed(hop) {
415 credit(&mut share.claimed, leg_mint, value);
416 }
417 }
418 }
419
420 fn price(self, prices: Option<&Prices>) -> BTreeMap<Pair, Direction> {
423 self.0
424 .into_iter()
425 .map(|(pair, accum)| {
426 let direction = accum.price(&pair.0, prices);
427 (pair, direction)
428 })
429 .filter(|(_, direction)| {
430 direction.present() || direction.l1_all > 0.0 || direction.requoted_all > 0.0
431 })
432 .collect()
433 }
434}
435
436fn key_of(hop: &RouteHop) -> Option<Pair> {
439 Some((
440 hop.input_mint()?.to_string(),
441 hop.output_mint()?.to_string(),
442 ))
443}
444
445fn credit(bucket: &mut Vec<(Address, f64)>, mint: Address, value: f64) {
448 match bucket.iter_mut().find(|(held, _)| *held == mint) {
449 Some((_, total)) => *total += value,
450 None => bucket.push((mint, value)),
451 }
452}
453
454#[derive(Default)]
456struct FlowAccum {
457 legs: u64,
458 raw: u128,
460 without_amount: u64,
461}
462
463impl FlowAccum {
464 fn price(self, mint: &str, prices: Option<&Prices>, share_usd: f64) -> Flow {
465 let usd = prices.and_then(|prices| prices.usd_str(mint, self.raw as f64));
466 Flow {
467 legs: self.legs,
468 usd: usd.unwrap_or_default(),
469 without_amount: self.without_amount,
470 without_price: match usd {
472 Some(_) => 0,
473 None => self.legs - self.without_amount,
474 },
475 share_usd,
476 }
477 }
478}
479
480#[derive(Default)]
482struct ShareAccum {
483 all: Vec<(Address, f64)>,
484 claimed: Vec<(Address, f64)>,
485}
486
487impl ShareAccum {
488 fn price(&self, prices: Option<&Prices>) -> (f64, f64) {
490 let sum = |bucket: &[(Address, f64)]| {
491 bucket
492 .iter()
493 .filter_map(|(mint, raw)| prices?.usd(mint, *raw))
494 .fold(0.0, |total, usd| total + usd)
497 };
498 (sum(&self.all), sum(&self.claimed))
499 }
500}
501
502#[derive(Default)]
504struct SideAccum {
505 flow: FlowAccum,
506 share: ShareAccum,
507}
508
509#[derive(Default)]
510struct DirectionAccum {
511 l1: SideAccum,
512 requoted: SideAccum,
513}
514
515impl DirectionAccum {
516 fn side_mut(&mut self, side: Side) -> &mut SideAccum {
517 match side {
518 Side::L1 => &mut self.l1,
519 Side::Requoted => &mut self.requoted,
520 }
521 }
522
523 fn price(self, mint: &str, prices: Option<&Prices>) -> Direction {
524 let (l1_all, l1_claimed) = self.l1.share.price(prices);
525 let (requoted_all, requoted_claimed) = self.requoted.share.price(prices);
526 Direction {
527 l1: self.l1.flow.price(mint, prices, l1_claimed),
528 requoted: self.requoted.flow.price(mint, prices, requoted_claimed),
529 l1_all,
530 requoted_all,
531 }
532 }
533}
534
535#[cfg(test)]
536mod tests {
537 use super::*;
538 use crate::{
539 mints,
540 reroute_report::testing::{hop, plan, record_of},
541 };
542
543 const SOL: &str = "So11111111111111111111111111111111111111112";
544 const USDC: &str = "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v";
545 const VENUE_PROGRAM: &str = "BiSoNHVpsVZW2F7rx2eQ59yQwKxzU5NvBcmKshCSUypi";
546 const OTHER_PROGRAM: &str = "whirLbMiicVdio4qvUfM5KAg6Ct8VwpYzGff3uctyCc";
547
548 fn anchors() -> Vec<LegRecord> {
551 (1..=3)
552 .map(|n| LegRecord {
553 original_realized_output_amount: Some(n * 100_000_000),
554 ..record_of(mints::SOL, mints::USDC, n * 1_000_000_000, None, None, None)
555 })
556 .collect()
557 }
558
559 fn venue() -> Target {
560 Target::new(
561 Some("BisonFi".to_string()),
562 Some(VENUE_PROGRAM.parse().expect("a venue program")),
563 )
564 }
565
566 fn fill(
567 program: &str,
568 label: &str,
569 input: &str,
570 output: &str,
571 amount: u64,
572 ) -> Option<RoutePlan> {
573 plan(vec![hop(Some(program), label, input, output, amount)])
574 }
575
576 fn report_of(records: &[LegRecord]) -> Report {
577 Report::from_records(venue(), records).expect("the venue appears")
578 }
579
580 fn priced(extra: impl IntoIterator<Item = LegRecord>) -> Vec<LegRecord> {
582 let mut records = anchors();
583 records.extend(extra);
584 records
585 }
586
587 fn won_leg(amount: u64) -> LegRecord {
589 let realized = fill(VENUE_PROGRAM, "BisonFi", SOL, USDC, amount);
590 let l1 = fill(OTHER_PROGRAM, "Whirlpool", SOL, USDC, amount);
591 record_of(mints::SOL, mints::USDC, amount, None, l1, realized)
592 }
593
594 #[test]
598 fn a_hop_with_an_unnamed_mint_opens_no_direction() {
599 let mut unnamed = hop(Some(VENUE_PROGRAM), "BisonFi", USDC, SOL, 1_000_000);
600 unnamed.swap_info.output_mint = None;
601 let l1 = plan(vec![
602 hop(Some(VENUE_PROGRAM), "BisonFi", SOL, USDC, 2_000_000_000),
603 unnamed,
604 ]);
605 let report = report_of(&priced([record_of(
606 mints::SOL,
607 mints::USDC,
608 2_000_000_000,
609 None,
610 l1,
611 None,
612 )]));
613
614 let pairs: Vec<&Pair> = report.by_direction().map(|(pair, _)| pair).collect();
615 assert_eq!(pairs, [&(SOL.to_string(), USDC.to_string())]);
616 assert_eq!(report.total().l1.legs, 1, "only the named hop counts");
617 }
618
619 #[test]
623 fn deferring_the_conversion_matches_pricing_each_hop_as_it_arrives() {
624 let report = report_of(&priced([won_leg(2_000_000_000), won_leg(3_000_000_000)]));
625 let total = report.total();
626
627 assert_eq!(report.sol_usd(), Some(100.0));
628 assert_eq!(total.requoted.legs, 2);
629 assert_eq!(total.requoted.usd, 500.0);
631 assert_eq!(total.l1.legs, 0, "L1 had these legs at another venue");
632 }
633
634 #[test]
637 fn the_result_does_not_depend_on_arrival_order() {
638 let forward = priced([won_leg(2_000_000_000), won_leg(3_000_000_000)]);
639 let mut backward = forward.clone();
640 backward.reverse();
641
642 let (forward, backward) = (report_of(&forward), report_of(&backward));
643 assert_eq!(forward.sol_usd(), backward.sol_usd());
644 assert_eq!(forward.total().requoted.usd, backward.total().requoted.usd);
645 assert_eq!(forward.render(None), backward.render(None));
646 }
647
648 #[test]
651 fn neither_side_counts_flow_that_never_landed() {
652 let records = priced([
653 won_leg(2_000_000_000),
654 LegRecord {
655 failed: true,
656 ..won_leg(9_000_000_000)
657 },
658 LegRecord {
659 original_failed: true,
660 ..won_leg(9_000_000_000)
661 },
662 ]);
663
664 let total = report_of(&records).total();
665 assert_eq!(total.requoted.legs, 1, "only the landed leg counts");
666 assert_eq!(total.requoted.usd, 200.0);
667 }
668
669 #[test]
672 fn a_share_splits_a_leg_where_notional_counts_it_twice() {
673 let two_hops = plan(vec![
674 hop(Some(VENUE_PROGRAM), "BisonFi", SOL, USDC, 1_000_000_000),
675 hop(Some(OTHER_PROGRAM), "Whirlpool", USDC, "BONK", 100_000_000),
676 ]);
677 let l1 = fill(VENUE_PROGRAM, "BisonFi", SOL, USDC, 1_000_000_000);
678 let record = record_of(mints::SOL, mints::USDC, 1_000_000_000, None, l1, two_hops);
679 let report = report_of(&priced([record]));
680
681 let total = report.total();
682 assert_eq!(total.requoted.usd, 100.0);
684 assert_eq!(total.requoted_all, 100.0, "the leg is counted once");
686 assert_eq!(
687 total.requoted.share_usd, 50.0,
688 "half the route was the venue's"
689 );
690 assert_eq!(total.share(), Some((100.0, 50.0)));
692
693 let (_, first) = report
695 .by_direction()
696 .find(|((input, output), _)| input == SOL && output == USDC)
697 .expect("the venue's direction");
698 assert_eq!(first.requoted.share_usd, 50.0);
699 assert_eq!(first.requoted_all, 50.0, "that direction held half the leg");
700 }
701
702 #[test]
705 fn a_fill_prefers_the_program_and_falls_back_to_the_label() {
706 let filled = fill(VENUE_PROGRAM, "BisonFi", SOL, USDC, 1_000);
707 let record = record_of(mints::SOL, mints::USDC, 1_000, None, filled.clone(), filled);
708 let hop = &record.original_route_plan.as_ref().expect("a plan").hops()[0];
709
710 let by_label = Target::new(Some("BisonFi".to_string()), None);
711 assert!(by_label.claims_fill(hop));
712 assert!(by_label.claims_quoted(hop));
713
714 let other = Target::new(Some("BisonFi".to_string()), Some(Address::new_unique()));
716 assert!(!other.claims_fill(hop));
717
718 let by_program = Target::new(None, Some(VENUE_PROGRAM.parse().expect("a program")));
719 assert!(by_program.claims_fill(hop));
720 assert!(!by_program.claims_quoted(hop));
722 }
723
724 #[test]
728 fn the_report_is_swaps_and_dollars_only() {
729 let sell = fill(VENUE_PROGRAM, "BisonFi", SOL, USDC, 1_000_000_000);
730 let buy = fill(VENUE_PROGRAM, "BisonFi", USDC, SOL, 100_000_000);
731 let report = report_of(&priced([
732 record_of(mints::SOL, mints::USDC, 1_000_000_000, None, None, sell),
733 record_of(mints::USDC, mints::SOL, 100_000_000, None, None, buy),
734 ]));
735
736 let json = report.to_json();
738 assert_eq!(json["total"]["l1"]["swaps"], 0);
739 assert_eq!(json["total"]["requoted"]["swaps"], 2);
740 assert_eq!(json["total"]["requoted"]["usd"], 200.0);
741
742 let table = report.render(None);
744 let totals = table.split('→').next().expect("a totals block");
745 assert!(totals.contains("swaps") && totals.contains("volume"));
746 assert!(!totals.contains("raw in"), "a raw amount reached the table");
747 assert!(!table.contains("quoted fill"));
749 }
750
751 #[test]
754 fn a_range_that_cannot_be_priced_reports_no_dollars() {
755 let report = report_of(&[won_leg(2_000_000_000)]);
756 let total = report.total();
757
758 assert_eq!(report.sol_usd(), None);
759 assert_eq!(total.requoted.legs, 1);
760 assert_eq!(total.requoted.without_price, 1);
761 assert!(total.fully_unpriced());
762
763 let table = report.render(None);
764 assert!(!table.contains("volume"), "a dollar row without a price");
765 assert!(table.contains("could not price"));
766 }
767
768 #[test]
771 fn a_selector_that_matches_nothing_says_so() {
772 let quote = plan(vec![hop(None, "Whirlpool", SOL, USDC, 1_000)]);
773 let records = vec![record_of(mints::SOL, mints::USDC, 1_000, quote, None, None)];
774
775 let target = Target::new(Some("Nope".to_string()), None);
776 let error = Report::from_records(target, &records).expect_err("the venue never appears");
777
778 let message = error.to_string();
779 assert!(message.contains("Nope"), "names what was asked for");
780 assert!(message.contains("Whirlpool (1)"));
782 }
783
784 #[test]
786 fn the_subtitle_is_the_callers() {
787 let report = report_of(&[won_leg(2_000_000_000)]);
788 assert!(report.render(Some("slots 1–100")).contains("slots 1–100"));
789 assert!(!report.render(None).contains("slots"));
790 }
791}