simulator-client 0.21.0

Async WebSocket client for the Solana simulator backtest API
Documentation
//! Pricing a reroute stream in dollars using nothing but the stream.
//!
//! No oracle and no external feed. SOL/USD comes from the range's own SOL<->USDC reroutes, the
//! other majors from their pairings against SOL, USDC and USDT, and everything else from its
//! major<->exotic legs. A derived price needs [`MIN_SAMPLES`] observations before it is trusted;
//! the SOL anchor is exempt, since every other price hangs from it.
//!
//! Decimals are per-mint and not derivable here: USDe is 9 on Solana, and a blanket 1e6 would
//! inflate those legs 1000x.

use std::collections::HashMap;

use crate::RerouteNotification;

/// $1 stables, with the symbol they display as and their token decimals.
const STABLE_DECIMALS: [(&str, &str, u32); 8] = [
    ("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v", "USDC", 6),
    ("Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB", "USDT", 6),
    ("2b1kV6DkPAnxd5ixfnxCpjxmKwqjjaYmCZfHsFu24GXo", "PYUSD", 6),
    ("USDSwr9ApdHk5bvJKMjzff41FfuX8bSxdKcR81vTwcA", "USDS", 6),
    ("DEkqHyPN7GMRJ5cArtQFAWefqbZb33Hyf6s5iCwjEonT", "USDe", 9),
    ("9zNQRsGLjNKwCUU5Gq5LR8beUCPzQMVMqKAi3SSZh54u", "FDUSD", 6),
    ("A1KLoBrKBde8Ty9qtNQUtq3C2ortoC3u7twggz7sEto6", "USDY", 6),
    ("USD1ttGY1N17NEEHLmELoaybftRBUSErhqYiQzvEmuB", "USD1", 6),
];

/// Non-stable majors priced from in-range quote medians, same shape.
const PRICED_DECIMALS: [(&str, &str, u32); 10] = [
    ("HzwqbKZw8HxMN6bF2yFZNrht3c2iXXzpKcFu7uBEDKtr", "EURC", 6),
    ("cbbtcf3aa214zXHbiAZQwf4122FBYbraNdFqgw4iMij", "cbBTC", 8),
    ("3NZ9JMVBmGAqocybic2c7LQCJScmgsAZ6vQqTDzcqmJh", "WBTC", 8),
    ("7vfCXTUXx5WJV5JADk17DUJ4ksgau7utNKj4b963voxs", "WETH", 8),
    ("J1toso1uCk3RLmjorhTtrVwY9HJ7X8V9yYac6Y7kGCPn", "jitoSOL", 9),
    ("mSoLzYCxHdYgdzU16g5QSh3i5K3z3KZK7ytfqcJm7So", "mSOL", 9),
    ("bSo13r4TkiE4KumL71LsHTPpL2euBYLFx6h9HP3piy1", "bSOL", 9),
    ("jupSoLaHXQiZZTSfEWMTRRgpnyFm8f6sZdosWBjx93v", "jupSOL", 9),
    ("5oVNBeEEQvYi1cX3ir8Dx5n1P7pdxydbGF2X4TxVusJm", "INF", 9),
    ("BNso1VUJnh4zcfpZa6986Ea66P6TCp59hvtNJ8b1X85", "bnSOL", 9),
];

/// Wrapped SOL, the mint every native-SOL leg trades as.
pub(super) const SOL: &str = "So11111111111111111111111111111111111111112";

const USDC: &str = STABLE_DECIMALS[0].0;
const USDT: &str = STABLE_DECIMALS[1].0;

/// `None` outside the tables, which displays as a shortened address rather than a guess.
pub(super) fn symbol(mint: &str) -> Option<&'static str> {
    if mint == SOL {
        return Some("SOL");
    }
    STABLE_DECIMALS
        .iter()
        .chain(PRICED_DECIMALS.iter())
        .find(|(candidate, ..)| *candidate == mint)
        .map(|(_, symbol, _)| *symbol)
}

/// The token's symbol, or a shortened address — a guessed symbol would be worse than an address.
pub fn short_mint(mint: &str) -> String {
    if let Some(symbol) = symbol(mint) {
        return symbol.to_string();
    }
    match mint.len() > 12 {
        true => format!("{}..{}", &mint[..6], &mint[mint.len() - 4..]),
        false => mint.to_string(),
    }
}

const LAMPORTS_PER_SOL: f64 = 1e9;
/// Sub-SOL probe swaps realize off-market and drag the median, so the anchor ignores them.
const ONE_SOL_LAMPORTS: u128 = 1_000_000_000;
const USDC_UNITS_PER_USD: f64 = 1e6;
/// A derived price needs at least this many samples to be trusted.
const MIN_SAMPLES: usize = 3;

fn decimals_in(table: &[(&str, &str, u32)], mint: &str) -> Option<u32> {
    table
        .iter()
        .find(|(candidate, ..)| *candidate == mint)
        .map(|(.., decimals)| *decimals)
}

fn stable_decimals(mint: &str) -> Option<u32> {
    decimals_in(&STABLE_DECIMALS, mint)
}

fn priced_decimals(mint: &str) -> Option<u32> {
    decimals_in(&PRICED_DECIMALS, mint)
}

/// Whether the mint is one the tables name, and so can anchor another mint's price.
fn is_major(mint: &str) -> bool {
    mint == SOL || stable_decimals(mint).is_some() || priced_decimals(mint).is_some()
}

/// One ExactIn reroute. ExactOut is excluded: its `amount` is in the output token and would
/// poison every ratio it entered.
struct Sample {
    input_mint: String,
    output_mint: String,
    amount: u128,
    original_output: u128,
}

/// Retained until the range ends, because a median cannot be folded. Two mints and two amounts
/// against a notification's multi-KB route plans, which is what lets a report skip the stream.
#[derive(Default)]
pub(super) struct Samples(Vec<Sample>);

impl Samples {
    /// The only rows where `amount` and `original_realized_output_amount` describe the same swap.
    pub(super) fn push(&mut self, notification: &RerouteNotification) {
        let [leg] = notification.legs.as_slice() else {
            return;
        };
        let Some(original_output) = notification.original_realized_output_amount else {
            return;
        };
        if leg.swap_mode != "ExactIn" || leg.amount == 0 || original_output == 0 {
            return;
        }
        // Every derivation anchors on a major, so a leg between two exotics is unreadable.
        if !is_major(&leg.input_mint) && !is_major(&leg.output_mint) {
            return;
        }
        self.0.push(Sample {
            input_mint: leg.input_mint.clone(),
            output_mint: leg.output_mint.clone(),
            amount: u128::from(leg.amount),
            original_output: u128::from(original_output),
        });
    }

    /// `None` when the range carries no SOL<->USDC ExactIn reroutes to anchor on.
    pub(super) fn prices(&self) -> Option<Prices> {
        let sol_usd = sol_price(&self.0)?;
        let mut prices = Prices {
            sol_usd,
            priced: priced_major_prices(&self.0, sol_usd),
            exotic: HashMap::new(),
        };
        prices.exotic = exotic_unit_prices(&self.0, &prices);
        Some(prices)
    }
}

/// Per-range prices, derived from the range's own reroutes.
pub(super) struct Prices {
    sol_usd: f64,
    /// USD per whole unit for the priced majors.
    priced: HashMap<String, f64>,
    /// USD per *raw* unit for exotics, inferred from their major<->exotic legs.
    exotic: HashMap<String, f64>,
}

impl Prices {
    pub(super) const fn sol_usd(&self) -> f64 {
        self.sol_usd
    }

    /// `None` when the range could not price the mint, which the report counts rather than
    /// folding in as zero.
    ///
    /// Linear in `raw` on every path, so a caller may sum one mint's raw amounts and convert the
    /// total once, or pass an amount a weight has already scaled out of whole units.
    pub(super) fn usd(&self, mint: &str, raw: f64) -> Option<f64> {
        self.scaled_major(mint, raw)
            .or_else(|| self.exotic.get(mint).map(|unit| raw * unit))
    }

    /// The majors alone, which is what [`exotic_unit_prices`] reads while building the exotics.
    fn scaled_major(&self, mint: &str, raw: f64) -> Option<f64> {
        if mint == SOL {
            return Some(raw / LAMPORTS_PER_SOL * self.sol_usd);
        }
        if let Some(decimals) = stable_decimals(mint) {
            return Some(raw / 10f64.powi(decimals as i32));
        }
        let decimals = priced_decimals(mint)?;
        let unit = self.priced.get(mint)?;
        Some(raw / 10f64.powi(decimals as i32) * unit)
    }
}

fn median(values: &mut [f64]) -> f64 {
    values.sort_by(|a, b| a.total_cmp(b));
    let n = values.len();
    match n % 2 {
        1 => values[n / 2],
        _ => (values[n / 2 - 1] + values[n / 2]) / 2.0,
    }
}

fn median_of(mut values: Vec<f64>) -> Option<f64> {
    (values.len() >= MIN_SAMPLES).then(|| median(&mut values))
}

fn sol_price(samples: &[Sample]) -> Option<f64> {
    let mut ratios: Vec<f64> = samples
        .iter()
        .filter_map(|sample| {
            let (input, output) = (sample.input_mint.as_str(), sample.output_mint.as_str());
            if input == SOL && output == USDC && sample.amount >= ONE_SOL_LAMPORTS {
                Some(
                    (sample.original_output as f64 / USDC_UNITS_PER_USD)
                        / (sample.amount as f64 / LAMPORTS_PER_SOL),
                )
            } else if input == USDC && output == SOL && sample.original_output >= ONE_SOL_LAMPORTS {
                Some(
                    (sample.amount as f64 / USDC_UNITS_PER_USD)
                        / (sample.original_output as f64 / LAMPORTS_PER_SOL),
                )
            } else {
                None
            }
        })
        .collect();
    (!ratios.is_empty()).then(|| median(&mut ratios))
}

/// Median USD per priced major, from its pairings with USDC/USDT ($1) and SOL, both directions.
fn priced_major_prices(samples: &[Sample], sol_usd: f64) -> HashMap<String, f64> {
    let mut per_mint: HashMap<String, Vec<f64>> = HashMap::new();
    for sample in samples {
        let oriented = [
            (
                &sample.input_mint,
                &sample.output_mint,
                sample.amount,
                sample.original_output,
            ),
            (
                &sample.output_mint,
                &sample.input_mint,
                sample.original_output,
                sample.amount,
            ),
        ];
        for (mint, other, mint_raw, other_raw) in oriented {
            let Some(decimals) = priced_decimals(mint) else {
                continue;
            };
            let other_usd = match other.as_str() {
                USDC | USDT => other_raw as f64 / USDC_UNITS_PER_USD,
                SOL => other_raw as f64 / LAMPORTS_PER_SOL * sol_usd,
                _ => continue,
            };
            per_mint
                .entry(mint.clone())
                .or_default()
                .push(other_usd / (mint_raw as f64 / 10f64.powi(decimals as i32)));
        }
    }
    per_mint
        .into_iter()
        .filter_map(|(mint, ratios)| Some((mint, median_of(ratios)?)))
        .collect()
}

/// Median USD per raw unit for each exotic, from its major<->exotic legs.
fn exotic_unit_prices(samples: &[Sample], prices: &Prices) -> HashMap<String, f64> {
    let mut per_mint: HashMap<String, Vec<f64>> = HashMap::new();
    for sample in samples {
        let (input, output) = (sample.input_mint.as_str(), sample.output_mint.as_str());
        match (is_major(input), is_major(output)) {
            (true, false) => {
                if let Some(usd) = prices.scaled_major(input, sample.amount as f64) {
                    per_mint
                        .entry(output.to_string())
                        .or_default()
                        .push(usd / sample.original_output as f64);
                }
            }
            (false, true) => {
                if let Some(usd) = prices.scaled_major(output, sample.original_output as f64) {
                    per_mint
                        .entry(input.to_string())
                        .or_default()
                        .push(usd / sample.amount as f64);
                }
            }
            _ => {}
        }
    }
    per_mint
        .into_iter()
        .filter_map(|(mint, ratios)| Some((mint, median_of(ratios)?)))
        .collect()
}
#[cfg(test)]
mod tests {
    use super::*;

    /// A duplicate reads as a missing mint, quietly widening what counts as exotic.
    #[test]
    fn the_major_universe_is_nineteen_distinct_mints() {
        let mut all: Vec<&str> = STABLE_DECIMALS
            .iter()
            .chain(PRICED_DECIMALS.iter())
            .map(|(mint, ..)| *mint)
            .chain([SOL])
            .collect();
        assert_eq!(all.len(), 19);
        all.sort_unstable();
        all.dedup();
        assert_eq!(all.len(), 19, "a mint is listed twice");
        assert!(all.iter().all(|mint| is_major(mint)));
        // Every major displays as a symbol, so an address in the output means an uncommon token.
        assert!(all.iter().all(|mint| symbol(mint).is_some()));

        let mut symbols: Vec<&str> = all.iter().filter_map(|mint| symbol(mint)).collect();
        symbols.sort_unstable();
        symbols.dedup();
        assert_eq!(symbols.len(), 19, "two mints share a symbol");
    }

    /// USDe is 9 decimals; treating every stable as 1e6 values its legs 1000x over.
    #[test]
    fn a_stable_is_valued_at_its_own_decimals() {
        let prices = Prices {
            sol_usd: 100.0,
            priced: HashMap::new(),
            exotic: HashMap::new(),
        };
        let usdc = STABLE_DECIMALS[0].0;
        let usde = STABLE_DECIMALS[4].0;
        assert_eq!(prices.usd(usdc, 1e6), Some(1.0));
        assert_eq!(prices.usd(usde, 1e6), Some(0.001));
        assert_eq!(prices.usd(usde, 1e9), Some(1.0));
        assert_eq!(prices.usd(SOL, 1e9), Some(100.0));
    }

    #[test]
    fn a_price_needs_enough_samples() {
        assert_eq!(median_of(vec![1.0, 2.0]), None);
        assert_eq!(median_of(vec![1.0, 2.0, 3.0]), Some(2.0));
        assert_eq!(median_of(vec![4.0, 1.0, 2.0, 3.0]), Some(2.5));
    }

    /// Sub-SOL swaps realize off-market and would drag the anchor.
    #[test]
    fn the_sol_anchor_ignores_swaps_under_one_sol() {
        let sample = |amount: u128, output: u128| Sample {
            input_mint: SOL.to_string(),
            output_mint: USDC.to_string(),
            amount,
            original_output: output,
        };
        // One dust swap priced at $1000/SOL, three real ones at $100.
        let samples = vec![
            sample(1_000, 1_000),
            sample(ONE_SOL_LAMPORTS, 100_000_000),
            sample(2 * ONE_SOL_LAMPORTS, 200_000_000),
            sample(3 * ONE_SOL_LAMPORTS, 300_000_000),
        ];
        assert_eq!(sol_price(&samples), Some(100.0));
    }

    #[test]
    fn an_unpriceable_mint_is_none_rather_than_zero() {
        let prices = Prices {
            sol_usd: 100.0,
            priced: HashMap::new(),
            exotic: HashMap::new(),
        };
        assert_eq!(prices.usd("SomeLongtailMintNobodyQuoted", 1e6), None);
    }
}