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::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_u256(&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_u256(&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_u256(&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_u256(&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_u256(&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 biguint_to_u256(value: &BigUint) -> Result<U256, SimulationError> {
445    let bytes = value.to_bytes_be();
446    if bytes.len() > 32 {
447        return Err(SimulationError::InvalidInput("amount_in exceeds uint256".to_owned(), None));
448    }
449    Ok(U256::from_be_slice(&bytes))
450}
451
452fn u256_to_biguint(value: U256) -> BigUint {
453    BigUint::from_bytes_be(&value.to_be_bytes::<32>())
454}
455
456fn map_quote_error(err: &QuoteError) -> SimulationError {
457    SimulationError::InvalidInput(format!("LunarBase quote rejected: {err:?}"), None)
458}
459
460#[cfg(test)]
461mod tests {
462    use tycho_common::models::Chain;
463
464    use super::*;
465
466    fn addr(byte: u8) -> [u8; 20] {
467        [byte; 20]
468    }
469
470    fn token(address: Address, symbol: &str, decimals: u32) -> Token {
471        Token::new(
472            &Bytes::from(address.to_vec()),
473            symbol,
474            decimals,
475            100,
476            &[Some(100_000)],
477            Chain::Base,
478            100,
479        )
480    }
481
482    fn state() -> LunarBaseState {
483        LunarBaseState {
484            pool: addr(9),
485            token_x: addr(1),
486            token_y: addr(2),
487            anchor_price_x96: U256::from(1u128 << 96),
488            fee_ask_x24: 0,
489            fee_bid_x24: 0,
490            latest_update_block: 100,
491            reserve_x: 1_000_000,
492            reserve_y: 1_000_000,
493            max_punishment_x24: 0,
494            block_delay: 2,
495            paused: false,
496            head_block: 100,
497        }
498    }
499
500    #[test]
501    fn limits_use_output_liquidity_for_asymmetric_reserves() {
502        for x_to_y in [true, false] {
503            let mut state = state();
504            let (sell, buy) = if x_to_y {
505                state.reserve_x = 1;
506                state.reserve_y = 100;
507                (state.token_x, state.token_y)
508            } else {
509                state.reserve_x = 100;
510                state.reserve_y = 1;
511                (state.token_y, state.token_x)
512            };
513            assert_eq!(
514                state
515                    .get_limits(sell.into(), buy.into())
516                    .unwrap(),
517                (100u32.into(), 100u32.into())
518            );
519        }
520    }
521
522    #[test]
523    fn limits_find_the_last_fill_before_punishment_saturates() {
524        let mut state = state();
525        state.reserve_x = 100;
526        state.reserve_y = 100;
527        state.fee_bid_x24 = 1 << 23;
528        state.fee_ask_x24 = 1 << 23;
529        state.max_punishment_x24 = MAX_U24;
530        for (sell, buy) in [(state.token_x, state.token_y), (state.token_y, state.token_x)] {
531            let expected = (1..=200u64)
532                .rev()
533                .find_map(|input| {
534                    state
535                        .quote_exact_in(sell, buy, U256::from(input))
536                        .ok()
537                        .map(|(output, _)| (BigUint::from(input), u256_to_biguint(output)))
538                })
539                .unwrap();
540            assert_eq!(
541                state
542                    .get_limits(sell.into(), buy.into())
543                    .unwrap(),
544                expected
545            );
546        }
547    }
548
549    #[test]
550    fn limits_use_remaining_input_reserve_capacity_exactly() {
551        let mut state = state();
552        state.reserve_x = MAX_U112 - 7;
553        state.reserve_y = 100;
554        assert_eq!(
555            state
556                .get_limits(state.token_x.into(), state.token_y.into())
557                .unwrap(),
558            (7u32.into(), 7u32.into())
559        );
560    }
561
562    #[test]
563    fn price_queries_fill_flat_pools_in_both_directions() {
564        use tycho_common::simulation::protocol_sim::{Price, SwapConstraint};
565        for x_to_y in [true, false] {
566            for trade_price in [true, false] {
567                let state = state();
568                let (sell, buy) = if x_to_y {
569                    (state.token_x, state.token_y)
570                } else {
571                    (state.token_y, state.token_x)
572                };
573                for max in [None, Some(BigUint::from(123u32))] {
574                    let price = Price::new(999u32.into(), 1000u32.into());
575                    let constraint = if trade_price {
576                        SwapConstraint::TradeLimitPrice {
577                            limit: price,
578                            tolerance: 1e-6,
579                            min_amount_in: None,
580                            max_amount_in: max.clone(),
581                        }
582                    } else {
583                        SwapConstraint::PoolTargetPrice {
584                            target: price,
585                            tolerance: 1e-6,
586                            min_amount_in: None,
587                            max_amount_in: max.clone(),
588                        }
589                    };
590                    // Raw-unit prices do not depend on display decimals.
591                    let params = QueryPoolSwapParams::new(
592                        token(sell, "IN", 18),
593                        token(buy, "OUT", 6),
594                        constraint,
595                    );
596                    let swap = state.query_pool_swap(&params).unwrap();
597                    let expected = max.unwrap_or_else(|| 1_000_000u32.into());
598                    assert_eq!(swap.amount_in(), &expected);
599                    assert_eq!(swap.amount_out(), &expected);
600                }
601            }
602        }
603    }
604
605    #[test]
606    fn price_queries_distinguish_rounded_trade_and_post_swap_prices() {
607        use tycho_common::simulation::protocol_sim::{Price, SwapConstraint};
608        let mut state = state();
609        state.reserve_y = 2;
610        state.fee_bid_x24 = 1 << 22;
611        let x = token(state.token_x, "X", 18);
612        let y = token(state.token_y, "Y", 18);
613        let params = QueryPoolSwapParams::new(
614            x.clone(),
615            y.clone(),
616            SwapConstraint::TradeLimitPrice {
617                limit: Price::new(9u32.into(), 10u32.into()),
618                tolerance: 0.0,
619                min_amount_in: None,
620                max_amount_in: None,
621            },
622        );
623        let result = state.query_pool_swap(&params).unwrap();
624        assert_eq!(result.amount_in(), &BigUint::from(2u32));
625        assert_eq!(result.amount_out(), &BigUint::from(2u32));
626        let params = QueryPoolSwapParams::new(
627            x,
628            y,
629            SwapConstraint::PoolTargetPrice {
630                target: Price::new(9u32.into(), 10u32.into()),
631                tolerance: 0.0,
632                min_amount_in: None,
633                max_amount_in: None,
634            },
635        );
636        assert!(state.query_pool_swap(&params).is_err());
637    }
638
639    #[test]
640    fn price_queries_preserve_bounds_zero_capacity_and_exact_equality() {
641        use tycho_common::simulation::protocol_sim::{Price, SwapConstraint};
642        for trade in [true, false] {
643            for (min, max, expected) in [
644                (None, None, 1_000_000u32),
645                (Some(12u32), Some(20u32), 20),
646                (None, Some(0), 0),
647                (Some(1_000_001), None, 0),
648            ] {
649                let mut state = state();
650                let constraint = if trade {
651                    SwapConstraint::TradeLimitPrice {
652                        limit: Price::new(1u32.into(), 1u32.into()),
653                        tolerance: 0.0,
654                        min_amount_in: min.map(BigUint::from),
655                        max_amount_in: max.map(BigUint::from),
656                    }
657                } else {
658                    SwapConstraint::PoolTargetPrice {
659                        target: Price::new(1u32.into(), 1u32.into()),
660                        tolerance: 0.0,
661                        min_amount_in: min.map(BigUint::from),
662                        max_amount_in: max.map(BigUint::from),
663                    }
664                };
665                let params = QueryPoolSwapParams::new(
666                    token(state.token_x, "X", 18),
667                    token(state.token_y, "Y", 18),
668                    constraint,
669                );
670                assert_eq!(
671                    state
672                        .query_pool_swap(&params)
673                        .unwrap()
674                        .amount_in(),
675                    &BigUint::from(expected)
676                );
677                state.paused = true;
678                assert_eq!(
679                    state
680                        .query_pool_swap(&params)
681                        .unwrap()
682                        .amount_in(),
683                    &BigUint::ZERO
684                );
685            }
686        }
687        let state = rounding_boundary_state(true, 1);
688        let params = QueryPoolSwapParams::new(
689            token(state.token_x, "X", 18),
690            token(state.token_y, "Y", 18),
691            SwapConstraint::TradeLimitPrice {
692                limit: Price::new(1u32.into(), 100u32.into()),
693                tolerance: 0.0,
694                min_amount_in: None,
695                max_amount_in: Some(2u32.into()),
696            },
697        );
698        assert_eq!(
699            state
700                .query_pool_swap(&params)
701                .unwrap()
702                .amount_in(),
703            &BigUint::ZERO
704        );
705    }
706
707    #[test]
708    fn price_queries_keep_interior_punishment_search() {
709        use tycho_common::simulation::protocol_sim::{Price, SwapConstraint};
710        let mut state = state();
711        state.max_punishment_x24 = 1 << 20;
712        let x = token(state.token_x, "X", 18);
713        let y = token(state.token_y, "Y", 6);
714        for trade in [true, false] {
715            let constraint = if trade {
716                SwapConstraint::TradeLimitPrice {
717                    limit: Price::new(99u32.into(), 100u32.into()),
718                    tolerance: 1e-6,
719                    min_amount_in: Some(100u32.into()),
720                    max_amount_in: Some(900_000u32.into()),
721                }
722            } else {
723                SwapConstraint::PoolTargetPrice {
724                    target: Price::new(99u32.into(), 100u32.into()),
725                    tolerance: 1e-6,
726                    min_amount_in: Some(100u32.into()),
727                    max_amount_in: Some(900_000u32.into()),
728                }
729            };
730            let params = QueryPoolSwapParams::new(x.clone(), y.clone(), constraint);
731            let result = state.query_pool_swap(&params).unwrap();
732            assert!(result.amount_in() > &BigUint::from(100u32));
733            assert!(result.amount_in() < &BigUint::from(900_000u32));
734            assert_eq!(
735                &state
736                    .get_amount_out(result.amount_in().clone(), &x, &y)
737                    .unwrap()
738                    .amount,
739                result.amount_out()
740            );
741            if trade {
742                assert!(result.amount_out() * 100u32 >= result.amount_in() * 99u32);
743            }
744        }
745    }
746
747    #[test]
748    fn price_queries_reject_fallback_below_exact_trade_limit() {
749        use tycho_common::simulation::protocol_sim::{Price, SwapConstraint};
750        let mut state = state();
751        state.max_punishment_x24 = 1 << 20;
752        let scale = BigUint::from(10u32).pow(30);
753        let params = QueryPoolSwapParams::new(
754            token(state.token_x, "X", 18),
755            token(state.token_y, "Y", 18),
756            SwapConstraint::TradeLimitPrice {
757                limit: Price::new(&scale * 99u32 + 1u32, &scale * 100u32),
758                tolerance: 1e-6,
759                min_amount_in: None,
760                max_amount_in: None,
761            },
762        );
763        // The generic f64 search rounds this limit to 0.99 and returns 320000 -> 316800.
764        // That fill is strictly below the requested rational price.
765        assert!(matches!(
766            state.query_pool_swap(&params),
767            Err(SimulationError::InvalidInput(message, _))
768                if message == "LunarBase fill below trade limit price"
769        ));
770    }
771
772    #[test]
773    fn randomized_limits_are_executable_and_maximal() {
774        // Fixed-seed xorshift keeps property coverage reproducible without a new dependency.
775        let mut seed = 0x1445_cafe_7813_u64;
776        let mut random = || {
777            seed ^= seed << 13;
778            seed ^= seed >> 7;
779            seed ^= seed << 17;
780            seed
781        };
782        for case in 0..6000 {
783            let mut state = state();
784            state.anchor_price_x96 = U256::from(random() % 17) << 94usize;
785            state.reserve_x = (random() % 32) as u128;
786            state.reserve_y = (random() % 32) as u128;
787            state.fee_ask_x24 = (random() % (1 << 24)) as u32;
788            state.fee_bid_x24 = (random() % (1 << 24)) as u32;
789            state.max_punishment_x24 = (random() % (1 << 24)) as u32;
790            if case % 5 == 0 {
791                state.max_punishment_x24 = MAX_U24;
792            }
793            if case % 7 == 0 {
794                state.fee_bid_x24 = MAX_U24;
795            }
796            if case % 11 == 0 {
797                state.reserve_x = MAX_U112 - state.reserve_x;
798            }
799            if case % 13 == 0 {
800                state.reserve_y = MAX_U112 - state.reserve_y;
801            }
802            if case % 17 == 0 {
803                state.paused = true;
804            }
805            if case % 19 == 0 {
806                state.head_block = 102;
807            }
808            for (sell, buy) in [(state.token_x, state.token_y), (state.token_y, state.token_x)] {
809                let token_in = token(sell, "IN", 18);
810                let token_out = token(buy, "OUT", 18);
811                let (input, output) = state
812                    .get_limits(sell.into(), buy.into())
813                    .unwrap();
814                if input != BigUint::ZERO {
815                    let quoted = state
816                        .get_amount_out(input.clone(), &token_in, &token_out)
817                        .unwrap();
818                    assert_eq!(quoted.amount, output, "case={case}");
819                    assert_ne!(output, BigUint::ZERO, "case={case}");
820                    assert!(
821                        state
822                            .get_amount_out(&input + 1u32, &token_in, &token_out)
823                            .is_err(),
824                        "case={case}"
825                    );
826                } else {
827                    assert_eq!(output, BigUint::ZERO);
828                }
829                if state.reserve_x < 32 && state.reserve_y < 32 {
830                    // At these anchors all possible fills fit in 512 input units.
831                    // Exhaustive search independently checks zero limits as well as maxima.
832                    let expected = (1..=512u64)
833                        .rev()
834                        .find_map(|amount| {
835                            state
836                                .get_amount_out(BigUint::from(amount), &token_in, &token_out)
837                                .ok()
838                                .map(|quote| (BigUint::from(amount), quote.amount))
839                        })
840                        .unwrap_or((BigUint::ZERO, BigUint::ZERO));
841                    assert_eq!(
842                        (input, output),
843                        expected,
844                        "case={case}, sell={sell:?}, state={state:?}"
845                    );
846                }
847            }
848        }
849    }
850
851    #[test]
852    fn quotes_x_to_y_and_transitions_reserves() {
853        let state = state();
854        let (amount_out, next_state) = state
855            .quote_exact_in(state.token_x, state.token_y, U256::from(1_000u64))
856            .unwrap();
857
858        assert_eq!(amount_out, U256::from(1_000u64));
859        assert_eq!(next_state.reserve_x, 1_001_000);
860        assert_eq!(next_state.reserve_y, 999_000);
861        assert_eq!(next_state.anchor_price_x96, state.anchor_price_x96);
862        assert_eq!(next_state.head_block, state.head_block);
863    }
864
865    #[test]
866    fn zero_amount_out_returns_zero_without_transition() {
867        let state = state();
868        let token_x = token(state.token_x, "ETH", 18);
869        let token_y = token(state.token_y, "USDC", 6);
870
871        let quote = state
872            .get_amount_out(BigUint::ZERO, &token_x, &token_y)
873            .unwrap();
874        let next_state = quote
875            .new_state
876            .as_any()
877            .downcast_ref::<LunarBaseState>()
878            .unwrap();
879
880        assert_eq!(quote.amount, BigUint::ZERO);
881        assert_eq!(next_state, &state);
882    }
883
884    #[test]
885    fn spot_price_uses_anchor_price() {
886        let mut state = state();
887        state.anchor_price_x96 = lunarbase_pmm_math::price_to_sqrt_price_x96(2_000.0 / 1e12);
888        state.reserve_x = 1_000_000_000_000_000_000;
889        state.reserve_y = 1_000_000;
890
891        let token_x = token(state.token_x, "ETH", 18);
892        let token_y = token(state.token_y, "USDC", 6);
893
894        let price = state
895            .spot_price(&token_x, &token_y)
896            .unwrap();
897        let inverse = state
898            .spot_price(&token_y, &token_x)
899            .unwrap();
900
901        assert!((price - 2_000.0).abs() < 1e-6);
902        assert!((inverse - 0.0005).abs() < 1e-12);
903    }
904
905    #[test]
906    fn spot_price_applies_directional_base_fee() {
907        let mut state = state();
908        state.anchor_price_x96 = lunarbase_pmm_math::price_to_sqrt_price_x96(2_000.0 / 1e12);
909        state.fee_ask_x24 = (1u32 << 24) / 100;
910        state.fee_bid_x24 = (2 * (1u32 << 24)) / 100;
911
912        let token_x = token(state.token_x, "ETH", 18);
913        let token_y = token(state.token_y, "USDC", 6);
914
915        let price = state
916            .spot_price(&token_x, &token_y)
917            .unwrap();
918        let inverse = state
919            .spot_price(&token_y, &token_x)
920            .unwrap();
921
922        assert!((price - (2_000.0 * 0.98)).abs() < 1e-3);
923        assert!((inverse - (0.0005 * 0.99)).abs() < 1e-9);
924    }
925
926    #[test]
927    fn rejects_stale_state() {
928        let mut state = state();
929        state.head_block = 102;
930
931        let err = state
932            .quote_exact_in(state.token_x, state.token_y, U256::from(1_000u64))
933            .unwrap_err();
934
935        assert_eq!(
936            err,
937            QuoteError::Stale { block_number: 102, latest_update_block: 100, block_delay: 2 }
938        );
939    }
940
941    #[test]
942    fn unavailable_pools_have_zero_limits_but_still_reject_swaps() {
943        for (paused, head_block) in [(true, 100), (false, 102), (true, 103)] {
944            let mut state = state();
945            state.paused = paused;
946            state.head_block = head_block;
947            for (sell, buy) in [(state.token_x, state.token_y), (state.token_y, state.token_x)] {
948                assert_eq!(
949                    state
950                        .get_limits(Bytes::from(sell), Bytes::from(buy))
951                        .unwrap(),
952                    (BigUint::ZERO, BigUint::ZERO)
953                );
954                assert!(state
955                    .get_amount_out(
956                        BigUint::from(1_000u64),
957                        &token(sell, "IN", 18),
958                        &token(buy, "OUT", 18),
959                    )
960                    .is_err());
961            }
962            assert!(state
963                .get_limits(Bytes::from(addr(3)), Bytes::from(state.token_y))
964                .is_err());
965        }
966    }
967
968    #[test]
969    fn limits_recover_after_unpause_or_fresh_operator_update() {
970        let mut state = state();
971        let sell = Bytes::from(state.token_x);
972        let buy = Bytes::from(state.token_y);
973        let available_limits = state
974            .get_limits(sell.clone(), buy.clone())
975            .unwrap();
976        assert!(available_limits.0 > BigUint::ZERO);
977        assert!(available_limits.1 > BigUint::ZERO);
978
979        state.paused = true;
980        assert_eq!(
981            state
982                .get_limits(sell.clone(), buy.clone())
983                .unwrap()
984                .0,
985            BigUint::ZERO
986        );
987        apply_delta(&mut state, HashMap::from([("paused".to_owned(), Bytes::from([0u8]))]))
988            .unwrap();
989        assert_eq!(
990            state
991                .get_limits(sell.clone(), buy.clone())
992                .unwrap(),
993            available_limits
994        );
995
996        state.apply_block(&BlockContext::new(102, 0));
997        assert_eq!(
998            state
999                .get_limits(sell.clone(), buy.clone())
1000                .unwrap()
1001                .0,
1002            BigUint::ZERO
1003        );
1004        apply_delta(
1005            &mut state,
1006            HashMap::from([("latest_update_block".to_owned(), Bytes::from(102u64))]),
1007        )
1008        .unwrap();
1009        assert_eq!(state.get_limits(sell, buy).unwrap(), available_limits);
1010    }
1011
1012    #[test]
1013    fn charges_immediate_punishment_and_accumulates_only_the_traded_direction() {
1014        let mut state = state();
1015        state.max_punishment_x24 = 16_778;
1016        let amount = U256::from(100_000u64);
1017
1018        let (first_out, first) = state
1019            .quote_exact_in(state.token_x, state.token_y, amount)
1020            .unwrap();
1021        assert_eq!(first_out, U256::from(99_995u64));
1022        assert_eq!((first.reserve_x, first.reserve_y), (1_100_000, 900_000));
1023        assert_eq!((first.fee_ask_x24, first.fee_bid_x24), (0, 839));
1024        assert_eq!(first.anchor_price_x96, state.anchor_price_x96);
1025        assert_eq!(first.latest_update_block, state.latest_update_block);
1026
1027        let (second_out, second) = first
1028            .quote_exact_in(state.token_x, state.token_y, amount)
1029            .unwrap();
1030        assert_eq!(second_out, U256::from(99_990u64));
1031        assert_eq!((second.fee_ask_x24, second.fee_bid_x24), (0, 1_678));
1032
1033        let (reverse_out, reverse) = second
1034            .quote_exact_in(state.token_y, state.token_x, amount)
1035            .unwrap();
1036        assert_eq!(reverse_out, U256::from(99_995u64));
1037        assert_eq!((reverse.fee_ask_x24, reverse.fee_bid_x24), (839, 1_678));
1038        assert_eq!((state.fee_ask_x24, state.fee_bid_x24), (0, 0));
1039    }
1040
1041    #[test]
1042    fn operator_update_replaces_accumulated_fees_and_restores_freshness() {
1043        let mut initial = state();
1044        initial.max_punishment_x24 = 16_778;
1045        let (_, mut state) = initial
1046            .quote_exact_in(initial.token_x, initial.token_y, U256::from(100_000u64))
1047            .unwrap();
1048        state.apply_block(&BlockContext::new(102, 0));
1049        let reserves = (state.reserve_x, state.reserve_y);
1050        state
1051            .delta_transition(
1052                ProtocolStateDelta {
1053                    updated_attributes: HashMap::from([
1054                        (
1055                            "anchor_price_x96".to_owned(),
1056                            Bytes::from(
1057                                (U256::from(2u64) << 96usize).to_be_bytes::<32>()[12..].to_vec(),
1058                            ),
1059                        ),
1060                        ("fee_ask_x24".to_owned(), Bytes::from(11u32)),
1061                        ("fee_bid_x24".to_owned(), Bytes::from(22u32)),
1062                        ("latest_update_block".to_owned(), Bytes::from(102u64)),
1063                        ("block_number".to_owned(), Bytes::from(102u64)),
1064                    ]),
1065                    ..Default::default()
1066                },
1067                &HashMap::new(),
1068                &Balances::default(),
1069            )
1070            .unwrap();
1071
1072        assert!(state.is_fresh());
1073        assert_eq!((state.fee_ask_x24, state.fee_bid_x24), (11, 22));
1074        assert_eq!(state.max_punishment_x24, 16_778);
1075        assert_eq!((state.reserve_x, state.reserve_y), reserves);
1076    }
1077
1078    #[test]
1079    fn full_fee_and_punishment_saturation_reject_without_changing_state() {
1080        let mut state = state();
1081        state.fee_bid_x24 = MAX_U24;
1082        let before = state.clone();
1083        assert_eq!(
1084            state.quote_exact_in(state.token_x, state.token_y, U256::from(1u64)),
1085            Err(QuoteError::Rejected)
1086        );
1087        assert_eq!(state, before);
1088        assert_eq!(
1089            state
1090                .spot_price(&token(state.token_x, "X", 18), &token(state.token_y, "Y", 18))
1091                .unwrap(),
1092            0.0
1093        );
1094
1095        state.fee_bid_x24 = MAX_U24 - 1;
1096        state.max_punishment_x24 = 1;
1097        let before = state.clone();
1098        assert_eq!(
1099            state.quote_exact_in(state.token_x, state.token_y, U256::from(1u64)),
1100            Err(QuoteError::Rejected)
1101        );
1102        assert_eq!(state, before);
1103    }
1104
1105    #[test]
1106    fn max_punishment_sentinel_uses_conceptual_one_hundred_percent() {
1107        let mut state = state();
1108        state.reserve_x = 0;
1109        state.reserve_y = 1_000_000;
1110        state.max_punishment_x24 = MAX_U24;
1111        assert_eq!(
1112            state.quote_exact_in(state.token_x, state.token_y, U256::from(1_000_000u64)),
1113            Err(QuoteError::Rejected)
1114        );
1115    }
1116
1117    #[test]
1118    fn rejects_uint112_reserve_overflow_and_invalid_math_state() {
1119        let mut state = state();
1120        state.reserve_x = lunarbase_pmm_math::MAX_U112;
1121        let before = state.clone();
1122        assert_eq!(
1123            state.quote_exact_in(state.token_x, state.token_y, U256::from(1u64)),
1124            Err(QuoteError::ReserveOverflow)
1125        );
1126        assert_eq!(state, before);
1127
1128        state.max_punishment_x24 = 1 << 24;
1129        assert_eq!(
1130            state.quote_exact_in(state.token_x, state.token_y, U256::from(1u64)),
1131            Err(QuoteError::Math(MathError::MaxPunishmentExceedsUint24))
1132        );
1133    }
1134
1135    #[test]
1136    fn quotes_anchor_above_uint128_and_checks_gross_liquidity() {
1137        let mut state = state();
1138        state.anchor_price_x96 = U256::from(1u64) << 129usize;
1139        state.reserve_y = 1u128 << 80;
1140        let expected_gross = U256::from(1u64) << 66usize;
1141        let (out, next) = state
1142            .quote_exact_in(state.token_x, state.token_y, U256::from(1u64))
1143            .unwrap();
1144        assert_eq!(out, expected_gross);
1145        assert_eq!(next.reserve_y, state.reserve_y - (1u128 << 66));
1146        state.reserve_y = (1u128 << 66) - 1;
1147        state.fee_bid_x24 = (1 << 24) / 2;
1148        assert_eq!(
1149            state.quote_exact_in(state.token_x, state.token_y, U256::from(1u64)),
1150            Err(QuoteError::Rejected)
1151        );
1152    }
1153
1154    #[test]
1155    fn execution_block_hook_expires_idle_pools_and_handles_reorgs() {
1156        let mut state = state();
1157        assert!(!state.apply_block(&BlockContext::new(101, 0)));
1158        assert_eq!(state.head_block, 101);
1159        assert!(state.is_fresh());
1160
1161        assert!(state.apply_block(&BlockContext::new(102, 0)));
1162        assert!(!state.is_fresh());
1163        assert!(!state.apply_block(&BlockContext::new(102, 0)));
1164        assert!(!state.apply_block(&BlockContext::new(103, 0)));
1165        assert!(matches!(
1166            state.quote_exact_in(state.token_x, state.token_y, U256::from(1u64)),
1167            Err(QuoteError::Stale { block_number: 103, .. })
1168        ));
1169
1170        assert!(state.apply_block(&BlockContext::new(101, 0)));
1171        assert!(state.is_fresh());
1172    }
1173
1174    #[test]
1175    fn zero_anchor_never_returns_infinite_spot_price() {
1176        let mut state = state();
1177        state.anchor_price_x96 = U256::ZERO;
1178        let x = token(state.token_x, "X", 18);
1179        let y = token(state.token_y, "Y", 18);
1180        assert_eq!(state.spot_price(&x, &y).unwrap(), 0.0);
1181        assert_eq!(state.spot_price(&y, &x).unwrap(), 0.0);
1182        assert_eq!(
1183            state.quote_exact_in(state.token_y, state.token_x, U256::from(1u64)),
1184            Err(QuoteError::Rejected)
1185        );
1186    }
1187
1188    #[test]
1189    fn limits_allow_both_directions_with_an_empty_input_reserve() {
1190        let mut state = state();
1191        state.anchor_price_x96 = U256::from(2u64) << 96usize;
1192        state.max_punishment_x24 = 16_778;
1193
1194        state.reserve_x = 0;
1195        state.reserve_y = 4_000_000;
1196        let (input, output) = state
1197            .get_limits(Bytes::from(state.token_x), Bytes::from(state.token_y))
1198            .unwrap();
1199        assert_eq!(input, BigUint::from(1_000_000u64));
1200        assert_eq!(output, BigUint::from(3_996_000u64));
1201
1202        state.reserve_x = 1_000_000;
1203        state.reserve_y = 0;
1204        let (input, output) = state
1205            .get_limits(Bytes::from(state.token_y), Bytes::from(state.token_x))
1206            .unwrap();
1207        // The last three input units still round down to the same gross output.
1208        assert_eq!(input, BigUint::from(4_000_003u64));
1209        assert_eq!(output, BigUint::from(999_000u64));
1210    }
1211
1212    #[test]
1213    fn limits_recover_minimum_trade_for_empty_and_small_input_reserves() {
1214        for x_to_y in [true, false] {
1215            // Reserve 1 starts below the minimum; reserve 4 halves 8 -> 4 -> 2,
1216            // skipping the only valid input (3). Reserve 3 already finds it.
1217            for reserve_in in [0, 1, 3, 4] {
1218                let state = rounding_boundary_state(x_to_y, reserve_in);
1219                let (sell, buy) = if x_to_y {
1220                    (state.token_x, state.token_y)
1221                } else {
1222                    (state.token_y, state.token_x)
1223                };
1224                assert_eq!(
1225                    state
1226                        .quote_exact_in(sell, buy, U256::from(3u64))
1227                        .unwrap()
1228                        .0,
1229                    U256::from(1u64)
1230                );
1231                assert_eq!(
1232                    state
1233                        .get_limits(Bytes::from(sell), Bytes::from(buy))
1234                        .unwrap(),
1235                    (BigUint::from(3u64), BigUint::from(1u64)),
1236                    "x_to_y={x_to_y}, reserve_in={reserve_in}"
1237                );
1238            }
1239        }
1240    }
1241
1242    fn rounding_boundary_state(x_to_y: bool, reserve_in: u128) -> LunarBaseState {
1243        let mut state = state();
1244        let q96 = U256::from(1u64) << 96usize;
1245        if x_to_y {
1246            state.anchor_price_x96 = q96 * U256::from(3u64) / U256::from(4u64);
1247            state.reserve_x = reserve_in;
1248            state.reserve_y = 1;
1249        } else {
1250            state.anchor_price_x96 = q96 * U256::from(4u64) / U256::from(3u64);
1251            state.reserve_x = 1;
1252            state.reserve_y = reserve_in;
1253        }
1254        state
1255    }
1256
1257    #[test]
1258    fn minimum_trade_limits_apply_fees_and_punishment() {
1259        for x_to_y in [true, false] {
1260            for (fee, punishment, available) in
1261                [(1 << 22, 1 << 22, true), (MAX_U24, 0, false), (MAX_U24 - 1, MAX_U24, false)]
1262            {
1263                let mut state = rounding_boundary_state(x_to_y, 1);
1264                state.fee_ask_x24 = fee;
1265                state.fee_bid_x24 = fee;
1266                state.max_punishment_x24 = punishment;
1267                let (sell, buy) = if x_to_y {
1268                    (state.token_x, state.token_y)
1269                } else {
1270                    (state.token_y, state.token_x)
1271                };
1272                let expected = if available {
1273                    (BigUint::from(3u64), BigUint::from(1u64))
1274                } else {
1275                    (BigUint::ZERO, BigUint::ZERO)
1276                };
1277                assert_eq!(
1278                    state
1279                        .get_limits(Bytes::from(sell), Bytes::from(buy))
1280                        .unwrap(),
1281                    expected
1282                );
1283            }
1284        }
1285    }
1286
1287    #[test]
1288    fn minimum_trade_limits_preserve_unavailable_states_and_math_errors() {
1289        for x_to_y in [true, false] {
1290            for case in [
1291                "paused",
1292                "stale",
1293                "no liquidity",
1294                "reserve overflow",
1295                "zero anchor",
1296                "minimum exceeds capacity",
1297                "output quantum exceeds liquidity",
1298                "invalid math",
1299            ] {
1300                let mut state = rounding_boundary_state(x_to_y, 1);
1301                let (sell, buy) = if x_to_y {
1302                    (state.token_x, state.token_y)
1303                } else {
1304                    (state.token_y, state.token_x)
1305                };
1306                match case {
1307                    "paused" => state.paused = true,
1308                    "stale" => state.head_block = 102,
1309                    "no liquidity" if x_to_y => state.reserve_y = 0,
1310                    "no liquidity" => state.reserve_x = 0,
1311                    "reserve overflow" if x_to_y => state.reserve_x = MAX_U112 - 2,
1312                    "reserve overflow" => state.reserve_y = MAX_U112 - 2,
1313                    "zero anchor" => state.anchor_price_x96 = U256::ZERO,
1314                    "minimum exceeds capacity" => {
1315                        state.anchor_price_x96 =
1316                            if x_to_y { U256::from(1u64) } else { U256::from(1u64) << 159usize };
1317                    }
1318                    "output quantum exceeds liquidity" => {
1319                        state.anchor_price_x96 =
1320                            U256::from(1u64) << if x_to_y { 97usize } else { 95usize };
1321                    }
1322                    "invalid math" => state.max_punishment_x24 = 1 << 24,
1323                    #[expect(
1324                        clippy::unreachable,
1325                        reason = "the test cases only name the cases above"
1326                    )]
1327                    _ => unreachable!(),
1328                }
1329                let limits = state.get_limits(Bytes::from(sell), Bytes::from(buy));
1330                if case == "invalid math" {
1331                    assert!(limits.is_err(), "x_to_y={x_to_y}, {case}");
1332                } else {
1333                    assert_eq!(
1334                        limits.unwrap(),
1335                        (BigUint::ZERO, BigUint::ZERO),
1336                        "x_to_y={x_to_y}, {case}"
1337                    );
1338                }
1339            }
1340        }
1341    }
1342
1343    #[test]
1344    fn empty_input_reserve_limit_inverts_both_rounding_steps() {
1345        for x_to_y in [true, false] {
1346            let mut state = state();
1347            let (sell, buy) = if x_to_y {
1348                state.anchor_price_x96 = (U256::from(3u64) << 96usize) / U256::from(4u64);
1349                state.reserve_x = 0;
1350                state.reserve_y = 1;
1351                (state.token_x, state.token_y)
1352            } else {
1353                state.anchor_price_x96 = (U256::from(3u64) << 96usize) / U256::from(2u64);
1354                state.reserve_x = 1;
1355                state.reserve_y = 0;
1356                (state.token_y, state.token_x)
1357            };
1358            assert_eq!(
1359                state
1360                    .quote_exact_in(sell, buy, U256::from(3u64))
1361                    .unwrap()
1362                    .0,
1363                U256::from(1u64)
1364            );
1365            let (input, output) = state
1366                .get_limits(Bytes::from(sell), Bytes::from(buy))
1367                .unwrap();
1368            assert_eq!(input, BigUint::from(if x_to_y { 3u64 } else { 4u64 }));
1369            assert_eq!(output, BigUint::from(1u64));
1370            assert_eq!(
1371                state.quote_exact_in(sell, buy, biguint_to_u256(&(input + 1u32)).unwrap()),
1372                Err(QuoteError::Rejected)
1373            );
1374        }
1375    }
1376
1377    #[test]
1378    fn empty_input_reserve_limits_match_exhaustive_small_quotes() {
1379        for anchor_quarters in 1..=16u64 {
1380            for reserve_out in 1..=8u128 {
1381                for x_to_y in [true, false] {
1382                    let mut state = state();
1383                    state.anchor_price_x96 = U256::from(anchor_quarters) << 94usize;
1384                    let (sell, buy) = if x_to_y {
1385                        state.reserve_x = 0;
1386                        state.reserve_y = reserve_out;
1387                        (state.token_x, state.token_y)
1388                    } else {
1389                        state.reserve_x = reserve_out;
1390                        state.reserve_y = 0;
1391                        (state.token_y, state.token_x)
1392                    };
1393                    // These prices/reserves exhaust output liquidity below 256 input units.
1394                    let expected = (1..=256u64)
1395                        .rev()
1396                        .find_map(|input| {
1397                            state
1398                                .quote_exact_in(sell, buy, U256::from(input))
1399                                .ok()
1400                                .map(|(output, _)| (BigUint::from(input), u256_to_biguint(output)))
1401                        })
1402                        .unwrap_or((BigUint::ZERO, BigUint::ZERO));
1403                    assert_eq!(
1404                        state.get_limits(Bytes::from(sell), Bytes::from(buy)).unwrap(),
1405                        expected,
1406                        "anchor_quarters={anchor_quarters}, reserve_out={reserve_out}, x_to_y={x_to_y}"
1407                    );
1408                }
1409            }
1410        }
1411    }
1412
1413    #[test]
1414    fn empty_input_reserve_limit_respects_uint112_capacity() {
1415        let mut state = state();
1416        state.anchor_price_x96 = U256::from(2u64) << 96usize;
1417        state.reserve_x = MAX_U112;
1418        state.reserve_y = 0;
1419        let (input, output) = state
1420            .get_limits(Bytes::from(state.token_y), Bytes::from(state.token_x))
1421            .unwrap();
1422        assert_eq!(input, BigUint::from(MAX_U112));
1423        assert_eq!(output, BigUint::from(MAX_U112 / 4));
1424    }
1425
1426    #[test]
1427    fn legacy_caller_policy_does_not_change_partner_quotes() {
1428        let mut state = state();
1429        state.max_punishment_x24 = 16_778;
1430        state.fee_bid_x24 = (1 << 24) / 4;
1431        let x = token(state.token_x, "X", 18);
1432        let y = token(state.token_y, "Y", 18);
1433        let amount = U256::from(100_000u64);
1434        let expected = state
1435            .quote_exact_in(state.token_x, state.token_y, amount)
1436            .unwrap();
1437        assert_eq!(expected.0, U256::from(74_995u64));
1438        assert_eq!(state.spot_price(&x, &y).unwrap(), 0.75);
1439
1440        apply_delta(
1441            &mut state,
1442            HashMap::from([
1443                ("quote_caller_whitelisted".to_owned(), Bytes::from([0u8])),
1444                ("blacklist_fee_multiplier".to_owned(), Bytes::from(U256::MAX.to_be_bytes::<32>())),
1445            ]),
1446        )
1447        .unwrap();
1448        assert_eq!(
1449            state
1450                .quote_exact_in(state.token_x, state.token_y, amount)
1451                .unwrap(),
1452            expected
1453        );
1454        assert_eq!(state.spot_price(&x, &y).unwrap(), 0.75);
1455    }
1456
1457    #[test]
1458    fn matches_base_partner_quotes_from_execution_fixture() {
1459        let capture: serde_json::Value = serde_json::from_str(include_str!(concat!(
1460            env!("CARGO_MANIFEST_DIR"),
1461            "/../../protocols/substreams/base-lunarbase/bootstrap/base-execution.json"
1462        )))
1463        .unwrap();
1464        let mut state = state();
1465        let address = |name: &str| {
1466            address_from_bytes(
1467                &hex::decode(
1468                    capture[name]
1469                        .as_str()
1470                        .unwrap()
1471                        .trim_start_matches("0x"),
1472                )
1473                .unwrap(),
1474            )
1475            .unwrap()
1476        };
1477        state.pool = address("pool");
1478        state.token_x = address("token_x");
1479        state.token_y = address("token_y");
1480        let snapshot = &capture["execution_state"];
1481        apply_delta(
1482            &mut state,
1483            snapshot["attributes"]
1484                .as_object()
1485                .unwrap()
1486                .iter()
1487                .map(|(name, value)| {
1488                    (
1489                        name.clone(),
1490                        value
1491                            .as_str()
1492                            .unwrap()
1493                            .parse::<Bytes>()
1494                            .unwrap(),
1495                    )
1496                })
1497                .collect(),
1498        )
1499        .unwrap();
1500        state.head_block = snapshot["block_number"]
1501            .as_u64()
1502            .unwrap();
1503        let mut directions = [0; 2];
1504        for quote in capture["observed_quotes"]
1505            .as_array()
1506            .unwrap()
1507        {
1508            let forward = match quote["signature"].as_str().unwrap() {
1509                "quoteXToY(uint256)" => true,
1510                "quoteYToX(uint256)" => false,
1511                other => panic!("unexpected quote: {other}"),
1512            };
1513            directions[usize::from(forward)] += 1;
1514            let amount = U256::from_str_radix(quote["arguments"][0].as_str().unwrap(), 10).unwrap();
1515            let expected: Vec<U256> = quote["result"]
1516                .as_array()
1517                .unwrap()
1518                .iter()
1519                .map(|value| U256::from_str_radix(value.as_str().unwrap(), 10).unwrap())
1520                .collect();
1521            let (token_in, token_out) = if forward {
1522                (state.token_x, state.token_y)
1523            } else {
1524                (state.token_y, state.token_x)
1525            };
1526            let (output, next) = state
1527                .quote_exact_in(token_in, token_out, amount)
1528                .unwrap();
1529            assert!(output > U256::ZERO);
1530            assert_eq!(output, expected[0]);
1531            assert_eq!(next.anchor_price_x96, expected[1]);
1532            let gross = if forward {
1533                state.reserve_y - next.reserve_y
1534            } else {
1535                state.reserve_x - next.reserve_x
1536            };
1537            assert_eq!(U256::from(gross) - output, expected[2]);
1538        }
1539        assert_eq!(directions, [3, 3]);
1540    }
1541
1542    #[test]
1543    fn derives_partner_quotes_from_base_capture_at_block_51297469() {
1544        // Recorded eth_call results at Base block 51,297,469, pool
1545        // 0x0000efc4ec03a7c47d3a38a9be7ff1d52dd01b99, with `from` set to
1546        // TychoRouter 0xAbA5B53b03eAfaD1C5fc8BD5Fc765fC85Bb3de67.
1547        // The historical caller paid multiplier 100 at this block.
1548        // Normalize the recorded fee (floor(gross * fee_x24 / Q24) * 100) to
1549        // multiplier one. This checks partner math, not historical caller parity.
1550        let mut state = state();
1551        state.pool =
1552            address_from_bytes(&hex::decode("0000efc4ec03a7c47d3a38a9be7ff1d52dd01b99").unwrap())
1553                .unwrap();
1554        state.token_x = [0; 20];
1555        state.token_y =
1556            address_from_bytes(&hex::decode("833589fcd6edb6e08f4c7c32d4f71b54bda02913").unwrap())
1557                .unwrap();
1558        state.anchor_price_x96 = U256::from(3_971_029_714_873_270_134_636_544u128);
1559        state.fee_ask_x24 = 1_835;
1560        state.fee_bid_x24 = 8_475;
1561        state.latest_update_block = 51_297_469;
1562        state.head_block = 51_297_469;
1563        state.max_punishment_x24 = 160_000;
1564        state.block_delay = 3;
1565        state.reserve_x = 9_683_337_552_179_635_497;
1566        state.reserve_y = 23_231_346_797;
1567
1568        // Direction, input, observed net output, observed output-token fee.
1569        let quotes = [
1570            (true, 1_000_000_000_000_000u128, 2_385_158u128, 127_000u128),
1571            (true, 100_000_000_000_000_000, 237_258_990, 13_956_900),
1572            (true, 1_000_000_000_000_000_000, 2_258_700_200, 253_458_700),
1573            (false, 1_000_000, 393_700_695_234_017, 4_363_296_513_600),
1574            (false, 100_000_000, 39_291_060_402_299_481, 515_338_772_582_000),
1575            (false, 1_000_000_000, 385_726_231_079_417_225, 12_337_760_669_557_200),
1576        ];
1577        for (x_to_y, input, observed_out, observed_fee) in quotes {
1578            assert_eq!(observed_fee % 100, 0);
1579            let expected_fee = observed_fee / 100;
1580            let expected_out = observed_out + observed_fee - expected_fee;
1581            let (token_in, token_out) = if x_to_y {
1582                (state.token_x, state.token_y)
1583            } else {
1584                (state.token_y, state.token_x)
1585            };
1586            let (out, next) = state
1587                .quote_exact_in(token_in, token_out, U256::from(input))
1588                .unwrap();
1589            assert_eq!(out, U256::from(expected_out), "direction={x_to_y}, input={input}");
1590            let gross = if x_to_y {
1591                state.reserve_y - next.reserve_y
1592            } else {
1593                state.reserve_x - next.reserve_x
1594            };
1595            assert_eq!(gross - expected_out, expected_fee);
1596            assert_eq!(next.anchor_price_x96, state.anchor_price_x96);
1597        }
1598    }
1599
1600    #[test]
1601    fn matches_bsc_router_quotes_observed_at_block_121835898() {
1602        // Recorded eth_call results at BSC block 121,835,898, pool
1603        // 0x00007904d186680c709519e71f4dc3e2df8f1b99, with `from` set to
1604        // 0x7f3d12bbafb8955e51b3ab9588b34c8ad95bda4e. Both tokens use 18
1605        // decimals; the observed caller multiplier was 1.
1606        let mut state = state();
1607        state.pool =
1608            address_from_bytes(&hex::decode("00007904d186680c709519e71f4dc3e2df8f1b99").unwrap())
1609                .unwrap();
1610        state.token_x = [0; 20];
1611        state.token_y =
1612            address_from_bytes(&hex::decode("55d398326f99059ff775485246999027b3197955").unwrap())
1613                .unwrap();
1614        state.anchor_price_x96 = U256::from(2_129_209_909_442_387_799_622_216_056_832u128);
1615        state.fee_ask_x24 = 3_092;
1616        state.fee_bid_x24 = 552;
1617        state.latest_update_block = 121_835_890;
1618        state.head_block = 121_835_898;
1619        state.max_punishment_x24 = 125_000;
1620        state.block_delay = 25;
1621        state.reserve_x = 40_982_882_360_761_506_608;
1622        state.reserve_y = 37_489_098_599_819_531_485_143;
1623
1624        // Direction, input, observed net output, observed output-token fee.
1625        let quotes: [(bool, u128, u128, u128); 6] = [
1626            (true, 1_000_000_000_000_000, 722_209_919_138_098_675, 23_848_861_901_283),
1627            (true, 100_000_000_000_000_000, 72_220_419_368_930_290_024, 2_957_431_069_707_870),
1628            (true, 1_000_000_000_000_000_000, 722_152_061_971_320_131_445, 81_706_028_679_847_714),
1629            (false, 1_000_000_000_000_000_000, 1_384_337_907_652_450, 255_342_216_199),
1630            (false, 100_000_000_000_000_000_000, 138_432_263_993_751_885, 27_060_993_113_036),
1631            (false, 1_000_000_000_000_000_000_000, 1_384_184_240_164_873_034, 409_009_703_776_182),
1632        ];
1633        for (x_to_y, input, expected_out, expected_fee) in quotes {
1634            let (token_in, token_out) = if x_to_y {
1635                (state.token_x, state.token_y)
1636            } else {
1637                (state.token_y, state.token_x)
1638            };
1639            let (out, next) = state
1640                .quote_exact_in(token_in, token_out, U256::from(input))
1641                .unwrap();
1642            assert_eq!(out, U256::from(expected_out), "direction={x_to_y}, input={input}");
1643            let gross = if x_to_y {
1644                state.reserve_y - next.reserve_y
1645            } else {
1646                state.reserve_x - next.reserve_x
1647            };
1648            assert_eq!(gross - expected_out, expected_fee);
1649            assert_eq!(next.anchor_price_x96, state.anchor_price_x96);
1650        }
1651    }
1652}