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