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    #[allow(missing_docs)]
78    pub fn label(&self) -> Option<&str> {
79        self.label.as_deref()
80    }
81
82    #[allow(missing_docs)]
83    pub fn program(&self) -> Option<Address> {
84        self.program.as_ref().map(|(program, _)| *program)
85    }
86
87    /// 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        (usd as u64, self.l1.legs.max(self.requoted.legs))
191    }
192}
193
194pub(super) fn fold(directions: impl IntoIterator<Item = Direction>) -> Direction {
195    directions
196        .into_iter()
197        .fold(Direction::default(), |mut total, direction| {
198            total.merge(direction);
199            total
200        })
201}
202
203/// A trade direction, keyed by the mints it moves between as `(input, output)`.
204pub type Pair = (String, String);
205
206#[derive(Clone, Copy)]
207enum Side {
208    L1,
209    Requoted,
210}
211
212/// One venue's flow across a set of reroute results, onchain against rerouted, by trade direction.
213#[derive(Debug)]
214pub struct Report {
215    by_direction: BTreeMap<Pair, Direction>,
216    target: Target,
217    /// Absent when the stream carried no SOL<->USDC reroutes to anchor from.
218    sol_usd: Option<f64>,
219}
220
221impl Report {
222    /// Build from anything that yields records — a mapped notification stream, a DB read.
223    pub fn from_records<'a>(
224        target: Target,
225        records: impl IntoIterator<Item = &'a LegRecord>,
226    ) -> Result<Self, RerouteReportError> {
227        let mut builder = ReportBuilder::new(target);
228        for record in records {
229            builder.push(record);
230        }
231        builder.finish()
232    }
233
234    /// The venue this report is about.
235    pub const fn target(&self) -> &Target {
236        &self.target
237    }
238
239    /// The SOL price the records gave, in USD. `None` when they carried no SOL-USDC reroutes to
240    /// anchor on, in which case nothing is priced.
241    pub const fn sol_usd(&self) -> Option<f64> {
242        self.sol_usd
243    }
244
245    /// Every direction the range priced, which includes those the venue never served — filter
246    /// on [`Direction::present`] for the venue's own.
247    pub fn by_direction(&self) -> impl Iterator<Item = (&Pair, &Direction)> {
248        self.by_direction.iter()
249    }
250
251    /// The directions summed. Share stays meaningful because both numerator and denominator are
252    /// per-leg normalized.
253    pub fn total(&self) -> Direction {
254        fold(self.by_direction.values().copied())
255    }
256}
257
258/// Accumulates a [`Report`] one record at a time, holding pricing samples, one accumulator per
259/// trade direction, and the venue labels seen — never the records.
260///
261/// Every price is a median over the whole stream, so amounts accumulate raw and convert once in
262/// [`ReportBuilder::finish`]. [`Prices::usd`] is linear in the amount, which is what makes that
263/// identical to converting each hop as it arrives.
264pub struct ReportBuilder {
265    target: Target,
266    samples: Samples,
267    by_direction: Directions,
268    /// Venue labels the quotes named, for the error a selector that matches nothing raises.
269    labels: BTreeMap<String, u64>,
270}
271
272impl ReportBuilder {
273    /// An empty builder for `target`.
274    pub fn new(target: Target) -> Self {
275        Self {
276            target,
277            samples: Samples::default(),
278            by_direction: Directions::default(),
279            labels: BTreeMap::new(),
280        }
281    }
282
283    /// Take one record's contribution. Cheap and order-independent.
284    pub fn push(&mut self, record: &LegRecord) {
285        self.samples.push(record);
286
287        // Neither column counts flow that never landed, so the two are filtered alike.
288        if record.failed || record.original_failed {
289            return;
290        }
291        let Self {
292            target,
293            by_direction,
294            labels,
295            ..
296        } = self;
297        fn hops_of(plan: &Option<RoutePlan>) -> Option<&[RouteHop]> {
298            plan.as_ref().map(RoutePlan::hops)
299        }
300        // Used twice: the census below, and the fallback when there is no fill plan.
301        let quoted = hops_of(&record.route_plan);
302        for label in quoted.iter().copied().flatten().filter_map(RouteHop::label) {
303            match labels.get_mut(label) {
304                Some(hops) => *hops += 1,
305                None => {
306                    labels.insert(label.to_string(), 1);
307                }
308            }
309        }
310
311        // The fill, so both columns compare a fill against a fill; the quote is the fallback.
312        let (requoted, from_quote) = match hops_of(&record.realized_route_plan) {
313            Some(filled) => (filled, false),
314            None => (quoted.unwrap_or_default(), true),
315        };
316        let claimed = |hop: &RouteHop| match from_quote {
317            true => target.claims_quoted(hop),
318            false => target.claims_fill(hop),
319        };
320        for hop in requoted.iter().filter(|hop| claimed(hop)) {
321            by_direction.record(Side::Requoted, hop);
322        }
323
324        let l1 = hops_of(&record.original_route_plan);
325        for hop in l1
326            .iter()
327            .copied()
328            .flatten()
329            .filter(|hop| target.claims_fill(hop))
330        {
331            by_direction.record(Side::L1, hop);
332        }
333
334        // The leg's own value, counted once whichever routes it took, so the shares are over
335        // the population rather than over the hops the venue served.
336        let leg_amount = u128::from(record.amount) as f64;
337        by_direction.accumulate_share(
338            Side::Requoted,
339            requoted,
340            record.input_mint,
341            leg_amount,
342            claimed,
343        );
344        if let Some(l1) = l1 {
345            by_direction.accumulate_share(Side::L1, l1, record.input_mint, leg_amount, |hop| {
346                target.claims_fill(hop)
347            });
348        }
349    }
350
351    /// Price the accumulated flow into a [`Report`]. Fails with
352    /// [`RerouteReportError::NothingMatched`] when no hop on either side matched the target.
353    pub fn finish(self) -> Result<Report, RerouteReportError> {
354        let prices = self.samples.prices();
355        let report = Report {
356            sol_usd: prices.as_ref().map(Prices::sol_usd),
357            by_direction: self.by_direction.price(prices.as_ref()),
358            target: self.target,
359        };
360        let total = report.total();
361        if total.l1.legs == 0 && total.requoted.legs == 0 {
362            return Err(RerouteReportError::NothingMatched {
363                asked: report.target.describe(),
364                venues: self.labels.into_iter().collect(),
365            });
366        }
367        Ok(report)
368    }
369}
370
371/// In its own type so `record` and `accumulate_share` borrow only the map, leaving the rest of
372/// the builder free.
373#[derive(Default)]
374struct Directions(BTreeMap<Pair, DirectionAccum>);
375
376impl Directions {
377    /// The hop's notional. Its input mint is the direction's, so raw amounts sum unpriced.
378    fn record(&mut self, side: Side, hop: &RouteHop) {
379        let Some(key) = key_of(hop) else {
380            return;
381        };
382        let flow = &mut self.0.entry(key).or_default().side_mut(side).flow;
383        flow.legs += 1;
384        match in_amount(hop) {
385            Some(amount) => flow.raw += amount,
386            None => flow.without_amount += 1,
387        }
388    }
389
390    /// A leg's value split across its route's venues, filed under each hop's own direction, so
391    /// every leg counts once and the shares over a direction sum to 100%.
392    ///
393    /// Credited in the *leg's* input mint, which is not the direction's on a multi-hop route —
394    /// hence a bucket per mint.
395    fn accumulate_share(
396        &mut self,
397        side: Side,
398        hops: &[RouteHop],
399        leg_mint: Address,
400        leg_amount: f64,
401        claimed: impl Fn(&RouteHop) -> bool,
402    ) {
403        let total: u64 = hops.iter().map(|hop| hop.percent).sum();
404        if total == 0 {
405            return;
406        }
407        for hop in hops {
408            let Some(key) = key_of(hop) else {
409                continue;
410            };
411            let value = leg_amount * hop.percent as f64 / total as f64;
412            let share = &mut self.0.entry(key).or_default().side_mut(side).share;
413            credit(&mut share.all, leg_mint, value);
414            if claimed(hop) {
415                credit(&mut share.claimed, leg_mint, value);
416            }
417        }
418    }
419
420    /// A direction with nothing priceable and no venue legs carries no measurement — its bucket
421    /// was opened before its mint was known to be unpriceable — so it is dropped, not zeroed.
422    fn price(self, prices: Option<&Prices>) -> BTreeMap<Pair, Direction> {
423        self.0
424            .into_iter()
425            .map(|(pair, accum)| {
426                let direction = accum.price(&pair.0, prices);
427                (pair, direction)
428            })
429            .filter(|(_, direction)| {
430                direction.present() || direction.l1_all > 0.0 || direction.requoted_all > 0.0
431            })
432            .collect()
433    }
434}
435
436/// `None` for a hop whose pair the plan never named: keying it on a default address would pool
437/// unrelated unnamed trades into one priced bucket, so such a hop opens no direction at all.
438fn key_of(hop: &RouteHop) -> Option<Pair> {
439    Some((
440        hop.input_mint()?.to_string(),
441        hop.output_mint()?.to_string(),
442    ))
443}
444
445/// Nearly every direction sees a single leg mint, so a scan beats a map; a hub pair terminating
446/// routes out of many exotics is the exception.
447fn credit(bucket: &mut Vec<(Address, f64)>, mint: Address, value: f64) {
448    match bucket.iter_mut().find(|(held, _)| *held == mint) {
449        Some((_, total)) => *total += value,
450        None => bucket.push((mint, value)),
451    }
452}
453
454/// Raw amounts for one side of one direction, awaiting a price.
455#[derive(Default)]
456struct FlowAccum {
457    legs: u64,
458    /// In the direction's input mint, shared by every hop filed here.
459    raw: u128,
460    without_amount: u64,
461}
462
463impl FlowAccum {
464    fn price(self, mint: &str, prices: Option<&Prices>, share_usd: f64) -> Flow {
465        let usd = prices.and_then(|prices| prices.usd_str(mint, self.raw as f64));
466        Flow {
467            legs: self.legs,
468            usd: usd.unwrap_or_default(),
469            without_amount: self.without_amount,
470            // Every hop here shares one mint, so the range prices all of them or none.
471            without_price: match usd {
472                Some(_) => 0,
473                None => self.legs - self.without_amount,
474            },
475            share_usd,
476        }
477    }
478}
479
480/// Weighted leg value for one side of one direction, per the leg's own input mint.
481#[derive(Default)]
482struct ShareAccum {
483    all: Vec<(Address, f64)>,
484    claimed: Vec<(Address, f64)>,
485}
486
487impl ShareAccum {
488    /// `(all, claimed)`. An unpriceable mint contributes to neither, keeping the ratio honest.
489    fn price(&self, prices: Option<&Prices>) -> (f64, f64) {
490        let sum = |bucket: &[(Address, f64)]| {
491            bucket
492                .iter()
493                .filter_map(|(mint, raw)| prices?.usd(mint, *raw))
494                // Not `sum`: `Sum` for floats starts at `-0.0`, so an empty bucket would
495                // render as `-0.0%`.
496                .fold(0.0, |total, usd| total + usd)
497        };
498        (sum(&self.all), sum(&self.claimed))
499    }
500}
501
502/// Paired so a hop's notional and its share cannot be filed against different sides.
503#[derive(Default)]
504struct SideAccum {
505    flow: FlowAccum,
506    share: ShareAccum,
507}
508
509#[derive(Default)]
510struct DirectionAccum {
511    l1: SideAccum,
512    requoted: SideAccum,
513}
514
515impl DirectionAccum {
516    fn side_mut(&mut self, side: Side) -> &mut SideAccum {
517        match side {
518            Side::L1 => &mut self.l1,
519            Side::Requoted => &mut self.requoted,
520        }
521    }
522
523    fn price(self, mint: &str, prices: Option<&Prices>) -> Direction {
524        let (l1_all, l1_claimed) = self.l1.share.price(prices);
525        let (requoted_all, requoted_claimed) = self.requoted.share.price(prices);
526        Direction {
527            l1: self.l1.flow.price(mint, prices, l1_claimed),
528            requoted: self.requoted.flow.price(mint, prices, requoted_claimed),
529            l1_all,
530            requoted_all,
531        }
532    }
533}
534
535#[cfg(test)]
536mod tests {
537    use super::*;
538    use crate::{
539        mints,
540        reroute_report::testing::{hop, plan, record_of},
541    };
542
543    const SOL: &str = "So11111111111111111111111111111111111111112";
544    const USDC: &str = "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v";
545    const VENUE_PROGRAM: &str = "BiSoNHVpsVZW2F7rx2eQ59yQwKxzU5NvBcmKshCSUypi";
546    const OTHER_PROGRAM: &str = "whirLbMiicVdio4qvUfM5KAg6Ct8VwpYzGff3uctyCc";
547
548    /// Fixes SOL at $100 from the stream's own swaps. Carries no route plan, so it prices the
549    /// range without contributing a hop to anything.
550    fn anchors() -> Vec<LegRecord> {
551        (1..=3)
552            .map(|n| LegRecord {
553                original_realized_output_amount: Some(n * 100_000_000),
554                ..record_of(mints::SOL, mints::USDC, n * 1_000_000_000, None, None, None)
555            })
556            .collect()
557    }
558
559    fn venue() -> Target {
560        Target::new(
561            Some("BisonFi".to_string()),
562            Some(VENUE_PROGRAM.parse().expect("a venue program")),
563        )
564    }
565
566    fn fill(
567        program: &str,
568        label: &str,
569        input: &str,
570        output: &str,
571        amount: u64,
572    ) -> Option<RoutePlan> {
573        plan(vec![hop(Some(program), label, input, output, amount)])
574    }
575
576    fn report_of(records: &[LegRecord]) -> Report {
577        Report::from_records(venue(), records).expect("the venue appears")
578    }
579
580    /// The anchors, plus whatever the test is actually about.
581    fn priced(extra: impl IntoIterator<Item = LegRecord>) -> Vec<LegRecord> {
582        let mut records = anchors();
583        records.extend(extra);
584        records
585    }
586
587    /// A leg the venue won: the re-quote routed it through the venue, L1 had it elsewhere.
588    fn won_leg(amount: u64) -> LegRecord {
589        let realized = fill(VENUE_PROGRAM, "BisonFi", SOL, USDC, amount);
590        let l1 = fill(OTHER_PROGRAM, "Whirlpool", SOL, USDC, amount);
591        record_of(mints::SOL, mints::USDC, amount, None, l1, realized)
592    }
593
594    /// A hop whose pair the plan never named opens no direction: keyed on a default address it
595    /// would pool unrelated unnamed trades into one priced bucket. Its named sibling still
596    /// counts alone.
597    #[test]
598    fn a_hop_with_an_unnamed_mint_opens_no_direction() {
599        let mut unnamed = hop(Some(VENUE_PROGRAM), "BisonFi", USDC, SOL, 1_000_000);
600        unnamed.swap_info.output_mint = None;
601        let l1 = plan(vec![
602            hop(Some(VENUE_PROGRAM), "BisonFi", SOL, USDC, 2_000_000_000),
603            unnamed,
604        ]);
605        let report = report_of(&priced([record_of(
606            mints::SOL,
607            mints::USDC,
608            2_000_000_000,
609            None,
610            l1,
611            None,
612        )]));
613
614        let pairs: Vec<&Pair> = report.by_direction().map(|(pair, _)| pair).collect();
615        assert_eq!(pairs, [&(SOL.to_string(), USDC.to_string())]);
616        assert_eq!(report.total().l1.legs, 1, "only the named hop counts");
617    }
618
619    /// Prices are medians over the whole stream, so no dollar figure exists until it ends. The
620    /// builder holds raw amounts and converts once — which only works because the conversion is
621    /// linear, and this is the test of that.
622    #[test]
623    fn deferring_the_conversion_matches_pricing_each_hop_as_it_arrives() {
624        let report = report_of(&priced([won_leg(2_000_000_000), won_leg(3_000_000_000)]));
625        let total = report.total();
626
627        assert_eq!(report.sol_usd(), Some(100.0));
628        assert_eq!(total.requoted.legs, 2);
629        // 2 SOL and 3 SOL at $100, whether summed raw and converted once or converted twice.
630        assert_eq!(total.requoted.usd, 500.0);
631        assert_eq!(total.l1.legs, 0, "L1 had these legs at another venue");
632    }
633
634    /// The order records arrive in is the order the session produced them, which is not a
635    /// property of the venue. Every figure must be a fold, not a sequence.
636    #[test]
637    fn the_result_does_not_depend_on_arrival_order() {
638        let forward = priced([won_leg(2_000_000_000), won_leg(3_000_000_000)]);
639        let mut backward = forward.clone();
640        backward.reverse();
641
642        let (forward, backward) = (report_of(&forward), report_of(&backward));
643        assert_eq!(forward.sol_usd(), backward.sol_usd());
644        assert_eq!(forward.total().requoted.usd, backward.total().requoted.usd);
645        assert_eq!(forward.render(None), backward.render(None));
646    }
647
648    /// Neither column counts flow that never landed, and the two must be filtered alike — a
649    /// reverted simulation is not a leg the venue won, and a failed original is not one it held.
650    #[test]
651    fn neither_side_counts_flow_that_never_landed() {
652        let records = priced([
653            won_leg(2_000_000_000),
654            LegRecord {
655                failed: true,
656                ..won_leg(9_000_000_000)
657            },
658            LegRecord {
659                original_failed: true,
660                ..won_leg(9_000_000_000)
661            },
662        ]);
663
664        let total = report_of(&records).total();
665        assert_eq!(total.requoted.legs, 1, "only the landed leg counts");
666        assert_eq!(total.requoted.usd, 200.0);
667    }
668
669    /// Volume share needs every leg counted once, so a two-hop route gives each half — where
670    /// per-hop notional credits both in full. The two answer different questions.
671    #[test]
672    fn a_share_splits_a_leg_where_notional_counts_it_twice() {
673        let two_hops = plan(vec![
674            hop(Some(VENUE_PROGRAM), "BisonFi", SOL, USDC, 1_000_000_000),
675            hop(Some(OTHER_PROGRAM), "Whirlpool", USDC, "BONK", 100_000_000),
676        ]);
677        let l1 = fill(VENUE_PROGRAM, "BisonFi", SOL, USDC, 1_000_000_000);
678        let record = record_of(mints::SOL, mints::USDC, 1_000_000_000, None, l1, two_hops);
679        let report = report_of(&priced([record]));
680
681        let total = report.total();
682        // The leg is one SOL, $100. Per-hop notional credits the venue the whole of its own hop.
683        assert_eq!(total.requoted.usd, 100.0);
684        // Share splits that $100 across the two hops on the route, and the venue holds one.
685        assert_eq!(total.requoted_all, 100.0, "the leg is counted once");
686        assert_eq!(
687            total.requoted.share_usd, 50.0,
688            "half the route was the venue's"
689        );
690        // On L1 it held the leg outright.
691        assert_eq!(total.share(), Some((100.0, 50.0)));
692
693        // Each hop is filed under its own direction, so the rows decompose the same measure.
694        let (_, first) = report
695            .by_direction()
696            .find(|((input, output), _)| input == SOL && output == USDC)
697            .expect("the venue's direction");
698        assert_eq!(first.requoted.share_usd, 50.0);
699        assert_eq!(first.requoted_all, 50.0, "that direction held half the leg");
700    }
701
702    /// The program wins when given; the label is the fallback, so naming only a label still
703    /// measures the fill columns rather than reporting a silent zero on them.
704    #[test]
705    fn a_fill_prefers_the_program_and_falls_back_to_the_label() {
706        let filled = fill(VENUE_PROGRAM, "BisonFi", SOL, USDC, 1_000);
707        let record = record_of(mints::SOL, mints::USDC, 1_000, None, filled.clone(), filled);
708        let hop = &record.original_route_plan.as_ref().expect("a plan").hops()[0];
709
710        let by_label = Target::new(Some("BisonFi".to_string()), None);
711        assert!(by_label.claims_fill(hop));
712        assert!(by_label.claims_quoted(hop));
713
714        // A program that was given and does not match is not rescued by a matching label.
715        let other = Target::new(Some("BisonFi".to_string()), Some(Address::new_unique()));
716        assert!(!other.claims_fill(hop));
717
718        let by_program = Target::new(None, Some(VENUE_PROGRAM.parse().expect("a program")));
719        assert!(by_program.claims_fill(hop));
720        // The quote names no program, so this key cannot match there.
721        assert!(!by_program.claims_quoted(hop));
722    }
723
724    /// Dollars cross mints; a raw amount does not. Summing each direction's own input mint added
725    /// lamports to stablecoin units and produced a figure that looked precise and meant nothing,
726    /// so no amount is reported in mint units anywhere — only legs and dollars.
727    #[test]
728    fn the_report_is_swaps_and_dollars_only() {
729        let sell = fill(VENUE_PROGRAM, "BisonFi", SOL, USDC, 1_000_000_000);
730        let buy = fill(VENUE_PROGRAM, "BisonFi", USDC, SOL, 100_000_000);
731        let report = report_of(&priced([
732            record_of(mints::SOL, mints::USDC, 1_000_000_000, None, None, sell),
733            record_of(mints::USDC, mints::SOL, 100_000_000, None, None, buy),
734        ]));
735
736        // Lamports in one direction, stablecoin units in the other; dollars survive the sum.
737        let json = report.to_json();
738        assert_eq!(json["total"]["l1"]["swaps"], 0);
739        assert_eq!(json["total"]["requoted"]["swaps"], 2);
740        assert_eq!(json["total"]["requoted"]["usd"], 200.0);
741
742        // And the rendered table carries the two rows, and no third.
743        let table = report.render(None);
744        let totals = table.split('→').next().expect("a totals block");
745        assert!(totals.contains("swaps") && totals.contains("volume"));
746        assert!(!totals.contains("raw in"), "a raw amount reached the table");
747        // A *quoted fill* line is what must not appear.
748        assert!(!table.contains("quoted fill"));
749    }
750
751    /// A range with nothing to anchor on prices nothing. Reporting those legs at $0 would read
752    /// as "worth nothing" rather than "not valued".
753    #[test]
754    fn a_range_that_cannot_be_priced_reports_no_dollars() {
755        let report = report_of(&[won_leg(2_000_000_000)]);
756        let total = report.total();
757
758        assert_eq!(report.sol_usd(), None);
759        assert_eq!(total.requoted.legs, 1);
760        assert_eq!(total.requoted.without_price, 1);
761        assert!(total.fully_unpriced());
762
763        let table = report.render(None);
764        assert!(!table.contains("volume"), "a dollar row without a price");
765        assert!(table.contains("could not price"));
766    }
767
768    /// A selector that matches nothing is a wrong address or a misspelling, not a venue with no
769    /// flow. Reporting it as $0 was indistinguishable from the real thing.
770    #[test]
771    fn a_selector_that_matches_nothing_says_so() {
772        let quote = plan(vec![hop(None, "Whirlpool", SOL, USDC, 1_000)]);
773        let records = vec![record_of(mints::SOL, mints::USDC, 1_000, quote, None, None)];
774
775        let target = Target::new(Some("Nope".to_string()), None);
776        let error = Report::from_records(target, &records).expect_err("the venue never appears");
777
778        let message = error.to_string();
779        assert!(message.contains("Nope"), "names what was asked for");
780        // And what the stream does name, so the misspelling is visible.
781        assert!(message.contains("Whirlpool (1)"));
782    }
783
784    /// The subtitle is the caller's, since this module cannot know a slot range.
785    #[test]
786    fn the_subtitle_is_the_callers() {
787        let report = report_of(&[won_leg(2_000_000_000)]);
788        assert!(report.render(Some("slots 1–100")).contains("slots 1–100"));
789        assert!(!report.render(None).contains("slots"));
790    }
791}