1mod prices;
23mod render;
24#[cfg(test)]
25mod testing;
26
27use std::collections::BTreeMap;
28
29use futures::{Stream, StreamExt};
30use simulator_api::route_plan::{RouteHop, RoutePlan};
31use solana_address::Address;
32
33pub use self::prices::short_mint;
34use self::prices::{Prices, Samples};
35use crate::RerouteNotification;
36
37fn in_amount(hop: &RouteHop) -> Option<u128> {
38 hop.swap_info.in_amount.as_ref()?.parse().ok()
39}
40
41#[derive(Debug, thiserror::Error)]
44pub enum RerouteReportError {
45 #[error(
46 "{asked} never appears in this stream.\nIt names {} venues; the busiest are {}.",
47 .venues.len(),
48 busiest(.venues),
49 )]
50 NothingMatched {
51 asked: String,
53 venues: Vec<(String, u64)>,
55 },
56}
57
58const NAMED_IN_ERROR: usize = 8;
59
60fn busiest(venues: &[(String, u64)]) -> String {
61 let mut ranked: Vec<_> = venues.iter().collect();
62 ranked.sort_unstable_by(|(a_label, a_hops), (b_label, b_hops)| {
63 b_hops.cmp(a_hops).then_with(|| a_label.cmp(b_label))
64 });
65 ranked
66 .iter()
67 .take(NAMED_IN_ERROR)
68 .map(|(label, hops)| format!("{label} ({hops})"))
69 .collect::<Vec<_>>()
70 .join(", ")
71}
72
73#[derive(Clone, Default, Debug)]
78pub struct Target {
79 label: Option<String>,
80 program: Option<(Address, String)>,
82}
83
84impl Target {
85 pub fn new(label: Option<String>, program: Option<Address>) -> Self {
86 Self {
87 label,
88 program: program.map(|program| (program, program.to_string())),
89 }
90 }
91
92 pub fn label(&self) -> Option<&str> {
93 self.label.as_deref()
94 }
95
96 pub fn program(&self) -> Option<Address> {
97 self.program.as_ref().map(|(program, _)| *program)
98 }
99
100 pub fn claims_quoted(&self, hop: &RouteHop) -> bool {
102 match &self.label {
103 Some(label) => hop.label() == Some(label.as_str()),
104 None => false,
105 }
106 }
107
108 pub fn claims_fill(&self, hop: &RouteHop) -> bool {
111 if let Some((_, key)) = &self.program {
112 return hop.program.as_deref() == Some(key.as_str());
113 }
114 self.claims_quoted(hop)
115 }
116
117 fn describe(&self) -> String {
118 if let Some(label) = &self.label {
119 format!("label {label:?}")
120 } else if let Some((program, _)) = &self.program {
121 format!("program {program}")
122 } else {
123 "that venue".to_string()
124 }
125 }
126}
127
128#[derive(Default, Clone, Copy, Debug)]
130pub struct Flow {
131 pub legs: u64,
133 pub usd: f64,
134 pub without_amount: u64,
135 pub without_price: u64,
137 share_usd: f64,
139}
140
141impl Flow {
142 fn merge(&mut self, other: Self) {
143 self.legs += other.legs;
144 self.usd += other.usd;
145 self.without_amount += other.without_amount;
146 self.without_price += other.without_price;
147 self.share_usd += other.share_usd;
148 }
149}
150
151#[derive(Default, Clone, Copy, Debug)]
153pub struct Direction {
154 pub l1: Flow,
155 pub requoted: Flow,
156 l1_all: f64,
158 requoted_all: f64,
159}
160
161impl Direction {
162 fn merge(&mut self, other: Self) {
163 self.l1.merge(other.l1);
164 self.requoted.merge(other.requoted);
165 self.l1_all += other.l1_all;
166 self.requoted_all += other.requoted_all;
167 }
168
169 pub fn share(&self) -> Option<(f64, f64)> {
172 (self.l1_all > 0.0 && self.requoted_all > 0.0).then(|| {
173 (
174 self.l1.share_usd / self.l1_all * 100.0,
175 self.requoted.share_usd / self.requoted_all * 100.0,
176 )
177 })
178 }
179
180 pub const fn present(&self) -> bool {
182 self.l1.legs > 0 || self.requoted.legs > 0
183 }
184
185 pub const fn unpriced(&self) -> bool {
186 self.l1.without_price > 0 || self.requoted.without_price > 0
187 }
188
189 pub fn fully_unpriced(&self) -> bool {
191 self.unpriced() && self.l1.usd == 0.0 && self.requoted.usd == 0.0
192 }
193
194 fn rank(&self) -> (u64, u64) {
196 let usd = self.l1.usd.max(self.requoted.usd);
197 (usd as u64, self.l1.legs.max(self.requoted.legs))
198 }
199}
200
201fn fold(directions: impl IntoIterator<Item = Direction>) -> Direction {
202 directions
203 .into_iter()
204 .fold(Direction::default(), |mut total, direction| {
205 total.merge(direction);
206 total
207 })
208}
209
210pub type Pair = (String, String);
212
213#[derive(Clone, Copy)]
214enum Side {
215 L1,
216 Requoted,
217}
218
219#[derive(Debug)]
221pub struct Report {
222 by_direction: BTreeMap<Pair, Direction>,
223 target: Target,
224 sol_usd: Option<f64>,
226}
227
228impl Report {
229 pub fn from_notifications<'a>(
231 target: Target,
232 notifications: impl IntoIterator<Item = &'a RerouteNotification>,
233 ) -> Result<Self, RerouteReportError> {
234 let mut builder = ReportBuilder::new(target);
235 for notification in notifications {
236 builder.push(notification);
237 }
238 builder.finish()
239 }
240
241 pub async fn from_stream(
243 target: Target,
244 stream: impl Stream<Item = RerouteNotification>,
245 ) -> Result<Self, RerouteReportError> {
246 let mut builder = ReportBuilder::new(target);
247 let mut stream = std::pin::pin!(stream);
248 while let Some(notification) = stream.next().await {
249 builder.push(¬ification);
250 }
251 builder.finish()
252 }
253
254 pub const fn target(&self) -> &Target {
255 &self.target
256 }
257
258 pub const fn sol_usd(&self) -> Option<f64> {
259 self.sol_usd
260 }
261
262 pub fn by_direction(&self) -> impl Iterator<Item = (&Pair, &Direction)> {
265 self.by_direction.iter()
266 }
267
268 pub fn total(&self) -> Direction {
271 fold(self.by_direction.values().copied())
272 }
273}
274
275pub struct ReportBuilder {
282 target: Target,
283 samples: Samples,
284 by_direction: Directions,
285 labels: BTreeMap<String, u64>,
287}
288
289impl ReportBuilder {
290 pub fn new(target: Target) -> Self {
291 Self {
292 target,
293 samples: Samples::default(),
294 by_direction: Directions::default(),
295 labels: BTreeMap::new(),
296 }
297 }
298
299 pub fn push(&mut self, notification: &RerouteNotification) {
301 self.samples.push(notification);
302
303 if notification.err.is_some() || notification.original_failed {
305 return;
306 }
307 let Self {
308 target,
309 by_direction,
310 labels,
311 ..
312 } = self;
313 fn hops_of(plan: &Option<RoutePlan>) -> Option<&[RouteHop]> {
314 plan.as_ref().map(RoutePlan::hops)
315 }
316 for leg in ¬ification.legs {
317 let quoted = hops_of(&leg.route_plan);
319 for label in quoted.iter().copied().flatten().filter_map(RouteHop::label) {
320 match labels.get_mut(label) {
321 Some(hops) => *hops += 1,
322 None => {
323 labels.insert(label.to_string(), 1);
324 }
325 }
326 }
327
328 let (requoted, from_quote) = match hops_of(&leg.realized_route_plan) {
330 Some(filled) => (filled, false),
331 None => (quoted.unwrap_or_default(), true),
332 };
333 let claimed = |hop: &RouteHop| match from_quote {
334 true => target.claims_quoted(hop),
335 false => target.claims_fill(hop),
336 };
337 for hop in requoted.iter().filter(|hop| claimed(hop)) {
338 by_direction.record(Side::Requoted, hop);
339 }
340
341 let l1 = hops_of(&leg.original_route_plan);
342 for hop in l1
343 .iter()
344 .copied()
345 .flatten()
346 .filter(|hop| target.claims_fill(hop))
347 {
348 by_direction.record(Side::L1, hop);
349 }
350
351 let leg_amount = u128::from(leg.amount) as f64;
354 by_direction.accumulate_share(
355 Side::Requoted,
356 requoted,
357 &leg.input_mint,
358 leg_amount,
359 claimed,
360 );
361 if let Some(l1) = l1 {
362 by_direction.accumulate_share(Side::L1, l1, &leg.input_mint, leg_amount, |hop| {
363 target.claims_fill(hop)
364 });
365 }
366 }
367 }
368
369 pub fn finish(self) -> Result<Report, RerouteReportError> {
371 let prices = self.samples.prices();
372 let report = Report {
373 sol_usd: prices.as_ref().map(Prices::sol_usd),
374 by_direction: self.by_direction.price(prices.as_ref()),
375 target: self.target,
376 };
377 let total = report.total();
378 if total.l1.legs == 0 && total.requoted.legs == 0 {
379 return Err(RerouteReportError::NothingMatched {
380 asked: report.target.describe(),
381 venues: self.labels.into_iter().collect(),
382 });
383 }
384 Ok(report)
385 }
386}
387
388#[derive(Default)]
391struct Directions(BTreeMap<Pair, DirectionAccum>);
392
393impl Directions {
394 fn record(&mut self, side: Side, hop: &RouteHop) {
396 let flow = &mut self.0.entry(key_of(hop)).or_default().side_mut(side).flow;
397 flow.legs += 1;
398 match in_amount(hop) {
399 Some(amount) => flow.raw += amount,
400 None => flow.without_amount += 1,
401 }
402 }
403
404 fn accumulate_share(
410 &mut self,
411 side: Side,
412 hops: &[RouteHop],
413 leg_mint: &str,
414 leg_amount: f64,
415 claimed: impl Fn(&RouteHop) -> bool,
416 ) {
417 let total: u64 = hops.iter().map(|hop| hop.percent).sum();
418 if total == 0 {
419 return;
420 }
421 for hop in hops {
422 let value = leg_amount * hop.percent as f64 / total as f64;
423 let share = &mut self.0.entry(key_of(hop)).or_default().side_mut(side).share;
424 credit(&mut share.all, leg_mint, value);
425 if claimed(hop) {
426 credit(&mut share.claimed, leg_mint, value);
427 }
428 }
429 }
430
431 fn price(self, prices: Option<&Prices>) -> BTreeMap<Pair, Direction> {
434 self.0
435 .into_iter()
436 .map(|(pair, accum)| {
437 let direction = accum.price(&pair.0, prices);
438 (pair, direction)
439 })
440 .filter(|(_, direction)| {
441 direction.present() || direction.l1_all > 0.0 || direction.requoted_all > 0.0
442 })
443 .collect()
444 }
445}
446
447fn key_of(hop: &RouteHop) -> Pair {
448 (
449 hop.input_mint().unwrap_or_default().to_string(),
450 hop.output_mint().unwrap_or_default().to_string(),
451 )
452}
453
454fn credit(bucket: &mut Vec<(String, f64)>, mint: &str, value: f64) {
457 match bucket.iter_mut().find(|(held, _)| held == mint) {
458 Some((_, total)) => *total += value,
459 None => bucket.push((mint.to_string(), value)),
460 }
461}
462
463#[derive(Default)]
465struct FlowAccum {
466 legs: u64,
467 raw: u128,
469 without_amount: u64,
470}
471
472impl FlowAccum {
473 fn price(self, mint: &str, prices: Option<&Prices>, share_usd: f64) -> Flow {
474 let usd = prices.and_then(|prices| prices.usd(mint, self.raw as f64));
475 Flow {
476 legs: self.legs,
477 usd: usd.unwrap_or_default(),
478 without_amount: self.without_amount,
479 without_price: match usd {
481 Some(_) => 0,
482 None => self.legs - self.without_amount,
483 },
484 share_usd,
485 }
486 }
487}
488
489#[derive(Default)]
491struct ShareAccum {
492 all: Vec<(String, f64)>,
493 claimed: Vec<(String, f64)>,
494}
495
496impl ShareAccum {
497 fn price(&self, prices: Option<&Prices>) -> (f64, f64) {
499 let sum = |bucket: &[(String, f64)]| {
500 bucket
501 .iter()
502 .filter_map(|(mint, raw)| prices?.usd(mint, *raw))
503 .fold(0.0, |total, usd| total + usd)
506 };
507 (sum(&self.all), sum(&self.claimed))
508 }
509}
510
511#[derive(Default)]
513struct SideAccum {
514 flow: FlowAccum,
515 share: ShareAccum,
516}
517
518#[derive(Default)]
519struct DirectionAccum {
520 l1: SideAccum,
521 requoted: SideAccum,
522}
523
524impl DirectionAccum {
525 fn side_mut(&mut self, side: Side) -> &mut SideAccum {
526 match side {
527 Side::L1 => &mut self.l1,
528 Side::Requoted => &mut self.requoted,
529 }
530 }
531
532 fn price(self, mint: &str, prices: Option<&Prices>) -> Direction {
533 let (l1_all, l1_claimed) = self.l1.share.price(prices);
534 let (requoted_all, requoted_claimed) = self.requoted.share.price(prices);
535 Direction {
536 l1: self.l1.flow.price(mint, prices, l1_claimed),
537 requoted: self.requoted.flow.price(mint, prices, requoted_claimed),
538 l1_all,
539 requoted_all,
540 }
541 }
542}
543
544#[cfg(test)]
545mod tests {
546 use super::{
547 prices::SOL,
548 testing::{Notification, hop, leg_of, plan},
549 *,
550 };
551
552 const USDC: &str = "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v";
553 const VENUE_PROGRAM: &str = "BiSoNHVpsVZW2F7rx2eQ59yQwKxzU5NvBcmKshCSUypi";
554 const OTHER_PROGRAM: &str = "whirLbMiicVdio4qvUfM5KAg6Ct8VwpYzGff3uctyCc";
555
556 fn anchors() -> Vec<RerouteNotification> {
559 (1..=3)
560 .map(|n| Notification::swap(SOL, USDC, n * 1_000_000_000, n * 100_000_000).build())
561 .collect()
562 }
563
564 fn venue() -> Target {
565 Target::new(
566 Some("BisonFi".to_string()),
567 Some(VENUE_PROGRAM.parse().expect("a venue program")),
568 )
569 }
570
571 fn fill(
572 program: &str,
573 label: &str,
574 input: &str,
575 output: &str,
576 amount: u64,
577 ) -> Option<RoutePlan> {
578 plan(vec![hop(Some(program), label, input, output, amount)])
579 }
580
581 fn report_of(notifications: &[RerouteNotification]) -> Report {
582 Report::from_notifications(venue(), notifications).expect("the venue appears")
583 }
584
585 fn priced(extra: impl IntoIterator<Item = Notification>) -> Vec<RerouteNotification> {
587 let mut notifications = anchors();
588 notifications.extend(extra.into_iter().map(Notification::build));
589 notifications
590 }
591
592 fn won_leg(amount: u64) -> Notification {
594 let realized = fill(VENUE_PROGRAM, "BisonFi", SOL, USDC, amount);
595 let l1 = fill(OTHER_PROGRAM, "Whirlpool", SOL, USDC, amount);
596 Notification::new(vec![leg_of(SOL, USDC, amount, None, l1, realized)])
597 }
598
599 #[test]
603 fn deferring_the_conversion_matches_pricing_each_hop_as_it_arrives() {
604 let report = report_of(&priced([won_leg(2_000_000_000), won_leg(3_000_000_000)]));
605 let total = report.total();
606
607 assert_eq!(report.sol_usd(), Some(100.0));
608 assert_eq!(total.requoted.legs, 2);
609 assert_eq!(total.requoted.usd, 500.0);
611 assert_eq!(total.l1.legs, 0, "L1 had these legs at another venue");
612 }
613
614 #[test]
617 fn the_result_does_not_depend_on_arrival_order() {
618 let forward = priced([won_leg(2_000_000_000), won_leg(3_000_000_000)]);
619 let mut backward = forward.clone();
620 backward.reverse();
621
622 let (forward, backward) = (report_of(&forward), report_of(&backward));
623 assert_eq!(forward.sol_usd(), backward.sol_usd());
624 assert_eq!(forward.total().requoted.usd, backward.total().requoted.usd);
625 assert_eq!(forward.render(None), backward.render(None));
626 }
627
628 #[test]
631 fn neither_side_counts_flow_that_never_landed() {
632 let notifications = priced([
633 won_leg(2_000_000_000),
634 won_leg(9_000_000_000).reverted(),
635 won_leg(9_000_000_000).original_failed(),
636 ]);
637
638 let total = report_of(¬ifications).total();
639 assert_eq!(total.requoted.legs, 1, "only the landed leg counts");
640 assert_eq!(total.requoted.usd, 200.0);
641 }
642
643 #[test]
646 fn a_share_splits_a_leg_where_notional_counts_it_twice() {
647 let two_hops = plan(vec![
648 hop(Some(VENUE_PROGRAM), "BisonFi", SOL, USDC, 1_000_000_000),
649 hop(Some(OTHER_PROGRAM), "Whirlpool", USDC, "BONK", 100_000_000),
650 ]);
651 let l1 = fill(VENUE_PROGRAM, "BisonFi", SOL, USDC, 1_000_000_000);
652 let leg = leg_of(SOL, USDC, 1_000_000_000, None, l1, two_hops);
653 let report = report_of(&priced([Notification::new(vec![leg])]));
654
655 let total = report.total();
656 assert_eq!(total.requoted.usd, 100.0);
658 assert_eq!(total.requoted_all, 100.0, "the leg is counted once");
660 assert_eq!(
661 total.requoted.share_usd, 50.0,
662 "half the route was the venue's"
663 );
664 assert_eq!(total.share(), Some((100.0, 50.0)));
666
667 let (_, first) = report
669 .by_direction()
670 .find(|((input, output), _)| input == SOL && output == USDC)
671 .expect("the venue's direction");
672 assert_eq!(first.requoted.share_usd, 50.0);
673 assert_eq!(first.requoted_all, 50.0, "that direction held half the leg");
674 }
675
676 #[test]
679 fn a_fill_prefers_the_program_and_falls_back_to_the_label() {
680 let filled = fill(VENUE_PROGRAM, "BisonFi", SOL, USDC, 1_000);
681 let leg = leg_of(SOL, USDC, 1_000, None, filled.clone(), filled);
682 let hop = &leg.original_route_plan.as_ref().expect("a plan").hops()[0];
683
684 let by_label = Target::new(Some("BisonFi".to_string()), None);
685 assert!(by_label.claims_fill(hop));
686 assert!(by_label.claims_quoted(hop));
687
688 let other = Target::new(Some("BisonFi".to_string()), Some(Address::new_unique()));
690 assert!(!other.claims_fill(hop));
691
692 let by_program = Target::new(None, Some(VENUE_PROGRAM.parse().expect("a program")));
693 assert!(by_program.claims_fill(hop));
694 assert!(!by_program.claims_quoted(hop));
696 }
697
698 #[test]
702 fn the_report_is_swaps_and_dollars_only() {
703 let sell = fill(VENUE_PROGRAM, "BisonFi", SOL, USDC, 1_000_000_000);
704 let buy = fill(VENUE_PROGRAM, "BisonFi", USDC, SOL, 100_000_000);
705 let report = report_of(&priced([
706 Notification::new(vec![leg_of(SOL, USDC, 1_000_000_000, None, None, sell)]),
707 Notification::new(vec![leg_of(USDC, SOL, 100_000_000, None, None, buy)]),
708 ]));
709
710 let json = report.to_json();
712 assert_eq!(json["total"]["l1"]["swaps"], 0);
713 assert_eq!(json["total"]["requoted"]["swaps"], 2);
714 assert_eq!(json["total"]["requoted"]["usd"], 200.0);
715
716 let table = report.render(None);
718 let totals = table.split('→').next().expect("a totals block");
719 assert!(totals.contains("swaps") && totals.contains("volume"));
720 assert!(!totals.contains("raw in"), "a raw amount reached the table");
721 assert!(!table.contains("quoted fill"));
723 }
724
725 #[test]
728 fn a_range_that_cannot_be_priced_reports_no_dollars() {
729 let report = report_of(&[won_leg(2_000_000_000).build()]);
730 let total = report.total();
731
732 assert_eq!(report.sol_usd(), None);
733 assert_eq!(total.requoted.legs, 1);
734 assert_eq!(total.requoted.without_price, 1);
735 assert!(total.fully_unpriced());
736
737 let table = report.render(None);
738 assert!(!table.contains("volume"), "a dollar row without a price");
739 assert!(table.contains("could not price"));
740 }
741
742 #[test]
745 fn a_selector_that_matches_nothing_says_so() {
746 let quote = plan(vec![hop(None, "Whirlpool", SOL, USDC, 1_000)]);
747 let leg = leg_of(SOL, USDC, 1_000, quote, None, None);
748 let notifications = vec![Notification::new(vec![leg]).build()];
749
750 let target = Target::new(Some("Nope".to_string()), None);
751 let error = Report::from_notifications(target, ¬ifications)
752 .expect_err("the venue never appears");
753
754 let message = error.to_string();
755 assert!(message.contains("Nope"), "names what was asked for");
756 assert!(message.contains("Whirlpool (1)"));
758 }
759
760 #[test]
762 fn the_subtitle_is_the_callers() {
763 let report = report_of(&[won_leg(2_000_000_000).build()]);
764 assert!(report.render(Some("slots 1–100")).contains("slots 1–100"));
765 assert!(!report.render(None).contains("slots"));
766 }
767}