1use 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;
19const ONE_SOL_LAMPORTS: u128 = 1_000_000_000;
21const USDC_UNITS_PER_USD: f64 = 1e6;
22const MIN_SAMPLES: usize = 3;
24
25struct Sample {
28 input_mint: Address,
29 output_mint: Address,
30 amount: u128,
31 original_output: u128,
32}
33
34#[derive(Default)]
40pub struct Samples(Vec<Sample>);
41
42impl Samples {
43 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 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 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
82pub struct Prices {
84 sol_usd: f64,
85 priced: HashMap<Address, f64>,
87 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 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 pub fn usd_str(&self, mint: &str, raw: f64) -> Option<f64> {
109 self.usd(&mint.parse().ok()?, raw)
110 }
111
112 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
156fn 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
197fn 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 const BONK: Address = address!("DezXAZ8z7PnrnRJjz3wXBoRgixCa6xjnB7YaB1pPB263");
236 const RAY: Address = address!("4k3Dyjzvzp8eMZWUXbBCjEvwSkkk59S5iCNLY3QrkX6R");
238 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 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 #[test]
285 fn the_sol_anchor_ignores_swaps_under_one_sol() {
286 let mut samples = Samples::default();
287 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 #[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 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 assert_eq!(prices.usd(&cbbtc, one_cbbtc as f64 / 2.0), Some(30_000.0));
323 }
324
325 fn unit_price(lamports: f64, exotic_raw: f64) -> f64 {
328 lamports / LAMPORTS_PER_SOL * SOL_USD / exotic_raw
329 }
330
331 #[test]
334 fn an_exotic_is_priced_per_raw_unit_off_its_major_leg() {
335 let mut samples = anchored();
336 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 #[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 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 assert_eq!(prices.usd(&RAY, 1e6), None);
388 }
389}