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
30#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
35pub struct PriceLevelStreamQuote {
36 pub amount_in: BigUint,
37 pub amount_out: BigUint,
38}
39
40impl PriceLevelStreamQuote {
41 pub fn new(amount_in: BigUint, amount_out: BigUint) -> Self {
42 Self { amount_in, amount_out }
43 }
44}
45
46#[derive(Debug, Clone, Serialize, Deserialize)]
53pub struct PriceLevelStreamState {
54 pub token0: Bytes,
55 pub token1: Bytes,
56 pub quotes_0_to_1: Vec<PriceLevelStreamQuote>,
57 pub quotes_1_to_0: Vec<PriceLevelStreamQuote>,
58 pub gas_cost: BigUint,
59 #[serde(skip)]
65 quotable_until: Option<Instant>,
66 #[serde(default, skip_serializing_if = "Option::is_none")]
71 overrides: Option<Arc<PammSimulationOverrides>>,
72}
73
74impl PriceLevelStreamState {
75 pub fn new(
80 token0: Bytes,
81 token1: Bytes,
82 mut quotes_0_to_1: Vec<PriceLevelStreamQuote>,
83 mut quotes_1_to_0: Vec<PriceLevelStreamQuote>,
84 gas_cost: BigUint,
85 ) -> Self {
86 for quotes in [&mut quotes_0_to_1, &mut quotes_1_to_0] {
87 quotes.sort_by(|a, b| a.amount_in.cmp(&b.amount_in));
88 quotes.dedup_by(|a, b| a.amount_in == b.amount_in);
89 }
90 Self {
91 token0,
92 token1,
93 quotes_0_to_1,
94 quotes_1_to_0,
95 gas_cost,
96 quotable_until: None,
97 overrides: None,
98 }
99 }
100
101 pub fn with_quotable_until(mut self, until: Instant) -> Self {
103 self.quotable_until = Some(until);
104 self
105 }
106
107 pub fn with_simulation_overrides(
109 mut self,
110 overrides: impl Into<Arc<PammSimulationOverrides>>,
111 ) -> Self {
112 self.overrides = Some(overrides.into());
113 self
114 }
115
116 pub fn simulation_overrides(&self) -> Option<&PammSimulationOverrides> {
120 self.overrides.as_deref()
121 }
122
123 pub fn quotable_until(&self) -> Option<Instant> {
126 self.quotable_until
127 }
128
129 fn ensure_quotable(&self, now: Instant) -> Result<(), SimulationError> {
132 match self.quotable_until {
133 Some(until) if now >= until => {
134 telemetry::record_quote_refused(telemetry::QuoteRefusedReason::PriceLevelsExpired);
135 Err(SimulationError::RecoverableError(format!(
136 "price levels expired: the message that carried them is older than {} s (one \
137 slot)",
138 QUOTE_TTL.as_secs()
139 )))
140 }
141 Some(_) | None => Ok(()),
142 }
143 }
144
145 fn quotes(
148 &self,
149 token_in: &Bytes,
150 token_out: &Bytes,
151 ) -> Result<&[PriceLevelStreamQuote], SimulationError> {
152 if token_in == &self.token0 && token_out == &self.token1 {
153 Ok(&self.quotes_0_to_1)
154 } else if token_in == &self.token1 && token_out == &self.token0 {
155 Ok(&self.quotes_1_to_0)
156 } else {
157 telemetry::record_quote_refused(telemetry::QuoteRefusedReason::UnknownPair);
158 Err(SimulationError::RecoverableError(format!(
159 "Invalid token addresses for pair {}/{}: {token_in}, {token_out}",
160 self.token0, self.token1
161 )))
162 }
163 }
164
165 fn interpolate(
173 &self,
174 quotes: &[PriceLevelStreamQuote],
175 amount_in: &BigUint,
176 ) -> Result<BigUint, SimulationError> {
177 let idx = quotes.partition_point(|quote| "e.amount_in < amount_in);
180 let upper = "es[idx];
181 if &upper.amount_in == amount_in {
182 return Ok(upper.amount_out.clone());
183 }
184 let lower = "es[idx - 1];
185 let Some(out_span) = upper
186 .amount_out
187 .checked_sub(&lower.amount_out)
188 else {
189 telemetry::record_quote_refused(telemetry::QuoteRefusedReason::NotMonotonic);
191 return Err(SimulationError::RecoverableError(format!(
192 "Quotes {}/{} are not monotonically increasing in amount_out around the \
193 requested amount {amount_in}: {} -> {}, but {} -> {}",
194 self.token0,
195 self.token1,
196 lower.amount_in,
197 lower.amount_out,
198 upper.amount_in,
199 upper.amount_out,
200 )));
201 };
202 let in_span = &upper.amount_in - &lower.amount_in;
203 let offset = amount_in - &lower.amount_in;
204 Ok(&lower.amount_out + out_span * offset / in_span)
205 }
206
207 fn consumed(&self) -> Box<dyn ProtocolSim> {
214 Box::new(Self {
215 token0: self.token0.clone(),
216 token1: self.token1.clone(),
217 quotes_0_to_1: Vec::new(),
218 quotes_1_to_0: Vec::new(),
219 gas_cost: self.gas_cost.clone(),
220 quotable_until: self.quotable_until,
221 overrides: self.overrides.clone(),
222 })
223 }
224}
225
226#[typetag::serde]
227impl ProtocolSim for PriceLevelStreamState {
228 fn fee(&self) -> f64 {
229 0.0
230 }
231
232 fn spot_price(&self, base: &Token, quote: &Token) -> Result<f64, SimulationError> {
233 self.ensure_quotable(Instant::now())?;
234 let quotes = self.quotes(&base.address, "e.address)?;
235 let best = quotes
236 .iter()
237 .find(|q| q.amount_in > BigUint::ZERO && q.amount_out > BigUint::ZERO)
238 .ok_or_else(|| {
239 telemetry::record_quote_refused(telemetry::QuoteRefusedReason::NoLiquidity);
240 SimulationError::RecoverableError("No liquidity available".to_string())
241 })?;
242 let amount_in = best.amount_in.to_f64().ok_or_else(|| {
243 SimulationError::RecoverableError("Can't convert amount in to f64".to_string())
244 })?;
245 let amount_out = best
246 .amount_out
247 .to_f64()
248 .ok_or_else(|| {
249 SimulationError::RecoverableError("Can't convert amount out to f64".to_string())
250 })?;
251 Ok((amount_out / 10f64.powi(quote.decimals as i32)) /
252 (amount_in / 10f64.powi(base.decimals as i32)))
253 }
254
255 fn get_amount_out(
256 &self,
257 amount_in: BigUint,
258 token_in: &Token,
259 token_out: &Token,
260 ) -> Result<GetAmountOutResult, SimulationError> {
261 self.ensure_quotable(Instant::now())?;
262 let quotes = self.quotes(&token_in.address, &token_out.address)?;
263 let (Some(first), Some(last)) = (quotes.first(), quotes.last()) else {
264 telemetry::record_quote_refused(telemetry::QuoteRefusedReason::NoLiquidity);
265 return Err(SimulationError::RecoverableError("No liquidity available".to_string()));
266 };
267 if amount_in < first.amount_in {
281 telemetry::record_quote_refused(telemetry::QuoteRefusedReason::BelowSmallestQuote);
282 return Err(SimulationError::InvalidInput(
283 format!(
284 "Input amount is below the smallest quote. input amount: {amount_in}, minimum quoted amount: {}",
285 first.amount_in
286 ),
287 None,
288 ));
289 }
290 if amount_in > last.amount_in {
293 let res = GetAmountOutResult {
294 amount: last.amount_out.clone(),
295 gas: self.gas_cost.clone(),
296 new_state: self.consumed(),
297 };
298 return Err(SimulationError::InvalidInput(
299 format!(
300 "Not enough liquidity to support complete swap. input amount: {amount_in}, maximum quoted amount: {}",
301 last.amount_in
302 ),
303 Some(res),
304 ));
305 }
306 Ok(GetAmountOutResult {
307 amount: self.interpolate(quotes, &amount_in)?,
308 gas: self.gas_cost.clone(),
309 new_state: self.consumed(),
310 })
311 }
312
313 fn get_limits(
314 &self,
315 sell_token: Bytes,
316 buy_token: Bytes,
317 ) -> Result<(BigUint, BigUint), SimulationError> {
318 self.ensure_quotable(Instant::now())?;
319 let quotes = self.quotes(&sell_token, &buy_token)?;
320 match quotes.last() {
321 Some(largest) => Ok((largest.amount_in.clone(), largest.amount_out.clone())),
322 None => Ok((BigUint::ZERO, BigUint::ZERO)),
323 }
324 }
325
326 fn delta_transition(
327 &mut self,
328 _delta: ProtocolStateDelta,
329 _tokens: &HashMap<Bytes, Token>,
330 _balances: &Balances,
331 ) -> Result<(), TransitionError> {
332 Err(TransitionError::DecodeError("Not implemented".into()))
333 }
334
335 fn clone_box(&self) -> Box<dyn ProtocolSim> {
336 Box::new(self.clone())
337 }
338
339 fn as_any(&self) -> &dyn Any {
340 self
341 }
342
343 fn as_any_mut(&mut self) -> &mut dyn Any {
344 self
345 }
346
347 fn eq(&self, other: &dyn ProtocolSim) -> bool {
367 other
368 .as_any()
369 .downcast_ref::<PriceLevelStreamState>()
370 .is_some_and(|other| {
371 let Self {
372 token0,
373 token1,
374 quotes_0_to_1,
375 quotes_1_to_0,
376 gas_cost,
377 quotable_until: _,
378 overrides,
379 } = other;
380 let same_overrides = match (&self.overrides, overrides) {
381 (Some(held), Some(arriving)) => {
382 held.block_number == arriving.block_number &&
383 held.accounts
384 .keys()
385 .eq(arriving.accounts.keys())
386 }
387 (None, None) => true,
388 _ => false,
389 };
390 &self.token0 == token0 &&
391 &self.token1 == token1 &&
392 &self.quotes_0_to_1 == quotes_0_to_1 &&
393 &self.quotes_1_to_0 == quotes_1_to_0 &&
394 &self.gas_cost == gas_cost &&
395 same_overrides
396 })
397 }
398}
399
400#[cfg(test)]
401mod tests {
402 use std::time::{Duration, Instant};
403
404 use rstest::rstest;
405
406 use super::{
407 super::{
408 convert::quotes_for_book,
409 telemetry::recorded::{counter_value, record_async},
410 test_support::{captured_book, test_overrides, token, tokens, USDC, WBTC, WETH},
411 },
412 *,
413 };
414
415 const TAG: &str = r#""PriceLevelStreamState""#;
417
418 const LEGACY_STATE: &str = r#"{
421 "token0": "0x2260fac5e5542a773aa44fbcfedf7c193bc2c599",
422 "token1": "0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48",
423 "quotes_0_to_1": [{"amount_in": [100000000], "amount_out": [1215752192, 23]}],
424 "quotes_1_to_0": [{"amount_in": [1215752192, 23], "amount_out": [99000000]}],
425 "gas_cost": [120000]
426 }"#;
427
428 fn tag_first(tag: &str, state: &str) -> String {
431 format!(r#"{{"protocol":{tag},"state":{state}}}"#)
432 }
433
434 fn content_first(tag: &str, state: &str) -> String {
437 format!(r#"{{"state":{state},"protocol":{tag}}}"#)
438 }
439
440 fn wbtc() -> Token {
441 token(WBTC, "WBTC", 8)
442 }
443
444 fn usdc() -> Token {
445 token(USDC, "USDC", 6)
446 }
447
448 fn weth() -> Token {
449 token(WETH, "WETH", 18)
450 }
451
452 fn quote(amount_in: u64, amount_out: u64) -> PriceLevelStreamQuote {
453 PriceLevelStreamQuote::new(BigUint::from(amount_in), BigUint::from(amount_out))
454 }
455
456 fn state() -> PriceLevelStreamState {
459 PriceLevelStreamState::new(
460 wbtc().address,
461 usdc().address,
462 vec![quote(100_000_000, 100_000_000_000), quote(200_000_000, 190_000_000_000)],
463 vec![quote(100_000_000_000, 99_000_000), quote(200_000_000_000, 190_000_000)],
464 BigUint::from(120_000u64),
465 )
466 }
467
468 fn captured_state() -> PriceLevelStreamState {
471 let tokens = tokens();
472 let book = captured_book("Bebop", "WETH", "USDC");
473 let weth = tokens
474 .get(&weth().address)
475 .expect("WETH is admitted");
476 let usdc = tokens
477 .get(&usdc().address)
478 .expect("USDC is admitted");
479 let (bids, asks) = quotes_for_book(&book, weth, usdc);
480 PriceLevelStreamState::new(
481 weth.address.clone(),
482 usdc.address.clone(),
483 bids.expect("the captured bids convert"),
484 asks.expect("the captured asks convert"),
485 BigUint::from(120_000u64),
486 )
487 }
488
489 #[test]
490 fn captured_state_carries_the_whole_captured_book() {
491 let state = captured_state();
492 assert_eq!(state.quotes_0_to_1.len(), 15);
493 assert_eq!(state.quotes_1_to_0.len(), 14);
494 }
495
496 #[test]
497 fn new_sorts_and_dedups_quotes() {
498 let state = PriceLevelStreamState::new(
499 wbtc().address,
500 usdc().address,
501 vec![quote(200, 380), quote(100, 200), quote(200, 999)],
502 vec![],
503 BigUint::ZERO,
504 );
505 assert_eq!(state.quotes_0_to_1, vec![quote(100, 200), quote(200, 380)]);
506 }
507
508 #[test]
509 fn get_amount_out_exact_level() {
510 let result = state()
511 .get_amount_out(BigUint::from(100_000_000u64), &wbtc(), &usdc())
512 .unwrap();
513 assert_eq!(result.amount, BigUint::from(100_000_000_000u64));
514 assert_eq!(result.gas, BigUint::from(120_000u64));
515 }
516
517 #[test]
518 fn get_amount_out_interpolates_between_levels() {
519 let result = state()
521 .get_amount_out(BigUint::from(150_000_000u64), &wbtc(), &usdc())
522 .unwrap();
523 assert_eq!(result.amount, BigUint::from(145_000_000_000u64));
524 }
525
526 fn glitched_state() -> PriceLevelStreamState {
529 PriceLevelStreamState::new(
530 wbtc().address,
531 usdc().address,
532 vec![quote(100, 200), quote(200, 150)],
533 vec![],
534 BigUint::ZERO,
535 )
536 }
537
538 fn empty_state() -> PriceLevelStreamState {
540 PriceLevelStreamState::new(wbtc().address, usdc().address, vec![], vec![], BigUint::ZERO)
541 }
542
543 #[test]
544 fn get_amount_out_on_glitched_quotes_is_rejected() {
545 let state = glitched_state();
548 let result = state.get_amount_out(BigUint::from(150u64), &wbtc(), &usdc());
549 assert!(matches!(result, Err(SimulationError::RecoverableError(_))));
550
551 let result = state
553 .get_amount_out(BigUint::from(100u64), &wbtc(), &usdc())
554 .unwrap();
555 assert_eq!(result.amount, BigUint::from(200u64));
556 }
557
558 #[test]
559 fn get_amount_out_below_smallest_level_is_rejected() {
560 let result = state().get_amount_out(BigUint::from(50_000_000u64), &wbtc(), &usdc());
563 assert!(matches!(result, Err(SimulationError::InvalidInput(_, None))));
564 }
565
566 #[test]
567 fn get_amount_out_reverse_direction() {
568 let result = state()
569 .get_amount_out(BigUint::from(100_000_000_000u64), &usdc(), &wbtc())
570 .unwrap();
571 assert_eq!(result.amount, BigUint::from(99_000_000u64));
572 }
573
574 #[test]
575 fn get_amount_out_beyond_largest_level_is_partial() {
576 let result = state().get_amount_out(BigUint::from(300_000_000u64), &wbtc(), &usdc());
577 match result {
578 Err(SimulationError::InvalidInput(_, Some(partial))) => {
579 assert_eq!(partial.amount, BigUint::from(190_000_000_000u64));
580 }
581 other => panic!("expected partial InvalidInput, got {other:?}"),
582 }
583 }
584
585 #[test]
586 fn get_amount_out_consumes_both_quote_lists() {
587 let result = state()
588 .get_amount_out(BigUint::from(100_000_000u64), &wbtc(), &usdc())
589 .unwrap();
590 let new_state = result
591 .new_state
592 .as_any()
593 .downcast_ref::<PriceLevelStreamState>()
594 .expect("price level state");
595 assert!(new_state.quotes_0_to_1.is_empty());
596 assert!(new_state.quotes_1_to_0.is_empty());
597 }
598
599 #[test]
600 fn get_amount_out_rejects_unknown_tokens() {
601 let result = state().get_amount_out(BigUint::from(1u64), &weth(), &usdc());
602 assert!(matches!(result, Err(SimulationError::RecoverableError(_))));
603 }
604
605 #[test]
606 fn get_amount_out_without_liquidity() {
607 let result = empty_state().get_amount_out(BigUint::from(1u64), &wbtc(), &usdc());
608 assert!(matches!(result, Err(SimulationError::RecoverableError(_))));
609 }
610
611 #[test]
612 fn spot_price_uses_smallest_quote() {
613 let price = state()
615 .spot_price(&wbtc(), &usdc())
616 .unwrap();
617 assert!((price - 100_000.0).abs() < 1e-9);
618
619 let inverse = state()
620 .spot_price(&usdc(), &wbtc())
621 .unwrap();
622 assert!((inverse - 9.9e-6).abs() < 1e-15);
624 }
625
626 #[test]
627 fn spot_price_skips_zero_amount_out_quotes() {
628 let state = PriceLevelStreamState::new(
631 wbtc().address,
632 usdc().address,
633 vec![quote(1, 0), quote(100_000_000, 100_000_000_000)],
634 vec![],
635 BigUint::ZERO,
636 );
637 let price = state
638 .spot_price(&wbtc(), &usdc())
639 .unwrap();
640 assert!((price - 100_000.0).abs() < 1e-9);
641 }
642
643 #[test]
644 fn get_limits_returns_largest_quote() {
645 let (max_in, max_out) = state()
646 .get_limits(wbtc().address, usdc().address)
647 .unwrap();
648 assert_eq!(max_in, BigUint::from(200_000_000u64));
649 assert_eq!(max_out, BigUint::from(190_000_000_000u64));
650 }
651
652 #[test]
653 fn get_limits_without_liquidity() {
654 let state = PriceLevelStreamState::new(
655 wbtc().address,
656 usdc().address,
657 vec![],
658 vec![],
659 BigUint::ZERO,
660 );
661 let (max_in, max_out) = state
662 .get_limits(wbtc().address, usdc().address)
663 .unwrap();
664 assert_eq!(max_in, BigUint::ZERO);
665 assert_eq!(max_out, BigUint::ZERO);
666 }
667
668 #[test]
669 fn eq_compares_quotes() {
670 let a = state();
671 let mut b = state();
672 assert!(a.eq(&b as &dyn ProtocolSim));
673 b.quotes_0_to_1[0].amount_out += 1u32;
674 assert!(!a.eq(&b as &dyn ProtocolSim));
675 }
676
677 #[rstest]
678 #[case::one_nanosecond_before(|until| until - Duration::from_nanos(1), true)]
679 #[case::at_quotable_until(|until| until, false)]
680 #[case::one_second_after(|until| until + Duration::from_secs(1), false)]
681 fn ensure_quotable_around_quotable_until(
682 #[case] now: fn(Instant) -> Instant,
683 #[case] quotable: bool,
684 ) {
685 let until = Instant::now() + Duration::from_secs(60);
686 let state = state().with_quotable_until(until);
687 assert_eq!(
688 state
689 .ensure_quotable(now(until))
690 .is_ok(),
691 quotable
692 );
693 }
694
695 #[rstest]
697 #[case::price_levels_expired(
698 state().with_quotable_until(Instant::now()),
699 100_000_000,
700 wbtc(),
701 "price_levels_expired"
702 )]
703 #[case::unknown_pair(state(), 1, weth(), "unknown_pair")]
704 #[case::no_liquidity(empty_state(), 1, wbtc(), "no_liquidity")]
705 #[case::below_smallest_quote(state(), 50_000_000, wbtc(), "below_smallest_quote")]
706 #[case::not_monotonic(glitched_state(), 150, wbtc(), "not_monotonic")]
707 fn a_refused_quote_is_counted_under_its_reason(
708 #[case] state: PriceLevelStreamState,
709 #[case] amount_in: u64,
710 #[case] token_in: Token,
711 #[case] reason: &str,
712 ) {
713 let (result, snapshot) = record_async(async {
714 state.get_amount_out(BigUint::from(amount_in), &token_in, &usdc())
715 });
716
717 assert!(result.is_err());
718 assert_eq!(
719 counter_value(
720 &snapshot,
721 "price_level_stream_quotes_refused_total",
722 &[("reason", reason)]
723 ),
724 1
725 );
726 }
727
728 #[test]
730 fn a_refused_spot_price_is_counted() {
731 let (result, snapshot) = record_async(async { empty_state().spot_price(&wbtc(), &usdc()) });
732
733 assert!(result.is_err());
734 assert_eq!(
735 counter_value(
736 &snapshot,
737 "price_level_stream_quotes_refused_total",
738 &[("reason", "no_liquidity")]
739 ),
740 1
741 );
742 }
743
744 #[test]
745 fn state_without_quotable_until_never_expires() {
746 let far = Instant::now() + Duration::from_secs(1_000_000);
747 assert!(state().ensure_quotable(far).is_ok());
748 }
749
750 #[test]
751 fn expired_state_refuses_every_query() {
752 let state = state().with_quotable_until(Instant::now());
755 assert!(matches!(
756 state.get_amount_out(BigUint::from(100_000_000u64), &wbtc(), &usdc()),
757 Err(SimulationError::RecoverableError(_))
758 ));
759 assert!(matches!(
760 state.spot_price(&wbtc(), &usdc()),
761 Err(SimulationError::RecoverableError(_))
762 ));
763 assert!(matches!(
764 state.get_limits(wbtc().address, usdc().address),
765 Err(SimulationError::RecoverableError(_))
766 ));
767 }
768
769 #[test]
770 fn fresh_state_answers_every_query() {
771 let state = state().with_quotable_until(Instant::now() + Duration::from_secs(60));
772 assert!(state
773 .get_amount_out(BigUint::from(100_000_000u64), &wbtc(), &usdc())
774 .is_ok());
775 assert!(state
776 .spot_price(&wbtc(), &usdc())
777 .is_ok());
778 assert!(state
779 .get_limits(wbtc().address, usdc().address)
780 .is_ok());
781 }
782
783 #[test]
784 fn successor_state_keeps_quotable_until() {
785 let until = Instant::now() + Duration::from_secs(60);
786 let state = state().with_quotable_until(until);
787 let result = state
788 .get_amount_out(BigUint::from(100_000_000u64), &wbtc(), &usdc())
789 .expect("fresh state quotes");
790 let successor = result
791 .new_state
792 .as_any()
793 .downcast_ref::<PriceLevelStreamState>()
794 .expect("price level state");
795 assert_eq!(successor.quotable_until, Some(until));
796 }
797
798 #[test]
799 fn quotable_until_serde_round_trip() {
800 let live = state().with_quotable_until(Instant::now());
801 let json = serde_json::to_value(&live).unwrap();
802 assert!(json
803 .as_object()
804 .unwrap()
805 .get("quotable_until")
806 .is_none());
807 let replayed: PriceLevelStreamState = serde_json::from_value(json).unwrap();
809 assert_eq!(replayed.quotable_until, None);
810 assert!(replayed
811 .spot_price(&wbtc(), &usdc())
812 .is_ok());
813 }
814
815 #[test]
817 fn eq_ignores_quotable_until() {
818 let until = Instant::now() + Duration::from_secs(60);
819 assert!(state().eq(&state().with_quotable_until(until)));
820 assert!(state()
821 .with_quotable_until(until)
822 .eq(&state().with_quotable_until(until + Duration::from_secs(1))));
823 }
824
825 #[test]
826 fn with_simulation_overrides_sets_and_exposes_them() {
827 assert_eq!(state().simulation_overrides(), None);
828 assert_eq!(
829 state()
830 .with_simulation_overrides(test_overrides())
831 .simulation_overrides(),
832 Some(&test_overrides())
833 );
834 }
835
836 #[rstest]
839 #[case::the_same_overrides(Some(test_overrides()), true)]
840 #[case::no_overrides(None, false)]
841 #[case::rebuilt_with_other_values(Some(rebuilt_with_other_values()), true)]
842 #[case::another_block(Some(in_another_block()), false)]
843 #[case::fewer_accounts(Some(with_one_account_fewer()), false)]
844 #[case::another_account(Some(with_another_account()), false)]
845 fn eq_compares_the_block_and_the_accounts_not_the_values(
846 #[case] other: Option<PammSimulationOverrides>,
847 #[case] equal: bool,
848 ) {
849 let held = state().with_simulation_overrides(test_overrides());
850 let other = match other {
851 Some(overrides) => state().with_simulation_overrides(overrides),
852 None => state(),
853 };
854
855 assert_eq!(held.eq(&other), equal);
856 assert_eq!(other.eq(&held), equal);
857 }
858
859 fn rebuilt_with_other_values() -> PammSimulationOverrides {
862 let mut rebuilt = test_overrides();
863 rebuilt.built_at_ns += 1;
864 for account in rebuilt.accounts.values_mut() {
865 account.balance = Some(Bytes::from(vec![0x42]));
866 account.nonce = account.nonce.map(|nonce| nonce + 1);
867 account.state_diff.clear();
868 }
869 rebuilt
870 }
871
872 fn in_another_block() -> PammSimulationOverrides {
874 PammSimulationOverrides { block_number: Some(26_201_955), ..test_overrides() }
875 }
876
877 fn with_another_account() -> PammSimulationOverrides {
880 let mut swapped = test_overrides();
881 let (_, account) = swapped
882 .accounts
883 .pop_first()
884 .expect("an account");
885 swapped
886 .accounts
887 .insert(Bytes::from(vec![0xab; 20]), account);
888 swapped
889 }
890
891 fn with_one_account_fewer() -> PammSimulationOverrides {
894 let mut fewer = test_overrides();
895 fewer.accounts.pop_first();
896 fewer
897 }
898
899 #[test]
902 fn successor_state_keeps_the_overrides() {
903 let state = state().with_simulation_overrides(test_overrides());
904 let result = state
905 .get_amount_out(BigUint::from(100_000_000u64), &wbtc(), &usdc())
906 .expect("fresh state quotes");
907 let successor = result
908 .new_state
909 .as_any()
910 .downcast_ref::<PriceLevelStreamState>()
911 .expect("price level state");
912 assert_eq!(successor.simulation_overrides(), Some(&test_overrides()));
913 }
914
915 #[test]
919 fn an_override_bearing_captured_state_round_trips_as_text_and_as_a_value() {
920 let state = captured_state().with_simulation_overrides(test_overrides());
921
922 let text = serde_json::to_string(&state).expect("serializes");
923 let value = serde_json::to_value(&state).expect("serializes into a Value");
924 let from_text: PriceLevelStreamState =
925 serde_json::from_str(&text).expect("reads back from text");
926 let from_value: PriceLevelStreamState =
927 serde_json::from_value(value).expect("reads back from a Value");
928
929 for read in [&from_text, &from_value] {
930 assert_eq!(read.simulation_overrides(), Some(&test_overrides()));
931 assert!(state.eq(read));
932 }
933 }
934
935 #[rstest]
941 #[case::tag_before_content(tag_first)]
942 #[case::content_before_tag(content_first)]
943 fn an_override_bearing_captured_state_round_trips_through_a_boxed_protocol_sim(
944 #[case] recording: fn(&str, &str) -> String,
945 ) {
946 let state = captured_state().with_simulation_overrides(test_overrides());
947 let text = recording(TAG, &serde_json::to_string(&state).expect("serializes"));
948
949 let boxed: Box<dyn ProtocolSim> = serde_json::from_str(&text).expect("reads back");
950
951 assert!(state.eq(boxed.as_ref()));
952 let read = boxed
953 .as_any()
954 .downcast_ref::<PriceLevelStreamState>()
955 .expect("price level state");
956 assert_eq!(read.simulation_overrides(), Some(&test_overrides()));
957 }
958
959 #[test]
961 fn typetag_writes_the_tag_the_recordings_carry() {
962 let text = serde_json::to_string(&state() as &dyn ProtocolSim).expect("serializes");
963
964 assert!(text.starts_with(&format!(r#"{{"protocol":{TAG},"#)), "{text}");
965 }
966
967 #[test]
975 fn the_serialized_overrides_key_is_named_overrides() {
976 let state = captured_state().with_simulation_overrides(test_overrides());
977
978 let text = serde_json::to_string(&state).expect("serializes");
979 let typed = serde_json::to_value(&state).expect("serializes");
980 let boxed = serde_json::to_value(&state as &dyn ProtocolSim).expect("serializes");
981
982 assert!(text.contains(r#""overrides":"#), "no `overrides` key in the state JSON");
983 for json in [&typed, &boxed["state"]] {
984 let overrides = json
985 .as_object()
986 .expect("an object")
987 .get("overrides")
988 .expect("the state object names them `overrides`");
989 let read: PammSimulationOverrides =
990 serde_json::from_value(overrides.clone()).expect("the overrides under that key");
991 assert_eq!(read, test_overrides());
992 }
993 }
994
995 #[test]
998 fn a_legacy_typed_recording_reads_back_without_overrides() {
999 let read: PriceLevelStreamState = serde_json::from_str(LEGACY_STATE).expect("reads back");
1000 assert_eq!(read.simulation_overrides(), None);
1001 assert_eq!(read.quotes_0_to_1, vec![quote(100_000_000, 100_000_000_000)]);
1002 assert_eq!(read.quotes_1_to_0, vec![quote(100_000_000_000, 99_000_000)]);
1003 }
1004
1005 #[rstest]
1008 #[case::tag_before_content(tag_first)]
1009 #[case::content_before_tag(content_first)]
1010 fn a_legacy_boxed_recording_reads_back_without_overrides(
1011 #[case] recording: fn(&str, &str) -> String,
1012 ) {
1013 let boxed: Box<dyn ProtocolSim> =
1014 serde_json::from_str(&recording(TAG, LEGACY_STATE)).expect("reads back");
1015 let read = boxed
1016 .as_any()
1017 .downcast_ref::<PriceLevelStreamState>()
1018 .expect("price level state");
1019 assert_eq!(read.simulation_overrides(), None);
1020 assert_eq!(read.quotes_0_to_1, vec![quote(100_000_000, 100_000_000_000)]);
1021 }
1022
1023 #[test]
1026 fn a_state_without_overrides_serializes_without_the_key() {
1027 let typed = serde_json::to_value(state()).expect("serializes");
1028 let boxed = serde_json::to_value(&state() as &dyn ProtocolSim).expect("serializes");
1029
1030 for json in [&typed, &boxed["state"]] {
1031 assert!(json
1032 .as_object()
1033 .expect("an object")
1034 .get("overrides")
1035 .is_none());
1036 }
1037 }
1038}