Skip to main content

simulator_api/reroute_report/
flow.rs

1//! What flowed through a venue in a reroute population, onchain and after the reroute.
2//!
3//! Both sides come off the same record, so the comparison needs no control run. The onchain
4//! column counts only legs among the rerouted population, not the venue's whole onchain flow.
5//!
6//! Nothing here does I/O.
7//!
8//! The two figures answer different questions. **Volume** is per-hop, valued by each hop's own
9//! `inAmount`, so a leg crossing the venue twice counts at both. **Share** is per-leg
10//! normalized, splitting each leg by `percent` across its route's venues, so the shares over a
11//! direction sum to 100%.
12
13use 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/// The selector named a venue the stream never carried — a wrong address or a misspelling.
25/// Reporting that as `$0` would be indistinguishable from a venue with no flow.
26#[derive(Debug, thiserror::Error)]
27pub enum RerouteReportError {
28    /// No hop on either side matched the [`Target`].
29    #[error(
30        "{asked} never appears in this stream.\nIt names {} venues; the busiest are {}.",
31        .venues.len(),
32        busiest(.venues),
33    )]
34    NothingMatched {
35        /// The selector, as the caller gave it.
36        asked: String,
37        /// Every venue the stream's quotes did name, with its hop count.
38        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/// The venue under test, as the two sides can each name it.
58///
59/// Either key alone works; both is strictest. Resolving a program to its router label is a
60/// network lookup and not done here — pass the label you already hold.
61#[derive(Clone, Default, Debug)]
62pub struct Target {
63    label: Option<String>,
64    /// Paired with its base58, encoded once rather than per hop.
65    program: Option<(Address, String)>,
66}
67
68impl Target {
69    /// A target matched by `label`, `program`, or both. With neither, nothing matches.
70    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    /// Whether a quoted hop is the target's. The quote plan names no program, so the label is
88    /// the only key it can be matched on.
89    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    /// Whether a filled hop is the target's. The program wins when given; a label-only target
97    /// falls back to the label.
98    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/// What crossed the venue in one trade direction, on one side of the comparison.
117#[derive(Default, Clone, Copy, Debug)]
118pub struct Flow {
119    /// Hops through the venue; a swap crossing it twice counts twice.
120    pub legs: u64,
121    /// Those hops' value in USD, from each hop's `inAmount`. 0 when unpriced.
122    pub usd: f64,
123    /// Hops with no readable `inAmount`.
124    pub without_amount: u64,
125    /// Hops in a mint the range could not price. Counted here rather than valued at zero.
126    pub without_price: u64,
127    /// The numerator of [`Direction::share`], which is the interface to it.
128    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/// One trade direction's before and after.
142#[derive(Default, Clone, Copy, Debug)]
143pub struct Direction {
144    /// The original swaps' flow through the venue, onchain.
145    pub l1: Flow,
146    /// The rerouted flow through the venue.
147    pub requoted: Flow,
148    /// Every venue's normalized value here — the denominator of [`Direction::share`].
149    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    /// The venue's percentage of all flow here, on each side. `None` when nothing could be
162    /// priced, which a `0.0%` would misreport.
163    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    /// Whether the venue was on either side, which is what makes the direction worth a row.
173    pub const fn present(&self) -> bool {
174        self.l1.legs > 0 || self.requoted.legs > 0
175    }
176
177    /// Whether any hop on either side could not be priced.
178    pub const fn unpriced(&self) -> bool {
179        self.l1.without_price > 0 || self.requoted.without_price > 0
180    }
181
182    /// Nothing priceable, so the dollars are dropped: a `$0` row reads as "worth nothing".
183    pub fn fully_unpriced(&self) -> bool {
184        self.unpriced() && self.l1.usd == 0.0 && self.requoted.usd == 0.0
185    }
186
187    /// Dollars, falling back to legs so an unpriceable book still sorts above an empty one.
188    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
208/// A trade direction, keyed by the mints it moves between as `(input, output)`.
209pub type Pair = (String, String);
210
211#[derive(Clone, Copy)]
212enum Side {
213    L1,
214    Requoted,
215}
216
217/// One venue's flow across a set of reroute results, onchain against rerouted, by trade direction.
218#[derive(Debug)]
219pub struct Report {
220    by_direction: BTreeMap<Pair, Direction>,
221    target: Target,
222    /// Absent when the stream carried no SOL<->USDC reroutes to anchor from.
223    sol_usd: Option<f64>,
224}
225
226impl Report {
227    /// Build from anything that yields records — a mapped notification stream, a DB read.
228    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    /// The venue this report is about.
240    pub const fn target(&self) -> &Target {
241        &self.target
242    }
243
244    /// The SOL price the records gave, in USD. `None` when they carried no SOL-USDC reroutes to
245    /// anchor on, in which case nothing is priced.
246    pub const fn sol_usd(&self) -> Option<f64> {
247        self.sol_usd
248    }
249
250    /// Every direction the range priced, which includes those the venue never served — filter
251    /// on [`Direction::present`] for the venue's own.
252    pub fn by_direction(&self) -> impl Iterator<Item = (&Pair, &Direction)> {
253        self.by_direction.iter()
254    }
255
256    /// The directions summed. Share stays meaningful because both numerator and denominator are
257    /// per-leg normalized.
258    pub fn total(&self) -> Direction {
259        fold(self.by_direction.values().copied())
260    }
261}
262
263/// Accumulates a [`Report`] one record at a time, holding pricing samples, one accumulator per
264/// trade direction, and the venue labels seen — never the records.
265///
266/// Every price is a median over the whole stream, so amounts accumulate raw and convert once in
267/// [`ReportBuilder::finish`]. [`Prices::usd`] is linear in the amount, which is what makes that
268/// identical to converting each hop as it arrives.
269pub struct ReportBuilder {
270    target: Target,
271    samples: Samples,
272    by_direction: Directions,
273    /// Venue labels the quotes named, for the error a selector that matches nothing raises.
274    labels: BTreeMap<String, u64>,
275}
276
277impl ReportBuilder {
278    /// An empty builder for `target`.
279    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    /// Take one record's contribution. Cheap and order-independent.
289    pub fn push(&mut self, record: &LegRecord) {
290        self.samples.push(record);
291
292        // Neither column counts flow that never landed, so the two are filtered alike.
293        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        // Used twice: the census below, and the fallback when there is no fill plan.
306        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        // The fill, so both columns compare a fill against a fill; the quote is the fallback.
317        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        // The leg's own value, counted once whichever routes it took, so the shares are over
343        // the population rather than over the hops the venue served.
344        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    /// Price the accumulated flow into a [`Report`]. Fails with
360    /// [`RerouteReportError::NothingMatched`] when no hop on either side matched the target.
361    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/// In its own type so `record` and `accumulate_share` borrow only the map, leaving the rest of
380/// the builder free.
381#[derive(Default)]
382struct Directions(BTreeMap<Pair, DirectionAccum>);
383
384impl Directions {
385    /// The hop's notional. Its input mint is the direction's, so raw amounts sum unpriced.
386    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    /// A leg's value split across its route's venues, filed under each hop's own direction, so
399    /// every leg counts once and the shares over a direction sum to 100%.
400    ///
401    /// Credited in the *leg's* input mint, which is not the direction's on a multi-hop route —
402    /// hence a bucket per mint.
403    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    /// A direction with nothing priceable and no venue legs carries no measurement — its bucket
429    /// was opened before its mint was known to be unpriceable — so it is dropped, not zeroed.
430    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
444/// `None` for a hop whose pair the plan never named: keying it on a default address would pool
445/// unrelated unnamed trades into one priced bucket, so such a hop opens no direction at all.
446fn key_of(hop: &RouteHop) -> Option<Pair> {
447    Some((
448        hop.input_mint()?.to_string(),
449        hop.output_mint()?.to_string(),
450    ))
451}
452
453/// Nearly every direction sees a single leg mint, so a scan beats a map; a hub pair terminating
454/// routes out of many exotics is the exception.
455fn 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/// Raw amounts for one side of one direction, awaiting a price.
463#[derive(Default)]
464struct FlowAccum {
465    legs: u64,
466    /// In the direction's input mint, shared by every hop filed here.
467    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            // Every hop here shares one mint, so the range prices all of them or none.
479            without_price: match usd {
480                Some(_) => 0,
481                None => self.legs - self.without_amount,
482            },
483            share_usd,
484        }
485    }
486}
487
488/// Weighted leg value for one side of one direction, per the leg's own input mint.
489#[derive(Default)]
490struct ShareAccum {
491    all: Vec<(Address, f64)>,
492    claimed: Vec<(Address, f64)>,
493}
494
495impl ShareAccum {
496    /// `(all, claimed)`. An unpriceable mint contributes to neither, keeping the ratio honest.
497    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                // Not `sum`: `Sum` for floats starts at `-0.0`, so an empty bucket would
503                // render as `-0.0%`.
504                .fold(0.0, |total, usd| total + usd)
505        };
506        (sum(&self.all), sum(&self.claimed))
507    }
508}
509
510/// Paired so a hop's notional and its share cannot be filed against different sides.
511#[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    /// 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<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    /// The anchors, plus whatever the test is actually about.
589    fn priced(extra: impl IntoIterator<Item = LegRecord>) -> Vec<LegRecord> {
590        let mut records = anchors();
591        records.extend(extra);
592        records
593    }
594
595    /// A leg the venue won: the re-quote routed it through the venue, L1 had it elsewhere.
596    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    /// A hop whose pair the plan never named opens no direction: keyed on a default address it
603    /// would pool unrelated unnamed trades into one priced bucket. Its named sibling still
604    /// counts alone.
605    #[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    /// Prices are medians over the whole stream, so no dollar figure exists until it ends. The
628    /// builder holds raw amounts and converts once — which only works because the conversion is
629    /// linear, and this is the test of that.
630    #[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        // 2 SOL and 3 SOL at $100, whether summed raw and converted once or converted twice.
638        assert_eq!(total.requoted.usd, 500.0);
639        assert_eq!(total.l1.legs, 0, "L1 had these legs at another venue");
640    }
641
642    /// The order records arrive in is the order the session produced them, which is not a
643    /// property of the venue. Every figure must be a fold, not a sequence.
644    #[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    /// Neither column counts flow that never landed, and the two must be filtered alike — a
657    /// reverted simulation is not a leg the venue won, and a failed original is not one it held.
658    #[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    /// Volume share needs every leg counted once, so a two-hop route gives each half — where
678    /// per-hop notional credits both in full. The two answer different questions.
679    #[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        // The leg is one SOL, $100. Per-hop notional credits the venue the whole of its own hop.
691        assert_eq!(total.requoted.usd, 100.0);
692        // Share splits that $100 across the two hops on the route, and the venue holds one.
693        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        // On L1 it held the leg outright.
699        assert_eq!(total.share(), Some((100.0, 50.0)));
700
701        // Each hop is filed under its own direction, so the rows decompose the same measure.
702        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    /// The program wins when given; the label is the fallback, so naming only a label still
711    /// measures the fill columns rather than reporting a silent zero on them.
712    #[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        // A program that was given and does not match is not rescued by a matching label.
723        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        // The quote names no program, so this key cannot match there.
729        assert!(!by_program.claims_quoted(hop));
730    }
731
732    /// Dollars cross mints; a raw amount does not. Summing each direction's own input mint added
733    /// lamports to stablecoin units and produced a figure that looked precise and meant nothing,
734    /// so no amount is reported in mint units anywhere — only legs and dollars.
735    #[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        // Lamports in one direction, stablecoin units in the other; dollars survive the sum.
745        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        // And the rendered table carries the two rows, and no third.
751        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        // A *quoted fill* line is what must not appear.
756        assert!(!table.contains("quoted fill"));
757    }
758
759    /// A range with nothing to anchor on prices nothing. Reporting those legs at $0 would read
760    /// as "worth nothing" rather than "not valued".
761    #[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    /// A selector that matches nothing is a wrong address or a misspelling, not a venue with no
777    /// flow. Reporting it as $0 was indistinguishable from the real thing.
778    #[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        // And what the stream does name, so the misspelling is visible.
789        assert!(message.contains("Whirlpool (1)"));
790    }
791
792    /// The subtitle is the caller's, since this module cannot know a slot range.
793    #[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}