Skip to main content

tycho_simulation/evm/protocol/lunarbase/
state.rs

1use std::{any::Any, collections::HashMap};
2
3use lunarbase_pmm_math::{
4    sqrt_price_x96_to_price, try_simulate_successful_swap, Direction, MathError, PoolParams,
5    RollbackReason, SimulationStatus, MAX_U112, MAX_U24, U256,
6};
7use num_bigint::BigUint;
8use tycho_common::{
9    dto::ProtocolStateDelta,
10    models::token::Token,
11    simulation::{
12        errors::{SimulationError, TransitionError},
13        protocol_sim::{
14            Balances, BlockContext, GetAmountOutResult, PoolSwap, ProtocolSim, QueryPoolSwapParams,
15            SwapConstraint,
16        },
17    },
18    Bytes,
19};
20
21use super::decoder::apply_delta;
22use crate::{evm::protocol::u256_num::biguint_to_uint, utils::decimals_exponent};
23
24pub type Address = [u8; 20];
25// Pool-call estimate for routing, not a transaction gas limit.
26const DEFAULT_GAS: u64 = 100_000;
27
28/// Native simulation of the linear anchor and immediate punishment mechanism.
29///
30/// Tycho partner quotes always use fee multiplier one.
31/// Active-reserve transitions assume standard token transfers and fully credited
32/// fees with sufficient fee-bucket capacity; caller-specific fee accounting and
33/// unsynced donations are not indexed.
34#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
35pub struct LunarBaseState {
36    pub pool: Address,
37    pub token_x: Address,
38    pub token_y: Address,
39    pub anchor_price_x96: U256,
40    pub fee_ask_x24: u32,
41    pub fee_bid_x24: u32,
42    pub latest_update_block: u64,
43    pub reserve_x: u128,
44    pub reserve_y: u128,
45    pub max_punishment_x24: u32,
46    pub block_delay: u64,
47    pub paused: bool,
48    pub head_block: u64,
49}
50
51impl LunarBaseState {
52    pub fn pool_params(&self) -> PoolParams {
53        PoolParams {
54            sqrt_price_x96: self.anchor_price_x96,
55            fee_ask_x24: self.fee_ask_x24,
56            fee_bid_x24: self.fee_bid_x24,
57            reserve_x: self.reserve_x,
58            reserve_y: self.reserve_y,
59            max_punishment_x24: self.max_punishment_x24,
60        }
61    }
62
63    pub fn is_fresh(&self) -> bool {
64        self.head_block <
65            self.latest_update_block
66                .saturating_add(self.block_delay)
67    }
68
69    fn quote_exact_in(
70        &self,
71        token_in: Address,
72        token_out: Address,
73        amount_in: U256,
74    ) -> Result<(U256, Self), QuoteError> {
75        if self.paused {
76            return Err(QuoteError::Paused);
77        }
78
79        if !self.is_fresh() {
80            return Err(QuoteError::Stale {
81                block_number: self.head_block,
82                latest_update_block: self.latest_update_block,
83                block_delay: self.block_delay,
84            });
85        }
86
87        let direction = if token_in == self.token_x && token_out == self.token_y {
88            Direction::XToY
89        } else if token_in == self.token_y && token_out == self.token_x {
90            Direction::YToX
91        } else {
92            return Err(QuoteError::InvalidTokenPair);
93        };
94        let simulation = try_simulate_successful_swap(
95            &self.pool_params(),
96            amount_in,
97            direction,
98            U256::from(1u64),
99        )
100        .map_err(QuoteError::Math)?;
101        match simulation.status {
102            SimulationStatus::Applied => {}
103            SimulationStatus::RolledBack(RollbackReason::SwapImpossible) => {
104                return Err(QuoteError::Rejected);
105            }
106            SimulationStatus::RolledBack(RollbackReason::ReserveTransitionOverflow) => {
107                return Err(QuoteError::ReserveOverflow);
108            }
109            SimulationStatus::RolledBack(RollbackReason::LaterRevert) => {
110                return Err(QuoteError::Rejected);
111            }
112        }
113
114        let mut next = self.clone();
115        next.reserve_x = simulation.post_swap.reserve_x;
116        next.reserve_y = simulation.post_swap.reserve_y;
117        next.fee_ask_x24 = simulation.post_swap.fee_ask_x24;
118        next.fee_bid_x24 = simulation.post_swap.fee_bid_x24;
119        Ok((simulation.quote.amount_out, next))
120    }
121}
122
123#[typetag::serde]
124impl ProtocolSim for LunarBaseState {
125    fn fee(&self) -> f64 {
126        0.0
127    }
128
129    fn spot_price(&self, base: &Token, quote: &Token) -> Result<f64, SimulationError> {
130        self.pool_params()
131            .validate()
132            .map_err(|err| map_quote_error(&QuoteError::Math(err)))?;
133        let token_in = address_from_bytes(base.address.as_ref())?;
134        let token_out = address_from_bytes(quote.address.as_ref())?;
135        if token_in == self.token_x && token_out == self.token_y {
136            return Ok(apply_fee_discount(
137                anchor_price(self.anchor_price_x96, base, quote)?,
138                self.fee_bid_x24,
139            ));
140        }
141        if token_in == self.token_y && token_out == self.token_x {
142            if self.anchor_price_x96.is_zero() {
143                return Ok(0.0);
144            }
145            return Ok(apply_fee_discount(
146                1.0 / anchor_price(self.anchor_price_x96, quote, base)?,
147                self.fee_ask_x24,
148            ));
149        }
150        Err(SimulationError::InvalidInput("invalid LunarBase token pair".to_owned(), None))
151    }
152
153    fn get_amount_out(
154        &self,
155        amount_in: BigUint,
156        token_in: &Token,
157        token_out: &Token,
158    ) -> Result<GetAmountOutResult, SimulationError> {
159        if amount_in == BigUint::ZERO {
160            return Ok(GetAmountOutResult::new(
161                BigUint::ZERO,
162                BigUint::from(DEFAULT_GAS),
163                Box::new(self.clone()),
164            ));
165        }
166
167        let (amount_out, next_state) = self
168            .quote_exact_in(
169                address_from_bytes(token_in.address.as_ref())?,
170                address_from_bytes(token_out.address.as_ref())?,
171                biguint_to_uint(&amount_in)?,
172            )
173            .map_err(|err| map_quote_error(&err))?;
174
175        Ok(GetAmountOutResult::new(
176            u256_to_biguint(amount_out),
177            BigUint::from(DEFAULT_GAS),
178            Box::new(next_state),
179        ))
180    }
181
182    fn get_limits(
183        &self,
184        sell_token: Bytes,
185        buy_token: Bytes,
186    ) -> Result<(BigUint, BigUint), SimulationError> {
187        let sell = address_from_bytes(sell_token.as_ref())?;
188        let buy = address_from_bytes(buy_token.as_ref())?;
189        if sell == self.token_x && buy == self.token_y {
190            return quote_limit(self, sell, buy, Direction::XToY);
191        }
192        if sell == self.token_y && buy == self.token_x {
193            return quote_limit(self, sell, buy, Direction::YToX);
194        }
195        Err(SimulationError::InvalidInput("invalid LunarBase token pair".to_owned(), None))
196    }
197
198    fn delta_transition(
199        &mut self,
200        delta: ProtocolStateDelta,
201        _tokens: &HashMap<Bytes, Token>,
202        _balances: &Balances,
203    ) -> Result<(), TransitionError> {
204        if let Some(name) = delta.deleted_attributes.iter().next() {
205            return Err(TransitionError::DecodeError(format!(
206                "LunarBase does not support deleted attributes: {name}"
207            )));
208        }
209
210        apply_delta(self, delta.updated_attributes)
211            .map_err(|err| TransitionError::DecodeError(format!("{err:?}")))?;
212        Ok(())
213    }
214
215    fn apply_block(&mut self, block: &BlockContext) -> bool {
216        let was_fresh = self.is_fresh();
217        self.head_block = block.number();
218        was_fresh != self.is_fresh()
219    }
220
221    fn query_pool_swap(&self, params: &QueryPoolSwapParams) -> Result<PoolSwap, SimulationError> {
222        let (price, tolerance, min_amount, max_amount, trade_price) = match params.swap_constraint()
223        {
224            SwapConstraint::TradeLimitPrice { limit, tolerance, min_amount_in, max_amount_in } => {
225                (limit, *tolerance, min_amount_in, max_amount_in, true)
226            }
227            SwapConstraint::PoolTargetPrice { target, tolerance, min_amount_in, max_amount_in } => {
228                (target, *tolerance, min_amount_in, max_amount_in, false)
229            }
230        };
231        if price.numerator == BigUint::ZERO ||
232            price.denominator == BigUint::ZERO ||
233            !tolerance.is_finite() ||
234            tolerance < 0.0 ||
235            matches!((min_amount, max_amount), (Some(min), Some(max)) if min > max)
236        {
237            return Err(SimulationError::InvalidInput(
238                "invalid LunarBase price query bounds".into(),
239                None,
240            ));
241        }
242        let token_in = params.token_in();
243        let token_out = params.token_out();
244        let (mut maximum, _) =
245            self.get_limits(token_in.address.clone(), token_out.address.clone())?;
246        if let Some(max) = max_amount {
247            maximum = maximum.min(max.clone());
248        }
249        let zero = || PoolSwap::new(BigUint::ZERO, BigUint::ZERO, Box::new(self.clone()), None);
250        if maximum == BigUint::ZERO {
251            return Ok(zero());
252        }
253        let direction = if token_in.address.as_ref() == self.token_x {
254            Direction::XToY
255        } else {
256            Direction::YToX
257        };
258        let (minimum, _) = quote_input_bounds(self, direction);
259        if maximum < minimum ||
260            min_amount
261                .as_ref()
262                .is_some_and(|min| maximum < *min)
263        {
264            return Ok(zero());
265        }
266        let (amount_out, next) = self
267            .quote_exact_in(
268                address_from_bytes(token_in.address.as_ref())?,
269                address_from_bytes(token_out.address.as_ref())?,
270                biguint_to_uint(&maximum)?,
271            )
272            .map_err(|err| map_quote_error(&err))?;
273        let amount_out = u256_to_biguint(amount_out);
274        let full_fill_allowed = if trade_price {
275            // Compare actual rounded output in raw token units, without f64/decimal loss.
276            &amount_out * &price.denominator >= &maximum * &price.numerator
277        } else {
278            // The post-swap marginal price includes the updated directional punishment.
279            let anchor_squared = u256_to_biguint(next.anchor_price_x96).pow(2);
280            let q192 = BigUint::from(1u32) << 192;
281            let (numerator, denominator, fee) = match direction {
282                Direction::XToY => (anchor_squared, q192, next.fee_bid_x24),
283                Direction::YToX => (q192, anchor_squared, next.fee_ask_x24),
284            };
285            let discount = if fee == MAX_U24 { 0 } else { (1u32 << 24) - fee };
286            numerator * discount * &price.denominator >=
287                denominator * (1u32 << 24) * &price.numerator
288        };
289        if full_fill_allowed {
290            // A liquidity/amount cap can prevent reaching the target even though every
291            // tradable amount remains above it. Return the capped fill instead of an error.
292            return Ok(PoolSwap::new(maximum, amount_out, Box::new(next), None));
293        }
294        // Keep the existing numerical search for an interior price crossing. Its search
295        // currently ignores optional amount bounds, so never return an out-of-bounds fill.
296        let result = crate::evm::query_pool_swap::query_pool_swap(self, params)?;
297        if result.amount_in() > &maximum ||
298            min_amount
299                .as_ref()
300                .is_some_and(|min| result.amount_in() < min)
301        {
302            return Err(SimulationError::InvalidInput(
303                "LunarBase price crossing outside amount bounds".into(),
304                None,
305            ));
306        }
307        // The numerical search can round distinct rational prices to the same f64.
308        if trade_price &&
309            result.amount_out() * &price.denominator < result.amount_in() * &price.numerator
310        {
311            return Err(SimulationError::InvalidInput(
312                "LunarBase fill below trade limit price".into(),
313                None,
314            ));
315        }
316        Ok(result)
317    }
318
319    fn clone_box(&self) -> Box<dyn ProtocolSim> {
320        Box::new(self.clone())
321    }
322
323    fn as_any(&self) -> &dyn Any {
324        self
325    }
326
327    fn as_any_mut(&mut self) -> &mut dyn Any {
328        self
329    }
330
331    fn eq(&self, other: &dyn ProtocolSim) -> bool {
332        other.as_any().downcast_ref::<Self>() == Some(self)
333    }
334}
335
336#[derive(Clone, Debug, PartialEq, Eq)]
337enum QuoteError {
338    Paused,
339    Stale { block_number: u64, latest_update_block: u64, block_delay: u64 },
340    InvalidTokenPair,
341    Rejected,
342    ReserveOverflow,
343    Math(MathError),
344}
345
346fn anchor_price(
347    anchor_price_x96: U256,
348    token_in: &Token,
349    token_out: &Token,
350) -> Result<f64, SimulationError> {
351    let decimals_adjustment = 10f64.powi(decimals_exponent(token_in.decimals, token_out.decimals)?);
352    Ok(sqrt_price_x96_to_price(anchor_price_x96) * decimals_adjustment)
353}
354
355fn apply_fee_discount(price: f64, fee_x24: u32) -> f64 {
356    if fee_x24 == MAX_U24 {
357        return 0.0;
358    }
359    price * (1.0 - fee_x24 as f64 / (1u64 << 24) as f64)
360}
361
362/// Invert both gross-output floors to bound all executable inputs. A positive gross
363/// quote stays positive unless the effective fee reaches the MAX_U24 sentinel.
364fn quote_input_bounds(state: &LunarBaseState, direction: Direction) -> (BigUint, BigUint) {
365    let (reserve_in, reserve_out) = match direction {
366        Direction::XToY => (state.reserve_x, state.reserve_y),
367        Direction::YToX => (state.reserve_y, state.reserve_x),
368    };
369    if reserve_out == 0 || state.anchor_price_x96.is_zero() {
370        return (BigUint::ZERO, BigUint::ZERO);
371    }
372    let anchor = u256_to_biguint(state.anchor_price_x96);
373    let q96 = BigUint::from(1u64) << 96;
374    let (numerator, denominator) = match direction {
375        Direction::XToY => (q96, anchor),
376        Direction::YToX => (anchor, q96),
377    };
378    // floor(x * d / n) <= r iff x <= ((r + 1) * n - 1) / d.
379    let intermediate = ((BigUint::from(reserve_out) + 1u32) * &numerator - 1u32) / &denominator;
380    let maximum = ((intermediate + 1u32) * &numerator - 1u32) / &denominator;
381    // Inverse ceilings find the first input with at least one gross output unit.
382    let intermediate = (&numerator + &denominator - 1u32) / &denominator;
383    let minimum = (intermediate * &numerator + &denominator - 1u32) / denominator;
384    (minimum, maximum.min(BigUint::from(MAX_U112 - reserve_in)))
385}
386
387fn quote_limit(
388    state: &LunarBaseState,
389    token_in: Address,
390    token_out: Address,
391    direction: Direction,
392) -> Result<(BigUint, BigUint), SimulationError> {
393    if state.paused || !state.is_fresh() {
394        return Ok((BigUint::ZERO, BigUint::ZERO));
395    }
396    state
397        .pool_params()
398        .validate()
399        .map_err(|err| map_quote_error(&QuoteError::Math(err)))?;
400    let (mut low, mut high) = quote_input_bounds(state, direction);
401    if high == BigUint::ZERO || low > high {
402        return Ok((BigUint::ZERO, BigUint::ZERO));
403    }
404    match state.quote_exact_in(token_in, token_out, biguint_to_uint(&high)?) {
405        Ok((output, _)) => return Ok((high, u256_to_biguint(output))),
406        Err(QuoteError::Rejected | QuoteError::ReserveOverflow) => {}
407        Err(err) => return Err(map_quote_error(&err)),
408    }
409    let mut low_output = match state.quote_exact_in(token_in, token_out, biguint_to_uint(&low)?) {
410        Ok((output, _)) => u256_to_biguint(output),
411        Err(QuoteError::Rejected | QuoteError::ReserveOverflow) => {
412            return Ok((BigUint::ZERO, BigUint::ZERO));
413        }
414        Err(err) => return Err(map_quote_error(&err)),
415    };
416    // Gross output and punishment are nondecreasing. Between the positive-output
417    // minimum and the reserve bounds, only fee saturation can stop execution.
418    // Keep low executable and high rejected; at most 112 bisections are needed.
419    while &high - &low > BigUint::from(1u32) {
420        let middle = (&low + &high) >> 1;
421        match state.quote_exact_in(token_in, token_out, biguint_to_uint(&middle)?) {
422            Ok((output, _)) => {
423                low = middle;
424                low_output = u256_to_biguint(output);
425            }
426            Err(QuoteError::Rejected | QuoteError::ReserveOverflow) => high = middle,
427            Err(err) => return Err(map_quote_error(&err)),
428        }
429    }
430    Ok((low, low_output))
431}
432
433fn address_from_bytes(value: &[u8]) -> Result<Address, SimulationError> {
434    value
435        .try_into()
436        .map_err(|_wrong_length| {
437            SimulationError::InvalidInput(
438                format!("expected 20-byte address, got {}", value.len()),
439                None,
440            )
441        })
442}
443
444fn u256_to_biguint(value: U256) -> BigUint {
445    BigUint::from_bytes_be(&value.to_be_bytes::<32>())
446}
447
448fn map_quote_error(err: &QuoteError) -> SimulationError {
449    SimulationError::InvalidInput(format!("LunarBase quote rejected: {err:?}"), None)
450}
451
452#[cfg(test)]
453mod tests {
454    use tycho_common::models::Chain;
455
456    use super::*;
457
458    fn addr(byte: u8) -> [u8; 20] {
459        [byte; 20]
460    }
461
462    fn token(address: Address, symbol: &str, decimals: u32) -> Token {
463        Token::new(
464            &Bytes::from(address.to_vec()),
465            symbol,
466            decimals,
467            100,
468            &[Some(100_000)],
469            Chain::Base,
470            100,
471        )
472    }
473
474    fn state() -> LunarBaseState {
475        LunarBaseState {
476            pool: addr(9),
477            token_x: addr(1),
478            token_y: addr(2),
479            anchor_price_x96: U256::from(1u128 << 96),
480            fee_ask_x24: 0,
481            fee_bid_x24: 0,
482            latest_update_block: 100,
483            reserve_x: 1_000_000,
484            reserve_y: 1_000_000,
485            max_punishment_x24: 0,
486            block_delay: 2,
487            paused: false,
488            head_block: 100,
489        }
490    }
491
492    #[test]
493    fn limits_use_output_liquidity_for_asymmetric_reserves() {
494        for x_to_y in [true, false] {
495            let mut state = state();
496            let (sell, buy) = if x_to_y {
497                state.reserve_x = 1;
498                state.reserve_y = 100;
499                (state.token_x, state.token_y)
500            } else {
501                state.reserve_x = 100;
502                state.reserve_y = 1;
503                (state.token_y, state.token_x)
504            };
505            assert_eq!(
506                state
507                    .get_limits(sell.into(), buy.into())
508                    .unwrap(),
509                (100u32.into(), 100u32.into())
510            );
511        }
512    }
513
514    #[test]
515    fn limits_find_the_last_fill_before_punishment_saturates() {
516        let mut state = state();
517        state.reserve_x = 100;
518        state.reserve_y = 100;
519        state.fee_bid_x24 = 1 << 23;
520        state.fee_ask_x24 = 1 << 23;
521        state.max_punishment_x24 = MAX_U24;
522        for (sell, buy) in [(state.token_x, state.token_y), (state.token_y, state.token_x)] {
523            let expected = (1..=200u64)
524                .rev()
525                .find_map(|input| {
526                    state
527                        .quote_exact_in(sell, buy, U256::from(input))
528                        .ok()
529                        .map(|(output, _)| (BigUint::from(input), u256_to_biguint(output)))
530                })
531                .unwrap();
532            assert_eq!(
533                state
534                    .get_limits(sell.into(), buy.into())
535                    .unwrap(),
536                expected
537            );
538        }
539    }
540
541    #[test]
542    fn limits_use_remaining_input_reserve_capacity_exactly() {
543        let mut state = state();
544        state.reserve_x = MAX_U112 - 7;
545        state.reserve_y = 100;
546        assert_eq!(
547            state
548                .get_limits(state.token_x.into(), state.token_y.into())
549                .unwrap(),
550            (7u32.into(), 7u32.into())
551        );
552    }
553
554    #[test]
555    fn price_queries_fill_flat_pools_in_both_directions() {
556        use tycho_common::simulation::protocol_sim::{Price, SwapConstraint};
557        for x_to_y in [true, false] {
558            for trade_price in [true, false] {
559                let state = state();
560                let (sell, buy) = if x_to_y {
561                    (state.token_x, state.token_y)
562                } else {
563                    (state.token_y, state.token_x)
564                };
565                for max in [None, Some(BigUint::from(123u32))] {
566                    let price = Price::new(999u32.into(), 1000u32.into());
567                    let constraint = if trade_price {
568                        SwapConstraint::TradeLimitPrice {
569                            limit: price,
570                            tolerance: 1e-6,
571                            min_amount_in: None,
572                            max_amount_in: max.clone(),
573                        }
574                    } else {
575                        SwapConstraint::PoolTargetPrice {
576                            target: price,
577                            tolerance: 1e-6,
578                            min_amount_in: None,
579                            max_amount_in: max.clone(),
580                        }
581                    };
582                    // Raw-unit prices do not depend on display decimals.
583                    let params = QueryPoolSwapParams::new(
584                        token(sell, "IN", 18),
585                        token(buy, "OUT", 6),
586                        constraint,
587                    );
588                    let swap = state.query_pool_swap(&params).unwrap();
589                    let expected = max.unwrap_or_else(|| 1_000_000u32.into());
590                    assert_eq!(swap.amount_in(), &expected);
591                    assert_eq!(swap.amount_out(), &expected);
592                }
593            }
594        }
595    }
596
597    #[test]
598    fn price_queries_distinguish_rounded_trade_and_post_swap_prices() {
599        use tycho_common::simulation::protocol_sim::{Price, SwapConstraint};
600        let mut state = state();
601        state.reserve_y = 2;
602        state.fee_bid_x24 = 1 << 22;
603        let x = token(state.token_x, "X", 18);
604        let y = token(state.token_y, "Y", 18);
605        let params = QueryPoolSwapParams::new(
606            x.clone(),
607            y.clone(),
608            SwapConstraint::TradeLimitPrice {
609                limit: Price::new(9u32.into(), 10u32.into()),
610                tolerance: 0.0,
611                min_amount_in: None,
612                max_amount_in: None,
613            },
614        );
615        let result = state.query_pool_swap(&params).unwrap();
616        assert_eq!(result.amount_in(), &BigUint::from(2u32));
617        assert_eq!(result.amount_out(), &BigUint::from(2u32));
618        let params = QueryPoolSwapParams::new(
619            x,
620            y,
621            SwapConstraint::PoolTargetPrice {
622                target: Price::new(9u32.into(), 10u32.into()),
623                tolerance: 0.0,
624                min_amount_in: None,
625                max_amount_in: None,
626            },
627        );
628        assert!(state.query_pool_swap(&params).is_err());
629    }
630
631    #[test]
632    fn price_queries_preserve_bounds_zero_capacity_and_exact_equality() {
633        use tycho_common::simulation::protocol_sim::{Price, SwapConstraint};
634        for trade in [true, false] {
635            for (min, max, expected) in [
636                (None, None, 1_000_000u32),
637                (Some(12u32), Some(20u32), 20),
638                (None, Some(0), 0),
639                (Some(1_000_001), None, 0),
640            ] {
641                let mut state = state();
642                let constraint = if trade {
643                    SwapConstraint::TradeLimitPrice {
644                        limit: Price::new(1u32.into(), 1u32.into()),
645                        tolerance: 0.0,
646                        min_amount_in: min.map(BigUint::from),
647                        max_amount_in: max.map(BigUint::from),
648                    }
649                } else {
650                    SwapConstraint::PoolTargetPrice {
651                        target: Price::new(1u32.into(), 1u32.into()),
652                        tolerance: 0.0,
653                        min_amount_in: min.map(BigUint::from),
654                        max_amount_in: max.map(BigUint::from),
655                    }
656                };
657                let params = QueryPoolSwapParams::new(
658                    token(state.token_x, "X", 18),
659                    token(state.token_y, "Y", 18),
660                    constraint,
661                );
662                assert_eq!(
663                    state
664                        .query_pool_swap(&params)
665                        .unwrap()
666                        .amount_in(),
667                    &BigUint::from(expected)
668                );
669                state.paused = true;
670                assert_eq!(
671                    state
672                        .query_pool_swap(&params)
673                        .unwrap()
674                        .amount_in(),
675                    &BigUint::ZERO
676                );
677            }
678        }
679        let state = rounding_boundary_state(true, 1);
680        let params = QueryPoolSwapParams::new(
681            token(state.token_x, "X", 18),
682            token(state.token_y, "Y", 18),
683            SwapConstraint::TradeLimitPrice {
684                limit: Price::new(1u32.into(), 100u32.into()),
685                tolerance: 0.0,
686                min_amount_in: None,
687                max_amount_in: Some(2u32.into()),
688            },
689        );
690        assert_eq!(
691            state
692                .query_pool_swap(&params)
693                .unwrap()
694                .amount_in(),
695            &BigUint::ZERO
696        );
697    }
698
699    #[test]
700    fn price_queries_keep_interior_punishment_search() {
701        use tycho_common::simulation::protocol_sim::{Price, SwapConstraint};
702        let mut state = state();
703        state.max_punishment_x24 = 1 << 20;
704        let x = token(state.token_x, "X", 18);
705        let y = token(state.token_y, "Y", 6);
706        for trade in [true, false] {
707            let constraint = if trade {
708                SwapConstraint::TradeLimitPrice {
709                    limit: Price::new(99u32.into(), 100u32.into()),
710                    tolerance: 1e-6,
711                    min_amount_in: Some(100u32.into()),
712                    max_amount_in: Some(900_000u32.into()),
713                }
714            } else {
715                SwapConstraint::PoolTargetPrice {
716                    target: Price::new(99u32.into(), 100u32.into()),
717                    tolerance: 1e-6,
718                    min_amount_in: Some(100u32.into()),
719                    max_amount_in: Some(900_000u32.into()),
720                }
721            };
722            let params = QueryPoolSwapParams::new(x.clone(), y.clone(), constraint);
723            let result = state.query_pool_swap(&params).unwrap();
724            assert!(result.amount_in() > &BigUint::from(100u32));
725            assert!(result.amount_in() < &BigUint::from(900_000u32));
726            assert_eq!(
727                &state
728                    .get_amount_out(result.amount_in().clone(), &x, &y)
729                    .unwrap()
730                    .amount,
731                result.amount_out()
732            );
733            if trade {
734                assert!(result.amount_out() * 100u32 >= result.amount_in() * 99u32);
735            }
736        }
737    }
738
739    #[test]
740    fn price_queries_reject_fallback_below_exact_trade_limit() {
741        use tycho_common::simulation::protocol_sim::{Price, SwapConstraint};
742        let mut state = state();
743        state.max_punishment_x24 = 1 << 20;
744        let scale = BigUint::from(10u32).pow(30);
745        let params = QueryPoolSwapParams::new(
746            token(state.token_x, "X", 18),
747            token(state.token_y, "Y", 18),
748            SwapConstraint::TradeLimitPrice {
749                limit: Price::new(&scale * 99u32 + 1u32, &scale * 100u32),
750                tolerance: 1e-6,
751                min_amount_in: None,
752                max_amount_in: None,
753            },
754        );
755        // The generic f64 search rounds this limit to 0.99 and returns 320000 -> 316800.
756        // That fill is strictly below the requested rational price.
757        assert!(matches!(
758            state.query_pool_swap(&params),
759            Err(SimulationError::InvalidInput(message, _))
760                if message == "LunarBase fill below trade limit price"
761        ));
762    }
763
764    #[test]
765    fn randomized_limits_are_executable_and_maximal() {
766        // Fixed-seed xorshift keeps property coverage reproducible without a new dependency.
767        let mut seed = 0x1445_cafe_7813_u64;
768        let mut random = || {
769            seed ^= seed << 13;
770            seed ^= seed >> 7;
771            seed ^= seed << 17;
772            seed
773        };
774        for case in 0..6000 {
775            let mut state = state();
776            state.anchor_price_x96 = U256::from(random() % 17) << 94usize;
777            state.reserve_x = (random() % 32) as u128;
778            state.reserve_y = (random() % 32) as u128;
779            state.fee_ask_x24 = (random() % (1 << 24)) as u32;
780            state.fee_bid_x24 = (random() % (1 << 24)) as u32;
781            state.max_punishment_x24 = (random() % (1 << 24)) as u32;
782            if case % 5 == 0 {
783                state.max_punishment_x24 = MAX_U24;
784            }
785            if case % 7 == 0 {
786                state.fee_bid_x24 = MAX_U24;
787            }
788            if case % 11 == 0 {
789                state.reserve_x = MAX_U112 - state.reserve_x;
790            }
791            if case % 13 == 0 {
792                state.reserve_y = MAX_U112 - state.reserve_y;
793            }
794            if case % 17 == 0 {
795                state.paused = true;
796            }
797            if case % 19 == 0 {
798                state.head_block = 102;
799            }
800            for (sell, buy) in [(state.token_x, state.token_y), (state.token_y, state.token_x)] {
801                let token_in = token(sell, "IN", 18);
802                let token_out = token(buy, "OUT", 18);
803                let (input, output) = state
804                    .get_limits(sell.into(), buy.into())
805                    .unwrap();
806                if input != BigUint::ZERO {
807                    let quoted = state
808                        .get_amount_out(input.clone(), &token_in, &token_out)
809                        .unwrap();
810                    assert_eq!(quoted.amount, output, "case={case}");
811                    assert_ne!(output, BigUint::ZERO, "case={case}");
812                    assert!(
813                        state
814                            .get_amount_out(&input + 1u32, &token_in, &token_out)
815                            .is_err(),
816                        "case={case}"
817                    );
818                } else {
819                    assert_eq!(output, BigUint::ZERO);
820                }
821                if state.reserve_x < 32 && state.reserve_y < 32 {
822                    // At these anchors all possible fills fit in 512 input units.
823                    // Exhaustive search independently checks zero limits as well as maxima.
824                    let expected = (1..=512u64)
825                        .rev()
826                        .find_map(|amount| {
827                            state
828                                .get_amount_out(BigUint::from(amount), &token_in, &token_out)
829                                .ok()
830                                .map(|quote| (BigUint::from(amount), quote.amount))
831                        })
832                        .unwrap_or((BigUint::ZERO, BigUint::ZERO));
833                    assert_eq!(
834                        (input, output),
835                        expected,
836                        "case={case}, sell={sell:?}, state={state:?}"
837                    );
838                }
839            }
840        }
841    }
842
843    #[test]
844    fn quotes_x_to_y_and_transitions_reserves() {
845        let state = state();
846        let (amount_out, next_state) = state
847            .quote_exact_in(state.token_x, state.token_y, U256::from(1_000u64))
848            .unwrap();
849
850        assert_eq!(amount_out, U256::from(1_000u64));
851        assert_eq!(next_state.reserve_x, 1_001_000);
852        assert_eq!(next_state.reserve_y, 999_000);
853        assert_eq!(next_state.anchor_price_x96, state.anchor_price_x96);
854        assert_eq!(next_state.head_block, state.head_block);
855    }
856
857    #[test]
858    fn zero_amount_out_returns_zero_without_transition() {
859        let state = state();
860        let token_x = token(state.token_x, "ETH", 18);
861        let token_y = token(state.token_y, "USDC", 6);
862
863        let quote = state
864            .get_amount_out(BigUint::ZERO, &token_x, &token_y)
865            .unwrap();
866        let next_state = quote
867            .new_state
868            .as_any()
869            .downcast_ref::<LunarBaseState>()
870            .unwrap();
871
872        assert_eq!(quote.amount, BigUint::ZERO);
873        assert_eq!(next_state, &state);
874    }
875
876    #[test]
877    fn spot_price_uses_anchor_price() {
878        let mut state = state();
879        state.anchor_price_x96 = lunarbase_pmm_math::price_to_sqrt_price_x96(2_000.0 / 1e12);
880        state.reserve_x = 1_000_000_000_000_000_000;
881        state.reserve_y = 1_000_000;
882
883        let token_x = token(state.token_x, "ETH", 18);
884        let token_y = token(state.token_y, "USDC", 6);
885
886        let price = state
887            .spot_price(&token_x, &token_y)
888            .unwrap();
889        let inverse = state
890            .spot_price(&token_y, &token_x)
891            .unwrap();
892
893        assert!((price - 2_000.0).abs() < 1e-6);
894        assert!((inverse - 0.0005).abs() < 1e-12);
895    }
896
897    #[test]
898    fn spot_price_applies_directional_base_fee() {
899        let mut state = state();
900        state.anchor_price_x96 = lunarbase_pmm_math::price_to_sqrt_price_x96(2_000.0 / 1e12);
901        state.fee_ask_x24 = (1u32 << 24) / 100;
902        state.fee_bid_x24 = (2 * (1u32 << 24)) / 100;
903
904        let token_x = token(state.token_x, "ETH", 18);
905        let token_y = token(state.token_y, "USDC", 6);
906
907        let price = state
908            .spot_price(&token_x, &token_y)
909            .unwrap();
910        let inverse = state
911            .spot_price(&token_y, &token_x)
912            .unwrap();
913
914        assert!((price - (2_000.0 * 0.98)).abs() < 1e-3);
915        assert!((inverse - (0.0005 * 0.99)).abs() < 1e-9);
916    }
917
918    #[test]
919    fn rejects_stale_state() {
920        let mut state = state();
921        state.head_block = 102;
922
923        let err = state
924            .quote_exact_in(state.token_x, state.token_y, U256::from(1_000u64))
925            .unwrap_err();
926
927        assert_eq!(
928            err,
929            QuoteError::Stale { block_number: 102, latest_update_block: 100, block_delay: 2 }
930        );
931    }
932
933    #[test]
934    fn unavailable_pools_have_zero_limits_but_still_reject_swaps() {
935        for (paused, head_block) in [(true, 100), (false, 102), (true, 103)] {
936            let mut state = state();
937            state.paused = paused;
938            state.head_block = head_block;
939            for (sell, buy) in [(state.token_x, state.token_y), (state.token_y, state.token_x)] {
940                assert_eq!(
941                    state
942                        .get_limits(Bytes::from(sell), Bytes::from(buy))
943                        .unwrap(),
944                    (BigUint::ZERO, BigUint::ZERO)
945                );
946                assert!(state
947                    .get_amount_out(
948                        BigUint::from(1_000u64),
949                        &token(sell, "IN", 18),
950                        &token(buy, "OUT", 18),
951                    )
952                    .is_err());
953            }
954            assert!(state
955                .get_limits(Bytes::from(addr(3)), Bytes::from(state.token_y))
956                .is_err());
957        }
958    }
959
960    #[test]
961    fn limits_recover_after_unpause_or_fresh_operator_update() {
962        let mut state = state();
963        let sell = Bytes::from(state.token_x);
964        let buy = Bytes::from(state.token_y);
965        let available_limits = state
966            .get_limits(sell.clone(), buy.clone())
967            .unwrap();
968        assert!(available_limits.0 > BigUint::ZERO);
969        assert!(available_limits.1 > BigUint::ZERO);
970
971        state.paused = true;
972        assert_eq!(
973            state
974                .get_limits(sell.clone(), buy.clone())
975                .unwrap()
976                .0,
977            BigUint::ZERO
978        );
979        apply_delta(&mut state, HashMap::from([("paused".to_owned(), Bytes::from([0u8]))]))
980            .unwrap();
981        assert_eq!(
982            state
983                .get_limits(sell.clone(), buy.clone())
984                .unwrap(),
985            available_limits
986        );
987
988        state.apply_block(&BlockContext::new(102, 0));
989        assert_eq!(
990            state
991                .get_limits(sell.clone(), buy.clone())
992                .unwrap()
993                .0,
994            BigUint::ZERO
995        );
996        apply_delta(
997            &mut state,
998            HashMap::from([("latest_update_block".to_owned(), Bytes::from(102u64))]),
999        )
1000        .unwrap();
1001        assert_eq!(state.get_limits(sell, buy).unwrap(), available_limits);
1002    }
1003
1004    #[test]
1005    fn charges_immediate_punishment_and_accumulates_only_the_traded_direction() {
1006        let mut state = state();
1007        state.max_punishment_x24 = 16_778;
1008        let amount = U256::from(100_000u64);
1009
1010        let (first_out, first) = state
1011            .quote_exact_in(state.token_x, state.token_y, amount)
1012            .unwrap();
1013        assert_eq!(first_out, U256::from(99_995u64));
1014        assert_eq!((first.reserve_x, first.reserve_y), (1_100_000, 900_000));
1015        assert_eq!((first.fee_ask_x24, first.fee_bid_x24), (0, 839));
1016        assert_eq!(first.anchor_price_x96, state.anchor_price_x96);
1017        assert_eq!(first.latest_update_block, state.latest_update_block);
1018
1019        let (second_out, second) = first
1020            .quote_exact_in(state.token_x, state.token_y, amount)
1021            .unwrap();
1022        assert_eq!(second_out, U256::from(99_990u64));
1023        assert_eq!((second.fee_ask_x24, second.fee_bid_x24), (0, 1_678));
1024
1025        let (reverse_out, reverse) = second
1026            .quote_exact_in(state.token_y, state.token_x, amount)
1027            .unwrap();
1028        assert_eq!(reverse_out, U256::from(99_995u64));
1029        assert_eq!((reverse.fee_ask_x24, reverse.fee_bid_x24), (839, 1_678));
1030        assert_eq!((state.fee_ask_x24, state.fee_bid_x24), (0, 0));
1031    }
1032
1033    #[test]
1034    fn operator_update_replaces_accumulated_fees_and_restores_freshness() {
1035        let mut initial = state();
1036        initial.max_punishment_x24 = 16_778;
1037        let (_, mut state) = initial
1038            .quote_exact_in(initial.token_x, initial.token_y, U256::from(100_000u64))
1039            .unwrap();
1040        state.apply_block(&BlockContext::new(102, 0));
1041        let reserves = (state.reserve_x, state.reserve_y);
1042        state
1043            .delta_transition(
1044                ProtocolStateDelta {
1045                    updated_attributes: HashMap::from([
1046                        (
1047                            "anchor_price_x96".to_owned(),
1048                            Bytes::from(
1049                                (U256::from(2u64) << 96usize).to_be_bytes::<32>()[12..].to_vec(),
1050                            ),
1051                        ),
1052                        ("fee_ask_x24".to_owned(), Bytes::from(11u32)),
1053                        ("fee_bid_x24".to_owned(), Bytes::from(22u32)),
1054                        ("latest_update_block".to_owned(), Bytes::from(102u64)),
1055                        ("block_number".to_owned(), Bytes::from(102u64)),
1056                    ]),
1057                    ..Default::default()
1058                },
1059                &HashMap::new(),
1060                &Balances::default(),
1061            )
1062            .unwrap();
1063
1064        assert!(state.is_fresh());
1065        assert_eq!((state.fee_ask_x24, state.fee_bid_x24), (11, 22));
1066        assert_eq!(state.max_punishment_x24, 16_778);
1067        assert_eq!((state.reserve_x, state.reserve_y), reserves);
1068    }
1069
1070    #[test]
1071    fn full_fee_and_punishment_saturation_reject_without_changing_state() {
1072        let mut state = state();
1073        state.fee_bid_x24 = MAX_U24;
1074        let before = state.clone();
1075        assert_eq!(
1076            state.quote_exact_in(state.token_x, state.token_y, U256::from(1u64)),
1077            Err(QuoteError::Rejected)
1078        );
1079        assert_eq!(state, before);
1080        assert_eq!(
1081            state
1082                .spot_price(&token(state.token_x, "X", 18), &token(state.token_y, "Y", 18))
1083                .unwrap(),
1084            0.0
1085        );
1086
1087        state.fee_bid_x24 = MAX_U24 - 1;
1088        state.max_punishment_x24 = 1;
1089        let before = state.clone();
1090        assert_eq!(
1091            state.quote_exact_in(state.token_x, state.token_y, U256::from(1u64)),
1092            Err(QuoteError::Rejected)
1093        );
1094        assert_eq!(state, before);
1095    }
1096
1097    #[test]
1098    fn max_punishment_sentinel_uses_conceptual_one_hundred_percent() {
1099        let mut state = state();
1100        state.reserve_x = 0;
1101        state.reserve_y = 1_000_000;
1102        state.max_punishment_x24 = MAX_U24;
1103        assert_eq!(
1104            state.quote_exact_in(state.token_x, state.token_y, U256::from(1_000_000u64)),
1105            Err(QuoteError::Rejected)
1106        );
1107    }
1108
1109    #[test]
1110    fn rejects_uint112_reserve_overflow_and_invalid_math_state() {
1111        let mut state = state();
1112        state.reserve_x = lunarbase_pmm_math::MAX_U112;
1113        let before = state.clone();
1114        assert_eq!(
1115            state.quote_exact_in(state.token_x, state.token_y, U256::from(1u64)),
1116            Err(QuoteError::ReserveOverflow)
1117        );
1118        assert_eq!(state, before);
1119
1120        state.max_punishment_x24 = 1 << 24;
1121        assert_eq!(
1122            state.quote_exact_in(state.token_x, state.token_y, U256::from(1u64)),
1123            Err(QuoteError::Math(MathError::MaxPunishmentExceedsUint24))
1124        );
1125    }
1126
1127    #[test]
1128    fn quotes_anchor_above_uint128_and_checks_gross_liquidity() {
1129        let mut state = state();
1130        state.anchor_price_x96 = U256::from(1u64) << 129usize;
1131        state.reserve_y = 1u128 << 80;
1132        let expected_gross = U256::from(1u64) << 66usize;
1133        let (out, next) = state
1134            .quote_exact_in(state.token_x, state.token_y, U256::from(1u64))
1135            .unwrap();
1136        assert_eq!(out, expected_gross);
1137        assert_eq!(next.reserve_y, state.reserve_y - (1u128 << 66));
1138        state.reserve_y = (1u128 << 66) - 1;
1139        state.fee_bid_x24 = (1 << 24) / 2;
1140        assert_eq!(
1141            state.quote_exact_in(state.token_x, state.token_y, U256::from(1u64)),
1142            Err(QuoteError::Rejected)
1143        );
1144    }
1145
1146    #[test]
1147    fn execution_block_hook_expires_idle_pools_and_handles_reorgs() {
1148        let mut state = state();
1149        assert!(!state.apply_block(&BlockContext::new(101, 0)));
1150        assert_eq!(state.head_block, 101);
1151        assert!(state.is_fresh());
1152
1153        assert!(state.apply_block(&BlockContext::new(102, 0)));
1154        assert!(!state.is_fresh());
1155        assert!(!state.apply_block(&BlockContext::new(102, 0)));
1156        assert!(!state.apply_block(&BlockContext::new(103, 0)));
1157        assert!(matches!(
1158            state.quote_exact_in(state.token_x, state.token_y, U256::from(1u64)),
1159            Err(QuoteError::Stale { block_number: 103, .. })
1160        ));
1161
1162        assert!(state.apply_block(&BlockContext::new(101, 0)));
1163        assert!(state.is_fresh());
1164    }
1165
1166    #[test]
1167    fn zero_anchor_never_returns_infinite_spot_price() {
1168        let mut state = state();
1169        state.anchor_price_x96 = U256::ZERO;
1170        let x = token(state.token_x, "X", 18);
1171        let y = token(state.token_y, "Y", 18);
1172        assert_eq!(state.spot_price(&x, &y).unwrap(), 0.0);
1173        assert_eq!(state.spot_price(&y, &x).unwrap(), 0.0);
1174        assert_eq!(
1175            state.quote_exact_in(state.token_y, state.token_x, U256::from(1u64)),
1176            Err(QuoteError::Rejected)
1177        );
1178    }
1179
1180    #[test]
1181    fn limits_allow_both_directions_with_an_empty_input_reserve() {
1182        let mut state = state();
1183        state.anchor_price_x96 = U256::from(2u64) << 96usize;
1184        state.max_punishment_x24 = 16_778;
1185
1186        state.reserve_x = 0;
1187        state.reserve_y = 4_000_000;
1188        let (input, output) = state
1189            .get_limits(Bytes::from(state.token_x), Bytes::from(state.token_y))
1190            .unwrap();
1191        assert_eq!(input, BigUint::from(1_000_000u64));
1192        assert_eq!(output, BigUint::from(3_996_000u64));
1193
1194        state.reserve_x = 1_000_000;
1195        state.reserve_y = 0;
1196        let (input, output) = state
1197            .get_limits(Bytes::from(state.token_y), Bytes::from(state.token_x))
1198            .unwrap();
1199        // The last three input units still round down to the same gross output.
1200        assert_eq!(input, BigUint::from(4_000_003u64));
1201        assert_eq!(output, BigUint::from(999_000u64));
1202    }
1203
1204    #[test]
1205    fn limits_recover_minimum_trade_for_empty_and_small_input_reserves() {
1206        for x_to_y in [true, false] {
1207            // Reserve 1 starts below the minimum; reserve 4 halves 8 -> 4 -> 2,
1208            // skipping the only valid input (3). Reserve 3 already finds it.
1209            for reserve_in in [0, 1, 3, 4] {
1210                let state = rounding_boundary_state(x_to_y, reserve_in);
1211                let (sell, buy) = if x_to_y {
1212                    (state.token_x, state.token_y)
1213                } else {
1214                    (state.token_y, state.token_x)
1215                };
1216                assert_eq!(
1217                    state
1218                        .quote_exact_in(sell, buy, U256::from(3u64))
1219                        .unwrap()
1220                        .0,
1221                    U256::from(1u64)
1222                );
1223                assert_eq!(
1224                    state
1225                        .get_limits(Bytes::from(sell), Bytes::from(buy))
1226                        .unwrap(),
1227                    (BigUint::from(3u64), BigUint::from(1u64)),
1228                    "x_to_y={x_to_y}, reserve_in={reserve_in}"
1229                );
1230            }
1231        }
1232    }
1233
1234    fn rounding_boundary_state(x_to_y: bool, reserve_in: u128) -> LunarBaseState {
1235        let mut state = state();
1236        let q96 = U256::from(1u64) << 96usize;
1237        if x_to_y {
1238            state.anchor_price_x96 = q96 * U256::from(3u64) / U256::from(4u64);
1239            state.reserve_x = reserve_in;
1240            state.reserve_y = 1;
1241        } else {
1242            state.anchor_price_x96 = q96 * U256::from(4u64) / U256::from(3u64);
1243            state.reserve_x = 1;
1244            state.reserve_y = reserve_in;
1245        }
1246        state
1247    }
1248
1249    #[test]
1250    fn minimum_trade_limits_apply_fees_and_punishment() {
1251        for x_to_y in [true, false] {
1252            for (fee, punishment, available) in
1253                [(1 << 22, 1 << 22, true), (MAX_U24, 0, false), (MAX_U24 - 1, MAX_U24, false)]
1254            {
1255                let mut state = rounding_boundary_state(x_to_y, 1);
1256                state.fee_ask_x24 = fee;
1257                state.fee_bid_x24 = fee;
1258                state.max_punishment_x24 = punishment;
1259                let (sell, buy) = if x_to_y {
1260                    (state.token_x, state.token_y)
1261                } else {
1262                    (state.token_y, state.token_x)
1263                };
1264                let expected = if available {
1265                    (BigUint::from(3u64), BigUint::from(1u64))
1266                } else {
1267                    (BigUint::ZERO, BigUint::ZERO)
1268                };
1269                assert_eq!(
1270                    state
1271                        .get_limits(Bytes::from(sell), Bytes::from(buy))
1272                        .unwrap(),
1273                    expected
1274                );
1275            }
1276        }
1277    }
1278
1279    #[test]
1280    fn minimum_trade_limits_preserve_unavailable_states_and_math_errors() {
1281        for x_to_y in [true, false] {
1282            for case in [
1283                "paused",
1284                "stale",
1285                "no liquidity",
1286                "reserve overflow",
1287                "zero anchor",
1288                "minimum exceeds capacity",
1289                "output quantum exceeds liquidity",
1290                "invalid math",
1291            ] {
1292                let mut state = rounding_boundary_state(x_to_y, 1);
1293                let (sell, buy) = if x_to_y {
1294                    (state.token_x, state.token_y)
1295                } else {
1296                    (state.token_y, state.token_x)
1297                };
1298                match case {
1299                    "paused" => state.paused = true,
1300                    "stale" => state.head_block = 102,
1301                    "no liquidity" if x_to_y => state.reserve_y = 0,
1302                    "no liquidity" => state.reserve_x = 0,
1303                    "reserve overflow" if x_to_y => state.reserve_x = MAX_U112 - 2,
1304                    "reserve overflow" => state.reserve_y = MAX_U112 - 2,
1305                    "zero anchor" => state.anchor_price_x96 = U256::ZERO,
1306                    "minimum exceeds capacity" => {
1307                        state.anchor_price_x96 =
1308                            if x_to_y { U256::from(1u64) } else { U256::from(1u64) << 159usize };
1309                    }
1310                    "output quantum exceeds liquidity" => {
1311                        state.anchor_price_x96 =
1312                            U256::from(1u64) << if x_to_y { 97usize } else { 95usize };
1313                    }
1314                    "invalid math" => state.max_punishment_x24 = 1 << 24,
1315                    #[expect(
1316                        clippy::unreachable,
1317                        reason = "the test cases only name the cases above"
1318                    )]
1319                    _ => unreachable!(),
1320                }
1321                let limits = state.get_limits(Bytes::from(sell), Bytes::from(buy));
1322                if case == "invalid math" {
1323                    assert!(limits.is_err(), "x_to_y={x_to_y}, {case}");
1324                } else {
1325                    assert_eq!(
1326                        limits.unwrap(),
1327                        (BigUint::ZERO, BigUint::ZERO),
1328                        "x_to_y={x_to_y}, {case}"
1329                    );
1330                }
1331            }
1332        }
1333    }
1334
1335    #[test]
1336    fn empty_input_reserve_limit_inverts_both_rounding_steps() {
1337        for x_to_y in [true, false] {
1338            let mut state = state();
1339            let (sell, buy) = if x_to_y {
1340                state.anchor_price_x96 = (U256::from(3u64) << 96usize) / U256::from(4u64);
1341                state.reserve_x = 0;
1342                state.reserve_y = 1;
1343                (state.token_x, state.token_y)
1344            } else {
1345                state.anchor_price_x96 = (U256::from(3u64) << 96usize) / U256::from(2u64);
1346                state.reserve_x = 1;
1347                state.reserve_y = 0;
1348                (state.token_y, state.token_x)
1349            };
1350            assert_eq!(
1351                state
1352                    .quote_exact_in(sell, buy, U256::from(3u64))
1353                    .unwrap()
1354                    .0,
1355                U256::from(1u64)
1356            );
1357            let (input, output) = state
1358                .get_limits(Bytes::from(sell), Bytes::from(buy))
1359                .unwrap();
1360            assert_eq!(input, BigUint::from(if x_to_y { 3u64 } else { 4u64 }));
1361            assert_eq!(output, BigUint::from(1u64));
1362            assert_eq!(
1363                state.quote_exact_in(sell, buy, biguint_to_uint(&(input + 1u32)).unwrap()),
1364                Err(QuoteError::Rejected)
1365            );
1366        }
1367    }
1368
1369    #[test]
1370    fn empty_input_reserve_limits_match_exhaustive_small_quotes() {
1371        for anchor_quarters in 1..=16u64 {
1372            for reserve_out in 1..=8u128 {
1373                for x_to_y in [true, false] {
1374                    let mut state = state();
1375                    state.anchor_price_x96 = U256::from(anchor_quarters) << 94usize;
1376                    let (sell, buy) = if x_to_y {
1377                        state.reserve_x = 0;
1378                        state.reserve_y = reserve_out;
1379                        (state.token_x, state.token_y)
1380                    } else {
1381                        state.reserve_x = reserve_out;
1382                        state.reserve_y = 0;
1383                        (state.token_y, state.token_x)
1384                    };
1385                    // These prices/reserves exhaust output liquidity below 256 input units.
1386                    let expected = (1..=256u64)
1387                        .rev()
1388                        .find_map(|input| {
1389                            state
1390                                .quote_exact_in(sell, buy, U256::from(input))
1391                                .ok()
1392                                .map(|(output, _)| (BigUint::from(input), u256_to_biguint(output)))
1393                        })
1394                        .unwrap_or((BigUint::ZERO, BigUint::ZERO));
1395                    assert_eq!(
1396                        state.get_limits(Bytes::from(sell), Bytes::from(buy)).unwrap(),
1397                        expected,
1398                        "anchor_quarters={anchor_quarters}, reserve_out={reserve_out}, x_to_y={x_to_y}"
1399                    );
1400                }
1401            }
1402        }
1403    }
1404
1405    #[test]
1406    fn empty_input_reserve_limit_respects_uint112_capacity() {
1407        let mut state = state();
1408        state.anchor_price_x96 = U256::from(2u64) << 96usize;
1409        state.reserve_x = MAX_U112;
1410        state.reserve_y = 0;
1411        let (input, output) = state
1412            .get_limits(Bytes::from(state.token_y), Bytes::from(state.token_x))
1413            .unwrap();
1414        assert_eq!(input, BigUint::from(MAX_U112));
1415        assert_eq!(output, BigUint::from(MAX_U112 / 4));
1416    }
1417
1418    #[test]
1419    fn legacy_caller_policy_does_not_change_partner_quotes() {
1420        let mut state = state();
1421        state.max_punishment_x24 = 16_778;
1422        state.fee_bid_x24 = (1 << 24) / 4;
1423        let x = token(state.token_x, "X", 18);
1424        let y = token(state.token_y, "Y", 18);
1425        let amount = U256::from(100_000u64);
1426        let expected = state
1427            .quote_exact_in(state.token_x, state.token_y, amount)
1428            .unwrap();
1429        assert_eq!(expected.0, U256::from(74_995u64));
1430        assert_eq!(state.spot_price(&x, &y).unwrap(), 0.75);
1431
1432        apply_delta(
1433            &mut state,
1434            HashMap::from([
1435                ("quote_caller_whitelisted".to_owned(), Bytes::from([0u8])),
1436                ("blacklist_fee_multiplier".to_owned(), Bytes::from(U256::MAX.to_be_bytes::<32>())),
1437            ]),
1438        )
1439        .unwrap();
1440        assert_eq!(
1441            state
1442                .quote_exact_in(state.token_x, state.token_y, amount)
1443                .unwrap(),
1444            expected
1445        );
1446        assert_eq!(state.spot_price(&x, &y).unwrap(), 0.75);
1447    }
1448
1449    #[test]
1450    fn matches_base_partner_quotes_from_execution_fixture() {
1451        let capture: serde_json::Value = serde_json::from_str(include_str!(concat!(
1452            env!("CARGO_MANIFEST_DIR"),
1453            "/../../protocols/substreams/base-lunarbase/bootstrap/base-execution.json"
1454        )))
1455        .unwrap();
1456        let mut state = state();
1457        let address = |name: &str| {
1458            address_from_bytes(
1459                &hex::decode(
1460                    capture[name]
1461                        .as_str()
1462                        .unwrap()
1463                        .trim_start_matches("0x"),
1464                )
1465                .unwrap(),
1466            )
1467            .unwrap()
1468        };
1469        state.pool = address("pool");
1470        state.token_x = address("token_x");
1471        state.token_y = address("token_y");
1472        let snapshot = &capture["execution_state"];
1473        apply_delta(
1474            &mut state,
1475            snapshot["attributes"]
1476                .as_object()
1477                .unwrap()
1478                .iter()
1479                .map(|(name, value)| {
1480                    (
1481                        name.clone(),
1482                        value
1483                            .as_str()
1484                            .unwrap()
1485                            .parse::<Bytes>()
1486                            .unwrap(),
1487                    )
1488                })
1489                .collect(),
1490        )
1491        .unwrap();
1492        state.head_block = snapshot["block_number"]
1493            .as_u64()
1494            .unwrap();
1495        let mut directions = [0; 2];
1496        for quote in capture["observed_quotes"]
1497            .as_array()
1498            .unwrap()
1499        {
1500            let forward = match quote["signature"].as_str().unwrap() {
1501                "quoteXToY(uint256)" => true,
1502                "quoteYToX(uint256)" => false,
1503                other => panic!("unexpected quote: {other}"),
1504            };
1505            directions[usize::from(forward)] += 1;
1506            let amount = U256::from_str_radix(quote["arguments"][0].as_str().unwrap(), 10).unwrap();
1507            let expected: Vec<U256> = quote["result"]
1508                .as_array()
1509                .unwrap()
1510                .iter()
1511                .map(|value| U256::from_str_radix(value.as_str().unwrap(), 10).unwrap())
1512                .collect();
1513            let (token_in, token_out) = if forward {
1514                (state.token_x, state.token_y)
1515            } else {
1516                (state.token_y, state.token_x)
1517            };
1518            let (output, next) = state
1519                .quote_exact_in(token_in, token_out, amount)
1520                .unwrap();
1521            assert!(output > U256::ZERO);
1522            assert_eq!(output, expected[0]);
1523            assert_eq!(next.anchor_price_x96, expected[1]);
1524            let gross = if forward {
1525                state.reserve_y - next.reserve_y
1526            } else {
1527                state.reserve_x - next.reserve_x
1528            };
1529            assert_eq!(U256::from(gross) - output, expected[2]);
1530        }
1531        assert_eq!(directions, [3, 3]);
1532    }
1533
1534    #[test]
1535    fn derives_partner_quotes_from_base_capture_at_block_51297469() {
1536        // Recorded eth_call results at Base block 51,297,469, pool
1537        // 0x0000efc4ec03a7c47d3a38a9be7ff1d52dd01b99, with `from` set to
1538        // TychoRouter 0xAbA5B53b03eAfaD1C5fc8BD5Fc765fC85Bb3de67.
1539        // The historical caller paid multiplier 100 at this block.
1540        // Normalize the recorded fee (floor(gross * fee_x24 / Q24) * 100) to
1541        // multiplier one. This checks partner math, not historical caller parity.
1542        let mut state = state();
1543        state.pool =
1544            address_from_bytes(&hex::decode("0000efc4ec03a7c47d3a38a9be7ff1d52dd01b99").unwrap())
1545                .unwrap();
1546        state.token_x = [0; 20];
1547        state.token_y =
1548            address_from_bytes(&hex::decode("833589fcd6edb6e08f4c7c32d4f71b54bda02913").unwrap())
1549                .unwrap();
1550        state.anchor_price_x96 = U256::from(3_971_029_714_873_270_134_636_544u128);
1551        state.fee_ask_x24 = 1_835;
1552        state.fee_bid_x24 = 8_475;
1553        state.latest_update_block = 51_297_469;
1554        state.head_block = 51_297_469;
1555        state.max_punishment_x24 = 160_000;
1556        state.block_delay = 3;
1557        state.reserve_x = 9_683_337_552_179_635_497;
1558        state.reserve_y = 23_231_346_797;
1559
1560        // Direction, input, observed net output, observed output-token fee.
1561        let quotes = [
1562            (true, 1_000_000_000_000_000u128, 2_385_158u128, 127_000u128),
1563            (true, 100_000_000_000_000_000, 237_258_990, 13_956_900),
1564            (true, 1_000_000_000_000_000_000, 2_258_700_200, 253_458_700),
1565            (false, 1_000_000, 393_700_695_234_017, 4_363_296_513_600),
1566            (false, 100_000_000, 39_291_060_402_299_481, 515_338_772_582_000),
1567            (false, 1_000_000_000, 385_726_231_079_417_225, 12_337_760_669_557_200),
1568        ];
1569        for (x_to_y, input, observed_out, observed_fee) in quotes {
1570            assert_eq!(observed_fee % 100, 0);
1571            let expected_fee = observed_fee / 100;
1572            let expected_out = observed_out + observed_fee - expected_fee;
1573            let (token_in, token_out) = if x_to_y {
1574                (state.token_x, state.token_y)
1575            } else {
1576                (state.token_y, state.token_x)
1577            };
1578            let (out, next) = state
1579                .quote_exact_in(token_in, token_out, U256::from(input))
1580                .unwrap();
1581            assert_eq!(out, U256::from(expected_out), "direction={x_to_y}, input={input}");
1582            let gross = if x_to_y {
1583                state.reserve_y - next.reserve_y
1584            } else {
1585                state.reserve_x - next.reserve_x
1586            };
1587            assert_eq!(gross - expected_out, expected_fee);
1588            assert_eq!(next.anchor_price_x96, state.anchor_price_x96);
1589        }
1590    }
1591
1592    #[test]
1593    fn matches_bsc_router_quotes_observed_at_block_121835898() {
1594        // Recorded eth_call results at BSC block 121,835,898, pool
1595        // 0x00007904d186680c709519e71f4dc3e2df8f1b99, with `from` set to
1596        // 0x7f3d12bbafb8955e51b3ab9588b34c8ad95bda4e. Both tokens use 18
1597        // decimals; the observed caller multiplier was 1.
1598        let mut state = state();
1599        state.pool =
1600            address_from_bytes(&hex::decode("00007904d186680c709519e71f4dc3e2df8f1b99").unwrap())
1601                .unwrap();
1602        state.token_x = [0; 20];
1603        state.token_y =
1604            address_from_bytes(&hex::decode("55d398326f99059ff775485246999027b3197955").unwrap())
1605                .unwrap();
1606        state.anchor_price_x96 = U256::from(2_129_209_909_442_387_799_622_216_056_832u128);
1607        state.fee_ask_x24 = 3_092;
1608        state.fee_bid_x24 = 552;
1609        state.latest_update_block = 121_835_890;
1610        state.head_block = 121_835_898;
1611        state.max_punishment_x24 = 125_000;
1612        state.block_delay = 25;
1613        state.reserve_x = 40_982_882_360_761_506_608;
1614        state.reserve_y = 37_489_098_599_819_531_485_143;
1615
1616        // Direction, input, observed net output, observed output-token fee.
1617        let quotes: [(bool, u128, u128, u128); 6] = [
1618            (true, 1_000_000_000_000_000, 722_209_919_138_098_675, 23_848_861_901_283),
1619            (true, 100_000_000_000_000_000, 72_220_419_368_930_290_024, 2_957_431_069_707_870),
1620            (true, 1_000_000_000_000_000_000, 722_152_061_971_320_131_445, 81_706_028_679_847_714),
1621            (false, 1_000_000_000_000_000_000, 1_384_337_907_652_450, 255_342_216_199),
1622            (false, 100_000_000_000_000_000_000, 138_432_263_993_751_885, 27_060_993_113_036),
1623            (false, 1_000_000_000_000_000_000_000, 1_384_184_240_164_873_034, 409_009_703_776_182),
1624        ];
1625        for (x_to_y, input, expected_out, expected_fee) in quotes {
1626            let (token_in, token_out) = if x_to_y {
1627                (state.token_x, state.token_y)
1628            } else {
1629                (state.token_y, state.token_x)
1630            };
1631            let (out, next) = state
1632                .quote_exact_in(token_in, token_out, U256::from(input))
1633                .unwrap();
1634            assert_eq!(out, U256::from(expected_out), "direction={x_to_y}, input={input}");
1635            let gross = if x_to_y {
1636                state.reserve_y - next.reserve_y
1637            } else {
1638                state.reserve_x - next.reserve_x
1639            };
1640            assert_eq!(gross - expected_out, expected_fee);
1641            assert_eq!(next.anchor_price_x96, state.anchor_price_x96);
1642        }
1643    }
1644}