use std::collections::HashMap;
use crate::RerouteNotification;
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),
];
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),
];
pub(super) const SOL: &str = "So11111111111111111111111111111111111111112";
const USDC: &str = STABLE_DECIMALS[0].0;
const USDT: &str = STABLE_DECIMALS[1].0;
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)
}
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;
const ONE_SOL_LAMPORTS: u128 = 1_000_000_000;
const USDC_UNITS_PER_USD: f64 = 1e6;
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)
}
fn is_major(mint: &str) -> bool {
mint == SOL || stable_decimals(mint).is_some() || priced_decimals(mint).is_some()
}
struct Sample {
input_mint: String,
output_mint: String,
amount: u128,
original_output: u128,
}
#[derive(Default)]
pub(super) struct Samples(Vec<Sample>);
impl Samples {
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;
}
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),
});
}
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)
}
}
pub(super) struct Prices {
sol_usd: f64,
priced: HashMap<String, f64>,
exotic: HashMap<String, f64>,
}
impl Prices {
pub(super) const fn sol_usd(&self) -> f64 {
self.sol_usd
}
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))
}
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))
}
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()
}
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::*;
#[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)));
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");
}
#[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));
}
#[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,
};
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);
}
}