Skip to main content

tycho_simulation/evm/protocol/pancakeswap_infinity_bin/
state.rs

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
43// Measured through the TychoRouter on a Base fork (`PancakeswapInfinityBinGas.t.sol`, which
44// pins them): `singleSwap` paid by `transferFrom` on the USDC/USDT pool in both directions,
45// crossing 0 to 21 bins, fit by least squares to 204.5k + 12.1k per bin crossed, residuals within
46// 6k. The router's work and the user's transfer are in scope on purpose: the executor is a
47// callback protocol, so the gas estimator adds nothing for the transfer and the quote has to carry
48// it. A quote's gas becomes `Swap::estimated_gas`, which the encoder sums into
49// `EncodedSolution::estimated_gas`, so these size the solution's gas as well as ranking routes.
50const SWAP_BASE_GAS: u64 = 205_000;
51const GAS_PER_BIN_CROSSED: u64 = 12_100;
52
53/// The pool takes the input and returns the output as `int128`, so an amount past this reverts.
54const MAX_POOL_AMOUNT: u128 = i128::MAX as u128;
55
56/// A bin's reserves after a step: the input credited less the protocol's share, the output taken.
57///
58/// Errors where the pool reverts, so `swap` propagates it and `get_limits` stops before the bin:
59/// the input reserve overflowing `u128`, or the bin's liquidity passing `MAX_LIQUIDITY_PER_BIN`.
60fn 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    // The protocol's cut leaves the pool: off the input, never off the output.
71    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/// A PancakeSwap Infinity Bin pool.
97///
98/// `x` is `currency0`, `y` is `currency1`, so `swap_for_y` means `token_in < token_out` by address.
99///
100/// Only bins with liquidity are kept, and the `BTreeMap` order replaces the on-chain bitmap tree:
101/// the next non-empty bin is a range query. The one bin that can hold liquidity outside the tree
102/// is the active one, after a burn down to `MINIMUM_SHARE`; `active_in_tree` marks it.
103///
104/// Built through [`Self::new`], which holds the invariants `swap` relies on: every id fits the
105/// chain's u24, and no bin is kept at `(0, 0)`. Deserialization goes through it too.
106#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
107#[serde(try_from = "PancakeswapInfinityBinStateData")]
108pub struct PancakeswapInfinityBinState {
109    /// Bin the next swap starts in. u24 on chain.
110    pub(crate) active_id: u32,
111    /// Whether the active bin is in the on-chain tree. A swap starts in the active bin either way,
112    /// but once it moves off a bin outside the tree, no swap reaches that bin again until a mint
113    /// re-adds it.
114    pub(crate) active_in_tree: bool,
115    /// Price ratio between neighbouring bins, in basis points.
116    pub(crate) bin_step: u16,
117    /// LP fee in pips (`1e6` denominator).
118    pub(crate) lp_fee: u32,
119    /// Protocol fee in pips charged when selling token0, the low 12 bits of the packed fee.
120    pub(crate) protocol_fee_zero_for_one: u16,
121    /// Protocol fee in pips charged when selling token1, the high 12 bits.
122    pub(crate) protocol_fee_one_for_zero: u16,
123    /// `bin id -> (reserve_x, reserve_y)`, absolute reserves as indexed from `reserveOfBin`.
124    pub(crate) bins: BTreeMap<u32, (u128, u128)>,
125}
126
127/// The wire shape of a state. `TryFrom` applies the invariants.
128#[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/// Outcome of an exact-input swap.
156#[derive(Debug)]
157struct BinSwapResult {
158    /// Output the swap pays, over every bin it took from.
159    amount_out: u128,
160    /// Bins stepped into beyond the first.
161    bins_crossed: u64,
162    new_state: PancakeswapInfinityBinState,
163}
164
165impl PancakeswapInfinityBinState {
166    /// A pool state, checked: `active_id` and every bin id below `BIN_ID_COUNT`, and no bin at
167    /// `(0, 0)`, which the walk would pay a crossing for.
168    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    /// Exact-input swap across as many bins as the input reaches.
201    ///
202    /// Errors `InvalidInput("Out of liquidity")` when the bins run out first: on chain the whole
203    /// swap reverts (`BinPool__OutOfLiquidity`), so a partial fill would quote an unexecutable
204    /// trade.
205    ///
206    /// [`BinPool.sol#L111-L222`](https://github.com/pancakeswap/infinity-core/blob/7c04695f/src/pool-bin/libraries/BinPool.sol#L111-L222)
207    fn swap(&self, swap_for_y: bool, amount_in: u128) -> Result<BinSwapResult, SimulationError> {
208        // Fixed before the loop, not per bin. Protocol fee is charged first, LP fee on the rest.
209        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            // A bin with nothing on the output side is skipped, not an error.
226            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        // The pool narrows the output with `safeInt128` before returning it.
268        //
269        // [`BinPool.sol#L210-L212`](https://github.com/pancakeswap/infinity-core/blob/7c04695f/src/pool-bin/libraries/BinPool.sol#L210-L212)
270        if amount_out > MAX_POOL_AMOUNT {
271            return Err(SimulationError::InvalidInput(
272                format!("output {amount_out} exceeds int128"),
273                None,
274            ));
275        }
276
277        // The walk only steps through tree bins, so a start bin outside the tree is out of reach
278        // once left. Whatever dust it keeps on chain would otherwise be quoted the other way.
279        //
280        // [`BinPool.sol#L293-L297`](https://github.com/pancakeswap/infinity-core/blob/7c04695f/src/pool-bin/libraries/BinPool.sol#L293-L297)
281        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    /// Next bin with liquidity, excluding `from`: lower id selling x, higher selling y.
292    ///
293    /// Matches `findFirstRight` / `findFirstLeft`, which step off `from` before searching despite
294    /// what their natspec says, because the caller has already spent that bin.
295    ///
296    /// [`BinPool.sol#L293-L297`](https://github.com/pancakeswap/infinity-core/blob/7c04695f/src/pool-bin/libraries/BinPool.sol#L293-L297)
297    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    /// First bin a swap takes output from: the active bin, else the next one in the swap's
312    /// direction with reserves on the output side. The same bins `swap` would skip are skipped.
313    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    /// Protocol fee in pips for one direction: `zero2one` when selling x.
327    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    /// Combined fee in pips charged on a bin: protocol fee first, LP fee on the remainder.
336    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    /// Swap fee as a ratio: protocol fee first, LP fee on the remainder.
349    ///
350    /// The protocol fee is directional, so one number only exists when both halves agree. The
351    /// trait allows a panic otherwise, as `uniswap_v4/state.rs` does. The pools indexed so far
352    /// carry equal halves, e.g. 3 pips each on the Base USDC/USDT pool.
353    #[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    /// Price of the bin a buy of `base` fills first, fee markup included. Constant sum inside a
367    /// bin, so it holds exactly until that bin empties, unlike a CLMM's marginal price.
368    ///
369    /// That bin is not always the active one: a burn never moves `activeId`, and a swap that ends
370    /// with no input left can stop on a bin whose output side it just drained. When no bin holds
371    /// `base`, the active bin's price is returned, as Uniswap v3/v4 price an empty pool; that the
372    /// trade cannot fill is `get_limits`' and `get_amount_out`'s to report.
373    fn spot_price(&self, base: &Token, quote: &Token) -> Result<f64, SimulationError> {
374        // Buying base means selling quote: selling y (`swap_for_y` false) when base is x.
375        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        // `price` is y per x, already quote-per-base when base is the lower address.
383        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        // currency0 is the lower address, so selling it is the x -> y direction.
397        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    /// Maximum input the pool absorbs, and its output. `(0, 0)` when the direction is dry.
420    ///
421    /// A floor: the sum over whole bins, in walk order, of the input that drains each one and the
422    /// reserve it pays out. The walk stops at the first bin a swap could not fill: its drain input
423    /// exceeds `u128`, crediting it would breach `MAX_LIQUIDITY_PER_BIN` or overflow, or a total
424    /// would pass `i128::MAX`, which is how the pool takes the input and returns the output. Dust
425    /// whose output rounds to zero still errors, as it does on chain.
426    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            // Draining credits the bin what `swap` would, so the walk stops where `swap` errors.
452            // A partial fill might still fit, but a floor can stop short.
453            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    /// Applies an indexer delta. The attribute encodings are documented in [`super::attributes`].
472    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        // The substreams classifies a bin written to zero as a deletion while still carrying the
500        // zero values, so both arrive. A bin left in the map costs the next swap a crossing.
501        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    /// Pool with `bin_step` 10 and a 100-pip LP fee, no protocol fee, so `swap_fee` is 100 pips
553    /// and the expectations below reuse the `math::bin` vectors.
554    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    /// Deserialization goes through `new`, so a wire state cannot skip the invariants.
568    #[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    /// Fits inside the active bin: no crossing, no move, reserves shift by the step's amounts.
579    #[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    /// Drains the active bin and finishes in the next one down. Per-bin expectations come from the
594    /// pinned `BinHelper.getAmountsOut`: 1001 in for 1000 out, then 999 in for 997 out.
595    #[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    /// With a protocol fee the pool keeps less than it charges: the protocol's share leaves the
616    /// Vault, so the bin is credited `amount_in_with_fee` minus that share. Crediting the full
617    /// amount would overstate every reserve after a swap and mis-price the next quote.
618    ///
619    /// Figures from the pinned Solidity for the pool the harness indexes, 3 pips per side over a
620    /// 7-pip LP fee: swap fee 10 pips, so 1e6 in pays 10 units of fee, 3 of which go to the
621    /// protocol and 7 stay in the bin.
622    #[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    /// Selling y walks up: drains the active bin, skips a bin holding only y, finishes two bins
640    /// further. Per-bin figures from the pinned `BinHelper.getAmountsOut` with `swapForY` false:
641    /// 1001 in for 1000 out, then 1999 in for 1992 out.
642    #[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                    // The y-only bin is untouched.
664                    (REAL_ID_SHIFT + 1, (0, 2_000)),
665                    (REAL_ID_SHIFT + 3, (2_008, 1_999)),
666                ]
667            )
668        );
669    }
670
671    /// A burn down to `MINIMUM_SHARE` takes the active bin out of the tree but leaves its dust.
672    /// A swap still starts there, but once it moves off, the chain cannot reach the bin again:
673    /// the returned state must not keep it, or a quote the other way would walk into it.
674    #[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        // The dust's single unit of y comes out first; its 2 units of input are then lost.
683        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    /// A swap that stays in an active dust bin keeps it, dust and all: it is still the start.
700    #[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    /// Five bins around the reference id, 1e9 of each token in each.
713    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    /// Protocol fees across several bins, from a copy of `BinPool.swap`'s exact-input loop run
721    /// on the pinned libraries. Unequal halves catch the two directions' fees being swapped:
722    /// equal ones cannot. The max-fee case pairs the 10% LP cap with the 4000-pip protocol cap,
723    /// which `calculateSwapFee` lets add up past 10%.
724    #[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        // Bins the swap touched, as `(offset from REAL_ID_SHIFT, reserves)`.
745        #[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    /// Input of exactly the bin's `max_amount_in` (1_000_100_011, from the pinned
773    /// `getAmountsOut`) drains it and stops there: nothing is left, so the walk does not step on.
774    /// One less takes the partial-fill branch and leaves a unit of y behind.
775    #[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    /// A bin at `MAX_LIQUIDITY_PER_BIN` (y = cap >> 128 at price 1) grows by the fee a swap
798    /// leaves in it, which reverts `BinPool__MaxLiquidityPerBinExceeded` on chain.
799    #[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    /// The protocol's cut leaves a drained bin, not the input it took, so limits computed from
817    /// each bin's `max_amount_in` still quote exactly with unequal protocol fees.
818    #[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    /// A bin with nothing on the output side costs a crossing, not an error.
849    #[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    /// Both on-chain reverts: `BinPool__OutOfLiquidity` when the bins run out before the input
870    /// does, and `BinPool__InsufficientAmountUnSpecified` when the output rounds to zero. Neither
871    /// may come back as a partial fill or a zero quote, which would not execute.
872    #[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    /// Crediting the input to a bin can overflow its `u128` reserve, and summing the output over
890    /// bins can overflow `u128` before the `int128` check sees it. Each is an error, not a wrap.
891    #[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        // Priced near 2^-60 y per x, two bins pay out more x together than `u128` holds for an
904        // input that fits comfortably.
905        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    /// Selling x walks down, selling y walks up, the spent bin is excluded either way, and running
918    /// out in the swap direction is what makes `swap` error rather than partially fill.
919    #[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    /// Base USDC, the lower address of the pair, so currency0 and the x side.
943    fn usdc() -> Token {
944        token("0x833589fcd6edb6e08f4c7c32d4f71b54bda02913", "USDC")
945    }
946
947    /// Base USDT, currency1 and the y side.
948    fn usdt() -> Token {
949        token("0xfde4c96c8593536e31f229ea8f37b2ada2699bb2", "USDT")
950    }
951
952    /// An 18-decimal token sorting above both, so it is always the y side.
953    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    /// Reserves sit on the x side and the tokens are passed y -> x, so a direction taken from
966    /// anything but address order errors instead of quoting. No crossing, so gas is the base.
967    #[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(205_000u64));
977    }
978
979    /// On chain the amount is an `int128`, so anything above that is rejected, not truncated.
980    #[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    /// A bin priced near 2^-60 y per x holding almost `u128::MAX` of x pays out more x than
996    /// `int128` holds for a modest input. The pool reverts on `safeInt128`, so the quote errors,
997    /// and `get_limits` stops short of that bin.
998    #[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        // The only bin pays out past `int128`, so nothing is quotable.
1016        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    /// Drains the active bin and finishes in the next, so gas carries one crossing.
1023    #[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(217_100u64), "base plus one crossing");
1036    }
1037
1038    /// Priced at bin `2^23 + 100` rather than 1.0, so an inverted ratio is visible, and against an
1039    /// 18-decimal token, since two 6-decimal tokens hide a dropped decimals correction. Expected
1040    /// values come from the pinned `pow` with the 100-pip markup applied.
1041    #[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, &quote).unwrap(),
1050            expected,
1051            max_relative = 1e-12
1052        );
1053    }
1054
1055    /// The active bin holds nothing to buy, as after a burn, so the price is the bin the buy
1056    /// fills first: liquidity sits at `2^23 + 100`, so the expectations match `test_spot_price`.
1057    /// The bin in between holds only the side being sold and is skipped, as `swap` skips it.
1058    #[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, &quote).unwrap(),
1080            expected,
1081            max_relative = 1e-12
1082        );
1083    }
1084
1085    /// Buying x sells y, so the `one2zero` protocol fee applies: swap fee 1100 pips over the
1086    /// 100-pip LP fee (`calculateSwapFee`), applied to the `base_is_x` price without its markup.
1087    #[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    /// No bin holds the token being bought: the active bin's price, as an empty Uniswap v3 pool
1102    /// still has one, while the quote path reports that nothing can fill. Active bin `2^23 + 100`,
1103    /// so the expectation matches `test_spot_price`'s `base_is_y` case.
1104    #[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        // Everything on the output side is reachable, and the limit itself still quotes.
1157        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        // One wei past it runs out of bins.
1166        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    /// Crediting a drained bin can push it over `MAX_LIQUIDITY_PER_BIN`, where `swap` errors, so
1177    /// the limit stops before such a bin: the limit quotes, one unit more does not.
1178    #[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    /// A bin far from the active one prices its reserve past `u128`, where `get_drain_amounts`
1215    /// is `None` and the pool reverts on `safe128`. The limit stops before it: the limit quotes,
1216    /// one unit more does not.
1217    #[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    /// Applies a delta to a state, panicking on a decode error.
1274    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    /// A bin's reserve pair replaces that bin's reserves and leaves every other bin alone; one
1296    /// half on its own leaves the other half as it was.
1297    #[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    /// A bin can be emptied two ways: zero values, or its keys in `deleted_attributes`. The
1319    /// substreams classifies a zeroed bin as a deletion while still carrying the zero values, so
1320    /// both arrive in practice, and a bin left in the map costs the next swap a crossing over
1321    /// nothing.
1322    #[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    /// `active_id` is emitted signed big-endian, so ids at or above `0x800000` arrive as 4 bytes
1350    /// with a leading `0x00`. The indexed pool sits above that boundary, and a fixed-width decoder
1351    /// passes the 3-byte case while failing this one.
1352    #[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    /// Protocol fees move on `ProtocolFeeUpdated`. The LP fee is the PoolKey's and never moves,
1362    /// so a `fee` attribute is ignored like any unknown key. Values are big-endian and minimal
1363    /// length, so 1000 pips is `[0x03, 0xe8]`.
1364    #[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        /// [`IQuoter.sol`](https://github.com/pancakeswap/infinity-periphery/blob/56a7a4f5076d57d5ed90c38a00421ecbac0d649c/src/interfaces/IQuoter.sol),
1388        /// the Bin lens.
1389        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    /// [`BinQuoter.sol`](https://github.com/pancakeswap/infinity-periphery/blob/56a7a4f5076d57d5ed90c38a00421ecbac0d649c/src/pool-bin/lens/BinQuoter.sol)
1411    /// on Base.
1412    const BIN_QUOTER: &str = "0xc631f4b0fc2dd68ad45f74b2942628db117dd359";
1413    /// Block the snapshot fixture was captured at. The quote has to be read at the same height.
1414    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        // Only the wire type is `Deserialize`; the decoder takes the converted one.
1422        serde_json::from_str::<dto::ComponentWithState>(&json)
1423            .expect("snapshot deserializes")
1424            .into()
1425    }
1426
1427    /// The fixture is a capture of what the package emitted for a live pool, so decoding it pins
1428    /// the decoder to the package's attribute schema. Every other test builds attributes with
1429    /// this crate's own helpers, where the two can drift apart unnoticed.
1430    #[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        // 29 bins each side of the active one, 4.237288 USDC or USDT each, and the active bin
1443        // half and half.
1444        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    /// The pool key the quoter needs, taken from the snapshot's static attributes rather than
1451    /// rebuilt, so the test cannot disagree with the indexer about which pool it is asking about.
1452    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    /// The port against the chain, end to end: the state decoded from a real snapshot must quote
1470    /// what `BinQuoter` quotes for the same input, to the wei.
1471    ///
1472    /// Everything else in this module checks the port against the pinned Solidity libraries in
1473    /// isolation. This is the only check that catches a divergence in how they are composed, or a
1474    /// snapshot that decodes into the wrong shape.
1475    #[tokio::test]
1476    #[ignore = "Requires BASE_RPC_URL pointing at a Base archive node"]
1477    async fn test_quotes_match_bin_quoter() {
1478        // Not RPC_URL: by repo convention that is Ethereum, where the quoter has no code.
1479        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        // A revert is `None`, so "no quote" compares on both sides. Only a revert counts: a
1496        // transport failure or any other error response would otherwise pass every expected
1497        // revert.
1498        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(&quoted.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            // Dust (zero output, so both sides must refuse it), inside the active bin, a few
1547            // crossings, about 20 crossings (the fixture's bins hold ~4.24 USDC), and the limit.
1548            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            // One past the limit runs out of bins: the quoter reverts, the port must error.
1566            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}