1use std::{
2 any::Any,
3 collections::HashMap,
4 sync::Arc,
5 time::{Duration, Instant},
6};
7
8use num_bigint::BigUint;
9use num_traits::{CheckedSub, ToPrimitive};
10use serde::{Deserialize, Serialize};
11use tycho_common::{
12 dto::ProtocolStateDelta,
13 models::token::Token,
14 simulation::{
15 errors::{SimulationError, TransitionError},
16 protocol_sim::{Balances, GetAmountOutResult, ProtocolSim},
17 },
18 Bytes,
19};
20
21use super::{overrides::PammSimulationOverrides, telemetry};
22use crate::utils::decimals_scale;
23
24pub const QUOTE_TTL: Duration = super::SLOT;
30
31const ALREADY_QUOTED: &str = "Price level stream already quoted in this route";
33
34#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
39pub struct PriceLevelStreamQuote {
40 pub amount_in: BigUint,
41 pub amount_out: BigUint,
42}
43
44impl PriceLevelStreamQuote {
45 pub fn new(amount_in: BigUint, amount_out: BigUint) -> Self {
46 Self { amount_in, amount_out }
47 }
48}
49
50#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
52struct StreamFill {
53 token_in: Bytes,
54 token_out: Bytes,
55 amount_in: BigUint,
57 amount_out: BigUint,
59}
60
61#[derive(Debug, Clone, Serialize, Deserialize)]
75#[expect(
76 clippy::partial_pub_fields,
77 reason = "public API; making every field public or private is a breaking change"
78)]
79pub struct PriceLevelStreamState {
80 pub token0: Bytes,
81 pub token1: Bytes,
82 pub quotes_0_to_1: Vec<PriceLevelStreamQuote>,
83 pub quotes_1_to_0: Vec<PriceLevelStreamQuote>,
84 pub gas_cost: BigUint,
85 #[serde(default, skip_serializing_if = "Option::is_none")]
87 fill: Option<StreamFill>,
88 #[serde(skip)]
94 quotable_until: Option<Instant>,
95 #[serde(default, skip_serializing_if = "Option::is_none")]
100 overrides: Option<Arc<PammSimulationOverrides>>,
101}
102
103impl PriceLevelStreamState {
104 pub fn new(
109 token0: Bytes,
110 token1: Bytes,
111 mut quotes_0_to_1: Vec<PriceLevelStreamQuote>,
112 mut quotes_1_to_0: Vec<PriceLevelStreamQuote>,
113 gas_cost: BigUint,
114 ) -> Self {
115 for quotes in [&mut quotes_0_to_1, &mut quotes_1_to_0] {
116 quotes.sort_by(|a, b| a.amount_in.cmp(&b.amount_in));
117 quotes.dedup_by(|a, b| a.amount_in == b.amount_in);
118 }
119 Self {
120 token0,
121 token1,
122 quotes_0_to_1,
123 quotes_1_to_0,
124 gas_cost,
125 fill: None,
126 quotable_until: None,
127 overrides: None,
128 }
129 }
130
131 pub fn with_quotable_until(mut self, until: Instant) -> Self {
133 self.quotable_until = Some(until);
134 self
135 }
136
137 pub fn with_simulation_overrides(
139 mut self,
140 overrides: impl Into<Arc<PammSimulationOverrides>>,
141 ) -> Self {
142 self.overrides = Some(overrides.into());
143 self
144 }
145
146 pub fn simulation_overrides(&self) -> Option<&PammSimulationOverrides> {
150 self.overrides.as_deref()
151 }
152
153 pub fn quotable_until(&self) -> Option<Instant> {
156 self.quotable_until
157 }
158
159 fn ensure_quotable(&self, now: Instant) -> Result<(), SimulationError> {
162 match self.quotable_until {
163 Some(until) if now >= until => {
164 telemetry::record_quote_refused(telemetry::QuoteRefusedReason::PriceLevelsExpired);
165 Err(SimulationError::RecoverableError(format!(
166 "price levels expired: the message that carried them is older than {} s (one \
167 slot)",
168 QUOTE_TTL.as_secs()
169 )))
170 }
171 Some(_) | None => Ok(()),
172 }
173 }
174
175 fn quotes(
178 &self,
179 token_in: &Bytes,
180 token_out: &Bytes,
181 ) -> Result<&[PriceLevelStreamQuote], SimulationError> {
182 if token_in == &self.token0 && token_out == &self.token1 {
183 Ok(&self.quotes_0_to_1)
184 } else if token_in == &self.token1 && token_out == &self.token0 {
185 Ok(&self.quotes_1_to_0)
186 } else {
187 telemetry::record_quote_refused(telemetry::QuoteRefusedReason::UnknownPair);
188 Err(SimulationError::RecoverableError(format!(
189 "Invalid token addresses for pair {}/{}: {token_in}, {token_out}",
190 self.token0, self.token1
191 )))
192 }
193 }
194
195 fn interpolate(
203 &self,
204 quotes: &[PriceLevelStreamQuote],
205 amount_in: &BigUint,
206 ) -> Result<BigUint, SimulationError> {
207 let idx = quotes.partition_point(|quote| "e.amount_in < amount_in);
210 let upper = "es[idx];
211 if &upper.amount_in == amount_in {
212 return Ok(upper.amount_out.clone());
213 }
214 let lower = "es[idx - 1];
215 let Some(out_span) = upper
216 .amount_out
217 .checked_sub(&lower.amount_out)
218 else {
219 telemetry::record_quote_refused(telemetry::QuoteRefusedReason::NotMonotonic);
221 return Err(SimulationError::RecoverableError(format!(
222 "Quotes {}/{} are not monotonically increasing in amount_out around the \
223 requested amount {amount_in}: {} -> {}, but {} -> {}",
224 self.token0,
225 self.token1,
226 lower.amount_in,
227 lower.amount_out,
228 upper.amount_in,
229 upper.amount_out,
230 )));
231 };
232 let in_span = &upper.amount_in - &lower.amount_in;
233 let offset = amount_in - &lower.amount_in;
234 Ok(&lower.amount_out + out_span * offset / in_span)
235 }
236
237 fn fill_on(
240 &self,
241 token_in: &Bytes,
242 token_out: &Bytes,
243 ) -> Result<Option<&StreamFill>, SimulationError> {
244 match &self.fill {
245 Some(fill) if &fill.token_in == token_in && &fill.token_out == token_out => {
246 Ok(Some(fill))
247 }
248 Some(_) => Err(SimulationError::RecoverableError(ALREADY_QUOTED.to_string())),
249 None => Ok(None),
250 }
251 }
252
253 fn with_fill(&self, fill: StreamFill) -> Box<dyn ProtocolSim> {
257 Box::new(Self { fill: Some(fill), ..self.clone() })
258 }
259
260 fn marginal_price(
265 &self,
266 quotes: &[PriceLevelStreamQuote],
267 filled: &BigUint,
268 base: &Token,
269 quote: &Token,
270 ) -> Result<f64, SimulationError> {
271 let no_liquidity = || {
272 telemetry::record_quote_refused(telemetry::QuoteRefusedReason::NoLiquidity);
273 SimulationError::RecoverableError("No liquidity available".to_string())
274 };
275 let idx = quotes.partition_point(|level| &level.amount_in <= filled);
276 let upper = quotes
277 .get(idx)
278 .ok_or_else(no_liquidity)?;
279 let (lower_in, lower_out) = match idx
280 .checked_sub(1)
281 .and_then(|lower| quotes.get(lower))
282 {
283 Some(lower) => (&lower.amount_in, &lower.amount_out),
284 None => (&BigUint::ZERO, &BigUint::ZERO),
285 };
286 let Some(out_span) = upper.amount_out.checked_sub(lower_out) else {
287 telemetry::record_quote_refused(telemetry::QuoteRefusedReason::NotMonotonic);
288 return Err(SimulationError::RecoverableError(format!(
289 "Quotes {}/{} are not monotonically increasing in amount_out around the filled \
290 amount {filled}",
291 self.token0, self.token1
292 )));
293 };
294 if out_span == BigUint::ZERO {
295 return Err(no_liquidity());
296 }
297 whole_unit_price(&(&upper.amount_in - lower_in), &out_span, base, quote)
298 }
299
300 fn priced_amount_out(
303 &self,
304 quotes: &[PriceLevelStreamQuote],
305 amount_in: &BigUint,
306 ) -> Result<PricedAmount, SimulationError> {
307 let (Some(first), Some(last)) = (quotes.first(), quotes.last()) else {
308 telemetry::record_quote_refused(telemetry::QuoteRefusedReason::NoLiquidity);
309 return Err(SimulationError::RecoverableError("No liquidity available".to_string()));
310 };
311 if amount_in < &first.amount_in {
325 telemetry::record_quote_refused(telemetry::QuoteRefusedReason::BelowSmallestQuote);
326 return Err(SimulationError::InvalidInput(
327 format!(
328 "Input amount is below the smallest quote. input amount: {amount_in}, minimum quoted amount: {}",
329 first.amount_in
330 ),
331 None,
332 ));
333 }
334 if amount_in > &last.amount_in {
337 return Ok(PricedAmount::Partial {
338 amount: last.amount_out.clone(),
339 message: format!(
340 "Not enough liquidity to support complete swap. input amount: {amount_in}, maximum quoted amount: {}",
341 last.amount_in
342 ),
343 });
344 }
345 Ok(PricedAmount::Complete(self.interpolate(quotes, amount_in)?))
346 }
347}
348
349enum PricedAmount {
351 Complete(BigUint),
353 Partial { amount: BigUint, message: String },
356}
357
358fn whole_unit_price(
360 amount_in: &BigUint,
361 amount_out: &BigUint,
362 base: &Token,
363 quote: &Token,
364) -> Result<f64, SimulationError> {
365 let amount_in = amount_in.to_f64().ok_or_else(|| {
366 SimulationError::RecoverableError("Can't convert amount in to f64".to_string())
367 })?;
368 let amount_out = amount_out.to_f64().ok_or_else(|| {
369 SimulationError::RecoverableError("Can't convert amount out to f64".to_string())
370 })?;
371 Ok((amount_out / decimals_scale(quote.decimals)) / (amount_in / decimals_scale(base.decimals)))
372}
373
374fn saturating_sub(amount: &BigUint, taken: &BigUint) -> BigUint {
376 amount
377 .checked_sub(taken)
378 .unwrap_or_default()
379}
380
381#[typetag::serde]
382impl ProtocolSim for PriceLevelStreamState {
383 fn fee(&self) -> f64 {
384 0.0
385 }
386
387 fn spot_price(&self, base: &Token, quote: &Token) -> Result<f64, SimulationError> {
390 self.ensure_quotable(Instant::now())?;
391 let quotes = self.quotes(&base.address, "e.address)?;
392 if let Some(fill) = self.fill_on(&base.address, "e.address)? {
393 return self.marginal_price(quotes, &fill.amount_in, base, quote);
394 }
395 let best = quotes
396 .iter()
397 .find(|q| q.amount_in > BigUint::ZERO && q.amount_out > BigUint::ZERO)
398 .ok_or_else(|| {
399 telemetry::record_quote_refused(telemetry::QuoteRefusedReason::NoLiquidity);
400 SimulationError::RecoverableError("No liquidity available".to_string())
401 })?;
402 whole_unit_price(&best.amount_in, &best.amount_out, base, quote)
403 }
404
405 fn get_amount_out(
409 &self,
410 amount_in: BigUint,
411 token_in: &Token,
412 token_out: &Token,
413 ) -> Result<GetAmountOutResult, SimulationError> {
414 self.ensure_quotable(Instant::now())?;
415 let quotes = self.quotes(&token_in.address, &token_out.address)?;
416 let previous = self.fill_on(&token_in.address, &token_out.address)?;
417 let merged_in = match previous {
418 Some(previous) => &previous.amount_in + &amount_in,
419 None => amount_in,
420 };
421 let (merged_out, partial_message) = match self.priced_amount_out(quotes, &merged_in)? {
422 PricedAmount::Complete(amount) => (amount, None),
423 PricedAmount::Partial { amount, message } => (amount, Some(message)),
424 };
425 let (amount, gas) = match previous {
426 Some(previous) => (saturating_sub(&merged_out, &previous.amount_out), BigUint::ZERO),
427 None => (merged_out.clone(), self.gas_cost.clone()),
428 };
429 let new_state = self.with_fill(StreamFill {
430 token_in: token_in.address.clone(),
431 token_out: token_out.address.clone(),
432 amount_in: merged_in,
433 amount_out: merged_out,
434 });
435 let result = GetAmountOutResult { amount, gas, new_state };
436 match partial_message {
437 Some(message) => Err(SimulationError::InvalidInput(message, Some(result))),
438 None => Ok(result),
439 }
440 }
441
442 fn get_limits(
445 &self,
446 sell_token: Bytes,
447 buy_token: Bytes,
448 ) -> Result<(BigUint, BigUint), SimulationError> {
449 self.ensure_quotable(Instant::now())?;
450 let quotes = self.quotes(&sell_token, &buy_token)?;
451 let fill = self.fill_on(&sell_token, &buy_token)?;
452 let (max_in, max_out) = match quotes.last() {
453 Some(largest) => (largest.amount_in.clone(), largest.amount_out.clone()),
454 None => (BigUint::ZERO, BigUint::ZERO),
455 };
456 Ok(match fill {
457 Some(fill) => (
458 saturating_sub(&max_in, &fill.amount_in),
459 saturating_sub(&max_out, &fill.amount_out),
460 ),
461 None => (max_in, max_out),
462 })
463 }
464
465 fn delta_transition(
466 &mut self,
467 _delta: ProtocolStateDelta,
468 _tokens: &HashMap<Bytes, Token>,
469 _balances: &Balances,
470 ) -> Result<(), TransitionError> {
471 Err(TransitionError::DecodeError("Not implemented".into()))
472 }
473
474 fn clone_box(&self) -> Box<dyn ProtocolSim> {
475 Box::new(self.clone())
476 }
477
478 fn as_any(&self) -> &dyn Any {
479 self
480 }
481
482 fn as_any_mut(&mut self) -> &mut dyn Any {
483 self
484 }
485
486 fn eq(&self, other: &dyn ProtocolSim) -> bool {
506 other
507 .as_any()
508 .downcast_ref::<PriceLevelStreamState>()
509 .is_some_and(|other| {
510 let Self {
511 token0,
512 token1,
513 quotes_0_to_1,
514 quotes_1_to_0,
515 gas_cost,
516 fill,
517 quotable_until: _,
518 overrides,
519 } = other;
520 let same_overrides = match (&self.overrides, overrides) {
521 (Some(held), Some(arriving)) => {
522 held.block_number == arriving.block_number &&
523 held.accounts
524 .keys()
525 .eq(arriving.accounts.keys())
526 }
527 (None, None) => true,
528 _ => false,
529 };
530 &self.token0 == token0 &&
531 &self.token1 == token1 &&
532 &self.quotes_0_to_1 == quotes_0_to_1 &&
533 &self.quotes_1_to_0 == quotes_1_to_0 &&
534 &self.gas_cost == gas_cost &&
535 &self.fill == fill &&
536 same_overrides
537 })
538 }
539}
540
541#[cfg(test)]
542mod tests {
543 use std::time::{Duration, Instant};
544
545 use rstest::rstest;
546
547 use super::{
548 super::{
549 convert::quotes_for_book,
550 telemetry::recorded::{counter_value, record_async},
551 test_support::{captured_book, test_overrides, token, tokens, USDC, WBTC, WETH},
552 },
553 *,
554 };
555
556 const TAG: &str = r#""PriceLevelStreamState""#;
558
559 const LEGACY_STATE: &str = r#"{
562 "token0": "0x2260fac5e5542a773aa44fbcfedf7c193bc2c599",
563 "token1": "0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48",
564 "quotes_0_to_1": [{"amount_in": [100000000], "amount_out": [1215752192, 23]}],
565 "quotes_1_to_0": [{"amount_in": [1215752192, 23], "amount_out": [99000000]}],
566 "gas_cost": [120000]
567 }"#;
568
569 fn tag_first(tag: &str, state: &str) -> String {
572 format!(r#"{{"protocol":{tag},"state":{state}}}"#)
573 }
574
575 fn content_first(tag: &str, state: &str) -> String {
578 format!(r#"{{"state":{state},"protocol":{tag}}}"#)
579 }
580
581 fn wbtc() -> Token {
582 token(WBTC, "WBTC", 8)
583 }
584
585 fn usdc() -> Token {
586 token(USDC, "USDC", 6)
587 }
588
589 fn weth() -> Token {
590 token(WETH, "WETH", 18)
591 }
592
593 fn quote(amount_in: u64, amount_out: u64) -> PriceLevelStreamQuote {
594 PriceLevelStreamQuote::new(BigUint::from(amount_in), BigUint::from(amount_out))
595 }
596
597 fn state() -> PriceLevelStreamState {
600 PriceLevelStreamState::new(
601 wbtc().address,
602 usdc().address,
603 vec![quote(100_000_000, 100_000_000_000), quote(200_000_000, 190_000_000_000)],
604 vec![quote(100_000_000_000, 99_000_000), quote(200_000_000_000, 190_000_000)],
605 BigUint::from(120_000u64),
606 )
607 }
608
609 fn captured_state() -> PriceLevelStreamState {
612 let tokens = tokens();
613 let book = captured_book("Bebop", "WETH", "USDC");
614 let weth = tokens
615 .get(&weth().address)
616 .expect("WETH is admitted");
617 let usdc = tokens
618 .get(&usdc().address)
619 .expect("USDC is admitted");
620 let (bids, asks) = quotes_for_book(&book, weth, usdc);
621 PriceLevelStreamState::new(
622 weth.address.clone(),
623 usdc.address.clone(),
624 bids.expect("the captured bids convert"),
625 asks.expect("the captured asks convert"),
626 BigUint::from(120_000u64),
627 )
628 }
629
630 #[test]
631 fn captured_state_carries_the_whole_captured_book() {
632 let state = captured_state();
633 assert_eq!(state.quotes_0_to_1.len(), 15);
634 assert_eq!(state.quotes_1_to_0.len(), 14);
635 }
636
637 #[test]
638 fn new_sorts_and_dedups_quotes() {
639 let state = PriceLevelStreamState::new(
640 wbtc().address,
641 usdc().address,
642 vec![quote(200, 380), quote(100, 200), quote(200, 999)],
643 vec![],
644 BigUint::ZERO,
645 );
646 assert_eq!(state.quotes_0_to_1, vec![quote(100, 200), quote(200, 380)]);
647 }
648
649 #[test]
650 fn get_amount_out_exact_level() {
651 let result = state()
652 .get_amount_out(BigUint::from(100_000_000u64), &wbtc(), &usdc())
653 .unwrap();
654 assert_eq!(result.amount, BigUint::from(100_000_000_000u64));
655 assert_eq!(result.gas, BigUint::from(120_000u64));
656 }
657
658 #[test]
659 fn get_amount_out_interpolates_between_levels() {
660 let result = state()
662 .get_amount_out(BigUint::from(150_000_000u64), &wbtc(), &usdc())
663 .unwrap();
664 assert_eq!(result.amount, BigUint::from(145_000_000_000u64));
665 }
666
667 fn glitched_state() -> PriceLevelStreamState {
670 PriceLevelStreamState::new(
671 wbtc().address,
672 usdc().address,
673 vec![quote(100, 200), quote(200, 150)],
674 vec![],
675 BigUint::ZERO,
676 )
677 }
678
679 fn empty_state() -> PriceLevelStreamState {
681 PriceLevelStreamState::new(wbtc().address, usdc().address, vec![], vec![], BigUint::ZERO)
682 }
683
684 #[test]
685 fn get_amount_out_on_glitched_quotes_is_rejected() {
686 let state = glitched_state();
689 let result = state.get_amount_out(BigUint::from(150u64), &wbtc(), &usdc());
690 assert!(matches!(result, Err(SimulationError::RecoverableError(_))));
691
692 let result = state
694 .get_amount_out(BigUint::from(100u64), &wbtc(), &usdc())
695 .unwrap();
696 assert_eq!(result.amount, BigUint::from(200u64));
697 }
698
699 #[test]
700 fn get_amount_out_below_smallest_level_is_rejected() {
701 let result = state().get_amount_out(BigUint::from(50_000_000u64), &wbtc(), &usdc());
704 assert!(matches!(result, Err(SimulationError::InvalidInput(_, None))));
705 }
706
707 #[test]
708 fn get_amount_out_reverse_direction() {
709 let result = state()
710 .get_amount_out(BigUint::from(100_000_000_000u64), &usdc(), &wbtc())
711 .unwrap();
712 assert_eq!(result.amount, BigUint::from(99_000_000u64));
713 }
714
715 #[test]
716 fn get_amount_out_beyond_largest_level_is_partial() {
717 let result = state().get_amount_out(BigUint::from(300_000_000u64), &wbtc(), &usdc());
718 match result {
719 Err(SimulationError::InvalidInput(_, Some(partial))) => {
720 assert_eq!(partial.amount, BigUint::from(190_000_000_000u64));
721 }
722 other => panic!("expected partial InvalidInput, got {other:?}"),
723 }
724 }
725
726 fn successor(result: &GetAmountOutResult) -> &PriceLevelStreamState {
727 result
728 .new_state
729 .as_any()
730 .downcast_ref::<PriceLevelStreamState>()
731 .expect("price level state")
732 }
733
734 fn state_after_one_wbtc() -> PriceLevelStreamState {
736 let result = state()
737 .get_amount_out(BigUint::from(100_000_000u64), &wbtc(), &usdc())
738 .unwrap();
739 successor(&result).clone()
740 }
741
742 fn wbtc_to_usdc_fill(amount_in: u64, amount_out: u64) -> StreamFill {
743 StreamFill {
744 token_in: wbtc().address,
745 token_out: usdc().address,
746 amount_in: BigUint::from(amount_in),
747 amount_out: BigUint::from(amount_out),
748 }
749 }
750
751 #[test]
752 fn get_amount_out_records_the_fill_and_keeps_the_quotes() {
753 let after = state_after_one_wbtc();
754 assert_eq!(after.fill, Some(wbtc_to_usdc_fill(100_000_000, 100_000_000_000)));
755 assert_eq!(after.quotes_0_to_1, state().quotes_0_to_1);
756 assert_eq!(after.quotes_1_to_0, state().quotes_1_to_0);
757 }
758
759 #[test]
760 fn two_chunks_pay_what_one_merged_swap_pays() {
761 let merged = state()
762 .get_amount_out(BigUint::from(150_000_000u64), &wbtc(), &usdc())
763 .unwrap();
764 let first = state()
765 .get_amount_out(BigUint::from(100_000_000u64), &wbtc(), &usdc())
766 .unwrap();
767 let second = successor(&first)
768 .get_amount_out(BigUint::from(50_000_000u64), &wbtc(), &usdc())
769 .unwrap();
770 assert_eq!(first.amount + &second.amount, merged.amount);
771 assert_eq!(second.gas, BigUint::ZERO);
772 assert_eq!(successor(&second).fill, successor(&merged).fill);
773 }
774
775 #[test]
776 fn continued_chunk_beyond_largest_level_is_partial_and_carries_the_fill() {
777 let result =
778 state_after_one_wbtc().get_amount_out(BigUint::from(200_000_000u64), &wbtc(), &usdc());
779 let Err(SimulationError::InvalidInput(_, Some(partial))) = result else {
780 panic!("expected partial InvalidInput, got {result:?}");
781 };
782 assert_eq!(partial.amount, BigUint::from(90_000_000_000u64));
784 assert_eq!(partial.gas, BigUint::ZERO);
785 assert_eq!(successor(&partial).fill, Some(wbtc_to_usdc_fill(300_000_000, 190_000_000_000)));
786 }
787
788 #[test]
790 fn the_other_direction_after_a_fill_is_refused() {
791 let after = state_after_one_wbtc();
792 let refused = [
793 after
794 .get_amount_out(BigUint::from(100_000_000_000u64), &usdc(), &wbtc())
795 .map(|_| ()),
796 after
797 .get_limits(usdc().address, wbtc().address)
798 .map(|_| ()),
799 after
800 .spot_price(&usdc(), &wbtc())
801 .map(|_| ()),
802 ];
803 for result in refused {
804 assert!(matches!(
805 result,
806 Err(SimulationError::RecoverableError(message))
807 if message == "Price level stream already quoted in this route"
808 ));
809 }
810 }
811
812 #[test]
813 fn get_amount_out_rejects_unknown_tokens() {
814 let result = state().get_amount_out(BigUint::from(1u64), &weth(), &usdc());
815 assert!(matches!(result, Err(SimulationError::RecoverableError(_))));
816 }
817
818 #[test]
819 fn get_amount_out_without_liquidity() {
820 let result = empty_state().get_amount_out(BigUint::from(1u64), &wbtc(), &usdc());
821 assert!(matches!(result, Err(SimulationError::RecoverableError(_))));
822 }
823
824 #[test]
825 fn spot_price_uses_smallest_quote() {
826 let price = state()
828 .spot_price(&wbtc(), &usdc())
829 .unwrap();
830 assert!((price - 100_000.0).abs() < 1e-9);
831
832 let inverse = state()
833 .spot_price(&usdc(), &wbtc())
834 .unwrap();
835 assert!((inverse - 9.9e-6).abs() < 1e-15);
837 }
838
839 #[test]
840 fn spot_price_skips_zero_amount_out_quotes() {
841 let state = PriceLevelStreamState::new(
844 wbtc().address,
845 usdc().address,
846 vec![quote(1, 0), quote(100_000_000, 100_000_000_000)],
847 vec![],
848 BigUint::ZERO,
849 );
850 let price = state
851 .spot_price(&wbtc(), &usdc())
852 .unwrap();
853 assert!((price - 100_000.0).abs() < 1e-9);
854 }
855
856 #[test]
857 fn get_limits_returns_largest_quote() {
858 let (max_in, max_out) = state()
859 .get_limits(wbtc().address, usdc().address)
860 .unwrap();
861 assert_eq!(max_in, BigUint::from(200_000_000u64));
862 assert_eq!(max_out, BigUint::from(190_000_000_000u64));
863 }
864
865 #[test]
866 fn get_limits_after_a_fill_are_the_quote_limits_less_the_fill() {
867 let (max_in, max_out) = state_after_one_wbtc()
868 .get_limits(wbtc().address, usdc().address)
869 .unwrap();
870 assert_eq!(max_in, BigUint::from(100_000_000u64));
871 assert_eq!(max_out, BigUint::from(90_000_000_000u64));
872 }
873
874 #[test]
875 fn get_limits_after_a_fill_beyond_the_quotes_are_zero() {
876 let state = PriceLevelStreamState {
877 fill: Some(wbtc_to_usdc_fill(300_000_000, 190_000_000_000)),
878 ..state()
879 };
880 let limits = state
881 .get_limits(wbtc().address, usdc().address)
882 .unwrap();
883 assert_eq!(limits, (BigUint::ZERO, BigUint::ZERO));
884 }
885
886 #[test]
887 fn spot_price_after_a_fill_is_the_marginal_price_at_the_filled_amount() {
888 let price = state_after_one_wbtc()
890 .spot_price(&wbtc(), &usdc())
891 .unwrap();
892 assert!((price - 90_000.0).abs() < 1e-9);
893 }
894
895 #[test]
896 fn spot_price_after_a_fill_to_the_largest_level_has_no_liquidity() {
897 let state = PriceLevelStreamState {
898 fill: Some(wbtc_to_usdc_fill(200_000_000, 190_000_000_000)),
899 ..state()
900 };
901 let result = state.spot_price(&wbtc(), &usdc());
902 assert!(matches!(
903 result,
904 Err(SimulationError::RecoverableError(message)) if message == "No liquidity available"
905 ));
906 }
907
908 #[test]
909 fn get_limits_without_liquidity() {
910 let state = PriceLevelStreamState::new(
911 wbtc().address,
912 usdc().address,
913 vec![],
914 vec![],
915 BigUint::ZERO,
916 );
917 let (max_in, max_out) = state
918 .get_limits(wbtc().address, usdc().address)
919 .unwrap();
920 assert_eq!(max_in, BigUint::ZERO);
921 assert_eq!(max_out, BigUint::ZERO);
922 }
923
924 #[test]
925 fn eq_compares_quotes() {
926 let a = state();
927 let mut b = state();
928 assert!(a.eq(&b as &dyn ProtocolSim));
929 b.quotes_0_to_1[0].amount_out += 1u32;
930 assert!(!a.eq(&b as &dyn ProtocolSim));
931 }
932
933 #[test]
934 fn eq_compares_fills() {
935 assert!(!state().eq(&state_after_one_wbtc() as &dyn ProtocolSim));
936 assert!(state_after_one_wbtc().eq(&state_after_one_wbtc() as &dyn ProtocolSim));
937 }
938
939 #[test]
940 fn a_state_serialized_without_a_fill_loads_with_none() {
941 let json = serde_json::to_value(state()).unwrap();
942 assert!(json
943 .as_object()
944 .unwrap()
945 .get("fill")
946 .is_none());
947 let loaded: PriceLevelStreamState = serde_json::from_value(json).unwrap();
948 assert_eq!(loaded.fill, None);
949 }
950
951 #[test]
952 fn a_fill_survives_a_serde_round_trip() {
953 let json = serde_json::to_value(state_after_one_wbtc()).unwrap();
954 let loaded: PriceLevelStreamState = serde_json::from_value(json).unwrap();
955 assert_eq!(loaded.fill, state_after_one_wbtc().fill);
956 }
957
958 #[rstest]
959 #[case::one_nanosecond_before(|until| until - Duration::from_nanos(1), true)]
960 #[case::at_quotable_until(|until| until, false)]
961 #[case::one_second_after(|until| until + Duration::from_secs(1), false)]
962 fn ensure_quotable_around_quotable_until(
963 #[case] now: fn(Instant) -> Instant,
964 #[case] quotable: bool,
965 ) {
966 let until = Instant::now() + Duration::from_secs(60);
967 let state = state().with_quotable_until(until);
968 assert_eq!(
969 state
970 .ensure_quotable(now(until))
971 .is_ok(),
972 quotable
973 );
974 }
975
976 #[rstest]
978 #[case::price_levels_expired(
979 state().with_quotable_until(Instant::now()),
980 100_000_000,
981 wbtc(),
982 "price_levels_expired"
983 )]
984 #[case::unknown_pair(state(), 1, weth(), "unknown_pair")]
985 #[case::no_liquidity(empty_state(), 1, wbtc(), "no_liquidity")]
986 #[case::below_smallest_quote(state(), 50_000_000, wbtc(), "below_smallest_quote")]
987 #[case::not_monotonic(glitched_state(), 150, wbtc(), "not_monotonic")]
988 fn a_refused_quote_is_counted_under_its_reason(
989 #[case] state: PriceLevelStreamState,
990 #[case] amount_in: u64,
991 #[case] token_in: Token,
992 #[case] reason: &str,
993 ) {
994 let (result, snapshot) = record_async(async {
995 state.get_amount_out(BigUint::from(amount_in), &token_in, &usdc())
996 });
997
998 assert!(result.is_err());
999 assert_eq!(
1000 counter_value(
1001 &snapshot,
1002 "price_level_stream_quotes_refused_total",
1003 &[("reason", reason)]
1004 ),
1005 1
1006 );
1007 }
1008
1009 #[test]
1011 fn a_refused_spot_price_is_counted() {
1012 let (result, snapshot) = record_async(async { empty_state().spot_price(&wbtc(), &usdc()) });
1013
1014 assert!(result.is_err());
1015 assert_eq!(
1016 counter_value(
1017 &snapshot,
1018 "price_level_stream_quotes_refused_total",
1019 &[("reason", "no_liquidity")]
1020 ),
1021 1
1022 );
1023 }
1024
1025 #[test]
1026 fn state_without_quotable_until_never_expires() {
1027 let far = Instant::now() + Duration::from_secs(1_000_000);
1028 assert!(state().ensure_quotable(far).is_ok());
1029 }
1030
1031 #[test]
1032 fn expired_state_refuses_every_query() {
1033 let state = state().with_quotable_until(Instant::now());
1036 assert!(matches!(
1037 state.get_amount_out(BigUint::from(100_000_000u64), &wbtc(), &usdc()),
1038 Err(SimulationError::RecoverableError(_))
1039 ));
1040 assert!(matches!(
1041 state.spot_price(&wbtc(), &usdc()),
1042 Err(SimulationError::RecoverableError(_))
1043 ));
1044 assert!(matches!(
1045 state.get_limits(wbtc().address, usdc().address),
1046 Err(SimulationError::RecoverableError(_))
1047 ));
1048 }
1049
1050 #[test]
1051 fn fresh_state_answers_every_query() {
1052 let state = state().with_quotable_until(Instant::now() + Duration::from_secs(60));
1053 assert!(state
1054 .get_amount_out(BigUint::from(100_000_000u64), &wbtc(), &usdc())
1055 .is_ok());
1056 assert!(state
1057 .spot_price(&wbtc(), &usdc())
1058 .is_ok());
1059 assert!(state
1060 .get_limits(wbtc().address, usdc().address)
1061 .is_ok());
1062 }
1063
1064 #[test]
1065 fn successor_state_keeps_quotable_until() {
1066 let until = Instant::now() + Duration::from_secs(60);
1067 let state = state().with_quotable_until(until);
1068 let result = state
1069 .get_amount_out(BigUint::from(100_000_000u64), &wbtc(), &usdc())
1070 .expect("fresh state quotes");
1071 let successor = result
1072 .new_state
1073 .as_any()
1074 .downcast_ref::<PriceLevelStreamState>()
1075 .expect("price level state");
1076 assert_eq!(successor.quotable_until, Some(until));
1077 }
1078
1079 #[test]
1080 fn quotable_until_serde_round_trip() {
1081 let live = state().with_quotable_until(Instant::now());
1082 let json = serde_json::to_value(&live).unwrap();
1083 assert!(json
1084 .as_object()
1085 .unwrap()
1086 .get("quotable_until")
1087 .is_none());
1088 let replayed: PriceLevelStreamState = serde_json::from_value(json).unwrap();
1090 assert_eq!(replayed.quotable_until, None);
1091 assert!(replayed
1092 .spot_price(&wbtc(), &usdc())
1093 .is_ok());
1094 }
1095
1096 #[test]
1098 fn eq_ignores_quotable_until() {
1099 let until = Instant::now() + Duration::from_secs(60);
1100 assert!(state().eq(&state().with_quotable_until(until)));
1101 assert!(state()
1102 .with_quotable_until(until)
1103 .eq(&state().with_quotable_until(until + Duration::from_secs(1))));
1104 }
1105
1106 #[test]
1107 fn with_simulation_overrides_sets_and_exposes_them() {
1108 assert_eq!(state().simulation_overrides(), None);
1109 assert_eq!(
1110 state()
1111 .with_simulation_overrides(test_overrides())
1112 .simulation_overrides(),
1113 Some(&test_overrides())
1114 );
1115 }
1116
1117 #[rstest]
1120 #[case::the_same_overrides(Some(test_overrides()), true)]
1121 #[case::no_overrides(None, false)]
1122 #[case::rebuilt_with_other_values(Some(rebuilt_with_other_values()), true)]
1123 #[case::another_block(Some(in_another_block()), false)]
1124 #[case::fewer_accounts(Some(with_one_account_fewer()), false)]
1125 #[case::another_account(Some(with_another_account()), false)]
1126 fn eq_compares_the_block_and_the_accounts_not_the_values(
1127 #[case] other: Option<PammSimulationOverrides>,
1128 #[case] equal: bool,
1129 ) {
1130 let held = state().with_simulation_overrides(test_overrides());
1131 let other = match other {
1132 Some(overrides) => state().with_simulation_overrides(overrides),
1133 None => state(),
1134 };
1135
1136 assert_eq!(held.eq(&other), equal);
1137 assert_eq!(other.eq(&held), equal);
1138 }
1139
1140 fn rebuilt_with_other_values() -> PammSimulationOverrides {
1143 let mut rebuilt = test_overrides();
1144 rebuilt.built_at_ns += 1;
1145 for account in rebuilt.accounts.values_mut() {
1146 account.balance = Some(Bytes::from(vec![0x42]));
1147 account.nonce = account.nonce.map(|nonce| nonce + 1);
1148 account.state_diff.clear();
1149 }
1150 rebuilt
1151 }
1152
1153 fn in_another_block() -> PammSimulationOverrides {
1155 PammSimulationOverrides { block_number: Some(26_201_955), ..test_overrides() }
1156 }
1157
1158 fn with_another_account() -> PammSimulationOverrides {
1161 let mut swapped = test_overrides();
1162 let (_, account) = swapped
1163 .accounts
1164 .pop_first()
1165 .expect("an account");
1166 swapped
1167 .accounts
1168 .insert(Bytes::from(vec![0xab; 20]), account);
1169 swapped
1170 }
1171
1172 fn with_one_account_fewer() -> PammSimulationOverrides {
1175 let mut fewer = test_overrides();
1176 fewer.accounts.pop_first();
1177 fewer
1178 }
1179
1180 #[test]
1182 fn successor_state_keeps_the_overrides() {
1183 let state = state().with_simulation_overrides(test_overrides());
1184 let result = state
1185 .get_amount_out(BigUint::from(100_000_000u64), &wbtc(), &usdc())
1186 .expect("fresh state quotes");
1187 let successor = result
1188 .new_state
1189 .as_any()
1190 .downcast_ref::<PriceLevelStreamState>()
1191 .expect("price level state");
1192 assert_eq!(successor.simulation_overrides(), Some(&test_overrides()));
1193 }
1194
1195 #[test]
1199 fn an_override_bearing_captured_state_round_trips_as_text_and_as_a_value() {
1200 let state = captured_state().with_simulation_overrides(test_overrides());
1201
1202 let text = serde_json::to_string(&state).expect("serializes");
1203 let value = serde_json::to_value(&state).expect("serializes into a Value");
1204 let from_text: PriceLevelStreamState =
1205 serde_json::from_str(&text).expect("reads back from text");
1206 let from_value: PriceLevelStreamState =
1207 serde_json::from_value(value).expect("reads back from a Value");
1208
1209 for read in [&from_text, &from_value] {
1210 assert_eq!(read.simulation_overrides(), Some(&test_overrides()));
1211 assert!(state.eq(read));
1212 }
1213 }
1214
1215 #[rstest]
1221 #[case::tag_before_content(tag_first)]
1222 #[case::content_before_tag(content_first)]
1223 fn an_override_bearing_captured_state_round_trips_through_a_boxed_protocol_sim(
1224 #[case] recording: fn(&str, &str) -> String,
1225 ) {
1226 let state = captured_state().with_simulation_overrides(test_overrides());
1227 let text = recording(TAG, &serde_json::to_string(&state).expect("serializes"));
1228
1229 let boxed: Box<dyn ProtocolSim> = serde_json::from_str(&text).expect("reads back");
1230
1231 assert!(state.eq(boxed.as_ref()));
1232 let read = boxed
1233 .as_any()
1234 .downcast_ref::<PriceLevelStreamState>()
1235 .expect("price level state");
1236 assert_eq!(read.simulation_overrides(), Some(&test_overrides()));
1237 }
1238
1239 #[test]
1241 fn typetag_writes_the_tag_the_recordings_carry() {
1242 let text = serde_json::to_string(&state() as &dyn ProtocolSim).expect("serializes");
1243
1244 assert!(text.starts_with(&format!(r#"{{"protocol":{TAG},"#)), "{text}");
1245 }
1246
1247 #[test]
1255 fn the_serialized_overrides_key_is_named_overrides() {
1256 let state = captured_state().with_simulation_overrides(test_overrides());
1257
1258 let text = serde_json::to_string(&state).expect("serializes");
1259 let typed = serde_json::to_value(&state).expect("serializes");
1260 let boxed = serde_json::to_value(&state as &dyn ProtocolSim).expect("serializes");
1261
1262 assert!(text.contains(r#""overrides":"#), "no `overrides` key in the state JSON");
1263 for json in [&typed, &boxed["state"]] {
1264 let overrides = json
1265 .as_object()
1266 .expect("an object")
1267 .get("overrides")
1268 .expect("the state object names them `overrides`");
1269 let read: PammSimulationOverrides =
1270 serde_json::from_value(overrides.clone()).expect("the overrides under that key");
1271 assert_eq!(read, test_overrides());
1272 }
1273 }
1274
1275 #[test]
1278 fn a_legacy_typed_recording_reads_back_without_overrides() {
1279 let read: PriceLevelStreamState = serde_json::from_str(LEGACY_STATE).expect("reads back");
1280 assert_eq!(read.simulation_overrides(), None);
1281 assert_eq!(read.quotes_0_to_1, vec![quote(100_000_000, 100_000_000_000)]);
1282 assert_eq!(read.quotes_1_to_0, vec![quote(100_000_000_000, 99_000_000)]);
1283 }
1284
1285 #[rstest]
1288 #[case::tag_before_content(tag_first)]
1289 #[case::content_before_tag(content_first)]
1290 fn a_legacy_boxed_recording_reads_back_without_overrides(
1291 #[case] recording: fn(&str, &str) -> String,
1292 ) {
1293 let boxed: Box<dyn ProtocolSim> =
1294 serde_json::from_str(&recording(TAG, LEGACY_STATE)).expect("reads back");
1295 let read = boxed
1296 .as_any()
1297 .downcast_ref::<PriceLevelStreamState>()
1298 .expect("price level state");
1299 assert_eq!(read.simulation_overrides(), None);
1300 assert_eq!(read.quotes_0_to_1, vec![quote(100_000_000, 100_000_000_000)]);
1301 }
1302
1303 #[test]
1306 fn a_state_without_overrides_serializes_without_the_key() {
1307 let typed = serde_json::to_value(state()).expect("serializes");
1308 let boxed = serde_json::to_value(&state() as &dyn ProtocolSim).expect("serializes");
1309
1310 for json in [&typed, &boxed["state"]] {
1311 assert!(json
1312 .as_object()
1313 .expect("an object")
1314 .get("overrides")
1315 .is_none());
1316 }
1317 }
1318}