1use std::{
19 cmp::Ordering,
20 collections::{BTreeMap, HashMap, HashSet, hash_map::Entry},
21};
22
23use serde::Serialize;
24use solana_address::Address;
25
26use super::{
27 fmt::{commas_u, median},
28 prices::Prices,
29 record::{LegRecord, SwapMode},
30};
31use crate::{mints, route_plan::RoutePlan};
32
33pub const VENUE_DUST_USD: f64 = 1e4;
35pub const OUTLIER_BPS: f64 = 2000.0;
38
39#[derive(Default, Debug)]
41pub struct LoadStats {
42 pub dropped_multi_row: usize,
44}
45
46pub fn collect(rows: Vec<LegRecord>) -> (Vec<LegRecord>, LoadStats) {
50 let mut kept: Vec<LegRecord> = Vec::new();
51 let mut first_row: HashMap<String, usize> = HashMap::new();
52 let mut dropped: HashSet<usize> = HashSet::new();
53 for row in rows {
54 if row.swap_mode == SwapMode::ExactOut && !mints::is_major(&row.input_mint) {
55 continue;
56 }
57 match first_row.entry(row.original_signature.clone()) {
58 Entry::Vacant(slot) => {
59 slot.insert(kept.len());
60 kept.push(row);
61 }
62 Entry::Occupied(slot) => {
63 dropped.insert(*slot.get());
64 }
65 }
66 }
67 let stats = LoadStats {
68 dropped_multi_row: dropped.len(),
69 };
70 (
71 kept.into_iter()
72 .enumerate()
73 .filter(|(index, _)| !dropped.contains(index))
74 .map(|(_, row)| row)
75 .collect(),
76 stats,
77 )
78}
79
80fn plan_input(plan: &RoutePlan, mint: &Address) -> Option<i64> {
84 let mint = mint.to_string();
85 let mut total = 0i64;
86 for hop in plan.hops() {
87 if hop.input_mint() != Some(mint.as_str()) {
88 continue;
89 }
90 total += match hop.swap_info.in_amount.as_deref() {
93 None => 0,
94 Some(amount) => amount
95 .parse::<i64>()
96 .ok()
97 .or_else(|| amount.parse::<f64>().ok().map(|float| float as i64))?,
98 };
99 }
100 (total > 0).then_some(total)
101}
102
103fn venue_weights(plan: &RoutePlan) -> Vec<(Option<&str>, f64)> {
106 plan.hops()
107 .iter()
108 .map(|hop| (hop.label(), hop.percent as f64 / 100.0))
109 .collect()
110}
111
112pub struct Measurement {
114 pub outcome: Ordering,
116 pub l1_usd: f64,
118 pub rerouted_usd: f64,
120}
121
122pub fn measure(record: &LegRecord, prices: &Prices) -> Option<Measurement> {
125 match record.swap_mode {
126 SwapMode::ExactOut => measure_exact_out(record, prices),
127 SwapMode::ExactIn => measure_exact_in(record, prices),
128 }
129}
130
131fn measure_exact_out(record: &LegRecord, prices: &Prices) -> Option<Measurement> {
132 let mint = &record.input_mint;
133 let rerouted = plan_input(record.route_plan.as_ref()?, mint)?;
134 let l1 = plan_input(record.original_route_plan.as_ref()?, mint)?;
135 let l1_usd = prices.usd(mint, l1 as f64)?;
136 let rerouted_usd = prices.usd(mint, (2 * l1 - rerouted) as f64)?;
138 if l1_usd <= 0.0 || (rerouted_usd / l1_usd - 1.0).abs() * 1e4 > OUTLIER_BPS {
139 return None;
140 }
141 Some(Measurement {
142 outcome: l1.cmp(&rerouted),
143 l1_usd,
144 rerouted_usd,
145 })
146}
147
148fn measure_exact_in(record: &LegRecord, prices: &Prices) -> Option<Measurement> {
149 let rerouted = record.realized_output_amount.unwrap_or(0) as i64;
150 let l1 = record.original_realized_output_amount.unwrap_or(0) as i64;
151 let bps = (rerouted as f64 / l1 as f64 - 1.0) * 1e4;
152 let scaled = |usd: f64| usd * (1.0 + bps / 1e4);
153 let (l1_usd, rerouted_usd) = if mints::is_major(&record.output_mint) {
156 (
157 prices.usd(&record.output_mint, l1 as f64),
158 prices.usd(&record.output_mint, rerouted as f64),
159 )
160 } else if mints::is_major(&record.input_mint) {
161 let spend = prices.usd(&record.input_mint, record.amount as f64);
162 (spend, spend.map(scaled))
163 } else if let Some(l1_usd) = prices.usd(&record.output_mint, l1 as f64) {
164 (
165 Some(l1_usd),
166 prices.usd(&record.output_mint, rerouted as f64),
167 )
168 } else {
169 let spend = prices.usd(&record.input_mint, record.amount as f64)?;
170 (Some(spend), Some(scaled(spend)))
171 };
172 let (l1_usd, rerouted_usd) = (l1_usd?, rerouted_usd?);
173 if l1_usd <= 0.0 || bps.abs() > OUTLIER_BPS {
174 return None;
175 }
176 Some(Measurement {
177 outcome: rerouted.cmp(&l1),
178 l1_usd,
179 rerouted_usd,
180 })
181}
182
183#[derive(Default, Clone, Serialize)]
185pub struct SideTotals {
186 pub vol: f64,
188 pub net: f64,
190}
191
192#[derive(Default, Clone, Serialize)]
194pub struct VenueTotals {
195 pub rerouted: f64,
197 pub l1: f64,
199 pub net: f64,
201}
202
203#[derive(Default, Clone, Serialize)]
206pub struct RangeReport {
207 pub n: u64,
209 pub better: u64,
211 pub same: u64,
213 pub worse: u64,
215 pub vol: f64,
217 pub net: f64,
219 pub vol_better: f64,
221 pub vol_same: f64,
223 pub vol_worse: f64,
225 pub bps: Vec<f64>,
227 pub majors: SideTotals,
229 pub exotic: SideTotals,
231 pub venues: BTreeMap<String, VenueTotals>,
233}
234
235impl RangeReport {
236 pub fn from_records(records: &[LegRecord], prices: &Prices) -> Self {
238 let mut report = Self::default();
239 for record in records {
240 if let Some(measurement) = measure(record, prices) {
241 report.record(record, &measurement);
242 }
243 }
244 report
245 }
246
247 fn record(&mut self, leg: &LegRecord, measurement: &Measurement) {
248 let delta = measurement.rerouted_usd - measurement.l1_usd;
249 self.n += 1;
250 let (count, vol) = match measurement.outcome {
251 Ordering::Greater => (&mut self.better, &mut self.vol_better),
252 Ordering::Equal => (&mut self.same, &mut self.vol_same),
253 Ordering::Less => (&mut self.worse, &mut self.vol_worse),
254 };
255 *count += 1;
256 *vol += measurement.l1_usd;
257 self.vol += measurement.l1_usd;
258 self.net += delta;
259 if measurement.l1_usd > 0.0 {
260 self.bps.push(delta / measurement.l1_usd * 1e4);
261 }
262 let side = if mints::trades_only_majors(&leg.input_mint, &leg.output_mint) {
263 &mut self.majors
264 } else {
265 &mut self.exotic
266 };
267 side.vol += measurement.l1_usd;
268 side.net += delta;
269 self.attribute_venues(leg, measurement.l1_usd, delta);
270 }
271
272 fn attribute_venues(&mut self, leg: &LegRecord, l1_usd: f64, delta: f64) {
275 for (rerouted, plan) in [(true, &leg.route_plan), (false, &leg.original_route_plan)] {
276 let Some(plan) = plan else {
277 continue;
278 };
279 let weights = venue_weights(plan);
280 let total: f64 = weights.iter().map(|(_, weight)| weight).sum();
281 let total = if total == 0.0 { 1.0 } else { total };
282 for (label, weight) in weights {
283 let label = label.unwrap_or("(unlabeled)");
284 let entry = self.venues.entry(label.to_string()).or_default();
285 let share = weight / total;
286 if rerouted {
287 entry.rerouted += l1_usd * share;
288 entry.net += delta * share;
289 } else {
290 entry.l1 += l1_usd * share;
291 }
292 }
293 }
294 }
295
296 pub fn merge(&mut self, other: &Self) {
298 self.n += other.n;
299 self.better += other.better;
300 self.same += other.same;
301 self.worse += other.worse;
302 self.vol += other.vol;
303 self.net += other.net;
304 self.vol_better += other.vol_better;
305 self.vol_same += other.vol_same;
306 self.vol_worse += other.vol_worse;
307 self.bps.extend_from_slice(&other.bps);
308 self.majors.vol += other.majors.vol;
309 self.majors.net += other.majors.net;
310 self.exotic.vol += other.exotic.vol;
311 self.exotic.net += other.exotic.net;
312 for (venue, totals) in &other.venues {
313 let entry = self.venues.entry(venue.clone()).or_default();
314 entry.rerouted += totals.rerouted;
315 entry.l1 += totals.l1;
316 entry.net += totals.net;
317 }
318 }
319
320 pub fn vw_bps(&self) -> f64 {
322 if self.vol == 0.0 {
323 0.0
324 } else {
325 self.net / self.vol * 1e4
326 }
327 }
328
329 pub fn render(&self, name: &str) -> String {
332 if self.vol == 0.0 {
333 return format!("### {name}: no measurable legs\n");
334 }
335 let mut lines = self.summary_lines(name);
336 lines.push(String::new());
337 lines.extend(self.venue_table());
338 lines.push(String::new());
339 lines.join("\n")
340 }
341
342 fn summary_lines(&self, name: &str) -> Vec<String> {
343 let mut bps = self.bps.clone();
344 let (q1_at, q3_at) = (bps.len() / 4, 3 * bps.len() / 4);
345 let med = median(&mut bps);
346 let mut lines = vec![
347 format!("### {name}"),
348 format!(
349 "vw vs historical: **{:+.2} bps** (net {}$ on ${})",
350 self.vw_bps(),
351 commas_signed(self.net),
352 commas(self.vol)
353 ),
354 format!(
355 "b/s/w: {} / {} / {} (by volume {:.1} / {:.1} / {:.1}%)",
356 commas_u(self.better),
357 commas_u(self.same),
358 commas_u(self.worse),
359 self.vol_better / self.vol * 100.0,
360 self.vol_same / self.vol * 100.0,
361 self.vol_worse / self.vol * 100.0
362 ),
363 format!(
364 "per-leg bps: median {med:+.2}, IQR [{:+.2}, {:+.2}]",
365 bps[q1_at], bps[q3_at]
366 ),
367 ];
368 for (label, side) in [
369 ("majors<->majors", &self.majors),
370 ("exotic-involved", &self.exotic),
371 ] {
372 if side.vol > 0.0 {
373 lines.push(format!(
374 "{label}: {:+.2} bps (net {}$ on ${})",
375 side.net / side.vol * 1e4,
376 commas_signed(side.net),
377 commas(side.vol)
378 ));
379 }
380 }
381 lines
382 }
383
384 fn venue_table(&self) -> Vec<String> {
385 let mut lines = vec![
386 "| Venue | rerouted share | historical share | vw bps (rerouted legs) |".to_string(),
387 "|---|---|---|---|".to_string(),
388 ];
389 let total_rerouted: f64 = self
390 .venues
391 .values()
392 .map(|e| e.rerouted)
393 .sum::<f64>()
394 .max(1.0);
395 let total_l1: f64 = self.venues.values().map(|e| e.l1).sum::<f64>().max(1.0);
396 let mut ranked: Vec<_> = self.venues.iter().collect();
397 ranked.sort_by(|a, b| b.1.rerouted.total_cmp(&a.1.rerouted));
398 for (venue, e) in ranked {
399 if e.rerouted < VENUE_DUST_USD && e.l1 < VENUE_DUST_USD {
400 continue;
401 }
402 let vw = if e.rerouted == 0.0 {
403 0.0
404 } else {
405 e.net / e.rerouted * 1e4
406 };
407 lines.push(format!(
408 "| {venue} | {:.1}% | {:.1}% | {vw:+.2} |",
409 e.rerouted / total_rerouted * 100.0,
410 e.l1 / total_l1 * 100.0
411 ));
412 }
413 lines
414 }
415}
416
417fn commas(x: f64) -> String {
418 commas_u(x.round().abs() as u64)
419}
420
421fn commas_signed(x: f64) -> String {
422 format!("{}{}", if x < 0.0 { "-" } else { "+" }, commas(x))
423}
424
425#[cfg(test)]
426mod tests {
427 use rstest::rstest;
428
429 use super::*;
430 use crate::{
431 reroute_report::{
432 Samples,
433 testing::{hop, plan, record_of},
434 },
435 route_plan::RouteHop,
436 };
437
438 #[rstest]
439 #[case::rounds_up("+1,235", 1_234.6)]
440 #[case::negative("-1,235", -1_234.6)]
441 fn signed_commas_carry_the_sign(#[case] expected: &str, #[case] x: f64) {
442 assert_eq!(commas_signed(x), expected);
443 }
444
445 fn hop_of(input_mint: &Address, in_amount: u64) -> RouteHop {
446 hop(
447 None,
448 "Venue",
449 &input_mint.to_string(),
450 &mints::USDT.to_string(),
451 in_amount,
452 )
453 }
454
455 fn amount_hop(in_amount: Option<&str>) -> RouteHop {
457 let mut hop = hop_of(&mints::USDC, 0);
458 hop.swap_info.in_amount = in_amount.map(str::to_string);
459 hop
460 }
461
462 #[rstest]
463 #[case::integer_amount(Some("1000"), Some(1_000))]
464 #[case::float_amount_truncates(Some("1000.9"), Some(1_000))]
465 #[case::float_string_truncates(Some("1.5e3"), Some(1_500))]
466 #[case::unparseable_voids_the_plan(Some("abc"), None)]
467 #[case::an_absent_amount_alone_sums_to_nothing(None, None)]
468 fn plan_input_reads_integer_and_float_amounts(
469 #[case] amount: Option<&str>,
470 #[case] expected: Option<i64>,
471 ) {
472 let plan = plan(vec![amount_hop(amount)]).expect("a plan");
473 assert_eq!(plan_input(&plan, &mints::USDC), expected);
474 }
475
476 #[test]
477 fn plan_input_sums_only_the_asked_mints_hops() {
478 let plan = plan(vec![
479 hop_of(&mints::USDC, 300),
480 hop_of(&Address::default(), 999),
481 hop_of(&mints::USDC, 700),
482 ])
483 .expect("a plan");
484 assert_eq!(plan_input(&plan, &mints::USDC), Some(1_000));
485
486 let empty: RoutePlan = serde_json::from_str("[]").expect("an empty plan");
488 assert_eq!(plan_input(&empty, &mints::USDC), None);
489 }
490
491 #[test]
492 fn an_absent_amount_contributes_zero_without_voiding() {
493 let plan = plan(vec![amount_hop(None), hop_of(&mints::USDC, 700)]).expect("a plan");
494 assert_eq!(plan_input(&plan, &mints::USDC), Some(700));
495 }
496
497 fn prices() -> Prices {
500 let mut samples = Samples::default();
501 for n in 1..=3u64 {
502 samples.push(&LegRecord {
503 original_realized_output_amount: Some(n * 100_000_000),
504 ..record_of(mints::SOL, mints::USDC, n * 1_000_000_000, None, None, None)
505 });
506 }
507 samples.prices().expect("anchored")
508 }
509
510 fn stable_record(mode: SwapMode, rerouted: u64, l1: u64) -> LegRecord {
511 LegRecord {
512 swap_mode: mode,
513 realized_output_amount: Some(rerouted),
514 original_realized_output_amount: Some(l1),
515 route_plan: plan(vec![hop_of(&mints::USDC, rerouted)]),
516 original_route_plan: plan(vec![hop_of(&mints::USDC, l1)]),
517 ..record_of(mints::USDC, mints::USDT, 1_000_000, None, None, None)
518 }
519 }
520
521 #[test]
522 fn exact_out_credits_the_input_saved() {
523 let m = measure(
524 &stable_record(SwapMode::ExactOut, 999_000, 1_000_000),
525 &prices(),
526 )
527 .expect("measurable");
528 assert_eq!(m.outcome, Ordering::Greater);
529 assert!((m.l1_usd - 1.0).abs() < 1e-9);
530 assert!((m.rerouted_usd - 1.001).abs() < 1e-9);
531 }
532
533 #[rstest]
534 #[case::win(1_010_000, 1_000_000, Some(Ordering::Greater))]
535 #[case::tie(1_000_000, 1_000_000, Some(Ordering::Equal))]
536 #[case::exactly_at_the_outlier_bound_stays(1_200_000, 1_000_000, Some(Ordering::Greater))]
537 #[case::past_the_outlier_bound_drops(1_210_000, 1_000_000, None)]
538 fn exact_in_measures_major_output_with_the_outlier_gate(
539 #[case] rerouted: u64,
540 #[case] l1: u64,
541 #[case] expected: Option<Ordering>,
542 ) {
543 let m = measure(&stable_record(SwapMode::ExactIn, rerouted, l1), &prices());
544 assert_eq!(m.map(|m| m.outcome), expected);
545 }
546
547 #[test]
549 fn collect_drops_multi_row_signatures_wholesale() {
550 let mut a = stable_record(SwapMode::ExactIn, 1_000_000, 999_000);
551 a.original_signature = "sigA".to_string();
552 let mut a2 = a.clone();
553 a2.amount = 2_000_000;
554 let mut b = stable_record(SwapMode::ExactIn, 1_000_000, 999_000);
555 b.original_signature = "sigB".to_string();
556
557 let (kept, stats) = collect(vec![a, a2, b]);
558 assert_eq!(kept.len(), 1);
559 assert_eq!(kept[0].original_signature, "sigB");
560 assert_eq!(stats.dropped_multi_row, 1);
561 }
562
563 #[test]
567 fn collect_skips_exact_out_legs_it_cannot_price() {
568 let exotic = LegRecord {
569 input_mint: Address::default(),
570 ..stable_record(SwapMode::ExactOut, 1_000_000, 999_000)
571 };
572 let major = stable_record(SwapMode::ExactOut, 1_000_000, 999_000);
573
574 let (kept, stats) = collect(vec![exotic, major]);
575 assert_eq!(kept.len(), 1);
576 assert_eq!(kept[0].input_mint, mints::USDC);
577 assert_eq!(stats.dropped_multi_row, 0, "a skipped row is not a pairing");
578 }
579}