1use std::{
2 any::Any,
3 collections::{BTreeMap, HashMap},
4};
5
6use alloy::primitives::U256;
7use itertools::Either;
8use num_bigint::BigUint;
9use num_traits::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 crate::{
22 evm::protocol::{
23 pancakeswap_infinity_bin::{
24 attributes::{
25 apply_reserve, decode_bin_id_attribute, decode_bool_attribute,
26 decode_u16_attribute, parse_bin_key,
27 },
28 math::{
29 bin::{
30 get_amounts_out, get_drain_amounts, get_liquidity, get_price_from_id,
31 BinAmounts,
32 },
33 constants::{BIN_ID_COUNT, MAX_LIQUIDITY_PER_BIN},
34 fee::{calculate_swap_fee, protocol_fee_amount},
35 },
36 },
37 u256_num::u256_to_f64,
38 utils::{add_fee_markup, uniswap::FEE_PIPS_DENOMINATOR as PIPS_DENOMINATOR},
39 },
40 utils::decimals_exponent,
41};
42
43const SWAP_BASE_GAS: u64 = 202_000;
51const GAS_PER_BIN_CROSSED: u64 = 12_100;
52
53const MAX_POOL_AMOUNT: u128 = i128::MAX as u128;
55
56fn credit_bin(
61 id: u32,
62 (x, y): (u128, u128),
63 swap_for_y: bool,
64 price: U256,
65 step: &BinAmounts,
66 protocol_fee: u16,
67 swap_fee: u32,
68) -> Result<(u128, u128), SimulationError> {
69 let (reserve_in, reserve_out) = if swap_for_y { (x, y) } else { (y, x) };
70 let credited =
72 step.amount_in_with_fee - protocol_fee_amount(step.fee_amount, protocol_fee, swap_fee)?;
73 let new_reserve_in = reserve_in
74 .checked_add(credited)
75 .ok_or_else(|| {
76 SimulationError::InvalidInput(
77 format!("bin {id} reserve overflows crediting {credited}"),
78 None,
79 )
80 })?;
81 let new_reserve_out = reserve_out - step.amount_out;
82 let (new_x, new_y) = if swap_for_y {
83 (new_reserve_in, new_reserve_out)
84 } else {
85 (new_reserve_out, new_reserve_in)
86 };
87 if get_liquidity(new_x, new_y, price)? > MAX_LIQUIDITY_PER_BIN {
88 return Err(SimulationError::InvalidInput(
89 format!("bin {id} exceeds MAX_LIQUIDITY_PER_BIN after the swap"),
90 None,
91 ));
92 }
93 Ok((new_x, new_y))
94}
95
96#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
107#[serde(try_from = "PancakeswapInfinityBinStateData")]
108pub struct PancakeswapInfinityBinState {
109 pub(crate) active_id: u32,
111 pub(crate) active_in_tree: bool,
115 pub(crate) bin_step: u16,
117 pub(crate) lp_fee: u32,
119 pub(crate) protocol_fee_zero_for_one: u16,
121 pub(crate) protocol_fee_one_for_zero: u16,
123 pub(crate) bins: BTreeMap<u32, (u128, u128)>,
125}
126
127#[derive(Deserialize)]
129struct PancakeswapInfinityBinStateData {
130 active_id: u32,
131 active_in_tree: bool,
132 bin_step: u16,
133 lp_fee: u32,
134 protocol_fee_zero_for_one: u16,
135 protocol_fee_one_for_zero: u16,
136 bins: BTreeMap<u32, (u128, u128)>,
137}
138
139impl TryFrom<PancakeswapInfinityBinStateData> for PancakeswapInfinityBinState {
140 type Error = SimulationError;
141
142 fn try_from(data: PancakeswapInfinityBinStateData) -> Result<Self, Self::Error> {
143 Self::new(
144 data.active_id,
145 data.active_in_tree,
146 data.bin_step,
147 data.lp_fee,
148 data.protocol_fee_zero_for_one,
149 data.protocol_fee_one_for_zero,
150 data.bins,
151 )
152 }
153}
154
155#[derive(Debug)]
157struct BinSwapResult {
158 amount_out: u128,
160 bins_crossed: u64,
162 new_state: PancakeswapInfinityBinState,
163}
164
165impl PancakeswapInfinityBinState {
166 pub fn new(
169 active_id: u32,
170 active_in_tree: bool,
171 bin_step: u16,
172 lp_fee: u32,
173 protocol_fee_zero_for_one: u16,
174 protocol_fee_one_for_zero: u16,
175 bins: BTreeMap<u32, (u128, u128)>,
176 ) -> Result<Self, SimulationError> {
177 let invalid = |message: String| SimulationError::InvalidInput(message, None);
178 if active_id >= BIN_ID_COUNT {
179 return Err(invalid(format!("active bin {active_id} is wider than the u24 on chain")));
180 }
181 for (&id, &reserves) in &bins {
182 if id >= BIN_ID_COUNT {
183 return Err(invalid(format!("bin {id} is wider than the u24 on chain")));
184 }
185 if reserves == (0, 0) {
186 return Err(invalid(format!("bin {id} holds nothing and must not be kept")));
187 }
188 }
189 Ok(Self {
190 active_id,
191 active_in_tree,
192 bin_step,
193 lp_fee,
194 protocol_fee_zero_for_one,
195 protocol_fee_one_for_zero,
196 bins,
197 })
198 }
199
200 fn swap(&self, swap_for_y: bool, amount_in: u128) -> Result<BinSwapResult, SimulationError> {
208 let protocol_fee = self.protocol_fee(swap_for_y);
210 let swap_fee = self.swap_fee(swap_for_y);
211 let mut new_state = self.clone();
212 let mut active = self.active_id;
213 let mut left = amount_in;
214 let mut amount_out = 0u128;
215 let mut bins_crossed = 0u64;
216
217 loop {
218 let (x, y) = new_state
219 .bins
220 .get(&active)
221 .copied()
222 .unwrap_or((0, 0));
223 let reserve_out = if swap_for_y { y } else { x };
224
225 if reserve_out > 0 {
227 let price = get_price_from_id(active, self.bin_step)?;
228 let step = get_amounts_out(reserve_out, swap_fee, price, swap_for_y, left)?;
229 let (new_x, new_y) =
230 credit_bin(active, (x, y), swap_for_y, price, &step, protocol_fee, swap_fee)?;
231
232 if new_x == 0 && new_y == 0 {
233 new_state.bins.remove(&active);
234 } else {
235 new_state
236 .bins
237 .insert(active, (new_x, new_y));
238 }
239
240 left -= step.amount_in_with_fee;
241 amount_out = amount_out
242 .checked_add(step.amount_out)
243 .ok_or_else(|| {
244 SimulationError::InvalidInput(
245 format!("output overflows u128 at bin {active}"),
246 None,
247 )
248 })?;
249 }
250
251 if left == 0 {
252 break;
253 }
254 let Some(next) = new_state.next_bin_with_liquidity(swap_for_y, active) else {
255 return Err(SimulationError::InvalidInput("Out of liquidity".to_string(), None));
256 };
257 active = next;
258 bins_crossed += 1;
259 }
260
261 if amount_out == 0 {
262 return Err(SimulationError::InvalidInput(
263 format!("swap of {amount_in} produced no output"),
264 None,
265 ));
266 }
267 if amount_out > MAX_POOL_AMOUNT {
271 return Err(SimulationError::InvalidInput(
272 format!("output {amount_out} exceeds int128"),
273 None,
274 ));
275 }
276
277 if active != self.active_id {
282 if !self.active_in_tree {
283 new_state.bins.remove(&self.active_id);
284 }
285 new_state.active_in_tree = true;
286 }
287 new_state.active_id = active;
288 Ok(BinSwapResult { amount_out, bins_crossed, new_state })
289 }
290
291 fn next_bin_with_liquidity(&self, swap_for_y: bool, from: u32) -> Option<u32> {
298 if swap_for_y {
299 self.bins
300 .range(..from)
301 .next_back()
302 .map(|(&id, _)| id)
303 } else {
304 self.bins
305 .range(from + 1..)
306 .next()
307 .map(|(&id, _)| id)
308 }
309 }
310
311 fn first_bin_with_output(&self, swap_for_y: bool) -> Option<u32> {
314 let has_output = |id: u32| {
315 self.bins
316 .get(&id)
317 .is_some_and(|&(x, y)| if swap_for_y { y > 0 } else { x > 0 })
318 };
319 let mut bin = self.active_id;
320 while !has_output(bin) {
321 bin = self.next_bin_with_liquidity(swap_for_y, bin)?;
322 }
323 Some(bin)
324 }
325
326 fn protocol_fee(&self, swap_for_y: bool) -> u16 {
328 if swap_for_y {
329 self.protocol_fee_zero_for_one
330 } else {
331 self.protocol_fee_one_for_zero
332 }
333 }
334
335 fn swap_fee(&self, swap_for_y: bool) -> u32 {
337 let protocol_fee = self.protocol_fee(swap_for_y);
338 if protocol_fee == 0 {
339 self.lp_fee
340 } else {
341 calculate_swap_fee(protocol_fee, self.lp_fee)
342 }
343 }
344}
345
346#[typetag::serde]
347impl ProtocolSim for PancakeswapInfinityBinState {
348 #[expect(
354 clippy::unimplemented,
355 reason = "fee() returns no error and the trait documents the panic for asymmetric fees"
356 )]
357 fn fee(&self) -> f64 {
358 if self.protocol_fee_zero_for_one != self.protocol_fee_one_for_zero {
359 unimplemented!(
360 "Bin pools charge a directional protocol fee; use spot_price or get_amount_out"
361 )
362 }
363 self.swap_fee(true) as f64 / f64::from(PIPS_DENOMINATOR)
364 }
365
366 fn spot_price(&self, base: &Token, quote: &Token) -> Result<f64, SimulationError> {
374 let base_is_x = base < quote;
376 let swap_for_y = !base_is_x;
377 let bin = self
378 .first_bin_with_output(swap_for_y)
379 .unwrap_or(self.active_id);
380 let price = u256_to_f64(get_price_from_id(bin, self.bin_step)?)? / 2.0f64.powi(128);
381
382 let (token0, token1) = if base_is_x { (base, quote) } else { (quote, base) };
384 let correction = 10f64.powi(decimals_exponent(token0.decimals, token1.decimals)?);
385 let price = if base_is_x { price * correction } else { 1.0 / (price * correction) };
386 let swap_fee = self.swap_fee(swap_for_y);
387 Ok(add_fee_markup(price, swap_fee as f64 / f64::from(PIPS_DENOMINATOR)))
388 }
389
390 fn get_amount_out(
391 &self,
392 amount_in: BigUint,
393 token_in: &Token,
394 token_out: &Token,
395 ) -> Result<GetAmountOutResult, SimulationError> {
396 let swap_for_y = token_in < token_out;
398 let amount = amount_in
399 .to_u128()
400 .filter(|amount| *amount <= MAX_POOL_AMOUNT)
401 .ok_or_else(|| {
402 SimulationError::InvalidInput(
403 format!("amount_in exceeds int128: {amount_in}"),
404 None,
405 )
406 })?;
407
408 let BinSwapResult { amount_out, bins_crossed, new_state } =
409 self.swap(swap_for_y, amount)?;
410 let gas = SWAP_BASE_GAS + bins_crossed * GAS_PER_BIN_CROSSED;
411
412 Ok(GetAmountOutResult::new(
413 BigUint::from(amount_out),
414 BigUint::from(gas),
415 Box::new(new_state),
416 ))
417 }
418
419 fn get_limits(
427 &self,
428 sell_token: Bytes,
429 buy_token: Bytes,
430 ) -> Result<(BigUint, BigUint), SimulationError> {
431 let swap_for_y = sell_token < buy_token;
432 let bins = if swap_for_y {
433 Either::Left(self.bins.range(..=self.active_id).rev())
434 } else {
435 Either::Right(self.bins.range(self.active_id..))
436 };
437
438 let protocol_fee = self.protocol_fee(swap_for_y);
439 let swap_fee = self.swap_fee(swap_for_y);
440 let mut total_in = 0u128;
441 let mut total_out = 0u128;
442 for (&id, &(x, y)) in bins {
443 let reserve_out = if swap_for_y { y } else { x };
444 if reserve_out == 0 {
445 continue;
446 }
447 let price = get_price_from_id(id, self.bin_step)?;
448 let Some(step) = get_drain_amounts(reserve_out, swap_fee, price, swap_for_y)? else {
449 break;
450 };
451 if credit_bin(id, (x, y), swap_for_y, price, &step, protocol_fee, swap_fee).is_err() {
454 break;
455 }
456 let (Some(next_in), Some(next_out)) = (
457 total_in.checked_add(step.amount_in_with_fee),
458 total_out.checked_add(step.amount_out),
459 ) else {
460 break;
461 };
462 if next_in > MAX_POOL_AMOUNT || next_out > MAX_POOL_AMOUNT {
463 break;
464 }
465 total_in = next_in;
466 total_out = next_out;
467 }
468 Ok((BigUint::from(total_in), BigUint::from(total_out)))
469 }
470
471 fn delta_transition(
473 &mut self,
474 delta: ProtocolStateDelta,
475 _tokens: &HashMap<Bytes, Token>,
476 _balances: &Balances,
477 ) -> Result<(), TransitionError> {
478 for (key, value) in delta.updated_attributes.iter() {
479 match key.as_str() {
480 "active_id" => self.active_id = decode_bin_id_attribute(key, value)?,
481 "active_in_tree" => self.active_in_tree = decode_bool_attribute(key, value)?,
482 "protocol_fees/zero2one" => {
483 self.protocol_fee_zero_for_one = decode_u16_attribute(key, value)?
484 }
485 "protocol_fees/one2zero" => {
486 self.protocol_fee_one_for_zero = decode_u16_attribute(key, value)?
487 }
488 _ if key.starts_with("bins/") => apply_reserve(&mut self.bins, key, value)?,
489 _ => {}
490 }
491 }
492
493 for key in delta.deleted_attributes.iter() {
494 if key.starts_with("bins/") {
495 let (id, _) = parse_bin_key(key)?;
496 self.bins.remove(&id);
497 }
498 }
499 self.bins
502 .retain(|_, reserves| *reserves != (0, 0));
503
504 Ok(())
505 }
506
507 fn clone_box(&self) -> Box<dyn ProtocolSim> {
508 Box::new(self.clone())
509 }
510
511 fn as_any(&self) -> &dyn Any {
512 self
513 }
514
515 fn as_any_mut(&mut self) -> &mut dyn Any {
516 self
517 }
518
519 fn eq(&self, other: &dyn ProtocolSim) -> bool {
520 other
521 .as_any()
522 .downcast_ref::<PancakeswapInfinityBinState>()
523 .is_some_and(|other| self == other)
524 }
525}
526
527#[cfg(test)]
528mod tests {
529 use std::str::FromStr;
530
531 use alloy::{
532 primitives::{aliases::U24, Address, Bytes as AlloyBytes, FixedBytes, U256},
533 providers::{Provider, ProviderBuilder},
534 rpc::types::TransactionRequest,
535 sol,
536 sol_types::SolCall,
537 };
538 use approx::assert_relative_eq;
539 use rstest::rstest;
540 use tycho_client::feed::{dto, synchronizer::ComponentWithState};
541 use tycho_common::models::Chain;
542
543 use super::{
544 super::{attributes::reserve_attributes, math::constants::REAL_ID_SHIFT},
545 *,
546 };
547 use crate::evm::protocol::{
548 pancakeswap_infinity_bin::attributes::decode_u32_attribute,
549 test_utils::try_decode_snapshot_with_defaults,
550 };
551
552 fn bin_state(active_id: u32, bins: &[(u32, (u128, u128))]) -> PancakeswapInfinityBinState {
555 PancakeswapInfinityBinState::new(
556 active_id,
557 true,
558 10,
559 100,
560 0,
561 0,
562 bins.iter().copied().collect(),
563 )
564 .unwrap()
565 }
566
567 #[rstest]
569 #[case::wide_active_id(r#"{"active_id":16777216,"active_in_tree":true,"bin_step":10,"lp_fee":100,"protocol_fee_zero_for_one":0,"protocol_fee_one_for_zero":0,"bins":{}}"#, "wider than the u24")]
570 #[case::wide_bin_id(r#"{"active_id":1,"active_in_tree":true,"bin_step":10,"lp_fee":100,"protocol_fee_zero_for_one":0,"protocol_fee_one_for_zero":0,"bins":{"16777216":[1,1]}}"#, "wider than the u24")]
571 #[case::empty_bin(r#"{"active_id":1,"active_in_tree":true,"bin_step":10,"lp_fee":100,"protocol_fee_zero_for_one":0,"protocol_fee_one_for_zero":0,"bins":{"1":[0,0]}}"#, "holds nothing")]
572 fn test_deserialize_applies_the_invariants(#[case] json: &str, #[case] message: &str) {
573 let err = serde_json::from_str::<PancakeswapInfinityBinState>(json)
574 .expect_err("an invalid wire state must not deserialize");
575 assert!(err.to_string().contains(message), "{err}");
576 }
577
578 #[test]
580 fn test_swap_within_active_bin() {
581 let state = bin_state(REAL_ID_SHIFT, &[(REAL_ID_SHIFT, (0, 1_000_000_000))]);
582
583 let result = state.swap(true, 1_000_000).unwrap();
584
585 assert_eq!(result.amount_out, 999_900);
586 assert_eq!(result.bins_crossed, 0);
587 assert_eq!(
588 result.new_state,
589 bin_state(REAL_ID_SHIFT, &[(REAL_ID_SHIFT, (1_000_000, 1_000_000_000 - 999_900))])
590 );
591 }
592
593 #[test]
596 fn test_swap_crosses_into_next_bin() {
597 let state = bin_state(
598 REAL_ID_SHIFT,
599 &[(REAL_ID_SHIFT - 1, (0, 5_000)), (REAL_ID_SHIFT, (0, 1_000))],
600 );
601
602 let result = state.swap(true, 2_000).unwrap();
603
604 assert_eq!(result.amount_out, 1_997);
605 assert_eq!(result.bins_crossed, 1);
606 assert_eq!(
607 result.new_state,
608 bin_state(
609 REAL_ID_SHIFT - 1,
610 &[(REAL_ID_SHIFT - 1, (999, 4_003)), (REAL_ID_SHIFT, (1_001, 0))]
611 )
612 );
613 }
614
615 #[test]
623 fn test_swap_withholds_the_protocol_fee_from_the_bin() {
624 let mut state = bin_state(REAL_ID_SHIFT, &[(REAL_ID_SHIFT, (0, 1_000_000_000))]);
625 state.lp_fee = 7;
626 state.protocol_fee_zero_for_one = 3;
627 state.protocol_fee_one_for_zero = 3;
628
629 let result = state.swap(true, 1_000_000).unwrap();
630
631 let mut expected = state;
632 expected
633 .bins
634 .insert(REAL_ID_SHIFT, (999_997, 1_000_000_000 - 999_990));
635 assert_eq!(result.amount_out, 999_990, "output nets the whole 10-pip swap fee");
636 assert_eq!(result.new_state, expected, "the protocol's 3 units never reach the bin");
637 }
638
639 #[test]
643 fn test_swap_selling_y_walks_up() {
644 let state = bin_state(
645 REAL_ID_SHIFT,
646 &[
647 (REAL_ID_SHIFT, (1_000, 500)),
648 (REAL_ID_SHIFT + 1, (0, 2_000)),
649 (REAL_ID_SHIFT + 3, (4_000, 0)),
650 ],
651 );
652
653 let result = state.swap(false, 3_000).unwrap();
654
655 assert_eq!(result.amount_out, 2_992);
656 assert_eq!(result.bins_crossed, 2);
657 assert_eq!(
658 result.new_state,
659 bin_state(
660 REAL_ID_SHIFT + 3,
661 &[
662 (REAL_ID_SHIFT, (0, 1_501)),
663 (REAL_ID_SHIFT + 1, (0, 2_000)),
665 (REAL_ID_SHIFT + 3, (2_008, 1_999)),
666 ]
667 )
668 );
669 }
670
671 #[test]
675 fn test_swap_off_an_active_dust_bin_drops_it() {
676 let mut state =
677 bin_state(REAL_ID_SHIFT, &[(REAL_ID_SHIFT - 1, (0, 5_000)), (REAL_ID_SHIFT, (1, 1))]);
678 state.active_in_tree = false;
679
680 let result = state.swap(true, 2_000).unwrap();
681
682 let mut expected = bin_state(REAL_ID_SHIFT - 1, &[(REAL_ID_SHIFT - 1, (1_998, 3_005))]);
684 expected.active_in_tree = true;
685 assert_eq!(result.amount_out, 1_996);
686 assert_eq!(result.bins_crossed, 1);
687 assert_eq!(result.new_state, expected);
688 assert_eq!(
689 result
690 .new_state
691 .swap(false, 1_000)
692 .unwrap()
693 .bins_crossed,
694 0,
695 "no bin above"
696 );
697 }
698
699 #[test]
701 fn test_swap_within_an_active_dust_bin_keeps_it() {
702 let mut state = bin_state(REAL_ID_SHIFT, &[(REAL_ID_SHIFT, (0, 1_000))]);
703 state.active_in_tree = false;
704
705 let result = state.swap(true, 500).unwrap();
706
707 let mut expected = bin_state(REAL_ID_SHIFT, &[(REAL_ID_SHIFT, (500, 1_000 - 499))]);
708 expected.active_in_tree = false;
709 assert_eq!(result.new_state, expected);
710 }
711
712 fn five_bins() -> PancakeswapInfinityBinState {
714 let bins: Vec<_> = (REAL_ID_SHIFT - 2..=REAL_ID_SHIFT + 2)
715 .map(|id| (id, (1_000_000_000, 1_000_000_000)))
716 .collect();
717 bin_state(REAL_ID_SHIFT, &bins)
718 }
719
720 #[rstest]
725 #[case::selling_x_charges_zero_for_one(
726 true, 100, 100, 400, 2_497_504_491, -2,
727 [(-2, (1_498_549_858, 502_495_509)), (-1, (2_001_100_121, 0)), (0, (2_000_100_021, 0))]
728 )]
729 #[case::selling_y_charges_one_for_zero(
730 false, 100, 100, 400, 2_496_755_989, 2,
731 [(0, (0, 2_000_100_051)), (1, (0, 2_001_100_151)), (2, (503_244_011, 1_497_799_798))]
732 )]
733 #[case::max_lp_and_protocol_fee(
734 true, 100_000, 4_000, 4_000, 2_239_520_717, -2,
735 [(-2, (1_266_666_666, 760_479_283)), (-1, (2_112_222_224, 0)), (0, (2_111_111_112, 0))]
736 )]
737 fn test_swap_withholds_directional_protocol_fee_across_bins(
738 #[case] swap_for_y: bool,
739 #[case] lp_fee: u32,
740 #[case] zero_for_one: u16,
741 #[case] one_for_zero: u16,
742 #[case] expected_out: u128,
743 #[case] final_offset: i32,
744 #[case] touched: [(i32, (u128, u128)); 3],
746 ) {
747 let mut state = five_bins();
748 state.lp_fee = lp_fee;
749 state.protocol_fee_zero_for_one = zero_for_one;
750 state.protocol_fee_one_for_zero = one_for_zero;
751
752 let result = state
753 .swap(swap_for_y, 2_500_000_000)
754 .unwrap();
755
756 let mut expected = state;
757 expected.active_id = REAL_ID_SHIFT
758 .checked_add_signed(final_offset)
759 .unwrap();
760 for (offset, reserves) in touched {
761 expected.bins.insert(
762 REAL_ID_SHIFT
763 .checked_add_signed(offset)
764 .unwrap(),
765 reserves,
766 );
767 }
768 assert_eq!(result.amount_out, expected_out);
769 assert_eq!(result.new_state, expected, "the two untouched bins must be as they were");
770 }
771
772 #[rstest]
776 #[case::exactly_max_drains(1_000_100_011, 1_000_000_000, (1_000_100_011, 0))]
777 #[case::one_below_max_is_partial(1_000_100_010, 999_999_999, (1_000_100_010, 1))]
778 fn test_swap_at_the_bin_capacity(
779 #[case] amount_in: u128,
780 #[case] expected_out: u128,
781 #[case] active_reserves: (u128, u128),
782 ) {
783 let state = bin_state(
784 REAL_ID_SHIFT,
785 &[(REAL_ID_SHIFT - 1, (0, 1_000_000_000)), (REAL_ID_SHIFT, (0, 1_000_000_000))],
786 );
787
788 let result = state.swap(true, amount_in).unwrap();
789
790 assert_eq!(result.amount_out, expected_out);
791 assert_eq!(result.bins_crossed, 0);
792 assert_eq!(result.new_state.active_id, REAL_ID_SHIFT);
793 assert_eq!(result.new_state.bins[&REAL_ID_SHIFT], active_reserves);
794 assert_eq!(result.new_state.bins[&(REAL_ID_SHIFT - 1)], (0, 1_000_000_000));
795 }
796
797 #[test]
800 fn test_swap_errors_past_max_liquidity_per_bin() {
801 let state = bin_state(
802 REAL_ID_SHIFT,
803 &[(REAL_ID_SHIFT, (0, 191_757_638_537_527_648_490_752_896_198_554))],
804 );
805
806 let err = state
807 .swap(true, 1_000_000_000_000)
808 .expect_err("a swap past the per-bin cap must not quote");
809 assert!(
810 err.to_string()
811 .contains("MAX_LIQUIDITY_PER_BIN"),
812 "{err}"
813 );
814 }
815
816 #[rstest]
819 #[case::selling_x(true)]
820 #[case::selling_y(false)]
821 fn test_limits_quote_exactly_with_protocol_fees(#[case] selling_x: bool) {
822 let mut state = five_bins();
823 state.protocol_fee_zero_for_one = 100;
824 state.protocol_fee_one_for_zero = 400;
825 let (token_in, token_out) = if selling_x { (usdc(), usdt()) } else { (usdt(), usdc()) };
826
827 let (max_in, max_out) = state
828 .get_limits(token_in.address.clone(), token_out.address.clone())
829 .unwrap();
830
831 assert_eq!(
832 state
833 .get_amount_out(max_in.clone(), &token_in, &token_out)
834 .unwrap()
835 .amount,
836 max_out
837 );
838 let over = state
839 .get_amount_out(max_in + BigUint::from(1u64), &token_in, &token_out)
840 .expect_err("one unit over the limit still quoted");
841 assert!(
842 over.to_string()
843 .contains("Out of liquidity"),
844 "{over}"
845 );
846 }
847
848 #[test]
850 fn test_swap_skips_bin_without_output_reserve() {
851 let state = bin_state(
852 REAL_ID_SHIFT,
853 &[(REAL_ID_SHIFT - 1, (0, 5_000)), (REAL_ID_SHIFT, (5_000, 0))],
854 );
855
856 let result = state.swap(true, 999).unwrap();
857
858 assert_eq!(result.amount_out, 997);
859 assert_eq!(result.bins_crossed, 1);
860 assert_eq!(
861 result.new_state,
862 bin_state(
863 REAL_ID_SHIFT - 1,
864 &[(REAL_ID_SHIFT - 1, (999, 4_003)), (REAL_ID_SHIFT, (5_000, 0))]
865 )
866 );
867 }
868
869 #[rstest]
873 #[case::bins_run_out(REAL_ID_SHIFT, (0, 1_000), 5_000, "Out of liquidity")]
874 #[case::output_rounds_to_zero(REAL_ID_SHIFT - 5_000, (0, 1_000_000_000), 1, "produced no output")]
875 fn test_swap_errors(
876 #[case] active_id: u32,
877 #[case] reserves: (u128, u128),
878 #[case] amount_in: u128,
879 #[case] message: &str,
880 ) {
881 let state = bin_state(active_id, &[(active_id, reserves)]);
882
883 let err = state
884 .swap(true, amount_in)
885 .expect_err("quoted where the pool would revert");
886 assert!(err.to_string().contains(message), "{err}");
887 }
888
889 #[test]
892 fn test_swap_errors_on_reserve_and_output_overflow() {
893 let state = bin_state(REAL_ID_SHIFT, &[(REAL_ID_SHIFT, (u128::MAX - 10, 1_000))]);
894 let err = state
895 .swap(true, 500)
896 .expect_err("the credited x overflows the bin");
897 assert!(
898 err.to_string()
899 .contains("reserve overflows crediting"),
900 "{err}"
901 );
902
903 let id = REAL_ID_SHIFT - 41_616;
906 let state = bin_state(id, &[(id, (u128::MAX - 1, 0)), (id + 1, (10, 0))]);
907 let err = state
908 .swap(false, 1 << 70)
909 .expect_err("the summed output overflows u128");
910 assert!(
911 err.to_string()
912 .contains("output overflows u128"),
913 "{err}"
914 );
915 }
916
917 #[rstest]
920 #[case::sells_x_walks_down(&[REAL_ID_SHIFT - 5, REAL_ID_SHIFT, REAL_ID_SHIFT + 7], true, Some(REAL_ID_SHIFT - 5))]
921 #[case::sells_y_walks_up(&[REAL_ID_SHIFT - 5, REAL_ID_SHIFT, REAL_ID_SHIFT + 7], false, Some(REAL_ID_SHIFT + 7))]
922 #[case::nothing_below(&[REAL_ID_SHIFT], true, None)]
923 #[case::nothing_above(&[REAL_ID_SHIFT], false, None)]
924 fn test_next_bin_with_liquidity(
925 #[case] ids: &[u32],
926 #[case] swap_for_y: bool,
927 #[case] expected: Option<u32>,
928 ) {
929 let bins: Vec<_> = ids
930 .iter()
931 .map(|id| (*id, (1_000, 1_000)))
932 .collect();
933 let state = bin_state(REAL_ID_SHIFT, &bins);
934
935 assert_eq!(state.next_bin_with_liquidity(swap_for_y, REAL_ID_SHIFT), expected);
936 }
937
938 fn token(address: &str, symbol: &str) -> Token {
939 Token::new(&Bytes::from_str(address).unwrap(), symbol, 6, 0, &[], Chain::Base, 100)
940 }
941
942 fn usdc() -> Token {
944 token("0x833589fcd6edb6e08f4c7c32d4f71b54bda02913", "USDC")
945 }
946
947 fn usdt() -> Token {
949 token("0xfde4c96c8593536e31f229ea8f37b2ada2699bb2", "USDT")
950 }
951
952 fn wei() -> Token {
954 Token::new(
955 &Bytes::from_str("0xffffffffffffffffffffffffffffffffffffffff").unwrap(),
956 "WEI",
957 18,
958 0,
959 &[],
960 Chain::Base,
961 100,
962 )
963 }
964
965 #[test]
968 fn test_get_amount_out_follows_address_order() {
969 let state = bin_state(REAL_ID_SHIFT, &[(REAL_ID_SHIFT, (1_000_000_000, 0))]);
970
971 let result = state
972 .get_amount_out(BigUint::from(1_000_000u64), &usdt(), &usdc())
973 .unwrap();
974
975 assert_eq!(result.amount, BigUint::from(999_900u64));
976 assert_eq!(result.gas, BigUint::from(202_000u64));
977 }
978
979 #[test]
981 fn test_get_amount_out_rejects_amount_above_int128() {
982 let state = bin_state(REAL_ID_SHIFT, &[(REAL_ID_SHIFT, (0, 1_000_000_000))]);
983 let too_large = BigUint::from(i128::MAX as u128 + 1);
984
985 let err = state
986 .get_amount_out(too_large, &usdc(), &usdt())
987 .expect_err("amounts above int128 must be rejected, not truncated");
988 assert!(
989 err.to_string()
990 .contains("amount_in exceeds int128"),
991 "{err}"
992 );
993 }
994
995 #[test]
999 fn test_output_above_int128_is_rejected() {
1000 let id = REAL_ID_SHIFT - 41_616;
1001 let state = bin_state(id, &[(id, (u128::MAX - 1, 0))]);
1002 let target_out = i128::MAX as u128 + (u128::MAX - i128::MAX as u128) / 2;
1003 let price = get_price_from_id(id, state.bin_step).unwrap();
1004 let amount_in = (U256::from(target_out) * price) >> 128;
1005
1006 let err = state
1007 .get_amount_out(BigUint::from(u128::try_from(amount_in).unwrap()), &usdt(), &usdc())
1008 .unwrap_err();
1009 assert!(
1010 err.to_string()
1011 .contains("exceeds int128"),
1012 "{err}"
1013 );
1014
1015 let (max_in, max_out) = state
1017 .get_limits(usdt().address, usdc().address)
1018 .unwrap();
1019 assert_eq!((max_in, max_out), (BigUint::ZERO, BigUint::ZERO));
1020 }
1021
1022 #[test]
1024 fn test_get_amount_out_charges_gas_per_crossing() {
1025 let state = bin_state(
1026 REAL_ID_SHIFT,
1027 &[(REAL_ID_SHIFT - 1, (0, 5_000)), (REAL_ID_SHIFT, (0, 1_000))],
1028 );
1029
1030 let result = state
1031 .get_amount_out(BigUint::from(2_000u64), &usdc(), &usdt())
1032 .unwrap();
1033
1034 assert_eq!(result.amount, BigUint::from(1_997u64));
1035 assert_eq!(result.gas, BigUint::from(214_100u64), "base plus one crossing");
1036 }
1037
1038 #[rstest]
1042 #[case::base_is_x(usdc(), usdt(), 1.105226220342802)]
1043 #[case::base_is_y(usdt(), usdc(), 0.9049731282105973)]
1044 #[case::quote_has_18_decimals(usdc(), wei(), 1.105226220342802e-12)]
1045 fn test_spot_price(#[case] base: Token, #[case] quote: Token, #[case] expected: f64) {
1046 let state = bin_state(REAL_ID_SHIFT + 100, &[(REAL_ID_SHIFT + 100, (1_000, 1_000))]);
1047
1048 assert_relative_eq!(
1049 state.spot_price(&base, "e).unwrap(),
1050 expected,
1051 max_relative = 1e-12
1052 );
1053 }
1054
1055 #[rstest]
1059 #[case::buying_x_walks_up(
1060 usdc(), usdt(), REAL_ID_SHIFT + 90,
1061 &[(REAL_ID_SHIFT + 95, (0, 1_000)), (REAL_ID_SHIFT + 100, (1_000, 0))],
1062 1.105226220342802
1063 )]
1064 #[case::buying_y_walks_down(
1065 usdt(), usdc(), REAL_ID_SHIFT + 110,
1066 &[(REAL_ID_SHIFT + 100, (0, 1_000)), (REAL_ID_SHIFT + 105, (1_000, 0))],
1067 0.9049731282105973
1068 )]
1069 fn test_spot_price_skips_bins_without_base(
1070 #[case] base: Token,
1071 #[case] quote: Token,
1072 #[case] active_id: u32,
1073 #[case] bins: &[(u32, (u128, u128))],
1074 #[case] expected: f64,
1075 ) {
1076 let state = bin_state(active_id, bins);
1077
1078 assert_relative_eq!(
1079 state.spot_price(&base, "e).unwrap(),
1080 expected,
1081 max_relative = 1e-12
1082 );
1083 }
1084
1085 #[test]
1088 fn test_spot_price_charges_the_fee_of_selling_quote() {
1089 let mut state = bin_state(REAL_ID_SHIFT + 100, &[(REAL_ID_SHIFT + 100, (1_000, 1_000))]);
1090 state.protocol_fee_one_for_zero = 1_000;
1091
1092 assert_relative_eq!(
1093 state
1094 .spot_price(&usdc(), &usdt())
1095 .unwrap(),
1096 1.105226220342802 * (1.0 - 0.0001) / (1.0 - 0.0011),
1097 max_relative = 1e-12
1098 );
1099 }
1100
1101 #[test]
1105 fn test_spot_price_falls_back_to_the_active_bin_without_base_liquidity() {
1106 let state = bin_state(REAL_ID_SHIFT + 100, &[(REAL_ID_SHIFT + 100, (1_000, 0))]);
1107
1108 assert_relative_eq!(
1109 state
1110 .spot_price(&usdt(), &usdc())
1111 .unwrap(),
1112 0.9049731282105973,
1113 max_relative = 1e-12
1114 );
1115 let refused = state
1116 .get_amount_out(BigUint::from(1_000u64), &usdc(), &usdt())
1117 .expect_err("nothing to buy, so the quote must still refuse");
1118 assert!(
1119 refused
1120 .to_string()
1121 .contains("Out of liquidity"),
1122 "{refused}"
1123 );
1124 }
1125
1126 #[test]
1127 fn test_fee_charges_protocol_then_lp() {
1128 let mut state = bin_state(REAL_ID_SHIFT, &[(REAL_ID_SHIFT, (1_000, 1_000))]);
1129 state.lp_fee = 3_000;
1130 state.protocol_fee_zero_for_one = 1_000;
1131 state.protocol_fee_one_for_zero = 1_000;
1132
1133 assert_relative_eq!(state.fee(), 0.003997);
1134 }
1135
1136 #[test]
1137 #[should_panic(expected = "directional protocol fee")]
1138 fn test_fee_rejects_asymmetric_protocol_fee() {
1139 let mut state = bin_state(REAL_ID_SHIFT, &[(REAL_ID_SHIFT, (1_000, 1_000))]);
1140 state.protocol_fee_zero_for_one = 1_000;
1141
1142 state.fee();
1143 }
1144
1145 #[test]
1146 fn test_limits_bound_what_can_be_quoted() {
1147 let state = bin_state(
1148 REAL_ID_SHIFT,
1149 &[(REAL_ID_SHIFT - 1, (0, 5_000)), (REAL_ID_SHIFT, (0, 1_000))],
1150 );
1151
1152 let (max_in, max_out) = state
1153 .get_limits(usdc().address, usdt().address)
1154 .unwrap();
1155
1156 assert_eq!(max_out, BigUint::from(6_000u64));
1158 assert_eq!(
1159 state
1160 .get_amount_out(max_in.clone(), &usdc(), &usdt())
1161 .unwrap()
1162 .amount,
1163 max_out
1164 );
1165 let over = state
1167 .get_amount_out(max_in + BigUint::from(1u64), &usdc(), &usdt())
1168 .expect_err("one wei over the limit still quoted");
1169 assert!(
1170 over.to_string()
1171 .contains("Out of liquidity"),
1172 "{over}"
1173 );
1174 }
1175
1176 #[rstest]
1179 #[case::capped_bin_is_second(REAL_ID_SHIFT - 1, 1_000)]
1180 #[case::capped_bin_is_active(REAL_ID_SHIFT, 0)]
1181 fn test_limits_stop_before_a_bin_the_cap_blocks(
1182 #[case] capped_bin: u32,
1183 #[case] expected_out: u128,
1184 ) {
1185 let mut bins = vec![(REAL_ID_SHIFT, (0, 1_000)), (REAL_ID_SHIFT - 1, (0, 5_000))];
1186 bins.retain(|(id, _)| *id != capped_bin);
1187 bins.push((capped_bin, (0, 191_757_638_537_527_648_490_752_896_198_554)));
1188 let state = bin_state(REAL_ID_SHIFT, &bins);
1189
1190 let (max_in, max_out) = state
1191 .get_limits(usdc().address, usdt().address)
1192 .unwrap();
1193
1194 assert_eq!(max_out, BigUint::from(expected_out));
1195 if expected_out > 0 {
1196 assert_eq!(
1197 state
1198 .get_amount_out(max_in.clone(), &usdc(), &usdt())
1199 .unwrap()
1200 .amount,
1201 max_out
1202 );
1203 }
1204 let over = state
1205 .get_amount_out(max_in + BigUint::from(1u64), &usdc(), &usdt())
1206 .expect_err("one unit over the limit enters the capped bin");
1207 assert!(
1208 over.to_string()
1209 .contains("MAX_LIQUIDITY_PER_BIN"),
1210 "{over}"
1211 );
1212 }
1213
1214 #[test]
1218 fn test_limits_stop_before_a_bin_whose_drain_input_overflows() {
1219 let mut state = bin_state(
1220 REAL_ID_SHIFT,
1221 &[(REAL_ID_SHIFT, (1_000, 0)), (REAL_ID_SHIFT + 7_000, (10u128.pow(18), 0))],
1222 );
1223 state.bin_step = 100;
1224
1225 let (max_in, max_out) = state
1226 .get_limits(usdt().address, usdc().address)
1227 .unwrap();
1228
1229 assert_eq!(max_out, BigUint::from(1_000u64));
1230 assert_eq!(
1231 state
1232 .get_amount_out(max_in.clone(), &usdt(), &usdc())
1233 .unwrap()
1234 .amount,
1235 max_out
1236 );
1237 let over = state
1238 .get_amount_out(max_in + BigUint::from(1u64), &usdt(), &usdc())
1239 .expect_err("one unit over the limit enters the far bin");
1240 assert!(
1241 over.to_string()
1242 .contains("exceeds u128"),
1243 "{over}"
1244 );
1245 }
1246
1247 #[test]
1248 fn test_limits_are_zero_when_direction_is_dry() {
1249 let state = bin_state(REAL_ID_SHIFT, &[(REAL_ID_SHIFT, (0, 1_000))]);
1250
1251 assert_eq!(
1252 state
1253 .get_limits(usdt().address, usdc().address)
1254 .unwrap(),
1255 (BigUint::ZERO, BigUint::ZERO)
1256 );
1257 }
1258
1259 fn delta(updated: &[(&str, Bytes)], deleted: &[&str]) -> ProtocolStateDelta {
1260 ProtocolStateDelta {
1261 component_id: "test_pool".to_string(),
1262 updated_attributes: updated
1263 .iter()
1264 .map(|(key, value)| (key.to_string(), value.clone()))
1265 .collect(),
1266 deleted_attributes: deleted
1267 .iter()
1268 .map(|key| key.to_string())
1269 .collect(),
1270 }
1271 }
1272
1273 fn apply(state: &mut PancakeswapInfinityBinState, delta: ProtocolStateDelta) {
1275 state
1276 .delta_transition(delta, &HashMap::new(), &Balances::default())
1277 .unwrap();
1278 }
1279
1280 #[rstest]
1281 #[case::leaves_the_tree(vec![0x00], false)]
1282 #[case::back_in_the_tree(vec![0x01], true)]
1283 fn test_delta_moves_active_bin_in_and_out_of_the_tree(
1284 #[case] flag: Vec<u8>,
1285 #[case] expected: bool,
1286 ) {
1287 let mut state = bin_state(REAL_ID_SHIFT, &[(REAL_ID_SHIFT, (0, 1_000))]);
1288 state.active_in_tree = !expected;
1289
1290 apply(&mut state, delta(&[("active_in_tree", Bytes::from(flag))], &[]));
1291
1292 assert_eq!(state.active_in_tree, expected);
1293 }
1294
1295 #[test]
1298 fn test_delta_updates_bin_reserves() {
1299 let mut state = bin_state(
1300 REAL_ID_SHIFT,
1301 &[(REAL_ID_SHIFT - 1, (0, 5_000)), (REAL_ID_SHIFT, (0, 1_000))],
1302 );
1303 let pair = reserve_attributes(REAL_ID_SHIFT, 7, 11);
1304 let pair: Vec<_> = pair
1305 .iter()
1306 .map(|(key, value)| (key.as_str(), value.clone()))
1307 .collect();
1308
1309 apply(&mut state, delta(&pair, &[]));
1310 assert_eq!(state.bins[&REAL_ID_SHIFT], (7, 11));
1311 assert_eq!(state.bins[&(REAL_ID_SHIFT - 1)], (0, 5_000));
1312
1313 let x_only = format!("bins/{}/reserve_x", REAL_ID_SHIFT - 1);
1314 apply(&mut state, delta(&[(&x_only, Bytes::from(vec![3]))], &[]));
1315 assert_eq!(state.bins[&(REAL_ID_SHIFT - 1)], (3, 5_000));
1316 }
1317
1318 #[rstest]
1323 #[case::zero_values(reserve_attributes(REAL_ID_SHIFT, 0, 0).to_vec(), vec![])]
1324 #[case::one_half_zeroed_to_empty(
1325 vec![(format!("bins/{REAL_ID_SHIFT}/reserve_y"), Bytes::from(vec![0]))],
1326 vec![]
1327 )]
1328 #[case::deleted_attributes(vec![], vec![format!("bins/{REAL_ID_SHIFT}/reserve_x"), format!("bins/{REAL_ID_SHIFT}/reserve_y")])]
1329 #[case::one_half_deleted(vec![], vec![format!("bins/{REAL_ID_SHIFT}/reserve_y")])]
1330 fn test_delta_removes_emptied_bin(
1331 #[case] updated: Vec<(String, Bytes)>,
1332 #[case] deleted: Vec<String>,
1333 ) {
1334 let mut state = bin_state(REAL_ID_SHIFT, &[(REAL_ID_SHIFT, (0, 1_000))]);
1335 let updated: Vec<_> = updated
1336 .iter()
1337 .map(|(key, value)| (key.as_str(), value.clone()))
1338 .collect();
1339 let deleted: Vec<_> = deleted
1340 .iter()
1341 .map(String::as_str)
1342 .collect();
1343
1344 apply(&mut state, delta(&updated, &deleted));
1345
1346 assert!(!state.bins.contains_key(&REAL_ID_SHIFT), "emptied bin stayed in the map");
1347 }
1348
1349 #[test]
1353 fn test_delta_moves_active_id() {
1354 let mut state = bin_state(REAL_ID_SHIFT, &[(REAL_ID_SHIFT, (0, 1_000))]);
1355
1356 apply(&mut state, delta(&[("active_id", Bytes::from(vec![0x00, 0x80, 0x00, 0x05]))], &[]));
1357
1358 assert_eq!(state.active_id, REAL_ID_SHIFT + 5);
1359 }
1360
1361 #[test]
1365 fn test_delta_updates_protocol_fees_only() {
1366 let mut state = bin_state(REAL_ID_SHIFT, &[(REAL_ID_SHIFT, (0, 1_000))]);
1367
1368 apply(
1369 &mut state,
1370 delta(
1371 &[
1372 ("fee", Bytes::from(vec![0x01, 0xf4])),
1373 ("protocol_fees/zero2one", Bytes::from(vec![0x03, 0xe8])),
1374 ("protocol_fees/one2zero", Bytes::from(vec![0x07, 0xd0])),
1375 ("balance_owner", Bytes::from(vec![0x01])),
1376 ],
1377 &[],
1378 ),
1379 );
1380
1381 assert_eq!(state.lp_fee, 100, "the LP fee is static");
1382 assert_eq!(state.protocol_fee_zero_for_one, 1000);
1383 assert_eq!(state.protocol_fee_one_for_zero, 2000);
1384 }
1385
1386 sol! {
1387 struct PoolKey {
1390 address currency0;
1391 address currency1;
1392 address hooks;
1393 address poolManager;
1394 uint24 fee;
1395 bytes32 parameters;
1396 }
1397
1398 struct QuoteExactSingleParams {
1399 PoolKey poolKey;
1400 bool zeroForOne;
1401 uint128 exactAmount;
1402 bytes hookData;
1403 }
1404
1405 function quoteExactInputSingle(QuoteExactSingleParams memory params)
1406 external
1407 returns (uint256 amountOut, uint256 gasEstimate);
1408 }
1409
1410 const BIN_QUOTER: &str = "0xc631f4b0fc2dd68ad45f74b2942628db117dd359";
1413 const SNAPSHOT_BLOCK: u64 = 32_980_292;
1415
1416 fn bin_snapshot() -> ComponentWithState {
1417 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
1418 .join("tests/assets/decoder/pancakeswap_infinity_bin_snapshot.json");
1419 let json = std::fs::read_to_string(path).expect("snapshot fixture");
1420
1421 serde_json::from_str::<dto::ComponentWithState>(&json)
1423 .expect("snapshot deserializes")
1424 .into()
1425 }
1426
1427 #[tokio::test]
1431 async fn test_snapshot_fixture_decodes() {
1432 let state =
1433 try_decode_snapshot_with_defaults::<PancakeswapInfinityBinState>(bin_snapshot())
1434 .await
1435 .expect("snapshot decodes");
1436
1437 assert_eq!(state.active_id, REAL_ID_SHIFT);
1438 assert!(state.active_in_tree);
1439 assert_eq!(state.bin_step, 10);
1440 assert_eq!(state.lp_fee, 7);
1441 assert_eq!((state.protocol_fee_zero_for_one, state.protocol_fee_one_for_zero), (3, 3));
1442 assert_eq!(state.bins.len(), 59);
1445 assert_eq!(state.bins[&(REAL_ID_SHIFT - 29)], (0, 4_237_288));
1446 assert_eq!(state.bins[&REAL_ID_SHIFT], (2_118_644, 2_118_644));
1447 assert_eq!(state.bins[&(REAL_ID_SHIFT + 29)], (4_237_288, 0));
1448 }
1449
1450 fn pool_key(snapshot: &ComponentWithState) -> PoolKey {
1453 let statics = &snapshot.component.static_attributes;
1454 let address = |value: &Bytes| Address::from_slice(value.as_ref());
1455
1456 PoolKey {
1457 currency0: address(&snapshot.component.tokens[0]),
1458 currency1: address(&snapshot.component.tokens[1]),
1459 hooks: Address::ZERO,
1460 poolManager: address(&statics["pool_manager"]),
1461 fee: U24::from(
1462 decode_u32_attribute("key_lp_fee", &statics["key_lp_fee"])
1463 .expect("key_lp_fee is a u24"),
1464 ),
1465 parameters: FixedBytes::from_slice(statics["parameters"].as_ref()),
1466 }
1467 }
1468
1469 #[tokio::test]
1476 #[ignore = "Requires BASE_RPC_URL pointing at a Base archive node"]
1477 async fn test_quotes_match_bin_quoter() {
1478 let rpc_url = std::env::var("BASE_RPC_URL").expect("BASE_RPC_URL must point at Base");
1480 let provider = ProviderBuilder::new()
1481 .connect(&rpc_url)
1482 .await
1483 .expect("provider");
1484
1485 let snapshot = bin_snapshot();
1486 let key = pool_key(&snapshot);
1487 let token_x =
1488 Token::new(&snapshot.component.tokens[0].clone(), "X", 6, 0, &[], Chain::Base, 100);
1489 let token_y =
1490 Token::new(&snapshot.component.tokens[1].clone(), "Y", 6, 0, &[], Chain::Base, 100);
1491 let state = try_decode_snapshot_with_defaults::<PancakeswapInfinityBinState>(snapshot)
1492 .await
1493 .expect("snapshot decodes");
1494
1495 let quoter = |zero_for_one: bool, amount_in: u128| {
1499 let params = QuoteExactSingleParams {
1500 poolKey: key.clone(),
1501 zeroForOne: zero_for_one,
1502 exactAmount: amount_in,
1503 hookData: AlloyBytes::new(),
1504 };
1505 let request = TransactionRequest::default()
1506 .to(Address::from_str(BIN_QUOTER).unwrap())
1507 .input(
1508 quoteExactInputSingleCall { params }
1509 .abi_encode()
1510 .into(),
1511 );
1512 let provider = provider.clone();
1513 async move {
1514 let returned = match provider
1515 .call(request)
1516 .block(SNAPSHOT_BLOCK.into())
1517 .await
1518 {
1519 Ok(returned) => returned,
1520 Err(err)
1521 if err
1522 .as_error_resp()
1523 .is_some_and(|resp| resp.as_revert_data().is_some()) =>
1524 {
1525 return None
1526 }
1527 Err(err) => panic!("quoter call failed: {err}"),
1528 };
1529 let quoted = quoteExactInputSingleCall::abi_decode_returns(&returned)
1530 .expect("quoter response")
1531 .amountOut;
1532 Some(BigUint::from_bytes_be("ed.to_be_bytes::<32>()))
1533 }
1534 };
1535
1536 for (zero_for_one, token_in, token_out) in
1537 [(true, &token_x, &token_y), (false, &token_y, &token_x)]
1538 {
1539 let limit = state
1540 .get_limits(token_in.address.clone(), token_out.address.clone())
1541 .expect("limits")
1542 .0
1543 .to_u128()
1544 .expect("limit fits u128");
1545
1546 let mut crossed = false;
1549 for amount_in in [1, 1_000, 10_000_000, 100_000_000, limit] {
1550 let ours = state
1551 .get_amount_out(BigUint::from(amount_in), token_in, token_out)
1552 .ok();
1553 crossed |= ours
1554 .as_ref()
1555 .is_some_and(|ours| ours.gas > BigUint::from(SWAP_BASE_GAS));
1556
1557 assert_eq!(
1558 ours.map(|ours| ours.amount),
1559 quoter(zero_for_one, amount_in).await,
1560 "zero_for_one={zero_for_one} amount={amount_in}: port and BinQuoter disagree"
1561 );
1562 }
1563 assert!(crossed, "zero_for_one={zero_for_one}: no amount crossed a bin");
1564
1565 let over = state
1567 .get_amount_out(BigUint::from(limit + 1), token_in, token_out)
1568 .expect_err("zero_for_one={zero_for_one}: port quoted past its own limit");
1569 assert!(
1570 over.to_string()
1571 .contains("Out of liquidity"),
1572 "{over}"
1573 );
1574 assert_eq!(
1575 quoter(zero_for_one, limit + 1).await,
1576 None,
1577 "zero_for_one={zero_for_one}: BinQuoter filled past the port's limit"
1578 );
1579 }
1580 }
1581}