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        };
484        let bid_ask = MetricBidAskResponse {
485            // 3000 * 2^64
486            bid_adj: big("55340232221128654848000"),
487            // 3010 * 2^64
488            ask_adj: big("55524699661865750400000"),
489            total_token0_available: Some(big("10000000000000000000")),
490            total_token1_available: Some(big("30000000000")),
491            server_ts: 100,
492            price_provider_status: Some("healthy".to_string()),
493            depth: MetricDepth::default(),
494        };
495        MetricState { base_token: weth, quote_token: usdc, metadata, bid_ask }
496    }
497
498    /// A book with an ask side only: one bin selling 1 WETH for 3011 USDC.
499    fn state_without_bid() -> MetricState {
500        let mut state = state();
501        state.bid_ask.bid_adj = BigUint::zero();
502        state.bid_ask.depth.asks = vec![depth_bin("1000000000000000000", "3011000000")];
503        state
504    }
505
506    /// A book with a bid side only: one bin buying 1 WETH for 2999 USDC.
507    fn state_without_ask() -> MetricState {
508        let mut state = state();
509        state.bid_ask.ask_adj = BigUint::from(u128::MAX);
510        state.bid_ask.depth.bids = vec![depth_bin("2999000000", "1000000000000000000")];
511        state
512    }
513
514    #[test]
515    fn book_without_bid_trades_only_the_ask_side() {
516        let state = state_without_bid();
517        let ask = state
518            .bid_ask
519            .ask_price()
520            .unwrap()
521            .unwrap();
522
523        assert!(state.bid_ask.is_quotable());
524        assert_eq!(
525            state
526                .spot_price(&weth(), &usdc())
527                .unwrap(),
528            ask
529        );
530        assert!(matches!(
531            state.get_limits(weth().address, usdc().address),
532            Err(SimulationError::RecoverableError(_))
533        ));
534        let Err(SimulationError::InvalidInput(msg, None)) =
535            state.get_amount_out(big("100000000000000000"), &weth(), &usdc())
536        else {
537            panic!("selling WETH into a book without a bid must fail");
538        };
539        assert!(msg.contains("quotes no price in this direction"), "{msg}");
540        assert_eq!(
541            state
542                .get_limits(usdc().address, weth().address)
543                .unwrap(),
544            (big("3011000000"), big("1000000000000000000"))
545        );
546    }
547
548    #[test]
549    fn book_without_ask_trades_only_the_bid_side() {
550        let state = state_without_ask();
551        let bid = state
552            .bid_ask
553            .bid_price()
554            .unwrap()
555            .unwrap();
556
557        assert!(state.bid_ask.is_quotable());
558        assert_eq!(
559            state
560                .spot_price(&weth(), &usdc())
561                .unwrap(),
562            bid
563        );
564        assert!(matches!(
565            state.get_limits(usdc().address, weth().address),
566            Err(SimulationError::RecoverableError(_))
567        ));
568        let Err(SimulationError::InvalidInput(msg, None)) =
569            state.get_amount_out(big("300000000"), &usdc(), &weth())
570        else {
571            panic!("buying WETH from a book without an ask must fail");
572        };
573        assert!(msg.contains("quotes no price in this direction"), "{msg}");
574        assert_eq!(
575            state
576                .get_limits(weth().address, usdc().address)
577                .unwrap(),
578            (big("1000000000000000000"), big("2999000000"))
579        );
580    }
581
582    #[test]
583    fn book_without_quotes_has_no_spot_price() {
584        let mut state = state();
585        state.bid_ask.bid_adj = BigUint::zero();
586        state.bid_ask.ask_adj = BigUint::from(u128::MAX);
587
588        let Err(SimulationError::RecoverableError(msg)) = state.spot_price(&weth(), &usdc()) else {
589            panic!("a book without quotes has no spot price");
590        };
591        assert_eq!(msg, "No liquidity");
592    }
593
594    #[test]
595    fn get_amount_out_zero_for_one() {
596        let state = state();
597        let result = state
598            .get_amount_out(
599                BigUint::from(1_000_000_000_000_000_000u128),
600                &state.base_token,
601                &state.quote_token,
602            )
603            .unwrap();
604
605        assert_eq!(result.amount, BigUint::from(3_000_000_000u64));
606    }
607
608    #[test]
609    fn get_amount_out_one_for_zero() {
610        let state = state();
611        let result = state
612            .get_amount_out(BigUint::from(3_010_000_000u64), &state.quote_token, &state.base_token)
613            .unwrap();
614
615        assert_eq!(result.amount, BigUint::from(1_000_000_000_000_000_000u128));
616    }
617
618    #[test]
619    fn get_amount_out_caps_to_available_liquidity() {
620        let mut state = state();
621        state.bid_ask.total_token1_available = Some(big("1500000000"));
622        let err = state
623            .get_amount_out(
624                BigUint::from(1_000_000_000_000_000_000u128),
625                &state.base_token,
626                &state.quote_token,
627            )
628            .unwrap_err();
629
630        assert!(matches!(err, SimulationError::InvalidInput(_, Some(_))));
631    }
632
633    #[test]
634    fn get_amount_out_depth_exhausted_reports_depth_message() {
635        let mut state = state();
636        state.bid_ask.depth.bids = vec![MetricDepthBin {
637            bin_idx: 0,
638            // 2900 * 2^64
639            price: big("53495557813757699686400"),
640            // Only 3000 USDC of depth, far less than the 30000 USDC aggregate inventory.
641            cumulative_volume: big("3000000000"),
642            // Full-bin input at avg price 2950 (3000 USDC / 2950) ≈ 1.0169 WETH.
643            cumulative_input_volume: big("1016949152542372881"),
644        }];
645
646        let err = state
647            .get_amount_out(
648                // 2 WETH buys more output than the depth can fill.
649                BigUint::from(2_000_000_000_000_000_000u128),
650                &state.base_token,
651                &state.quote_token,
652            )
653            .unwrap_err();
654
655        match err {
656            SimulationError::InvalidInput(msg, Some(_)) => {
657                assert!(msg.contains("depth exhausted"), "unexpected message: {msg}");
658            }
659            other => panic!("expected InvalidInput, got {other:?}"),
660        }
661    }
662
663    #[test]
664    fn get_amount_out_exhausted_returns_exact_cap() {
665        let mut state = state();
666        // An 18-decimal cap above 2^53 that is NOT representable exactly as f64. This is the
667        // value from the production log; the f64 round-trip would drift it to ...662912.
668        let cap = "6575581573690662958";
669        state.bid_ask.depth.asks = vec![MetricDepthBin {
670            bin_idx: 0,
671            // 3100 * 2^64
672            price: big("57184906628499610009600"),
673            cumulative_volume: big(cap),
674            // Full-bin input at avg price 3055 (~6.5756 WETH * 3055) ≈ 20088 USDC, below the
675            // 30000 USDC input so the whole bin is consumed and the trade is depth-exhausted.
676            cumulative_input_volume: big("20088000000"),
677        }];
678
679        let err = state
680            .get_amount_out(
681                // 30000 USDC buys more WETH than the depth can fill.
682                BigUint::from(30_000_000_000u64),
683                &state.quote_token,
684                &state.base_token,
685            )
686            .unwrap_err();
687
688        match err {
689            SimulationError::InvalidInput(msg, Some(res)) => {
690                assert!(msg.contains("depth exhausted"), "unexpected message: {msg}");
691                // Exact cap, not the f64-reconstructed 6575581573690662912.
692                assert_eq!(res.amount, BigUint::from_str(cap).unwrap());
693            }
694            other => panic!("expected InvalidInput, got {other:?}"),
695        }
696    }
697
698    #[test]
699    fn get_limits_caps_to_depth() {
700        let mut state = state();
701        state.bid_ask.depth.bids = vec![MetricDepthBin {
702            bin_idx: 0,
703            // 2900 * 2^64
704            price: big("53495557813757699686400"),
705            // 1500 USDC of depth, below the 30000 USDC aggregate inventory.
706            cumulative_volume: big("1500000000"),
707            // 1500 USDC / avg price 2950 ≈ 0.508 WETH.
708            cumulative_input_volume: big("508474576271186440"),
709        }];
710
711        let (sell_limit, buy_limit) = state
712            .get_limits(state.base_token.address.clone(), state.quote_token.address.clone())
713            .unwrap();
714
715        // Output limit follows the depth, not the aggregate inventory.
716        assert_eq!(buy_limit, BigUint::from(1_500_000_000u64));
717        // Input limit is Metric's own accounting: the last bin's cumulativeInputVolume, not a
718        // top-of-book reconstruction (which would understate it by the price impact).
719        assert_eq!(sell_limit, BigUint::from(508_474_576_271_186_440u128));
720    }
721
722    #[test]
723    fn get_limits_aggregate_truncates_depth() {
724        let mut state = state();
725        // Aggregate inventory (1000 USDC) is below the 3000 USDC depth total, so the exact
726        // last-bin input does not apply and the limit falls back to the top-of-book estimate.
727        state.bid_ask.total_token1_available = Some(big("1000000000"));
728        state.bid_ask.depth.bids = vec![MetricDepthBin {
729            bin_idx: 0,
730            // 2900 * 2^64
731            price: big("53495557813757699686400"),
732            cumulative_volume: big("3000000000"),
733            cumulative_input_volume: big("1016949152542372881"),
734        }];
735
736        let (sell_limit, buy_limit) = state
737            .get_limits(state.base_token.address.clone(), state.quote_token.address.clone())
738            .unwrap();
739
740        // Output limit follows the aggregate inventory, not the deeper book.
741        assert_eq!(buy_limit, BigUint::from(1_000_000_000u64));
742        // Input limit estimated at the top-of-book bid (3000): 1000 USDC / 3000 = 1/3 WETH,
743        // rounded through the f64 estimate path (this fallback is an estimate by design).
744        assert_eq!(sell_limit, BigUint::from(333_333_333_333_333_312u128));
745    }
746
747    #[test]
748    fn get_limits_uses_aggregate_without_depth() {
749        let state = state();
750
751        let (_, buy_limit) = state
752            .get_limits(state.base_token.address.clone(), state.quote_token.address.clone())
753            .unwrap();
754
755        // No depth bins: fall back to aggregate inventory (30000 USDC).
756        assert_eq!(buy_limit, BigUint::from(30_000_000_000u64));
757    }
758
759    #[test]
760    fn get_amount_out_walks_bid_depth() {
761        let mut state = state();
762        state.bid_ask.depth.bids = vec![MetricDepthBin {
763            bin_idx: 0,
764            // 2900 * 2^64
765            price: big("53495557813757699686400"),
766            cumulative_volume: big("3000000000"),
767            // Full-bin input at avg price 2950 (3000 USDC / 2950) ≈ 1.0169 WETH.
768            cumulative_input_volume: big("1016949152542372881"),
769        }];
770
771        let result = state
772            .get_amount_out(
773                BigUint::from(1_000_000_000_000_000_000u128),
774                &state.base_token,
775                &state.quote_token,
776            )
777            .unwrap();
778
779        // Pro-rata at the bin's own average price (3000 USDC over 1.016949... WETH = 2950):
780        // 1 WETH buys exactly 2950 USDC.
781        assert_eq!(result.amount, BigUint::from(2_950_000_000u64));
782    }
783
784    #[test]
785    fn get_amount_out_walks_ask_depth() {
786        let mut state = state();
787        state.bid_ask.depth.asks = vec![MetricDepthBin {
788            bin_idx: 0,
789            // 3100 * 2^64
790            price: big("57184906628499610009600"),
791            cumulative_volume: big("1000000000000000000"),
792            // Full-bin input at avg price 3055 (1 WETH * 3055) = 3055 USDC.
793            cumulative_input_volume: big("3055000000"),
794        }];
795
796        let result = state
797            .get_amount_out(BigUint::from(3_000_000_000u64), &state.quote_token, &state.base_token)
798            .unwrap();
799
800        assert!(result.amount < BigUint::from(1_000_000_000_000_000_000u128));
801        assert!(result.amount > BigUint::from(980_000_000_000_000_000u128));
802    }
803
804    fn depth_bin(cumulative_volume: &str, cumulative_input_volume: &str) -> MetricDepthBin {
805        MetricDepthBin {
806            bin_idx: 0,
807            // 2900 * 2^64; the integer walk prices from the volume/input columns, not this field.
808            price: big("53495557813757699686400"),
809            cumulative_volume: big(cumulative_volume),
810            cumulative_input_volume: big(cumulative_input_volume),
811        }
812    }
813
814    #[test]
815    fn depth_output_for_input_partially_fills_bid_bin() {
816        // Full-bin input at price 2950: 3000 USDC costs 3000/2950 ≈ 1.0169 WETH.
817        let bins = vec![depth_bin("3000000000", "1016949152542372881")];
818
819        let fill = depth_output_for_input(
820            &bins,
821            &BigUint::from(1_000_000_000_000_000_000u128),
822            &BigUint::from(3_000_000_000u64),
823        )
824        .unwrap();
825
826        // Pro-rata within the bin: 1 WETH buys exactly 2950 USDC.
827        assert_eq!(fill.output, BigUint::from(2_950_000_000u64));
828        assert!(!fill.exhausted);
829    }
830
831    #[test]
832    fn depth_output_for_input_partially_fills_ask_bin() {
833        // Full-bin input at price 3055: 1 WETH costs 3055 USDC.
834        let bins = vec![depth_bin("1000000000000000000", "3055000000")];
835
836        let fill = depth_output_for_input(
837            &bins,
838            &BigUint::from(3_000_000_000u64),
839            &BigUint::from(1_000_000_000_000_000_000u128),
840        )
841        .unwrap();
842
843        // Pro-rata within the bin, rounded down: 1e18 * 3000 / 3055.
844        let expected = BigUint::from(1_000_000_000_000_000_000u128) *
845            BigUint::from(3_000_000_000u64) /
846            BigUint::from(3_055_000_000u64);
847        assert_eq!(fill.output, expected);
848        assert!(!fill.exhausted);
849    }
850
851    #[test]
852    fn depth_output_for_input_exhausts_available_depth() {
853        let bins = vec![depth_bin("3000000000", "1016949152542372881")];
854
855        let fill = depth_output_for_input(
856            &bins,
857            &BigUint::from(2_000_000_000_000_000_000u128),
858            &BigUint::from(3_000_000_000u64),
859        )
860        .unwrap();
861
862        assert_eq!(fill.output, BigUint::from(3_000_000_000u64));
863        assert!(fill.exhausted);
864    }
865
866    #[test]
867    fn depth_output_for_input_walks_multiple_bins() {
868        // Bin 1 sells 3000 USDC for 1 WETH; bin 2 sells another 3000 USDC for 1.1 WETH.
869        let bins = vec![
870            depth_bin("3000000000", "1000000000000000000"),
871            depth_bin("6000000000", "2100000000000000000"),
872        ];
873
874        let fill = depth_output_for_input(
875            &bins,
876            // 1.55 WETH: consumes bin 1 fully, then half of bin 2's 1.1 WETH.
877            &BigUint::from(1_550_000_000_000_000_000u128),
878            &BigUint::from(6_000_000_000u64),
879        )
880        .unwrap();
881
882        // 3000 + 3000 * 0.55/1.1 = 4500 USDC.
883        assert_eq!(fill.output, BigUint::from(4_500_000_000u64));
884        assert!(!fill.exhausted);
885    }
886
887    #[test]
888    fn depth_output_for_input_caps_slice_to_aggregate_inventory() {
889        let bins = vec![depth_bin("3000000000", "1000000000000000000")];
890
891        // Aggregate inventory truncates the bin to 1500 USDC; the fillable slice costs a
892        // pro-rata 0.5 WETH, so 1 WETH exhausts it.
893        let fill = depth_output_for_input(
894            &bins,
895            &BigUint::from(1_000_000_000_000_000_000u128),
896            &BigUint::from(1_500_000_000u64),
897        )
898        .unwrap();
899
900        assert_eq!(fill.output, BigUint::from(1_500_000_000u64));
901        assert!(fill.exhausted);
902    }
903
904    #[test]
905    fn depth_output_for_input_rejects_inconsistent_bin() {
906        // Volume without input would hand out output for free.
907        let bins = vec![depth_bin("3000000000", "0")];
908
909        let err = depth_output_for_input(
910            &bins,
911            &BigUint::from(1_000_000_000_000_000_000u128),
912            &BigUint::from(3_000_000_000u64),
913        )
914        .unwrap_err();
915
916        assert!(matches!(err, SimulationError::RecoverableError(_)));
917    }
918
919    #[test]
920    fn depth_output_for_input_rejects_non_monotonic_bins() {
921        let bins = vec![
922            depth_bin("3000000000", "1000000000000000000"),
923            // Cumulative volume goes backwards.
924            depth_bin("2000000000", "2000000000000000000"),
925        ];
926
927        let err = depth_output_for_input(
928            &bins,
929            &BigUint::from(2_000_000_000_000_000_000u128),
930            &BigUint::from(3_000_000_000u64),
931        )
932        .unwrap_err();
933
934        assert!(matches!(err, SimulationError::RecoverableError(_)));
935    }
936
937    #[tokio::test]
938    #[ignore = "hits Metric's public API; requires METRIC_API_KEY"]
939    async fn live_metric_api_state_get_amount_out() {
940        use crate::pamm::protocols::metric::models::PaginatedMetadataResponse;
941
942        let api_key = std::env::var("METRIC_API_KEY").expect("METRIC_API_KEY not set");
943
944        // Base: the only supported chain with pools published on the live API so far.
945        let weth = base_weth();
946        let usdc = base_usdc();
947        let base_url = "https://api.metric.xyz";
948
949        let http_client = reqwest::Client::new();
950        let metadata: PaginatedMetadataResponse = http_client
951            .get(format!("{base_url}/public/v1/evm/8453/metadata"))
952            .header("accept", "application/json")
953            .query(&[("count", "500")])
954            .bearer_auth(&api_key)
955            .send()
956            .await
957            .unwrap()
958            .json()
959            .await
960            .unwrap();
961
962        let mut selected = None;
963        for pool in metadata
964            .data
965            .into_iter()
966            .filter(|pool| pool.token0 == weth.address && pool.token1 == usdc.address)
967        {
968            let checksummed =
969                alloy::primitives::Address::from_slice(&pool.pool_address).to_checksum(None);
970            let bid_ask: MetricBidAskResponse = http_client
971                .get(format!("{base_url}/public/v1/evm/8453/{checksummed}/bid_ask"))
972                .header("accept", "application/json")
973                .bearer_auth(&api_key)
974                .send()
975                .await
976                .unwrap()
977                .json()
978                .await
979                .unwrap();
980            let has_enough_quote_liquidity = bid_ask
981                .total_token1_available()
982                .map(|available| available > BigUint::from(10u8))
983                .unwrap_or(false);
984            if bid_ask.is_quotable() && has_enough_quote_liquidity {
985                selected = Some((pool, bid_ask));
986                break;
987            }
988        }
989
990        let Some((metadata, bid_ask)) = selected else {
991            eprintln!("Metric live API returned no liquid Base WETH/USDC pool; skipping");
992            return;
993        };
994
995        let state = MetricState { base_token: weth, quote_token: usdc, metadata, bid_ask };
996        assert!(state.bid_ask.is_quotable());
997
998        let amount_in = BigUint::from(1_000_000_000u64);
999        let quote = state
1000            .get_amount_out(amount_in, &state.base_token, &state.quote_token)
1001            .unwrap();
1002
1003        assert!(quote.amount > BigUint::from(0u8));
1004    }
1005
1006    /// The pool a Metric swap settles against reverts on a zero input, so simulating one must
1007    /// not report a fill.
1008    #[test]
1009    fn rejects_a_zero_amount() {
1010        let state = state();
1011
1012        let result = state.get_amount_out(BigUint::ZERO, &weth(), &usdc());
1013
1014        assert!(matches!(result, Err(SimulationError::InvalidInput(_, None))), "{result:?}");
1015    }
1016}