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