simulator_api/reroute_report/
render.rs1use std::fmt::Write as _;
4
5use super::flow::{Direction, Flow, Report, fold};
6use crate::mints::short_mint;
7
8const MAX_DIRECTIONS: usize = 12;
11
12impl Report {
13 #[expect(
18 clippy::let_underscore_must_use,
19 reason = "fmt::Write for String is infallible"
20 )]
21 pub fn render(&self, subtitle: Option<&str>) -> String {
22 let target = self.target();
23 let mut out = String::new();
24 let name = target
25 .label()
26 .map(str::to_string)
27 .or_else(|| target.program().map(|program| program.to_string()))
28 .unwrap_or_else(|| "venue".to_string());
29 let _ = write!(out, "\n {name}");
30 if let Some(subtitle) = subtitle {
31 let _ = write!(out, " {subtitle}");
32 }
33 out.push_str("\n\n");
34
35 let priced = self.sol_usd().is_some();
36 out.push_str(&row("", "historical", "rerouted", "delta"));
37 let total = self.total();
38 out.push_str(&rows_for(&total, "", priced));
39 out.push_str(&share_row(&total, ""));
40
41 let mut ranked: Vec<_> = self
42 .by_direction()
43 .filter(|(_, direction)| direction.present())
44 .collect();
45 ranked.sort_unstable_by_key(|(mints, direction)| {
46 (std::cmp::Reverse(direction.rank()), *mints)
47 });
48 for ((input, output), direction) in ranked.iter().take(MAX_DIRECTIONS) {
49 let _ = writeln!(out, "\n {} → {}", short_mint(input), short_mint(output));
50 out.push_str(&rows_for(direction, " ", priced));
51 out.push_str(&share_row(direction, " "));
52 }
53 if let Some(rest) = ranked.get(MAX_DIRECTIONS..).filter(|rest| !rest.is_empty()) {
54 let tail = fold(rest.iter().map(|(_, direction)| **direction));
55 let _ = writeln!(out, "\n + {} more directions", rest.len());
56 out.push_str(&rows_for(&tail, " ", priced));
57 out.push_str(&share_row(&tail, " "));
58 }
59
60 out
61 }
62
63 pub fn to_json(&self) -> serde_json::Value {
66 let target = self.target();
67 let total = self.total();
68 let directions: Vec<_> = self
69 .by_direction()
70 .map(|((input, output), direction)| {
71 serde_json::json!({
72 "inputMint": input,
73 "outputMint": output,
74 "l1": flow_json(&direction.l1),
75 "requoted": flow_json(&direction.requoted),
76 "sharePct": direction.share().map(|(l1, _)| l1),
77 "requotedSharePct": direction.share().map(|(_, requoted)| requoted),
78 })
79 })
80 .collect();
81 serde_json::json!({
82 "label": target.label(),
83 "program": target.program().map(|program| program.to_string()),
84 "total": {
85 "l1": flow_json(&total.l1),
86 "requoted": flow_json(&total.requoted),
87 },
88 "share": {
90 "l1Pct": total.share().map(|(l1, _)| l1),
91 "requotedPct": total.share().map(|(_, requoted)| requoted),
92 },
93 "byDirection": directions,
94 })
95 }
96}
97
98fn flow_json(flow: &Flow) -> serde_json::Value {
99 serde_json::json!({
100 "swaps": flow.legs,
101 "usd": flow.usd,
102 "swapsWithoutAmount": flow.without_amount,
103 "swapsWithoutPrice": flow.without_price,
104 })
105}
106
107fn share_row(direction: &Direction, indent: &str) -> String {
108 let Some((l1, requoted)) = direction.share() else {
109 return String::new();
110 };
111 row(
112 &format!("{indent}share"),
113 &format!("{l1:.1}%"),
114 &format!("{requoted:.1}%"),
115 &format!("{:+.1}pp", requoted - l1),
116 )
117}
118
119fn row(label: &str, l1: &str, requoted: &str, delta: &str) -> String {
120 format!(" {label:<10} {l1:>14} {requoted:>14} {delta:>14}\n")
121}
122
123fn rows_for(direction: &Direction, indent: &str, priced: bool) -> String {
126 let mut out = totals("swaps", indent, direction.l1.legs, direction.requoted.legs);
127 if priced && !direction.fully_unpriced() {
128 out.push_str(&usd_row(direction, indent));
129 }
130 if direction.unpriced() {
131 #[expect(
132 clippy::let_underscore_must_use,
133 reason = "fmt::Write for String is infallible"
134 )]
135 let _ = writeln!(
136 out,
137 "{indent} ({} swaps in mints this range could not price)",
138 direction.l1.without_price + direction.requoted.without_price
139 );
140 }
141 out
142}
143
144fn totals(label: &str, indent: &str, l1: u64, requoted: u64) -> String {
145 row(
146 &format!("{indent}{label}"),
147 &l1.to_string(),
148 &requoted.to_string(),
149 &signed(i128::from(requoted) - i128::from(l1)),
150 )
151}
152
153fn usd_row(direction: &Direction, indent: &str) -> String {
154 row(
155 &format!("{indent}volume"),
156 &money(direction.l1.usd),
157 &money(direction.requoted.usd),
158 &format!(
159 "{}{}",
160 if direction.requoted.usd < direction.l1.usd {
161 "-"
162 } else {
163 "+"
164 },
165 money((direction.requoted.usd - direction.l1.usd).abs())
166 ),
167 )
168}
169
170fn money(usd: f64) -> String {
171 match usd {
172 usd if usd >= 1e6 => format!("${:.2}M", usd / 1e6),
173 usd if usd >= 1e3 => format!("${:.1}k", usd / 1e3),
174 usd => format!("${usd:.0}"),
175 }
176}
177
178fn signed(delta: i128) -> String {
179 if delta < 0 {
180 delta.to_string()
181 } else {
182 format!("+{delta}")
183 }
184}