Skip to main content

simulator_api/reroute_report/
render.rs

1//! The report as a table and as JSON.
2
3use super::flow::{Direction, Flow, Report, fold};
4use crate::mints::short_mint;
5
6/// A longtail book reaches the hundreds, and the tail is individually negligible but
7/// collectively not, so the rest fold into one line rather than being dropped.
8const MAX_DIRECTIONS: usize = 12;
9
10impl Report {
11    /// The gap between the columns includes the reroute effect, not just any configured change.
12    ///
13    /// `subtitle` prints beside the venue name — the slot range, say, which this module cannot
14    /// know.
15    pub fn render(&self, subtitle: Option<&str>) -> String {
16        let target = self.target();
17        let mut out = String::new();
18        let name = target
19            .label()
20            .map(str::to_string)
21            .or_else(|| target.program().map(|program| program.to_string()))
22            .unwrap_or_else(|| "venue".to_string());
23        out.push_str(&format!("\n  {name}"));
24        if let Some(subtitle) = subtitle {
25            out.push_str(&format!("   {subtitle}"));
26        }
27        out.push_str("\n\n");
28
29        let priced = self.sol_usd().is_some();
30        out.push_str(&row("", "historical", "rerouted", "delta"));
31        let total = self.total();
32        out.push_str(&rows_for(&total, "", priced));
33        out.push_str(&share_row(&total, ""));
34
35        let mut ranked: Vec<_> = self
36            .by_direction()
37            .filter(|(_, direction)| direction.present())
38            .collect();
39        ranked.sort_unstable_by_key(|(mints, direction)| {
40            (std::cmp::Reverse(direction.rank()), *mints)
41        });
42        for ((input, output), direction) in ranked.iter().take(MAX_DIRECTIONS) {
43            out.push_str(&format!(
44                "\n  {} → {}\n",
45                short_mint(input),
46                short_mint(output)
47            ));
48            out.push_str(&rows_for(direction, "  ", priced));
49            out.push_str(&share_row(direction, "  "));
50        }
51        if let Some(rest) = ranked.get(MAX_DIRECTIONS..).filter(|rest| !rest.is_empty()) {
52            let tail = fold(rest.iter().map(|(_, direction)| **direction));
53            out.push_str(&format!("\n  + {} more directions\n", rest.len()));
54            out.push_str(&rows_for(&tail, "  ", priced));
55            out.push_str(&share_row(&tail, "  "));
56        }
57
58        out
59    }
60
61    /// The report as JSON: `label`, `program`, `total`, `share` and `byDirection`. Kept flat so
62    /// several reports join as rows.
63    pub fn to_json(&self) -> serde_json::Value {
64        let target = self.target();
65        let total = self.total();
66        let directions: Vec<_> = self
67            .by_direction()
68            .map(|((input, output), direction)| {
69                serde_json::json!({
70                    "inputMint": input,
71                    "outputMint": output,
72                    "l1": flow_json(&direction.l1),
73                    "requoted": flow_json(&direction.requoted),
74                    "sharePct": direction.share().map(|(l1, _)| l1),
75                    "requotedSharePct": direction.share().map(|(_, requoted)| requoted),
76                })
77            })
78            .collect();
79        serde_json::json!({
80            "label": target.label(),
81            "program": target.program().map(|program| program.to_string()),
82            "total": {
83                "l1": flow_json(&total.l1),
84                "requoted": flow_json(&total.requoted),
85            },
86            // Per-leg normalized, unlike the per-hop `usd` above.
87            "share": {
88                "l1Pct": total.share().map(|(l1, _)| l1),
89                "requotedPct": total.share().map(|(_, requoted)| requoted),
90            },
91            "byDirection": directions,
92        })
93    }
94}
95
96fn flow_json(flow: &Flow) -> serde_json::Value {
97    serde_json::json!({
98        "swaps": flow.legs,
99        "usd": flow.usd,
100        "swapsWithoutAmount": flow.without_amount,
101        "swapsWithoutPrice": flow.without_price,
102    })
103}
104
105fn share_row(direction: &Direction, indent: &str) -> String {
106    let Some((l1, requoted)) = direction.share() else {
107        return String::new();
108    };
109    row(
110        &format!("{indent}share"),
111        &format!("{l1:.1}%"),
112        &format!("{requoted:.1}%"),
113        &format!("{:+.1}pp", requoted - l1),
114    )
115}
116
117fn row(label: &str, l1: &str, requoted: &str, delta: &str) -> String {
118    format!("  {label:<10} {l1:>14} {requoted:>14} {delta:>14}\n")
119}
120
121/// Legs and dollars only: each direction's amount is in its own input mint, and dollars are the
122/// only figure that crosses them.
123fn rows_for(direction: &Direction, indent: &str, priced: bool) -> String {
124    let mut out = totals("swaps", indent, direction.l1.legs, direction.requoted.legs);
125    if priced && !direction.fully_unpriced() {
126        out.push_str(&usd_row(direction, indent));
127    }
128    if direction.unpriced() {
129        out.push_str(&format!(
130            "{indent}  ({} swaps in mints this range could not price)\n",
131            direction.l1.without_price + direction.requoted.without_price
132        ));
133    }
134    out
135}
136
137fn totals(label: &str, indent: &str, l1: u64, requoted: u64) -> String {
138    row(
139        &format!("{indent}{label}"),
140        &l1.to_string(),
141        &requoted.to_string(),
142        &signed(i128::from(requoted) - i128::from(l1)),
143    )
144}
145
146fn usd_row(direction: &Direction, indent: &str) -> String {
147    row(
148        &format!("{indent}volume"),
149        &money(direction.l1.usd),
150        &money(direction.requoted.usd),
151        &format!(
152            "{}{}",
153            if direction.requoted.usd < direction.l1.usd {
154                "-"
155            } else {
156                "+"
157            },
158            money((direction.requoted.usd - direction.l1.usd).abs())
159        ),
160    )
161}
162
163fn money(usd: f64) -> String {
164    match usd {
165        usd if usd >= 1e6 => format!("${:.2}M", usd / 1e6),
166        usd if usd >= 1e3 => format!("${:.1}k", usd / 1e3),
167        usd => format!("${usd:.0}"),
168    }
169}
170
171fn signed(delta: i128) -> String {
172    match delta < 0 {
173        true => delta.to_string(),
174        false => format!("+{delta}"),
175    }
176}