Skip to main content

simulator_api/reroute_report/
prices.rs

1//! Pricing a reroute stream in dollars using nothing but the stream.
2//!
3//! No oracle and no external feed. SOL/USD comes from the range's own SOL<->USDC reroutes, the
4//! other majors from their pairings against SOL, USDC and USDT, and everything else from its
5//! major<->exotic legs. A derived price needs [`MIN_SAMPLES`] observations before it is trusted;
6//! the SOL anchor is exempt, since every other price hangs from it.
7
8use std::collections::HashMap;
9
10use solana_address::Address;
11
12use super::{
13    fmt::median,
14    record::{LegRecord, SwapMode},
15};
16use crate::mints;
17
18const LAMPORTS_PER_SOL: f64 = 1e9;
19/// Sub-SOL probe swaps realize off-market and drag the median, so the anchor ignores them.
20const ONE_SOL_LAMPORTS: u128 = 1_000_000_000;
21const USDC_UNITS_PER_USD: f64 = 1e6;
22/// A derived price needs at least this many samples to be trusted.
23const MIN_SAMPLES: usize = 3;
24
25/// One ExactIn reroute. ExactOut is excluded: its `amount` is in the output token and would
26/// poison every ratio it entered.
27struct Sample {
28    input_mint: Address,
29    output_mint: Address,
30    amount: u128,
31    original_output: u128,
32}
33
34/// Pricing samples gathered from [`LegRecord`]s; turn them into [`Prices`] with
35/// [`Samples::prices`].
36///
37/// Held until the range ends, because a median cannot be folded. Each sample is two mints and two
38/// amounts, far smaller than the records it came from.
39#[derive(Default)]
40pub struct Samples(Vec<Sample>);
41
42impl Samples {
43    /// Keeps the leg as a pricing sample only if it can price something: ExactIn, a realized and
44    /// nonzero original output, a nonzero input amount, the original didn't fail, and at least
45    /// one side is a major to anchor on. Anything else is silently dropped.
46    pub fn push(&mut self, record: &LegRecord) {
47        let Some(original_output) = record.original_realized_output_amount else {
48            return;
49        };
50        if record.swap_mode != SwapMode::ExactIn
51            || record.amount == 0
52            || original_output == 0
53            || record.original_failed
54        {
55            return;
56        }
57        // Every derivation anchors on a major, so a leg between two exotics is unreadable.
58        if !mints::is_major(&record.input_mint) && !mints::is_major(&record.output_mint) {
59            return;
60        }
61        self.0.push(Sample {
62            input_mint: record.input_mint,
63            output_mint: record.output_mint,
64            amount: u128::from(record.amount),
65            original_output: u128::from(original_output),
66        });
67    }
68
69    /// `None` when the range carries no SOL<->USDC ExactIn reroutes to anchor on.
70    pub fn prices(&self) -> Option<Prices> {
71        let sol_usd = sol_price(&self.0)?;
72        let mut prices = Prices {
73            sol_usd,
74            priced: priced_major_prices(&self.0, sol_usd),
75            exotic: HashMap::new(),
76        };
77        prices.exotic = exotic_unit_prices(&self.0, &prices);
78        Some(prices)
79    }
80}
81
82/// USD prices for one range, derived from the range's own reroutes.
83pub struct Prices {
84    sol_usd: f64,
85    /// USD per whole unit for the priced majors.
86    priced: HashMap<Address, f64>,
87    /// USD per *raw* unit for exotics, inferred from their major<->exotic legs.
88    exotic: HashMap<Address, f64>,
89}
90
91impl Prices {
92    #[expect(missing_docs, reason = "self-explanatory")]
93    pub const fn sol_usd(&self) -> f64 {
94        self.sol_usd
95    }
96
97    /// The USD value of `raw` base units of `mint`. `None` when the range could not price the
98    /// mint, which the report counts rather than folding in as zero.
99    ///
100    /// Linear in `raw` on every path, so a caller may sum one mint's raw amounts and convert the
101    /// total once, or pass an amount a weight has already scaled out of whole units.
102    pub fn usd(&self, mint: &Address, raw: f64) -> Option<f64> {
103        self.scaled_major(mint, raw)
104            .or_else(|| self.exotic.get(mint).map(|unit| raw * unit))
105    }
106
107    /// [`Self::usd`] for a mint still in its wire form. Unparseable is unpriceable.
108    pub fn usd_str(&self, mint: &str, raw: f64) -> Option<f64> {
109        self.usd(&mint.parse().ok()?, raw)
110    }
111
112    /// The majors alone, which is what [`exotic_unit_prices`] reads while building the exotics.
113    fn scaled_major(&self, mint: &Address, raw: f64) -> Option<f64> {
114        if *mint == mints::SOL {
115            return Some(raw / LAMPORTS_PER_SOL * self.sol_usd);
116        }
117        if let Some(decimals) = mints::stable_decimals(mint) {
118            return Some(raw / 10f64.powi(decimals.cast_signed()));
119        }
120        let decimals = mints::priced_decimals(mint)?;
121        let unit = self.priced.get(mint)?;
122        Some(raw / 10f64.powi(decimals.cast_signed()) * unit)
123    }
124}
125
126fn median_of(mut values: Vec<f64>) -> Option<f64> {
127    (values.len() >= MIN_SAMPLES).then(|| median(&mut values))
128}
129
130fn sol_price(samples: &[Sample]) -> Option<f64> {
131    let mut ratios: Vec<f64> = samples
132        .iter()
133        .filter_map(|sample| {
134            let (input, output) = (sample.input_mint, sample.output_mint);
135            if input == mints::SOL && output == mints::USDC && sample.amount >= ONE_SOL_LAMPORTS {
136                Some(
137                    (sample.original_output as f64 / USDC_UNITS_PER_USD)
138                        / (sample.amount as f64 / LAMPORTS_PER_SOL),
139                )
140            } else if input == mints::USDC
141                && output == mints::SOL
142                && sample.original_output >= ONE_SOL_LAMPORTS
143            {
144                Some(
145                    (sample.amount as f64 / USDC_UNITS_PER_USD)
146                        / (sample.original_output as f64 / LAMPORTS_PER_SOL),
147                )
148            } else {
149                None
150            }
151        })
152        .collect();
153    (!ratios.is_empty()).then(|| median(&mut ratios))
154}
155
156/// Median USD per priced major, from its pairings with USDC/USDT ($1) and SOL, both directions.
157fn priced_major_prices(samples: &[Sample], sol_usd: f64) -> HashMap<Address, f64> {
158    let mut per_mint: HashMap<Address, Vec<f64>> = HashMap::new();
159    for sample in samples {
160        let oriented = [
161            (
162                sample.input_mint,
163                sample.output_mint,
164                sample.amount,
165                sample.original_output,
166            ),
167            (
168                sample.output_mint,
169                sample.input_mint,
170                sample.original_output,
171                sample.amount,
172            ),
173        ];
174        for (mint, other, mint_raw, other_raw) in oriented {
175            let Some(decimals) = mints::priced_decimals(&mint) else {
176                continue;
177            };
178            let other_usd = if other == mints::USDC || other == mints::USDT {
179                other_raw as f64 / USDC_UNITS_PER_USD
180            } else if other == mints::SOL {
181                other_raw as f64 / LAMPORTS_PER_SOL * sol_usd
182            } else {
183                continue;
184            };
185            per_mint
186                .entry(mint)
187                .or_default()
188                .push(other_usd / (mint_raw as f64 / 10f64.powi(decimals.cast_signed())));
189        }
190    }
191    per_mint
192        .into_iter()
193        .filter_map(|(mint, ratios)| Some((mint, median_of(ratios)?)))
194        .collect()
195}
196
197/// Median USD per raw unit for each exotic, from its major<->exotic legs.
198fn exotic_unit_prices(samples: &[Sample], prices: &Prices) -> HashMap<Address, f64> {
199    let mut per_mint: HashMap<Address, Vec<f64>> = HashMap::new();
200    for sample in samples {
201        let (input, output) = (sample.input_mint, sample.output_mint);
202        match (mints::is_major(&input), mints::is_major(&output)) {
203            (true, false) => {
204                if let Some(usd) = prices.scaled_major(&input, sample.amount as f64) {
205                    per_mint
206                        .entry(output)
207                        .or_default()
208                        .push(usd / sample.original_output as f64);
209                }
210            }
211            (false, true) => {
212                if let Some(usd) = prices.scaled_major(&output, sample.original_output as f64) {
213                    per_mint
214                        .entry(input)
215                        .or_default()
216                        .push(usd / sample.amount as f64);
217                }
218            }
219            _ => {}
220        }
221    }
222    per_mint
223        .into_iter()
224        .filter_map(|(mint, ratios)| Some((mint, median_of(ratios)?)))
225        .collect()
226}
227
228#[cfg(test)]
229mod tests {
230    use solana_address::address;
231
232    use super::*;
233
234    /// A longtail mint no table names, so it can only be priced through a major leg.
235    const BONK: Address = address!("DezXAZ8z7PnrnRJjz3wXBoRgixCa6xjnB7YaB1pPB263");
236    /// A governance blue-chip: parseable, deliberately not a major, and quoted by nobody below.
237    const RAY: Address = address!("4k3Dyjzvzp8eMZWUXbBCjEvwSkkk59S5iCNLY3QrkX6R");
238    /// What [`anchored`] derives, and what every price hanging off it is stated in.
239    const SOL_USD: f64 = 100.0;
240
241    fn sample_record(
242        input: Address,
243        output: Address,
244        amount: u64,
245        original_output: u64,
246    ) -> LegRecord {
247        LegRecord {
248            original_signature: "sig".to_string(),
249            input_mint: input,
250            output_mint: output,
251            amount,
252            swap_mode: SwapMode::ExactIn,
253            failed: false,
254            original_failed: false,
255            realized_output_amount: None,
256            original_realized_output_amount: Some(original_output),
257            route_plan: None,
258            original_route_plan: None,
259            realized_route_plan: None,
260            template: None,
261            quoted_output_amount: None,
262            new_output_amount: None,
263            error_category: None,
264            output_bps: None,
265        }
266    }
267
268    /// Three SOL->USDC reroutes at [`SOL_USD`], which is the only thing a range needs before any
269    /// other price can be derived.
270    fn anchored() -> Samples {
271        let mut samples = Samples::default();
272        for (amount, output) in [
273            (1_000_000_000, 100_000_000),
274            (2_000_000_000, 200_000_000),
275            (3_000_000_000, 300_000_000),
276        ] {
277            samples.push(&sample_record(mints::SOL, mints::USDC, amount, output));
278        }
279        samples
280    }
281
282    /// Sub-SOL swaps realize off-market and would drag the anchor. Two of each, so dropping the
283    /// gate moves the median off `SOL_USD` instead of leaving the real legs a majority.
284    #[test]
285    fn the_sol_anchor_ignores_swaps_under_one_sol() {
286        let mut samples = Samples::default();
287        // Two dust swaps priced at $1000/SOL and two real ones at $100: ungated the median would
288        // be 550.0.
289        for (amount, output) in [
290            (1_000, 1_000),
291            (2_000, 2_000),
292            (1_000_000_000, 100_000_000),
293            (2_000_000_000, 200_000_000),
294        ] {
295            samples.push(&sample_record(mints::SOL, mints::USDC, amount, output));
296        }
297        let prices = samples.prices().expect("anchored");
298        assert_eq!(prices.sol_usd(), SOL_USD);
299    }
300
301    /// The oriented-pair loop reads a priced major from either side of a leg, and the ratio has
302    /// to invert with it — transposed, one cbBTC would be worth 1/60,000th of a dollar.
303    #[test]
304    fn a_priced_major_medians_both_orientations_of_its_legs() {
305        let cbbtc = mints::PRICED_MAJORS[1].address;
306        assert_eq!(mints::priced_decimals(&cbbtc), Some(8));
307        let one_cbbtc: u64 = 1_00000000;
308
309        let mut samples = anchored();
310        // $59,000, $60,000 and — quoted the other way round — $61,000 per cbBTC.
311        for (input, output, amount, original_output) in [
312            (cbbtc, mints::USDC, one_cbbtc, 59_000_000_000),
313            (cbbtc, mints::USDC, 2 * one_cbbtc, 120_000_000_000),
314            (mints::USDC, cbbtc, 61_000_000_000, one_cbbtc),
315        ] {
316            samples.push(&sample_record(input, output, amount, original_output));
317        }
318
319        let prices = samples.prices().expect("anchored");
320        assert_eq!(prices.usd(&cbbtc, one_cbbtc as f64), Some(60_000.0));
321        // Linear in the raw amount, and read at cbBTC's eight decimals rather than USDC's six.
322        assert_eq!(prices.usd(&cbbtc, one_cbbtc as f64 / 2.0), Some(30_000.0));
323    }
324
325    /// USD per raw exotic unit, folded exactly as the derivation folds it: the major side's
326    /// dollars over the raw units they bought.
327    fn unit_price(lamports: f64, exotic_raw: f64) -> f64 {
328        lamports / LAMPORTS_PER_SOL * SOL_USD / exotic_raw
329    }
330
331    /// An exotic has no decimals to read, so it is priced per *raw* unit off its major leg.
332    /// Transposing that division would price the whole longtail at ~1e10 dollars a unit.
333    #[test]
334    fn an_exotic_is_priced_per_raw_unit_off_its_major_leg() {
335        let mut samples = anchored();
336        // 1e12 BONK per SOL, then 2e12 (half the price per unit), then 1e12 again — so the
337        // median unit is the one the first leg quotes, not the cheap outlier in the middle.
338        for (lamports, bonk) in [
339            (1_000_000_000, 1_000_000_000_000),
340            (2_000_000_000, 4_000_000_000_000),
341            (3_000_000_000, 3_000_000_000_000),
342        ] {
343            samples.push(&sample_record(mints::SOL, BONK, lamports, bonk));
344        }
345
346        let prices = samples.prices().expect("anchored");
347        let unit = unit_price(1_000_000_000.0, 1_000_000_000_000.0);
348        assert_eq!(prices.usd(&BONK, 1e12), Some(1e12 * unit));
349        assert_eq!(prices.usd(&BONK, 5e11), Some(5e11 * unit));
350    }
351
352    /// USDe is 9 decimals; treating every stable as 1e6 values its legs 1000x over. Stable
353    /// pricing reads decimals alone, so the USDe<->USDC legs below anchor nothing — the range
354    /// still needs its own SOL<->USDC reroutes to produce a `Prices` at all.
355    #[test]
356    fn a_stable_is_valued_at_its_own_decimals() {
357        let usde_mint = mints::STABLES[4].address;
358        let mut samples = anchored();
359        for _ in 0..3 {
360            samples.push(&sample_record(
361                usde_mint,
362                mints::USDC,
363                1_000_000_000,
364                1_000_000,
365            ));
366        }
367        let prices = samples.prices().expect("anchored");
368        assert_eq!(prices.usd(&usde_mint, 1e6), Some(1e6 / 1e9));
369        assert_eq!(prices.usd(&mints::USDC, 1e6), Some(1.0));
370        // Linear in the raw amount on every path, which is what lets a caller sum first.
371        assert_eq!(prices.usd(&usde_mint, 1e9), Some(1.0));
372        assert_eq!(prices.usd(&mints::SOL, 1e9), Some(SOL_USD));
373    }
374
375    #[test]
376    fn a_price_needs_enough_samples() {
377        assert_eq!(median_of(vec![1.0, 2.0]), None);
378        assert_eq!(median_of(vec![1.0, 2.0, 3.0]), Some(2.0));
379        assert_eq!(median_of(vec![4.0, 1.0, 2.0, 3.0]), Some(2.5));
380    }
381
382    #[test]
383    fn an_unpriceable_mint_is_none_rather_than_zero() {
384        let prices = anchored().prices().expect("anchored");
385        assert_eq!(prices.usd_str("SomeLongtailMintNobodyQuoted", 1e6), None);
386        // A mint the range simply never traded is as unpriceable as an unparseable one.
387        assert_eq!(prices.usd(&RAY, 1e6), None);
388    }
389}