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 #[expect(missing_docs, reason = "self-explanatory")]
78 pub fn label(&self) -> Option<&str> {
79 self.label.as_deref()
80 }
81
82 #[expect(missing_docs, reason = "self-explanatory")]
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 #[expect(
191 clippy::cast_possible_truncation,
192 clippy::cast_sign_loss,
193 reason = "non-negative USD volume truncated to whole dollars for display sorting"
194 )]
195 (usd as u64, self.l1.legs.max(self.requoted.legs))
196 }
197}
198
199pub(super) fn fold(directions: impl IntoIterator<Item = Direction>) -> Direction {
200 directions
201 .into_iter()
202 .fold(Direction::default(), |mut total, direction| {
203 total.merge(direction);
204 total
205 })
206}
207
208pub type Pair = (String, String);
210
211#[derive(Clone, Copy)]
212enum Side {
213 L1,
214 Requoted,
215}
216
217#[derive(Debug)]
219pub struct Report {
220 by_direction: BTreeMap<Pair, Direction>,
221 target: Target,
222 sol_usd: Option<f64>,
224}
225
226impl Report {
227 pub fn from_records<'a>(
229 target: Target,
230 records: impl IntoIterator<Item = &'a LegRecord>,
231 ) -> Result<Self, RerouteReportError> {
232 let mut builder = ReportBuilder::new(target);
233 for record in records {
234 builder.push(record);
235 }
236 builder.finish()
237 }
238
239 pub const fn target(&self) -> &Target {
241 &self.target
242 }
243
244 pub const fn sol_usd(&self) -> Option<f64> {
247 self.sol_usd
248 }
249
250 pub fn by_direction(&self) -> impl Iterator<Item = (&Pair, &Direction)> {
253 self.by_direction.iter()
254 }
255
256 pub fn total(&self) -> Direction {
259 fold(self.by_direction.values().copied())
260 }
261}
262
263pub struct ReportBuilder {
270 target: Target,
271 samples: Samples,
272 by_direction: Directions,
273 labels: BTreeMap<String, u64>,
275}
276
277impl ReportBuilder {
278 pub fn new(target: Target) -> Self {
280 Self {
281 target,
282 samples: Samples::default(),
283 by_direction: Directions::default(),
284 labels: BTreeMap::new(),
285 }
286 }
287
288 pub fn push(&mut self, record: &LegRecord) {
290 self.samples.push(record);
291
292 if record.failed || record.original_failed {
294 return;
295 }
296 let Self {
297 target,
298 by_direction,
299 labels,
300 ..
301 } = self;
302 fn hops_of(plan: &Option<RoutePlan>) -> Option<&[RouteHop]> {
303 plan.as_ref().map(RoutePlan::hops)
304 }
305 let quoted = hops_of(&record.route_plan);
307 for label in quoted.iter().copied().flatten().filter_map(RouteHop::label) {
308 match labels.get_mut(label) {
309 Some(hops) => *hops += 1,
310 None => {
311 labels.insert(label.to_string(), 1);
312 }
313 }
314 }
315
316 let (requoted, from_quote) = match hops_of(&record.realized_route_plan) {
318 Some(filled) => (filled, false),
319 None => (quoted.unwrap_or_default(), true),
320 };
321 let claimed = |hop: &RouteHop| {
322 if from_quote {
323 target.claims_quoted(hop)
324 } else {
325 target.claims_fill(hop)
326 }
327 };
328 for hop in requoted.iter().filter(|hop| claimed(hop)) {
329 by_direction.record(Side::Requoted, hop);
330 }
331
332 let l1 = hops_of(&record.original_route_plan);
333 for hop in l1
334 .iter()
335 .copied()
336 .flatten()
337 .filter(|hop| target.claims_fill(hop))
338 {
339 by_direction.record(Side::L1, hop);
340 }
341
342 let leg_amount = u128::from(record.amount) as f64;
345 by_direction.accumulate_share(
346 Side::Requoted,
347 requoted,
348 record.input_mint,
349 leg_amount,
350 claimed,
351 );
352 if let Some(l1) = l1 {
353 by_direction.accumulate_share(Side::L1, l1, record.input_mint, leg_amount, |hop| {
354 target.claims_fill(hop)
355 });
356 }
357 }
358
359 pub fn finish(self) -> Result<Report, RerouteReportError> {
362 let prices = self.samples.prices();
363 let report = Report {
364 sol_usd: prices.as_ref().map(Prices::sol_usd),
365 by_direction: self.by_direction.price(prices.as_ref()),
366 target: self.target,
367 };
368 let total = report.total();
369 if total.l1.legs == 0 && total.requoted.legs == 0 {
370 return Err(RerouteReportError::NothingMatched {
371 asked: report.target.describe(),
372 venues: self.labels.into_iter().collect(),
373 });
374 }
375 Ok(report)
376 }
377}
378
379#[derive(Default)]
382struct Directions(BTreeMap<Pair, DirectionAccum>);
383
384impl Directions {
385 fn record(&mut self, side: Side, hop: &RouteHop) {
387 let Some(key) = key_of(hop) else {
388 return;
389 };
390 let flow = &mut self.0.entry(key).or_default().side_mut(side).flow;
391 flow.legs += 1;
392 match in_amount(hop) {
393 Some(amount) => flow.raw += amount,
394 None => flow.without_amount += 1,
395 }
396 }
397
398 fn accumulate_share(
404 &mut self,
405 side: Side,
406 hops: &[RouteHop],
407 leg_mint: Address,
408 leg_amount: f64,
409 claimed: impl Fn(&RouteHop) -> bool,
410 ) {
411 let total: u64 = hops.iter().map(|hop| hop.percent).sum();
412 if total == 0 {
413 return;
414 }
415 for hop in hops {
416 let Some(key) = key_of(hop) else {
417 continue;
418 };
419 let value = leg_amount * hop.percent as f64 / total as f64;
420 let share = &mut self.0.entry(key).or_default().side_mut(side).share;
421 credit(&mut share.all, leg_mint, value);
422 if claimed(hop) {
423 credit(&mut share.claimed, leg_mint, value);
424 }
425 }
426 }
427
428 fn price(self, prices: Option<&Prices>) -> BTreeMap<Pair, Direction> {
431 self.0
432 .into_iter()
433 .map(|(pair, accum)| {
434 let direction = accum.price(&pair.0, prices);
435 (pair, direction)
436 })
437 .filter(|(_, direction)| {
438 direction.present() || direction.l1_all > 0.0 || direction.requoted_all > 0.0
439 })
440 .collect()
441 }
442}
443
444fn key_of(hop: &RouteHop) -> Option<Pair> {
447 Some((
448 hop.input_mint()?.to_string(),
449 hop.output_mint()?.to_string(),
450 ))
451}
452
453fn credit(bucket: &mut Vec<(Address, f64)>, mint: Address, value: f64) {
456 match bucket.iter_mut().find(|(held, _)| *held == mint) {
457 Some((_, total)) => *total += value,
458 None => bucket.push((mint, value)),
459 }
460}
461
462#[derive(Default)]
464struct FlowAccum {
465 legs: u64,
466 raw: u128,
468 without_amount: u64,
469}
470
471impl FlowAccum {
472 fn price(self, mint: &str, prices: Option<&Prices>, share_usd: f64) -> Flow {
473 let usd = prices.and_then(|prices| prices.usd_str(mint, self.raw as f64));
474 Flow {
475 legs: self.legs,
476 usd: usd.unwrap_or_default(),
477 without_amount: self.without_amount,
478 without_price: match usd {
480 Some(_) => 0,
481 None => self.legs - self.without_amount,
482 },
483 share_usd,
484 }
485 }
486}
487
488#[derive(Default)]
490struct ShareAccum {
491 all: Vec<(Address, f64)>,
492 claimed: Vec<(Address, f64)>,
493}
494
495impl ShareAccum {
496 fn price(&self, prices: Option<&Prices>) -> (f64, f64) {
498 let sum = |bucket: &[(Address, f64)]| {
499 bucket
500 .iter()
501 .filter_map(|(mint, raw)| prices?.usd(mint, *raw))
502 .fold(0.0, |total, usd| total + usd)
505 };
506 (sum(&self.all), sum(&self.claimed))
507 }
508}
509
510#[derive(Default)]
512struct SideAccum {
513 flow: FlowAccum,
514 share: ShareAccum,
515}
516
517#[derive(Default)]
518struct DirectionAccum {
519 l1: SideAccum,
520 requoted: SideAccum,
521}
522
523impl DirectionAccum {
524 fn side_mut(&mut self, side: Side) -> &mut SideAccum {
525 match side {
526 Side::L1 => &mut self.l1,
527 Side::Requoted => &mut self.requoted,
528 }
529 }
530
531 fn price(self, mint: &str, prices: Option<&Prices>) -> Direction {
532 let (l1_all, l1_claimed) = self.l1.share.price(prices);
533 let (requoted_all, requoted_claimed) = self.requoted.share.price(prices);
534 Direction {
535 l1: self.l1.flow.price(mint, prices, l1_claimed),
536 requoted: self.requoted.flow.price(mint, prices, requoted_claimed),
537 l1_all,
538 requoted_all,
539 }
540 }
541}
542
543#[cfg(test)]
544mod tests {
545 use super::*;
546 use crate::{
547 mints,
548 reroute_report::testing::{hop, plan, record_of},
549 };
550
551 const SOL: &str = "So11111111111111111111111111111111111111112";
552 const USDC: &str = "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v";
553 const VENUE_PROGRAM: &str = "BiSoNHVpsVZW2F7rx2eQ59yQwKxzU5NvBcmKshCSUypi";
554 const OTHER_PROGRAM: &str = "whirLbMiicVdio4qvUfM5KAg6Ct8VwpYzGff3uctyCc";
555
556 fn anchors() -> Vec<LegRecord> {
559 (1..=3)
560 .map(|n| LegRecord {
561 original_realized_output_amount: Some(n * 100_000_000),
562 ..record_of(mints::SOL, mints::USDC, n * 1_000_000_000, None, None, None)
563 })
564 .collect()
565 }
566
567 fn venue() -> Target {
568 Target::new(
569 Some("BisonFi".to_string()),
570 Some(VENUE_PROGRAM.parse().expect("a venue program")),
571 )
572 }
573
574 fn fill(
575 program: &str,
576 label: &str,
577 input: &str,
578 output: &str,
579 amount: u64,
580 ) -> Option<RoutePlan> {
581 plan(vec![hop(Some(program), label, input, output, amount)])
582 }
583
584 fn report_of(records: &[LegRecord]) -> Report {
585 Report::from_records(venue(), records).expect("the venue appears")
586 }
587
588 fn priced(extra: impl IntoIterator<Item = LegRecord>) -> Vec<LegRecord> {
590 let mut records = anchors();
591 records.extend(extra);
592 records
593 }
594
595 fn won_leg(amount: u64) -> LegRecord {
597 let realized = fill(VENUE_PROGRAM, "BisonFi", SOL, USDC, amount);
598 let l1 = fill(OTHER_PROGRAM, "Whirlpool", SOL, USDC, amount);
599 record_of(mints::SOL, mints::USDC, amount, None, l1, realized)
600 }
601
602 #[test]
606 fn a_hop_with_an_unnamed_mint_opens_no_direction() {
607 let mut unnamed = hop(Some(VENUE_PROGRAM), "BisonFi", USDC, SOL, 1_000_000);
608 unnamed.swap_info.output_mint = None;
609 let l1 = plan(vec![
610 hop(Some(VENUE_PROGRAM), "BisonFi", SOL, USDC, 2_000_000_000),
611 unnamed,
612 ]);
613 let report = report_of(&priced([record_of(
614 mints::SOL,
615 mints::USDC,
616 2_000_000_000,
617 None,
618 l1,
619 None,
620 )]));
621
622 let pairs: Vec<&Pair> = report.by_direction().map(|(pair, _)| pair).collect();
623 assert_eq!(pairs, [&(SOL.to_string(), USDC.to_string())]);
624 assert_eq!(report.total().l1.legs, 1, "only the named hop counts");
625 }
626
627 #[test]
631 fn deferring_the_conversion_matches_pricing_each_hop_as_it_arrives() {
632 let report = report_of(&priced([won_leg(2_000_000_000), won_leg(3_000_000_000)]));
633 let total = report.total();
634
635 assert_eq!(report.sol_usd(), Some(100.0));
636 assert_eq!(total.requoted.legs, 2);
637 assert_eq!(total.requoted.usd, 500.0);
639 assert_eq!(total.l1.legs, 0, "L1 had these legs at another venue");
640 }
641
642 #[test]
645 fn the_result_does_not_depend_on_arrival_order() {
646 let forward = priced([won_leg(2_000_000_000), won_leg(3_000_000_000)]);
647 let mut backward = forward.clone();
648 backward.reverse();
649
650 let (forward, backward) = (report_of(&forward), report_of(&backward));
651 assert_eq!(forward.sol_usd(), backward.sol_usd());
652 assert_eq!(forward.total().requoted.usd, backward.total().requoted.usd);
653 assert_eq!(forward.render(None), backward.render(None));
654 }
655
656 #[test]
659 fn neither_side_counts_flow_that_never_landed() {
660 let records = priced([
661 won_leg(2_000_000_000),
662 LegRecord {
663 failed: true,
664 ..won_leg(9_000_000_000)
665 },
666 LegRecord {
667 original_failed: true,
668 ..won_leg(9_000_000_000)
669 },
670 ]);
671
672 let total = report_of(&records).total();
673 assert_eq!(total.requoted.legs, 1, "only the landed leg counts");
674 assert_eq!(total.requoted.usd, 200.0);
675 }
676
677 #[test]
680 fn a_share_splits_a_leg_where_notional_counts_it_twice() {
681 let two_hops = plan(vec![
682 hop(Some(VENUE_PROGRAM), "BisonFi", SOL, USDC, 1_000_000_000),
683 hop(Some(OTHER_PROGRAM), "Whirlpool", USDC, "BONK", 100_000_000),
684 ]);
685 let l1 = fill(VENUE_PROGRAM, "BisonFi", SOL, USDC, 1_000_000_000);
686 let record = record_of(mints::SOL, mints::USDC, 1_000_000_000, None, l1, two_hops);
687 let report = report_of(&priced([record]));
688
689 let total = report.total();
690 assert_eq!(total.requoted.usd, 100.0);
692 assert_eq!(total.requoted_all, 100.0, "the leg is counted once");
694 assert_eq!(
695 total.requoted.share_usd, 50.0,
696 "half the route was the venue's"
697 );
698 assert_eq!(total.share(), Some((100.0, 50.0)));
700
701 let (_, first) = report
703 .by_direction()
704 .find(|((input, output), _)| input == SOL && output == USDC)
705 .expect("the venue's direction");
706 assert_eq!(first.requoted.share_usd, 50.0);
707 assert_eq!(first.requoted_all, 50.0, "that direction held half the leg");
708 }
709
710 #[test]
713 fn a_fill_prefers_the_program_and_falls_back_to_the_label() {
714 let filled = fill(VENUE_PROGRAM, "BisonFi", SOL, USDC, 1_000);
715 let record = record_of(mints::SOL, mints::USDC, 1_000, None, filled.clone(), filled);
716 let hop = &record.original_route_plan.as_ref().expect("a plan").hops()[0];
717
718 let by_label = Target::new(Some("BisonFi".to_string()), None);
719 assert!(by_label.claims_fill(hop));
720 assert!(by_label.claims_quoted(hop));
721
722 let other = Target::new(Some("BisonFi".to_string()), Some(Address::new_unique()));
724 assert!(!other.claims_fill(hop));
725
726 let by_program = Target::new(None, Some(VENUE_PROGRAM.parse().expect("a program")));
727 assert!(by_program.claims_fill(hop));
728 assert!(!by_program.claims_quoted(hop));
730 }
731
732 #[test]
736 fn the_report_is_swaps_and_dollars_only() {
737 let sell = fill(VENUE_PROGRAM, "BisonFi", SOL, USDC, 1_000_000_000);
738 let buy = fill(VENUE_PROGRAM, "BisonFi", USDC, SOL, 100_000_000);
739 let report = report_of(&priced([
740 record_of(mints::SOL, mints::USDC, 1_000_000_000, None, None, sell),
741 record_of(mints::USDC, mints::SOL, 100_000_000, None, None, buy),
742 ]));
743
744 let json = report.to_json();
746 assert_eq!(json["total"]["l1"]["swaps"], 0);
747 assert_eq!(json["total"]["requoted"]["swaps"], 2);
748 assert_eq!(json["total"]["requoted"]["usd"], 200.0);
749
750 let table = report.render(None);
752 let totals = table.split('→').next().expect("a totals block");
753 assert!(totals.contains("swaps") && totals.contains("volume"));
754 assert!(!totals.contains("raw in"), "a raw amount reached the table");
755 assert!(!table.contains("quoted fill"));
757 }
758
759 #[test]
762 fn a_range_that_cannot_be_priced_reports_no_dollars() {
763 let report = report_of(&[won_leg(2_000_000_000)]);
764 let total = report.total();
765
766 assert_eq!(report.sol_usd(), None);
767 assert_eq!(total.requoted.legs, 1);
768 assert_eq!(total.requoted.without_price, 1);
769 assert!(total.fully_unpriced());
770
771 let table = report.render(None);
772 assert!(!table.contains("volume"), "a dollar row without a price");
773 assert!(table.contains("could not price"));
774 }
775
776 #[test]
779 fn a_selector_that_matches_nothing_says_so() {
780 let quote = plan(vec![hop(None, "Whirlpool", SOL, USDC, 1_000)]);
781 let records = vec![record_of(mints::SOL, mints::USDC, 1_000, quote, None, None)];
782
783 let target = Target::new(Some("Nope".to_string()), None);
784 let error = Report::from_records(target, &records).expect_err("the venue never appears");
785
786 let message = error.to_string();
787 assert!(message.contains("Nope"), "names what was asked for");
788 assert!(message.contains("Whirlpool (1)"));
790 }
791
792 #[test]
794 fn the_subtitle_is_the_callers() {
795 let report = report_of(&[won_leg(2_000_000_000)]);
796 assert!(report.render(Some("slots 1–100")).contains("slots 1–100"));
797 assert!(!report.render(None).contains("slots"));
798 }
799}