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 => panic!("expected InvalidInput, got {other:?}"),
661        }
662    }
663
664    #[test]
665    fn get_amount_out_exhausted_returns_exact_cap() {
666        let mut state = state();
667        // An 18-decimal cap above 2^53 that is NOT representable exactly as f64. This is the
668        // value from the production log; the f64 round-trip would drift it to ...662912.
669        let cap = "6575581573690662958";
670        state.bid_ask.depth.asks = vec![MetricDepthBin {
671            bin_idx: 0,
672            // 3100 * 2^64
673            price: big("57184906628499610009600"),
674            cumulative_volume: big(cap),
675            // Full-bin input at avg price 3055 (~6.5756 WETH * 3055) ≈ 20088 USDC, below the
676            // 30000 USDC input so the whole bin is consumed and the trade is depth-exhausted.
677            cumulative_input_volume: big("20088000000"),
678        }];
679
680        let err = state
681            .get_amount_out(
682                // 30000 USDC buys more WETH than the depth can fill.
683                BigUint::from(30_000_000_000u64),
684                &state.quote_token,
685                &state.base_token,
686            )
687            .unwrap_err();
688
689        match err {
690            SimulationError::InvalidInput(msg, Some(res)) => {
691                assert!(msg.contains("depth exhausted"), "unexpected message: {msg}");
692                // Exact cap, not the f64-reconstructed 6575581573690662912.
693                assert_eq!(res.amount, BigUint::from_str(cap).unwrap());
694            }
695            other => panic!("expected InvalidInput, got {other:?}"),
696        }
697    }
698
699    #[test]
700    fn get_limits_caps_to_depth() {
701        let mut state = state();
702        state.bid_ask.depth.bids = vec![MetricDepthBin {
703            bin_idx: 0,
704            // 2900 * 2^64
705            price: big("53495557813757699686400"),
706            // 1500 USDC of depth, below the 30000 USDC aggregate inventory.
707            cumulative_volume: big("1500000000"),
708            // 1500 USDC / avg price 2950 ≈ 0.508 WETH.
709            cumulative_input_volume: big("508474576271186440"),
710        }];
711
712        let (sell_limit, buy_limit) = state
713            .get_limits(state.base_token.address.clone(), state.quote_token.address.clone())
714            .unwrap();
715
716        // Output limit follows the depth, not the aggregate inventory.
717        assert_eq!(buy_limit, BigUint::from(1_500_000_000u64));
718        // Input limit is Metric's own accounting: the last bin's cumulativeInputVolume, not a
719        // top-of-book reconstruction (which would understate it by the price impact).
720        assert_eq!(sell_limit, BigUint::from(508_474_576_271_186_440u128));
721    }
722
723    #[test]
724    fn get_limits_aggregate_truncates_depth() {
725        let mut state = state();
726        // Aggregate inventory (1000 USDC) is below the 3000 USDC depth total, so the exact
727        // last-bin input does not apply and the limit falls back to the top-of-book estimate.
728        state.bid_ask.total_token1_available = Some(big("1000000000"));
729        state.bid_ask.depth.bids = vec![MetricDepthBin {
730            bin_idx: 0,
731            // 2900 * 2^64
732            price: big("53495557813757699686400"),
733            cumulative_volume: big("3000000000"),
734            cumulative_input_volume: big("1016949152542372881"),
735        }];
736
737        let (sell_limit, buy_limit) = state
738            .get_limits(state.base_token.address.clone(), state.quote_token.address.clone())
739            .unwrap();
740
741        // Output limit follows the aggregate inventory, not the deeper book.
742        assert_eq!(buy_limit, BigUint::from(1_000_000_000u64));
743        // Input limit estimated at the top-of-book bid (3000): 1000 USDC / 3000 = 1/3 WETH,
744        // rounded through the f64 estimate path (this fallback is an estimate by design).
745        assert_eq!(sell_limit, BigUint::from(333_333_333_333_333_312u128));
746    }
747
748    #[test]
749    fn get_limits_uses_aggregate_without_depth() {
750        let state = state();
751
752        let (_, buy_limit) = state
753            .get_limits(state.base_token.address.clone(), state.quote_token.address.clone())
754            .unwrap();
755
756        // No depth bins: fall back to aggregate inventory (30000 USDC).
757        assert_eq!(buy_limit, BigUint::from(30_000_000_000u64));
758    }
759
760    #[test]
761    fn get_amount_out_walks_bid_depth() {
762        let mut state = state();
763        state.bid_ask.depth.bids = vec![MetricDepthBin {
764            bin_idx: 0,
765            // 2900 * 2^64
766            price: big("53495557813757699686400"),
767            cumulative_volume: big("3000000000"),
768            // Full-bin input at avg price 2950 (3000 USDC / 2950) ≈ 1.0169 WETH.
769            cumulative_input_volume: big("1016949152542372881"),
770        }];
771
772        let result = state
773            .get_amount_out(
774                BigUint::from(1_000_000_000_000_000_000u128),
775                &state.base_token,
776                &state.quote_token,
777            )
778            .unwrap();
779
780        // Pro-rata at the bin's own average price (3000 USDC over 1.016949... WETH = 2950):
781        // 1 WETH buys exactly 2950 USDC.
782        assert_eq!(result.amount, BigUint::from(2_950_000_000u64));
783    }
784
785    #[test]
786    fn get_amount_out_walks_ask_depth() {
787        let mut state = state();
788        state.bid_ask.depth.asks = vec![MetricDepthBin {
789            bin_idx: 0,
790            // 3100 * 2^64
791            price: big("57184906628499610009600"),
792            cumulative_volume: big("1000000000000000000"),
793            // Full-bin input at avg price 3055 (1 WETH * 3055) = 3055 USDC.
794            cumulative_input_volume: big("3055000000"),
795        }];
796
797        let result = state
798            .get_amount_out(BigUint::from(3_000_000_000u64), &state.quote_token, &state.base_token)
799            .unwrap();
800
801        assert!(result.amount < BigUint::from(1_000_000_000_000_000_000u128));
802        assert!(result.amount > BigUint::from(980_000_000_000_000_000u128));
803    }
804
805    fn depth_bin(cumulative_volume: &str, cumulative_input_volume: &str) -> MetricDepthBin {
806        MetricDepthBin {
807            bin_idx: 0,
808            // 2900 * 2^64; the integer walk prices from the volume/input columns, not this field.
809            price: big("53495557813757699686400"),
810            cumulative_volume: big(cumulative_volume),
811            cumulative_input_volume: big(cumulative_input_volume),
812        }
813    }
814
815    #[test]
816    fn depth_output_for_input_partially_fills_bid_bin() {
817        // Full-bin input at price 2950: 3000 USDC costs 3000/2950 ≈ 1.0169 WETH.
818        let bins = vec![depth_bin("3000000000", "1016949152542372881")];
819
820        let fill = depth_output_for_input(
821            &bins,
822            &BigUint::from(1_000_000_000_000_000_000u128),
823            &BigUint::from(3_000_000_000u64),
824        )
825        .unwrap();
826
827        // Pro-rata within the bin: 1 WETH buys exactly 2950 USDC.
828        assert_eq!(fill.output, BigUint::from(2_950_000_000u64));
829        assert!(!fill.exhausted);
830    }
831
832    #[test]
833    fn depth_output_for_input_partially_fills_ask_bin() {
834        // Full-bin input at price 3055: 1 WETH costs 3055 USDC.
835        let bins = vec![depth_bin("1000000000000000000", "3055000000")];
836
837        let fill = depth_output_for_input(
838            &bins,
839            &BigUint::from(3_000_000_000u64),
840            &BigUint::from(1_000_000_000_000_000_000u128),
841        )
842        .unwrap();
843
844        // Pro-rata within the bin, rounded down: 1e18 * 3000 / 3055.
845        let expected = BigUint::from(1_000_000_000_000_000_000u128) *
846            BigUint::from(3_000_000_000u64) /
847            BigUint::from(3_055_000_000u64);
848        assert_eq!(fill.output, expected);
849        assert!(!fill.exhausted);
850    }
851
852    #[test]
853    fn depth_output_for_input_exhausts_available_depth() {
854        let bins = vec![depth_bin("3000000000", "1016949152542372881")];
855
856        let fill = depth_output_for_input(
857            &bins,
858            &BigUint::from(2_000_000_000_000_000_000u128),
859            &BigUint::from(3_000_000_000u64),
860        )
861        .unwrap();
862
863        assert_eq!(fill.output, BigUint::from(3_000_000_000u64));
864        assert!(fill.exhausted);
865    }
866
867    #[test]
868    fn depth_output_for_input_walks_multiple_bins() {
869        // Bin 1 sells 3000 USDC for 1 WETH; bin 2 sells another 3000 USDC for 1.1 WETH.
870        let bins = vec![
871            depth_bin("3000000000", "1000000000000000000"),
872            depth_bin("6000000000", "2100000000000000000"),
873        ];
874
875        let fill = depth_output_for_input(
876            &bins,
877            // 1.55 WETH: consumes bin 1 fully, then half of bin 2's 1.1 WETH.
878            &BigUint::from(1_550_000_000_000_000_000u128),
879            &BigUint::from(6_000_000_000u64),
880        )
881        .unwrap();
882
883        // 3000 + 3000 * 0.55/1.1 = 4500 USDC.
884        assert_eq!(fill.output, BigUint::from(4_500_000_000u64));
885        assert!(!fill.exhausted);
886    }
887
888    #[test]
889    fn depth_output_for_input_caps_slice_to_aggregate_inventory() {
890        let bins = vec![depth_bin("3000000000", "1000000000000000000")];
891
892        // Aggregate inventory truncates the bin to 1500 USDC; the fillable slice costs a
893        // pro-rata 0.5 WETH, so 1 WETH exhausts it.
894        let fill = depth_output_for_input(
895            &bins,
896            &BigUint::from(1_000_000_000_000_000_000u128),
897            &BigUint::from(1_500_000_000u64),
898        )
899        .unwrap();
900
901        assert_eq!(fill.output, BigUint::from(1_500_000_000u64));
902        assert!(fill.exhausted);
903    }
904
905    #[test]
906    fn depth_output_for_input_rejects_inconsistent_bin() {
907        // Volume without input would hand out output for free.
908        let bins = vec![depth_bin("3000000000", "0")];
909
910        let err = depth_output_for_input(
911            &bins,
912            &BigUint::from(1_000_000_000_000_000_000u128),
913            &BigUint::from(3_000_000_000u64),
914        )
915        .unwrap_err();
916
917        assert!(matches!(err, SimulationError::RecoverableError(_)));
918    }
919
920    #[test]
921    fn depth_output_for_input_rejects_non_monotonic_bins() {
922        let bins = vec![
923            depth_bin("3000000000", "1000000000000000000"),
924            // Cumulative volume goes backwards.
925            depth_bin("2000000000", "2000000000000000000"),
926        ];
927
928        let err = depth_output_for_input(
929            &bins,
930            &BigUint::from(2_000_000_000_000_000_000u128),
931            &BigUint::from(3_000_000_000u64),
932        )
933        .unwrap_err();
934
935        assert!(matches!(err, SimulationError::RecoverableError(_)));
936    }
937
938    #[tokio::test]
939    #[ignore = "hits Metric's public API; requires METRIC_API_KEY"]
940    async fn live_metric_api_state_get_amount_out() {
941        use crate::pamm::protocols::metric::models::PaginatedMetadataResponse;
942
943        let api_key = std::env::var("METRIC_API_KEY").expect("METRIC_API_KEY not set");
944
945        // Base: the only supported chain with pools published on the live API so far.
946        let weth = base_weth();
947        let usdc = base_usdc();
948        let base_url = "https://api.metric.xyz";
949
950        let http_client = reqwest::Client::new();
951        let metadata: PaginatedMetadataResponse = http_client
952            .get(format!("{base_url}/public/v1/evm/8453/metadata"))
953            .header("accept", "application/json")
954            .query(&[("count", "500")])
955            .bearer_auth(&api_key)
956            .send()
957            .await
958            .unwrap()
959            .json()
960            .await
961            .unwrap();
962
963        let mut selected = None;
964        for pool in metadata
965            .data
966            .into_iter()
967            .filter(|pool| pool.token0 == weth.address && pool.token1 == usdc.address)
968        {
969            let checksummed =
970                alloy::primitives::Address::from_slice(&pool.pool_address).to_checksum(None);
971            let bid_ask: MetricBidAskResponse = http_client
972                .get(format!("{base_url}/public/v1/evm/8453/{checksummed}/bid_ask"))
973                .header("accept", "application/json")
974                .bearer_auth(&api_key)
975                .send()
976                .await
977                .unwrap()
978                .json()
979                .await
980                .unwrap();
981            let has_enough_quote_liquidity = bid_ask
982                .total_token1_available()
983                .map(|available| available > BigUint::from(10u8))
984                .unwrap_or(false);
985            if bid_ask.is_quotable() && has_enough_quote_liquidity {
986                selected = Some((pool, bid_ask));
987                break;
988            }
989        }
990
991        let Some((metadata, bid_ask)) = selected else {
992            eprintln!("Metric live API returned no liquid Base WETH/USDC pool; skipping");
993            return;
994        };
995
996        let state = MetricState { base_token: weth, quote_token: usdc, metadata, bid_ask };
997        assert!(state.bid_ask.is_quotable());
998
999        let amount_in = BigUint::from(1_000_000_000u64);
1000        let quote = state
1001            .get_amount_out(amount_in, &state.base_token, &state.quote_token)
1002            .unwrap();
1003
1004        assert!(quote.amount > BigUint::from(0u8));
1005    }
1006
1007    /// The pool a Metric swap settles against reverts on a zero input, so simulating one must
1008    /// not report a fill.
1009    #[test]
1010    fn rejects_a_zero_amount() {
1011        let state = state();
1012
1013        let result = state.get_amount_out(BigUint::ZERO, &weth(), &usdc());
1014
1015        assert!(matches!(result, Err(SimulationError::InvalidInput(_, None))), "{result:?}");
1016    }
1017}