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