Skip to main content

tycho_simulation/pamm/protocols/metric/
state.rs

1use std::{any::Any, collections::HashMap};
2
3use num_bigint::BigUint;
4use num_traits::Zero;
5use serde::{Deserialize, Serialize};
6use tycho_common::{
7    dto::ProtocolStateDelta,
8    models::token::Token,
9    simulation::{
10        errors::{SimulationError, TransitionError},
11        protocol_sim::{Balances, GetAmountOutResult, ProtocolSim},
12    },
13    Bytes,
14};
15
16use super::fill::{exact_fill_inside_bin, Bin, BookSide};
17use crate::{
18    book::{component::PairState, sim},
19    pamm::protocols::metric::models::{MetricBidAskResponse, MetricDepthBin, MetricMetadata},
20};
21
22/// Gas estimate for one MetricExecutor swap (pool swap + callback settlement).
23const METRIC_SWAP_GAS: u64 = 235_000;
24
25#[derive(Clone, derive_more::Debug, Serialize, Deserialize)]
26pub struct MetricState {
27    pub(super) base_token: Token,
28    pub(super) quote_token: Token,
29    #[debug("{{ pool_address: {:?}, .. }}", metadata.pool_address)]
30    pub(super) metadata: MetricMetadata,
31    /// The depth bins are too long for a log line; the timestamp says which quote this is.
32    #[debug("{{ server_ts: {}, .. }}", bid_ask.server_ts)]
33    pub(super) bid_ask: MetricBidAskResponse,
34}
35
36impl MetricState {
37    fn direction(
38        &self,
39        token_in: &Bytes,
40        token_out: &Bytes,
41    ) -> Result<MetricDirection, SimulationError> {
42        if token_in == &self.base_token.address && token_out == &self.quote_token.address {
43            Ok(MetricDirection::ZeroForOne)
44        } else if token_in == &self.quote_token.address && token_out == &self.base_token.address {
45            Ok(MetricDirection::OneForZero)
46        } else {
47            Err(SimulationError::InvalidInput(
48                format!(
49                    "Invalid token addresses. Got in={token_in}, out={token_out}, expected {} / {}",
50                    self.base_token.address, self.quote_token.address
51                ),
52                None,
53            ))
54        }
55    }
56
57    /// The book side `direction` trades against — the bid when selling token0, the ask when
58    /// buying it — or `None` when that side cannot be traded: Metric quotes no price on it or it
59    /// has no depth.
60    fn tradable_side(
61        &self,
62        direction: MetricDirection,
63    ) -> Result<Option<TradableSide<'_>>, SimulationError> {
64        let bins = match direction {
65            MetricDirection::ZeroForOne => self.bid_ask.tradable_bids(),
66            MetricDirection::OneForZero => self.bid_ask.tradable_asks(),
67        };
68        let Some(bins) = bins else {
69            return Ok(None);
70        };
71        let Some((last_bin, _)) = bins.split_last() else {
72            return Ok(None);
73        };
74        let price = match direction {
75            MetricDirection::ZeroForOne => self.bid_ask.bid_price()?,
76            MetricDirection::OneForZero => self.bid_ask.ask_price()?,
77        };
78        let Some(price) = price else {
79            return Ok(None);
80        };
81        let side = match direction {
82            MetricDirection::ZeroForOne => BookSide::Bids,
83            MetricDirection::OneForZero => BookSide::Asks,
84        };
85        let decimals = (self.base_token.decimals, self.quote_token.decimals);
86        Ok(Some(TradableSide { price, bins, last_bin, side, decimals }))
87    }
88}
89
90/// One side of the book that can be traded: Metric quotes its price and it has at least one
91/// bin.
92struct TradableSide<'a> {
93    /// Top-of-book price of token0 in token1.
94    price: f64,
95    /// The side's bins, nearest the top of the book first.
96    bins: &'a [MetricDepthBin],
97    /// The deepest bin, which carries the side's cumulative totals.
98    last_bin: &'a MetricDepthBin,
99    /// Which side of the book an order walks, and the token0 and token1 decimals.
100    side: BookSide,
101    decimals: (u32, u32),
102}
103
104impl TradableSide<'_> {
105    /// The output `amount_in` buys walking this side's bins, capped by `max_output`.
106    fn quote(
107        &self,
108        amount_in: &BigUint,
109        max_output: &BigUint,
110    ) -> Result<DepthQuote, SimulationError> {
111        let effective_max_output = self
112            .last_bin
113            .cumulative_volume
114            .clone()
115            .min(max_output.clone());
116        let depth_fill = depth_output_for_input(
117            self.bins,
118            self.side,
119            self.decimals,
120            amount_in,
121            &effective_max_output,
122        )?;
123        Ok(DepthQuote {
124            amount_out: depth_fill.output,
125            max_output: effective_max_output,
126            exhausted: depth_fill.exhausted,
127        })
128    }
129}
130
131#[derive(Debug, Clone, Copy)]
132enum MetricDirection {
133    ZeroForOne,
134    OneForZero,
135}
136
137struct DepthQuote {
138    amount_out: BigUint,
139    max_output: BigUint,
140    exhausted: bool,
141}
142
143#[derive(Debug)]
144struct DepthFill {
145    output: BigUint,
146    exhausted: bool,
147}
148
149impl PairState for MetricState {
150    fn base_token(&self) -> &Token {
151        &self.base_token
152    }
153
154    fn quote_token(&self) -> &Token {
155        &self.quote_token
156    }
157
158    fn directions(&self) -> Vec<(Bytes, Bytes)> {
159        let tradable =
160            |direction| matches!(self.tradable_side(direction), Ok(Some(side)) if side.price > 0.0);
161        sim::directions(
162            &self.base_token,
163            &self.quote_token,
164            tradable(MetricDirection::ZeroForOne),
165            tradable(MetricDirection::OneForZero),
166        )
167    }
168}
169
170#[typetag::serde]
171impl ProtocolSim for MetricState {
172    fn fee(&self) -> f64 {
173        0.0
174    }
175
176    fn spot_price(&self, base: &Token, quote: &Token) -> Result<f64, SimulationError> {
177        let side_price = |direction| -> Result<Option<f64>, SimulationError> {
178            Ok(self
179                .tradable_side(direction)?
180                .map(|side| side.price))
181        };
182        let bid = side_price(MetricDirection::ZeroForOne)?;
183        let ask = side_price(MetricDirection::OneForZero)?;
184        let price = match (bid, ask) {
185            (Some(bid), Some(ask)) => (bid + ask) / 2.0,
186            (Some(bid), None) => bid,
187            (None, Some(ask)) => ask,
188            (None, None) => return Err(SimulationError::RecoverableError("No liquidity".into())),
189        };
190        if base.address == self.base_token.address && quote.address == self.quote_token.address {
191            Ok(price)
192        } else if base.address == self.quote_token.address &&
193            quote.address == self.base_token.address
194        {
195            Ok(1.0 / price)
196        } else {
197            Err(SimulationError::InvalidInput(
198                format!(
199                    "Invalid token addresses. Got base={}, quote={}, expected {} / {}",
200                    base.address, quote.address, self.base_token.address, self.quote_token.address
201                ),
202                None,
203            ))
204        }
205    }
206
207    fn get_amount_out(
208        &self,
209        amount_in: BigUint,
210        token_in: &Token,
211        token_out: &Token,
212    ) -> Result<GetAmountOutResult, SimulationError> {
213        // The pool a Metric swap settles against reverts `InvalidAmount()` on a zero input, and
214        // the venue's routing API answers one with `400 amountIn must be positive`.
215        sim::require_positive_amount(&amount_in)?;
216
217        let direction = self.direction(&token_in.address, &token_out.address)?;
218        let Some(side) = self.tradable_side(direction)? else {
219            return Err(SimulationError::InvalidInput(
220                format!(
221                    "Metric pool has no tradable side in this direction (no price or no depth). \
222                     Input {amount_in} cannot be filled"
223                ),
224                None,
225            ));
226        };
227        let max_output = match direction {
228            MetricDirection::ZeroForOne => self.bid_ask.total_token1_available()?,
229            MetricDirection::OneForZero => self.bid_ask.total_token0_available()?,
230        };
231
232        // The depth walk runs entirely in raw integer units on Metric's own per-bin accounting,
233        // so the cap it reports when the depth is exhausted is exact (no f64 round-trip); see
234        // `depth_output_for_input` for the intra-bin rounding.
235        let quote = side.quote(&amount_in, &max_output)?;
236        let res = GetAmountOutResult {
237            amount: quote.amount_out,
238            gas: BigUint::from(METRIC_SWAP_GAS),
239            new_state: self.clone_box(),
240        };
241        if quote.exhausted {
242            return Err(SimulationError::InvalidInput(
243                format!(
244                    "Metric pool depth exhausted. Input {amount_in} cannot be fully filled; \
245                     tradable depth caps output at {}",
246                    quote.max_output
247                ),
248                Some(res),
249            ));
250        }
251        Ok(res)
252    }
253
254    fn get_limits(
255        &self,
256        sell_token: Bytes,
257        buy_token: Bytes,
258    ) -> Result<(BigUint, BigUint), SimulationError> {
259        let direction = self.direction(&sell_token, &buy_token)?;
260        let Some(side) = self.tradable_side(direction)? else {
261            // An untradable side is no swap at any size, so there is no limit to report.
262            return Err(SimulationError::RecoverableError("No liquidity".into()));
263        };
264        // Price of one buy-token unit in sell tokens, plus the per-direction inventory cap and
265        // token decimals.
266        let (sell_per_buy, aggregate, sell_decimals, buy_decimals) = match direction {
267            MetricDirection::ZeroForOne => (
268                1.0 / side.price,
269                self.bid_ask.total_token1_available()?,
270                self.base_token.decimals,
271                self.quote_token.decimals,
272            ),
273            MetricDirection::OneForZero => (
274                side.price,
275                self.bid_ask.total_token0_available()?,
276                self.quote_token.decimals,
277                self.base_token.decimals,
278            ),
279        };
280
281        // Metric's own accounting gives the exact input required to consume the whole book: the
282        // last bin's cumulativeInputVolume. Prefer it over reconstructing the input from the
283        // top-of-book price, which understates the limit by the cumulative price impact.
284        if side.last_bin.cumulative_volume <= aggregate {
285            return Ok((
286                side.last_bin
287                    .cumulative_input_volume
288                    .clone(),
289                side.last_bin.cumulative_volume.clone(),
290            ));
291        }
292
293        // The aggregate inventory truncates the walkable depth, so it is the binding output cap
294        // and get_amount_out reports anything beyond it as depth-exhausted. Estimate the matching
295        // input from the top-of-book price.
296        let buy_limit = aggregate;
297        let buy_limit_human = sim::to_human(&buy_limit, buy_decimals);
298        let sell_limit = sim::to_atomic(buy_limit_human * sell_per_buy, sell_decimals)?;
299        Ok((sell_limit, buy_limit))
300    }
301
302    fn delta_transition(
303        &mut self,
304        _delta: ProtocolStateDelta,
305        _tokens: &HashMap<Bytes, Token>,
306        _balances: &Balances,
307    ) -> Result<(), TransitionError> {
308        // RFQ updates arrive as full API snapshots, not block deltas.
309        Err(TransitionError::DecodeError(
310            "Metric RFQ state is snapshot-based and does not support deltas".into(),
311        ))
312    }
313
314    fn clone_box(&self) -> Box<dyn ProtocolSim> {
315        Box::new(self.clone())
316    }
317
318    fn as_any(&self) -> &dyn Any {
319        self
320    }
321
322    fn as_any_mut(&mut self) -> &mut dyn Any {
323        self
324    }
325
326    fn eq(&self, other: &dyn ProtocolSim) -> bool {
327        if let Some(other_state) = other
328            .as_any()
329            .downcast_ref::<MetricState>()
330        {
331            self.base_token == other_state.base_token &&
332                self.quote_token == other_state.quote_token &&
333                self.metadata == other_state.metadata &&
334                self.bid_ask == other_state.bid_ask
335        } else {
336            false
337        }
338    }
339}
340
341/// Walks the depth bins and computes the output bought by `amount_in`, entirely in raw integer
342/// units using Metric's own per-bin accounting.
343///
344/// Full bins cost exactly their `cumulativeInputVolume` difference — Metric's authoritative,
345/// fee-adjusted accounting. The bin an order ends in is priced along its own straight-line curve
346/// (see `fill::exact_fill_inside_bin`). A bin the inventory cap cuts short is charged pro-rata.
347fn depth_output_for_input(
348    bins: &[MetricDepthBin],
349    side: BookSide,
350    decimals: (u32, u32),
351    amount_in: &BigUint,
352    max_output: &BigUint,
353) -> Result<DepthFill, SimulationError> {
354    if amount_in.is_zero() || max_output.is_zero() {
355        return Ok(DepthFill { output: BigUint::ZERO, exhausted: !amount_in.is_zero() });
356    }
357
358    let mut previous_output = BigUint::ZERO;
359    let mut previous_input = BigUint::ZERO;
360    let mut remaining_input = amount_in.clone();
361    let mut output = BigUint::ZERO;
362
363    for bin in bins {
364        // Metric reports both sides cumulatively to each boundary: output volume in output-token
365        // raw units and the input required to reach it in input-token raw units. Adjacent
366        // differences give the per-bin amounts.
367        let cumulative_output = &bin.cumulative_volume;
368        let cumulative_input = &bin.cumulative_input_volume;
369        if cumulative_output < &previous_output || cumulative_input < &previous_input {
370            return Err(SimulationError::RecoverableError(
371                "Metric depth cumulative volumes are not monotonic".into(),
372            ));
373        }
374        let volume_in_bin = cumulative_output - &previous_output;
375        let input_in_bin = cumulative_input - &previous_input;
376        previous_output = cumulative_output.clone();
377        previous_input = cumulative_input.clone();
378
379        // Price-grid bins without liquidity carry neither volume nor input.
380        if volume_in_bin.is_zero() && input_in_bin.is_zero() {
381            continue;
382        }
383        // A bin with volume but no input (or vice versa) would hand out output for free or charge
384        // input for nothing; refuse to price against corrupt data.
385        if volume_in_bin.is_zero() || input_in_bin.is_zero() {
386            return Err(SimulationError::RecoverableError(
387                "Metric depth bin has inconsistent volume and input".into(),
388            ));
389        }
390
391        let output_capacity = max_output - &output;
392        if output_capacity.is_zero() {
393            break;
394        }
395
396        if volume_in_bin > output_capacity {
397            // The aggregate inventory cap cuts the bin short: charge the fillable slice pro-rata,
398            // rounding the input up so the quote never undercharges.
399            let fillable_input = (&input_in_bin * &output_capacity + &volume_in_bin -
400                BigUint::from(1u8)) /
401                &volume_in_bin;
402            if remaining_input >= fillable_input {
403                output += &output_capacity;
404                remaining_input -= &fillable_input;
405                continue;
406            }
407            output += &output_capacity * &remaining_input / &fillable_input;
408            remaining_input = BigUint::ZERO;
409            break;
410        }
411
412        if remaining_input >= input_in_bin {
413            output += &volume_in_bin;
414            remaining_input -= &input_in_bin;
415            continue;
416        }
417
418        // The input runs out inside this bin: the exact fill along the bin's own curve.
419        let bin_curve = Bin { input: &input_in_bin, output: &volume_in_bin, price: &bin.price };
420        output += exact_fill_inside_bin(bin_curve, side, &remaining_input, decimals)
421            .unwrap_or_else(|| &volume_in_bin * &remaining_input / &input_in_bin);
422        remaining_input = BigUint::ZERO;
423        break;
424    }
425
426    Ok(DepthFill { output, exhausted: !remaining_input.is_zero() })
427}
428
429#[cfg(test)]
430mod tests {
431    use std::str::FromStr;
432
433    use tycho_common::models::Chain;
434
435    use super::*;
436    use crate::pamm::protocols::metric::models::MetricDepth;
437
438    fn big(value: &str) -> BigUint {
439        value.parse().unwrap()
440    }
441
442    fn weth() -> Token {
443        Token::new(
444            &Bytes::from_str("0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2").unwrap(),
445            "WETH",
446            18,
447            0,
448            &[Some(2300)],
449            Chain::Ethereum,
450            100,
451        )
452    }
453
454    fn usdc() -> Token {
455        Token::new(
456            &Bytes::from_str("0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48").unwrap(),
457            "USDC",
458            6,
459            0,
460            &[Some(1)],
461            Chain::Ethereum,
462            100,
463        )
464    }
465
466    fn base_weth() -> Token {
467        Token::new(
468            &Bytes::from_str("0x4200000000000000000000000000000000000006").unwrap(),
469            "WETH",
470            18,
471            0,
472            &[Some(2300)],
473            Chain::Base,
474            100,
475        )
476    }
477
478    fn base_usdc() -> Token {
479        Token::new(
480            &Bytes::from_str("0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913").unwrap(),
481            "USDC",
482            6,
483            0,
484            &[Some(1)],
485            Chain::Base,
486            100,
487        )
488    }
489
490    fn state() -> MetricState {
491        let weth = weth();
492        let usdc = usdc();
493        let metadata = MetricMetadata {
494            pool_address: Bytes::from_str("0xbF48bCf474d57fF82A3215319229e0DE1476A557").unwrap(),
495            token0: weth.address.clone(),
496            token1: usdc.address.clone(),
497            tvl_fiat: Some(3000.0),
498            pause_level: Some(0),
499        };
500        let bid_ask = MetricBidAskResponse {
501            // 3000 * 2^64
502            bid_adj: big("55340232221128654848000"),
503            // 3010 * 2^64
504            ask_adj: big("55524699661865750400000"),
505            total_token0_available: Some(big("10000000000000000000")),
506            total_token1_available: Some(big("30000000000")),
507            server_ts: 100,
508            price_provider_status: Some("healthy".to_string()),
509            // One flat bin per side at the quoted prices: the bid buys 10 WETH for 30000 USDC
510            // (3000), the ask sells 10 WETH for 30100 USDC (3010). Closing at the
511            // quoted price keeps each bin flat, so the walk takes the proportional
512            // share.
513            depth: MetricDepth {
514                bids: vec![MetricDepthBin {
515                    price: big("55340232221128654848000"),
516                    ..depth_bin("30000000000", "10000000000000000000")
517                }],
518                asks: vec![MetricDepthBin {
519                    price: big("55524699661865750400000"),
520                    ..depth_bin("10000000000000000000", "30100000000")
521                }],
522            },
523        };
524        MetricState { base_token: weth, quote_token: usdc, metadata, bid_ask }
525    }
526
527    /// A book whose bid side Metric closed, as it answers one: the bid sentinel and no bid bins.
528    /// The ask side is one bin selling 1 WETH for 3011 USDC.
529    fn state_without_bid() -> MetricState {
530        let mut state = state();
531        state.bid_ask.bid_adj = BigUint::zero();
532        state.bid_ask.depth.bids = vec![];
533        state.bid_ask.depth.asks = vec![depth_bin("1000000000000000000", "3011000000")];
534        state
535    }
536
537    /// A book whose ask side Metric closed: the ask sentinel and no ask bins. The bid side is one
538    /// bin buying 1 WETH for 2999 USDC.
539    fn state_without_ask() -> MetricState {
540        let mut state = state();
541        state.bid_ask.ask_adj = BigUint::from(u128::MAX);
542        state.bid_ask.depth.asks = vec![];
543        state.bid_ask.depth.bids = vec![depth_bin("2999000000", "1000000000000000000")];
544        state
545    }
546
547    /// A side whose price Metric quotes but whose depth holds nothing is not traded at the top of
548    /// the book: there is no size the quote is good for. Metric sends such a side either with no
549    /// bins or with bins whose volumes are all zero.
550    #[rstest::rstest]
551    #[case::no_bins(vec![])]
552    #[case::bins_without_volume(vec![depth_bin("0", "0"), depth_bin("0", "0")])]
553    fn a_priced_side_without_depth_is_not_tradable(#[case] bids: Vec<MetricDepthBin>) {
554        let mut state = state();
555        state.bid_ask.depth.bids = bids;
556        let ask = state
557            .bid_ask
558            .ask_price()
559            .unwrap()
560            .unwrap();
561
562        assert_eq!(state.directions(), vec![(usdc().address, weth().address)]);
563        assert_eq!(
564            state
565                .spot_price(&weth(), &usdc())
566                .unwrap(),
567            ask
568        );
569        assert!(matches!(
570            state.get_limits(weth().address, usdc().address),
571            Err(SimulationError::RecoverableError(_))
572        ));
573        let Err(SimulationError::InvalidInput(msg, None)) =
574            state.get_amount_out(big("100000000000000000"), &weth(), &usdc())
575        else {
576            panic!("selling WETH into a bid without depth must fail");
577        };
578        assert!(msg.contains("no tradable side"), "{msg}");
579    }
580
581    /// A side Metric closed by its sentinel price is not traded even when bins are left on it.
582    #[test]
583    fn a_side_with_bins_but_no_price_is_not_tradable() {
584        let mut state = state();
585        state.bid_ask.ask_adj = BigUint::from(u128::MAX);
586
587        assert_eq!(state.directions(), vec![(weth().address, usdc().address)]);
588        assert!(state
589            .get_amount_out(big("3010000000"), &usdc(), &weth())
590            .is_err());
591    }
592
593    #[test]
594    fn book_without_bid_trades_only_the_ask_side() {
595        let state = state_without_bid();
596        let ask = state
597            .bid_ask
598            .ask_price()
599            .unwrap()
600            .unwrap();
601
602        assert!(state.bid_ask.is_quotable());
603        assert_eq!(
604            state
605                .spot_price(&weth(), &usdc())
606                .unwrap(),
607            ask
608        );
609        assert!(matches!(
610            state.get_limits(weth().address, usdc().address),
611            Err(SimulationError::RecoverableError(_))
612        ));
613        let Err(SimulationError::InvalidInput(msg, None)) =
614            state.get_amount_out(big("100000000000000000"), &weth(), &usdc())
615        else {
616            panic!("selling WETH into a book without a bid must fail");
617        };
618        assert!(msg.contains("no tradable side"), "{msg}");
619        assert_eq!(
620            state
621                .get_limits(usdc().address, weth().address)
622                .unwrap(),
623            (big("3011000000"), big("1000000000000000000"))
624        );
625    }
626
627    #[test]
628    fn book_without_ask_trades_only_the_bid_side() {
629        let state = state_without_ask();
630        let bid = state
631            .bid_ask
632            .bid_price()
633            .unwrap()
634            .unwrap();
635
636        assert!(state.bid_ask.is_quotable());
637        assert_eq!(
638            state
639                .spot_price(&weth(), &usdc())
640                .unwrap(),
641            bid
642        );
643        assert!(matches!(
644            state.get_limits(usdc().address, weth().address),
645            Err(SimulationError::RecoverableError(_))
646        ));
647        let Err(SimulationError::InvalidInput(msg, None)) =
648            state.get_amount_out(big("300000000"), &usdc(), &weth())
649        else {
650            panic!("buying WETH from a book without an ask must fail");
651        };
652        assert!(msg.contains("no tradable side"), "{msg}");
653        assert_eq!(
654            state
655                .get_limits(weth().address, usdc().address)
656                .unwrap(),
657            (big("1000000000000000000"), big("2999000000"))
658        );
659    }
660
661    /// A zero ask price is no quote, so the ask side is not traded even with bins on it:
662    /// `directions`, `get_limits` and `get_amount_out` all leave it out, and the bid side still
663    /// trades.
664    #[test]
665    fn zero_ask_price_is_not_quoted() {
666        let mut state = state();
667        state.bid_ask.ask_adj = BigUint::zero();
668
669        assert!(state.bid_ask.is_quotable());
670        assert_eq!(state.directions(), vec![(weth().address, usdc().address)]);
671        assert!(matches!(
672            state.get_limits(usdc().address, weth().address),
673            Err(SimulationError::RecoverableError(_))
674        ));
675        let Err(SimulationError::InvalidInput(msg, None)) =
676            state.get_amount_out(big("300000000"), &usdc(), &weth())
677        else {
678            panic!("buying WETH from a zero ask price must fail");
679        };
680        assert!(msg.contains("no tradable side"), "{msg}");
681    }
682
683    #[test]
684    fn book_without_quotes_has_no_spot_price() {
685        let mut state = state();
686        state.bid_ask.bid_adj = BigUint::zero();
687        state.bid_ask.ask_adj = BigUint::from(u128::MAX);
688
689        let Err(SimulationError::RecoverableError(msg)) = state.spot_price(&weth(), &usdc()) else {
690            panic!("a book without quotes has no spot price");
691        };
692        assert_eq!(msg, "No liquidity");
693    }
694
695    #[test]
696    fn get_amount_out_zero_for_one() {
697        let state = state();
698        let result = state
699            .get_amount_out(
700                BigUint::from(1_000_000_000_000_000_000u128),
701                &state.base_token,
702                &state.quote_token,
703            )
704            .unwrap();
705
706        assert_eq!(result.amount, BigUint::from(3_000_000_000u64));
707    }
708
709    #[test]
710    fn get_amount_out_one_for_zero() {
711        let state = state();
712        let result = state
713            .get_amount_out(BigUint::from(3_010_000_000u64), &state.quote_token, &state.base_token)
714            .unwrap();
715
716        assert_eq!(result.amount, BigUint::from(1_000_000_000_000_000_000u128));
717    }
718
719    #[test]
720    fn get_amount_out_caps_to_available_liquidity() {
721        let mut state = state();
722        state.bid_ask.total_token1_available = Some(big("1500000000"));
723        let err = state
724            .get_amount_out(
725                BigUint::from(1_000_000_000_000_000_000u128),
726                &state.base_token,
727                &state.quote_token,
728            )
729            .unwrap_err();
730
731        assert!(matches!(err, SimulationError::InvalidInput(_, Some(_))));
732    }
733
734    #[test]
735    fn get_amount_out_depth_exhausted_reports_depth_message() {
736        let mut state = state();
737        state.bid_ask.depth.bids = vec![MetricDepthBin {
738            bin_idx: 0,
739            // 2900 * 2^64
740            price: big("53495557813757699686400"),
741            // Only 3000 USDC of depth, far less than the 30000 USDC aggregate inventory.
742            cumulative_volume: big("3000000000"),
743            // Full-bin input at avg price 2950 (3000 USDC / 2950) ≈ 1.0169 WETH.
744            cumulative_input_volume: big("1016949152542372881"),
745        }];
746
747        let err = state
748            .get_amount_out(
749                // 2 WETH buys more output than the depth can fill.
750                BigUint::from(2_000_000_000_000_000_000u128),
751                &state.base_token,
752                &state.quote_token,
753            )
754            .unwrap_err();
755
756        match err {
757            SimulationError::InvalidInput(msg, Some(_)) => {
758                assert!(msg.contains("depth exhausted"), "unexpected message: {msg}");
759            }
760            other @ (SimulationError::FatalError(_) |
761            SimulationError::InvalidInput(..) |
762            SimulationError::RecoverableError(_)) => panic!("expected InvalidInput, got {other:?}"),
763        }
764    }
765
766    #[test]
767    fn get_amount_out_exhausted_returns_exact_cap() {
768        let mut state = state();
769        // An 18-decimal cap above 2^53 that is NOT representable exactly as f64. This is the
770        // value from the production log; the f64 round-trip would drift it to ...662912.
771        let cap = "6575581573690662958";
772        state.bid_ask.depth.asks = vec![MetricDepthBin {
773            bin_idx: 0,
774            // 3100 * 2^64
775            price: big("57184906628499610009600"),
776            cumulative_volume: big(cap),
777            // Full-bin input at avg price 3055 (~6.5756 WETH * 3055) ≈ 20088 USDC, below the
778            // 30000 USDC input so the whole bin is consumed and the trade is depth-exhausted.
779            cumulative_input_volume: big("20088000000"),
780        }];
781
782        let err = state
783            .get_amount_out(
784                // 30000 USDC buys more WETH than the depth can fill.
785                BigUint::from(30_000_000_000u64),
786                &state.quote_token,
787                &state.base_token,
788            )
789            .unwrap_err();
790
791        match err {
792            SimulationError::InvalidInput(msg, Some(res)) => {
793                assert!(msg.contains("depth exhausted"), "unexpected message: {msg}");
794                // Exact cap, not the f64-reconstructed 6575581573690662912.
795                assert_eq!(res.amount, BigUint::from_str(cap).unwrap());
796            }
797            other @ (SimulationError::FatalError(_) |
798            SimulationError::InvalidInput(..) |
799            SimulationError::RecoverableError(_)) => panic!("expected InvalidInput, got {other:?}"),
800        }
801    }
802
803    #[test]
804    fn get_limits_caps_to_depth() {
805        let mut state = state();
806        state.bid_ask.depth.bids = vec![MetricDepthBin {
807            bin_idx: 0,
808            // 2900 * 2^64
809            price: big("53495557813757699686400"),
810            // 1500 USDC of depth, below the 30000 USDC aggregate inventory.
811            cumulative_volume: big("1500000000"),
812            // 1500 USDC / avg price 2950 ≈ 0.508 WETH.
813            cumulative_input_volume: big("508474576271186440"),
814        }];
815
816        let (sell_limit, buy_limit) = state
817            .get_limits(state.base_token.address.clone(), state.quote_token.address.clone())
818            .unwrap();
819
820        // Output limit follows the depth, not the aggregate inventory.
821        assert_eq!(buy_limit, BigUint::from(1_500_000_000u64));
822        // Input limit is Metric's own accounting: the last bin's cumulativeInputVolume, not a
823        // top-of-book reconstruction (which would understate it by the price impact).
824        assert_eq!(sell_limit, BigUint::from(508_474_576_271_186_440u128));
825    }
826
827    #[test]
828    fn get_limits_aggregate_truncates_depth() {
829        let mut state = state();
830        // Aggregate inventory (1000 USDC) is below the 3000 USDC depth total, so the exact
831        // last-bin input does not apply and the limit falls back to the top-of-book estimate.
832        state.bid_ask.total_token1_available = Some(big("1000000000"));
833        state.bid_ask.depth.bids = vec![MetricDepthBin {
834            bin_idx: 0,
835            // 2900 * 2^64
836            price: big("53495557813757699686400"),
837            cumulative_volume: big("3000000000"),
838            cumulative_input_volume: big("1016949152542372881"),
839        }];
840
841        let (sell_limit, buy_limit) = state
842            .get_limits(state.base_token.address.clone(), state.quote_token.address.clone())
843            .unwrap();
844
845        // Output limit follows the aggregate inventory, not the deeper book.
846        assert_eq!(buy_limit, BigUint::from(1_000_000_000u64));
847        // Input limit estimated at the top-of-book bid (3000): 1000 USDC / 3000 = 1/3 WETH,
848        // rounded through the f64 estimate path (this fallback is an estimate by design).
849        assert_eq!(sell_limit, BigUint::from(333_333_333_333_333_312u128));
850    }
851
852    #[test]
853    fn get_amount_out_walks_bid_depth() {
854        let mut state = state();
855        state.bid_ask.depth.bids = vec![MetricDepthBin {
856            bin_idx: 0,
857            // 2900 * 2^64
858            price: big("53495557813757699686400"),
859            cumulative_volume: big("3000000000"),
860            // Full-bin input at avg price 2950 (3000 USDC / 2950) ≈ 1.0169 WETH.
861            cumulative_input_volume: big("1016949152542372881"),
862        }];
863
864        let result = state
865            .get_amount_out(
866                BigUint::from(1_000_000_000_000_000_000u128),
867                &state.base_token,
868                &state.quote_token,
869            )
870            .unwrap();
871
872        // Pro-rata at the bin's own average price (3000 USDC over 1.016949... WETH = 2950):
873        // 1 WETH buys exactly 2950 USDC.
874        assert_eq!(result.amount, BigUint::from(2_950_000_000u64));
875    }
876
877    #[test]
878    fn get_amount_out_walks_ask_depth() {
879        let mut state = state();
880        state.bid_ask.depth.asks = vec![MetricDepthBin {
881            bin_idx: 0,
882            // 3100 * 2^64
883            price: big("57184906628499610009600"),
884            cumulative_volume: big("1000000000000000000"),
885            // Full-bin input at avg price 3055 (1 WETH * 3055) = 3055 USDC.
886            cumulative_input_volume: big("3055000000"),
887        }];
888
889        let result = state
890            .get_amount_out(BigUint::from(3_000_000_000u64), &state.quote_token, &state.base_token)
891            .unwrap();
892
893        assert!(result.amount < BigUint::from(1_000_000_000_000_000_000u128));
894        assert!(result.amount > BigUint::from(980_000_000_000_000_000u128));
895    }
896
897    fn depth_bin(cumulative_volume: &str, cumulative_input_volume: &str) -> MetricDepthBin {
898        MetricDepthBin {
899            bin_idx: 0,
900            // 2900 * 2^64; the integer walk prices from the volume/input columns, not this field.
901            price: big("53495557813757699686400"),
902            cumulative_volume: big(cumulative_volume),
903            cumulative_input_volume: big(cumulative_input_volume),
904        }
905    }
906
907    #[test]
908    fn depth_output_for_input_partially_fills_bid_bin() {
909        // Full-bin input at price 2950: 3000 USDC costs 3000/2950 ≈ 1.0169 WETH.
910        let bins = vec![depth_bin("3000000000", "1016949152542372881")];
911
912        let fill = depth_output_for_input(
913            &bins,
914            BookSide::Bids,
915            (18, 6),
916            &BigUint::from(1_000_000_000_000_000_000u128),
917            &BigUint::from(3_000_000_000u64),
918        )
919        .unwrap();
920
921        // Pro-rata within the bin: 1 WETH buys exactly 2950 USDC.
922        assert_eq!(fill.output, BigUint::from(2_950_000_000u64));
923        assert!(!fill.exhausted);
924    }
925
926    #[test]
927    fn depth_output_for_input_partially_fills_ask_bin() {
928        // Full-bin input at price 3055: 1 WETH costs 3055 USDC.
929        let bins = vec![depth_bin("1000000000000000000", "3055000000")];
930
931        let fill = depth_output_for_input(
932            &bins,
933            BookSide::Asks,
934            (18, 6),
935            &BigUint::from(3_000_000_000u64),
936            &BigUint::from(1_000_000_000_000_000_000u128),
937        )
938        .unwrap();
939
940        // Pro-rata within the bin, rounded down: 1e18 * 3000 / 3055.
941        let expected = BigUint::from(1_000_000_000_000_000_000u128) *
942            BigUint::from(3_000_000_000u64) /
943            BigUint::from(3_055_000_000u64);
944        assert_eq!(fill.output, expected);
945        assert!(!fill.exhausted);
946    }
947
948    #[test]
949    fn depth_output_for_input_exhausts_available_depth() {
950        let bins = vec![depth_bin("3000000000", "1016949152542372881")];
951
952        let fill = depth_output_for_input(
953            &bins,
954            BookSide::Bids,
955            (18, 6),
956            &BigUint::from(2_000_000_000_000_000_000u128),
957            &BigUint::from(3_000_000_000u64),
958        )
959        .unwrap();
960
961        assert_eq!(fill.output, BigUint::from(3_000_000_000u64));
962        assert!(fill.exhausted);
963    }
964
965    #[test]
966    fn depth_output_for_input_walks_multiple_bins() {
967        // Bin 1 sells 3000 USDC for 1 WETH; bin 2 sells another 3000 USDC for 1.1 WETH.
968        let bins = vec![
969            depth_bin("3000000000", "1000000000000000000"),
970            depth_bin("6000000000", "2100000000000000000"),
971        ];
972
973        let fill = depth_output_for_input(
974            &bins,
975            BookSide::Bids,
976            (18, 6),
977            // 1.55 WETH: consumes bin 1 fully, then half of bin 2's 1.1 WETH.
978            &BigUint::from(1_550_000_000_000_000_000u128),
979            &BigUint::from(6_000_000_000u64),
980        )
981        .unwrap();
982
983        // 3000 + 3000 * 0.55/1.1 = 4500 USDC.
984        assert_eq!(fill.output, BigUint::from(4_500_000_000u64));
985        assert!(!fill.exhausted);
986    }
987
988    #[test]
989    fn depth_output_for_input_caps_slice_to_aggregate_inventory() {
990        let bins = vec![depth_bin("3000000000", "1000000000000000000")];
991
992        // Aggregate inventory truncates the bin to 1500 USDC; the fillable slice costs a
993        // pro-rata 0.5 WETH, so 1 WETH exhausts it.
994        let fill = depth_output_for_input(
995            &bins,
996            BookSide::Bids,
997            (18, 6),
998            &BigUint::from(1_000_000_000_000_000_000u128),
999            &BigUint::from(1_500_000_000u64),
1000        )
1001        .unwrap();
1002
1003        assert_eq!(fill.output, BigUint::from(1_500_000_000u64));
1004        assert!(fill.exhausted);
1005    }
1006
1007    #[test]
1008    fn depth_output_for_input_rejects_inconsistent_bin() {
1009        // Volume without input would hand out output for free.
1010        let bins = vec![depth_bin("3000000000", "0")];
1011
1012        let err = depth_output_for_input(
1013            &bins,
1014            BookSide::Bids,
1015            (18, 6),
1016            &BigUint::from(1_000_000_000_000_000_000u128),
1017            &BigUint::from(3_000_000_000u64),
1018        )
1019        .unwrap_err();
1020
1021        assert!(matches!(err, SimulationError::RecoverableError(_)));
1022    }
1023
1024    #[test]
1025    fn depth_output_for_input_rejects_non_monotonic_bins() {
1026        let bins = vec![
1027            depth_bin("3000000000", "1000000000000000000"),
1028            // Cumulative volume goes backwards.
1029            depth_bin("2000000000", "2000000000000000000"),
1030        ];
1031
1032        let err = depth_output_for_input(
1033            &bins,
1034            BookSide::Bids,
1035            (18, 6),
1036            &BigUint::from(2_000_000_000_000_000_000u128),
1037            &BigUint::from(3_000_000_000u64),
1038        )
1039        .unwrap_err();
1040
1041        assert!(matches!(err, SimulationError::RecoverableError(_)));
1042    }
1043
1044    #[tokio::test]
1045    #[ignore = "hits Metric's public API; requires METRIC_API_KEY"]
1046    async fn live_metric_api_state_get_amount_out() {
1047        use crate::pamm::protocols::metric::models::PaginatedMetadataResponse;
1048
1049        let api_key = std::env::var("METRIC_API_KEY").expect("METRIC_API_KEY not set");
1050
1051        // Base: the only supported chain with pools published on the live API so far.
1052        let weth = base_weth();
1053        let usdc = base_usdc();
1054        let base_url = "https://api.metric.xyz";
1055
1056        let http_client = reqwest::Client::new();
1057        let metadata: PaginatedMetadataResponse = http_client
1058            .get(format!("{base_url}/public/v1/evm/8453/metadata"))
1059            .header("accept", "application/json")
1060            .query(&[("count", "500")])
1061            .bearer_auth(&api_key)
1062            .send()
1063            .await
1064            .unwrap()
1065            .json()
1066            .await
1067            .unwrap();
1068
1069        let mut selected = None;
1070        for pool in metadata
1071            .data
1072            .into_iter()
1073            .filter(|pool| pool.token0 == weth.address && pool.token1 == usdc.address)
1074        {
1075            let checksummed =
1076                alloy::primitives::Address::from_slice(&pool.pool_address).to_checksum(None);
1077            let bid_ask: MetricBidAskResponse = http_client
1078                .get(format!("{base_url}/public/v1/evm/8453/{checksummed}/bid_ask"))
1079                .header("accept", "application/json")
1080                .bearer_auth(&api_key)
1081                .send()
1082                .await
1083                .unwrap()
1084                .json()
1085                .await
1086                .unwrap();
1087            let has_enough_quote_liquidity = bid_ask
1088                .total_token1_available()
1089                .map(|available| available > BigUint::from(10u8))
1090                .unwrap_or(false);
1091            if bid_ask.is_quotable() && has_enough_quote_liquidity {
1092                selected = Some((pool, bid_ask));
1093                break;
1094            }
1095        }
1096
1097        let Some((metadata, bid_ask)) = selected else {
1098            eprintln!("Metric live API returned no liquid Base WETH/USDC pool; skipping");
1099            return;
1100        };
1101
1102        let state = MetricState { base_token: weth, quote_token: usdc, metadata, bid_ask };
1103        assert!(state.bid_ask.is_quotable());
1104
1105        let amount_in = BigUint::from(1_000_000_000u64);
1106        let quote = state
1107            .get_amount_out(amount_in, &state.base_token, &state.quote_token)
1108            .unwrap();
1109
1110        assert!(quote.amount > BigUint::from(0u8));
1111    }
1112
1113    /// The pool a Metric swap settles against reverts on a zero input, so simulating one must
1114    /// not report a fill.
1115    #[test]
1116    fn rejects_a_zero_amount() {
1117        let state = state();
1118
1119        let result = state.get_amount_out(BigUint::ZERO, &weth(), &usdc());
1120
1121        assert!(matches!(result, Err(SimulationError::InvalidInput(_, None))), "{result:?}");
1122    }
1123
1124    /// The WETH/USDC example of Metric's "Estimate a fill from depth" page: 5 WETH sold into two
1125    /// bid bins. The second bin is only partly filled, and the page's exact fill inside it gives
1126    /// 13535754492 raw USDC in total.
1127    #[test]
1128    fn get_amount_out_fills_the_bin_on_the_pool_curve() {
1129        let mut state = state();
1130        state.bid_ask.depth.bids = vec![
1131            MetricDepthBin {
1132                bin_idx: -1,
1133                price: big("49937913286041055521250"),
1134                cumulative_volume: big("7430706558"),
1135                cumulative_input_volume: big("2744786401520641763"),
1136            },
1137            MetricDepthBin {
1138                bin_idx: -2,
1139                price: big("49932918995283375647711"),
1140                cumulative_volume: big("21731301391"),
1141                cumulative_input_volume: big("8027598362225637937"),
1142            },
1143        ];
1144
1145        let result = state
1146            .get_amount_out(big("5000000000000000000"), &state.base_token, &state.quote_token)
1147            .unwrap();
1148
1149        assert_eq!(result.amount, big("13535754492"));
1150    }
1151}