Skip to main content

simulator_client/reroute_report/
mod.rs

1//! What flowed through a venue in a reroute stream, on L1 and after the re-quote.
2//!
3//! Both sides come off the same notification, so the comparison needs no control run. The L1
4//! column counts only legs among the re-quoted population, not the venue's whole L1 footprint.
5//!
6//! Nothing here does I/O.
7//!
8//! ```no_run
9//! # use simulator_client::{RerouteNotification, reroute_report::{Report, Target}};
10//! # fn example(notifications: &[RerouteNotification]) -> Result<(), Box<dyn std::error::Error>> {
11//! let target = Target::new(Some("BisonFi".to_string()), None);
12//! let report = Report::from_notifications(target, notifications)?;
13//! println!("{}", report.render(None));
14//! # Ok(()) }
15//! ```
16//!
17//! The two figures answer different questions. **Volume** is per-hop, valued by each hop's own
18//! `inAmount`, so a leg crossing the venue twice counts at both. **Share** is per-leg
19//! normalized, splitting each leg by `percent` across its route's venues, so the shares over a
20//! direction sum to 100%.
21
22mod 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/// The selector named a venue the stream never carried — a wrong address or a misspelling.
42/// Reporting that as `$0` would be indistinguishable from a venue with no flow.
43#[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        /// The selector, as the caller gave it.
52        asked: String,
53        /// Every venue the stream's quotes did name, with its hop count.
54        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/// The venue under test, as the two sides can each name it.
74///
75/// Either key alone works; both is strictest. Resolving a program to its metis label is a
76/// network lookup and not done here — pass the label you already hold.
77#[derive(Clone, Default, Debug)]
78pub struct Target {
79    label: Option<String>,
80    /// Paired with its base58, encoded once rather than per hop.
81    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    /// The quote plan names no program, so the label is the only key it can be matched on.
101    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    /// The program wins when given; the label fallback is what lets a label-only target measure
109    /// this side instead of reporting zero.
110    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/// What crossed the venue in one trade direction, on one side of the comparison.
129#[derive(Default, Clone, Copy, Debug)]
130pub struct Flow {
131    /// A swap crossing the venue twice counts twice.
132    pub legs: u64,
133    pub usd: f64,
134    pub without_amount: u64,
135    /// Priced at nothing rather than zero, so the dollar figure never absorbs them silently.
136    pub without_price: u64,
137    /// The numerator of [`Direction::share`], which is the interface to it.
138    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/// One trade direction's before and after.
152#[derive(Default, Clone, Copy, Debug)]
153pub struct Direction {
154    pub l1: Flow,
155    pub requoted: Flow,
156    /// Every venue's normalized value here — the denominator of [`Direction::share`].
157    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    /// The venue's percentage of all flow here, on each side. `None` when nothing could be
170    /// priced, which a `0.0%` would misreport.
171    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    /// Whether the venue was on either side, which is what makes the direction worth a row.
181    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    /// Nothing priceable, so the dollars are dropped: a `$0` row reads as "worth nothing".
190    pub fn fully_unpriced(&self) -> bool {
191        self.unpriced() && self.l1.usd == 0.0 && self.requoted.usd == 0.0
192    }
193
194    /// Dollars, falling back to legs so an unpriceable book still sorts above an empty one.
195    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
210/// A trade direction, keyed by the mints it moves between as `(input, output)`.
211pub type Pair = (String, String);
212
213#[derive(Clone, Copy)]
214enum Side {
215    L1,
216    Requoted,
217}
218
219/// What a stream said about one venue.
220#[derive(Debug)]
221pub struct Report {
222    by_direction: BTreeMap<Pair, Direction>,
223    target: Target,
224    /// Absent when the stream carried no SOL<->USDC reroutes to anchor from.
225    sol_usd: Option<f64>,
226}
227
228impl Report {
229    /// Build from anything that yields notifications — a slice, a `Vec`, a lazily-parsed file.
230    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    /// Build from a live stream, holding no more than [`ReportBuilder`] does.
242    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(&notification);
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    /// Every direction the range priced, which includes those the venue never served — filter
263    /// on [`Direction::present`] for the venue's own.
264    pub fn by_direction(&self) -> impl Iterator<Item = (&Pair, &Direction)> {
265        self.by_direction.iter()
266    }
267
268    /// The directions summed. Share stays meaningful because both numerator and denominator are
269    /// per-leg normalized.
270    pub fn total(&self) -> Direction {
271        fold(self.by_direction.values().copied())
272    }
273}
274
275/// Accumulates a [`Report`] one notification at a time, holding pricing samples, one
276/// accumulator per trade direction, and the venue labels seen — never the notifications.
277///
278/// Every price is a median over the whole stream, so amounts accumulate raw and convert once in
279/// [`ReportBuilder::finish`]. [`Prices::usd`] is linear in the amount, which is what makes that
280/// identical to converting each hop as it arrives.
281pub struct ReportBuilder {
282    target: Target,
283    samples: Samples,
284    by_direction: Directions,
285    /// Venue labels the quotes named, for the error a selector that matches nothing raises.
286    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    /// Take one notification's contribution. Cheap and order-independent.
300    pub fn push(&mut self, notification: &RerouteNotification) {
301        self.samples.push(notification);
302
303        // Neither column counts flow that never landed, so the two are filtered alike.
304        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 &notification.legs {
317            // Used twice: the census below, and the fallback when there is no fill plan.
318            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            // The fill, so both columns compare a fill against a fill; the quote is the fallback.
329            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            // The leg's own value, counted once whichever routes it took, so the shares are over
352            // the population rather than over the hops the venue served.
353            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    /// Nothing matched on either side means the selector named something the stream never saw.
370    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/// In its own type so `record` and `accumulate_share` borrow only the map, leaving the rest of
389/// the builder free.
390#[derive(Default)]
391struct Directions(BTreeMap<Pair, DirectionAccum>);
392
393impl Directions {
394    /// The hop's notional. Its input mint is the direction's, so raw amounts sum unpriced.
395    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    /// A leg's value split across its route's venues, filed under each hop's own direction, so
405    /// every leg counts once and the shares over a direction sum to 100%.
406    ///
407    /// Credited in the *leg's* input mint, which is not the direction's on a multi-hop route —
408    /// hence a bucket per mint.
409    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    /// A direction with nothing priceable and no venue legs carries no measurement — its bucket
432    /// was opened before its mint was known to be unpriceable — so it is dropped, not zeroed.
433    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
454/// Nearly every direction sees a single leg mint, so a scan beats a map; a hub pair terminating
455/// routes out of many exotics is the exception.
456fn 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/// Raw amounts for one side of one direction, awaiting a price.
464#[derive(Default)]
465struct FlowAccum {
466    legs: u64,
467    /// In the direction's input mint, shared by every hop filed here.
468    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            // Every hop here shares one mint, so the range prices all of them or none.
480            without_price: match usd {
481                Some(_) => 0,
482                None => self.legs - self.without_amount,
483            },
484            share_usd,
485        }
486    }
487}
488
489/// Weighted leg value for one side of one direction, per the leg's own input mint.
490#[derive(Default)]
491struct ShareAccum {
492    all: Vec<(String, f64)>,
493    claimed: Vec<(String, f64)>,
494}
495
496impl ShareAccum {
497    /// `(all, claimed)`. An unpriceable mint contributes to neither, keeping the ratio honest.
498    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                // Not `sum`: `Sum` for floats starts at `-0.0`, so an empty bucket would
504                // render as `-0.0%`.
505                .fold(0.0, |total, usd| total + usd)
506        };
507        (sum(&self.all), sum(&self.claimed))
508    }
509}
510
511/// Paired so a hop's notional and its share cannot be filed against different sides.
512#[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    /// Fixes SOL at $100 from the stream's own swaps. Carries no route plan, so it prices the
557    /// range without contributing a hop to anything.
558    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    /// The anchors, plus whatever the test is actually about.
586    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    /// A leg the venue won: the re-quote routed it through the venue, L1 had it elsewhere.
593    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    /// Prices are medians over the whole stream, so no dollar figure exists until it ends. The
600    /// builder holds raw amounts and converts once — which only works because the conversion is
601    /// linear, and this is the test of that.
602    #[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        // 2 SOL and 3 SOL at $100, whether summed raw and converted once or converted twice.
610        assert_eq!(total.requoted.usd, 500.0);
611        assert_eq!(total.l1.legs, 0, "L1 had these legs at another venue");
612    }
613
614    /// The order notifications arrive in is the order the session produced them, which is not a
615    /// property of the venue. Every figure must be a fold, not a sequence.
616    #[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    /// Neither column counts flow that never landed, and the two must be filtered alike — a
629    /// reverted simulation is not a leg the venue won, and a failed original is not one it held.
630    #[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(&notifications).total();
639        assert_eq!(total.requoted.legs, 1, "only the landed leg counts");
640        assert_eq!(total.requoted.usd, 200.0);
641    }
642
643    /// Volume share needs every leg counted once, so a two-hop route gives each half — where
644    /// per-hop notional credits both in full. The two answer different questions.
645    #[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        // The leg is one SOL, $100. Per-hop notional credits the venue the whole of its own hop.
657        assert_eq!(total.requoted.usd, 100.0);
658        // Share splits that $100 across the two hops on the route, and the venue holds one.
659        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        // On L1 it held the leg outright.
665        assert_eq!(total.share(), Some((100.0, 50.0)));
666
667        // Each hop is filed under its own direction, so the rows decompose the same measure.
668        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    /// The program wins when given; the label is the fallback, so naming only a label still
677    /// measures the fill columns rather than reporting a silent zero on them.
678    #[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        // A program that was given and does not match is not rescued by a matching label.
689        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        // The quote names no program, so this key cannot match there.
695        assert!(!by_program.claims_quoted(hop));
696    }
697
698    /// Dollars cross mints; a raw amount does not. Summing each direction's own input mint added
699    /// lamports to stablecoin units and produced a figure that looked precise and meant nothing,
700    /// so no amount is reported in mint units anywhere — only legs and dollars.
701    #[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        // Lamports in one direction, stablecoin units in the other; dollars survive the sum.
711        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        // And the rendered table carries the two rows, and no third.
717        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        // "re-quoted" is a column heading; a *quoted fill* line is what must not appear.
722        assert!(!table.contains("quoted fill"));
723    }
724
725    /// A range with nothing to anchor on prices nothing. Reporting those legs at $0 would read
726    /// as "worth nothing" rather than "not valued".
727    #[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    /// A selector that matches nothing is a wrong address or a misspelling, not a venue with no
743    /// flow. Reporting it as $0 was indistinguishable from the real thing.
744    #[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, &notifications)
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        // And what the stream does name, so the misspelling is visible.
757        assert!(message.contains("Whirlpool (1)"));
758    }
759
760    /// The subtitle is the caller's, since this module cannot know a slot range.
761    #[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}