1use std::{any::Any, borrow::Cow, collections::HashMap, sync::Arc};
2
3use async_trait::async_trait;
4use num_bigint::BigUint;
5use num_traits::FromPrimitive;
6use serde::{Deserialize, Serialize};
7use tycho_common::{
8 dto::ProtocolStateDelta,
9 models::{protocol::GetAmountOutParams, token::Token},
10 simulation::{
11 errors::{SimulationError, TransitionError},
12 indicatively_priced::{IndicativelyPriced, SignedQuote},
13 protocol_sim::{Balances, GetAmountOutResult, ProtocolSim},
14 },
15 Bytes,
16};
17
18use crate::{
19 book::{
20 all_pairs::{all_pairs_state, PricesAfterFill, RefusesQuote, SignedByVenue},
21 component::PairState,
22 levels::Levels,
23 sim::{self, SwapDirection},
24 },
25 rfq::protocols::native::{
26 client::NativeClient,
27 models::{NativeBookSide, NativePriceData},
28 },
29};
30
31const NATIVE_SWAP_GAS: u64 = 134_000;
33
34#[derive(Clone, derive_more::Debug, Serialize, Deserialize)]
35pub struct NativeState {
36 pub(super) base_token: Token,
37 pub(super) quote_token: Token,
38 #[debug(skip)]
39 pub(super) book: NativePriceData,
40 #[serde(skip)]
41 #[debug(skip)]
42 client: Option<Arc<NativeClient>>,
43}
44
45impl NativeState {
46 pub(super) fn new(
48 base_token: Token,
49 quote_token: Token,
50 book: NativePriceData,
51 client: Arc<NativeClient>,
52 ) -> Self {
53 NativeState { base_token, quote_token, book, client: Some(client) }
54 }
55
56 fn enforce_minimum(
57 amount: &BigUint,
58 minimum: f64,
59 amount_kind: &str,
60 ) -> Result<(), SimulationError> {
61 if minimum == 0.0 {
62 return Ok(())
63 }
64 let minimum = BigUint::from_f64(minimum.ceil()).ok_or_else(|| {
67 SimulationError::FatalError(format!(
68 "Can't convert Native minimum {amount_kind} amount to BigUint"
69 ))
70 })?;
71 if amount < &minimum {
72 return Err(SimulationError::RecoverableError(format!(
73 "Amount below minimum {amount_kind}. Amount: {amount}, min amount: {minimum}"
74 )))
75 }
76 Ok(())
77 }
78
79 fn side(&self, direction: SwapDirection) -> &NativeBookSide {
82 match direction {
83 SwapDirection::BaseToQuote => &self.book.bids,
84 SwapDirection::QuoteToBase => &self.book.asks,
85 }
86 }
87
88 fn ladder(&self, direction: SwapDirection) -> Cow<'_, Levels> {
91 match direction {
92 SwapDirection::BaseToQuote => Cow::Borrowed(&self.book.bids.levels),
93 SwapDirection::QuoteToBase => Cow::Owned(self.book.asks.levels.invert()),
94 }
95 }
96}
97
98impl PairState for NativeState {
99 fn base_token(&self) -> &Token {
100 &self.base_token
101 }
102
103 fn quote_token(&self) -> &Token {
104 &self.quote_token
105 }
106
107 fn directions(&self) -> Vec<(Bytes, Bytes)> {
108 sim::directions(
109 &self.base_token,
110 &self.quote_token,
111 !self.book.bids.levels.is_empty(),
112 !self.book.asks.levels.is_empty(),
113 )
114 }
115}
116
117impl PricesAfterFill for NativeState {
118 fn marginal_price(
119 &self,
120 token_in: &Bytes,
121 token_out: &Bytes,
122 filled: &BigUint,
123 ) -> Result<f64, SimulationError> {
124 let direction =
125 SwapDirection::require(&self.base_token, &self.quote_token, token_in, token_out)?;
126 let (sell_decimals, _) = direction.decimals(&self.base_token, &self.quote_token);
127 sim::marginal_price(&self.ladder(direction), filled, sell_decimals)
128 }
129}
130
131#[typetag::serde]
132impl ProtocolSim for NativeState {
133 fn fee(&self) -> f64 {
134 0.0
135 }
136
137 fn spot_price(&self, base: &Token, quote: &Token) -> Result<f64, SimulationError> {
138 let direction = SwapDirection::require(
139 &self.base_token,
140 &self.quote_token,
141 &base.address,
142 "e.address,
143 )?;
144 let best_bid = self
145 .book
146 .bids
147 .levels
148 .first()
149 .map(|lvl| lvl.price);
150 let best_ask = self
151 .book
152 .asks
153 .levels
154 .first()
155 .map(|lvl| lvl.price);
156 let average_price = match (best_bid, best_ask) {
157 (Some(bid), Some(ask)) => bid.midpoint(ask),
158 (Some(bid), None) => bid,
159 (None, Some(ask)) => ask,
160 (None, None) => {
161 return Err(SimulationError::RecoverableError("No liquidity".to_string()))
162 }
163 };
164 let spot_price = match direction {
165 SwapDirection::BaseToQuote => average_price,
166 SwapDirection::QuoteToBase => average_price.recip(),
167 };
168 if !spot_price.is_finite() || spot_price <= 0.0 {
169 return Err(SimulationError::RecoverableError(
170 "Native spot price is not positive and finite".to_string(),
171 ))
172 }
173 Ok(spot_price)
174 }
175
176 fn get_amount_out(
177 &self,
178 amount_in: BigUint,
179 token_in: &Token,
180 token_out: &Token,
181 ) -> Result<GetAmountOutResult, SimulationError> {
182 sim::require_positive_amount(&amount_in)?;
185
186 let direction = SwapDirection::require(
187 &self.base_token,
188 &self.quote_token,
189 &token_in.address,
190 &token_out.address,
191 )?;
192 let side = self.side(direction);
193 Self::enforce_minimum(&amount_in, side.minimum_in, "input")?;
194
195 let ladder = self.ladder(direction);
196
197 let amount_in = sim::to_human(&amount_in, token_in.decimals);
198 let fill = ladder.fill(amount_in);
199 let result = sim::fill_result(fill, amount_in, token_out.decimals, NATIVE_SWAP_GAS, self)?;
200 Self::enforce_minimum(&result.amount, side.minimum_out, "output")?;
201 Ok(result)
202 }
203
204 fn get_limits(
205 &self,
206 sell_token: Bytes,
207 buy_token: Bytes,
208 ) -> Result<(BigUint, BigUint), SimulationError> {
209 let direction =
210 SwapDirection::require(&self.base_token, &self.quote_token, &sell_token, &buy_token)?;
211 let ladder = self.ladder(direction);
212 if ladder.is_empty() {
214 return Err(SimulationError::RecoverableError("No liquidity".into()));
215 }
216 let (sell_decimals, buy_decimals) = direction.decimals(&self.base_token, &self.quote_token);
217 sim::limits(&ladder, sell_decimals, buy_decimals)
218 }
219
220 fn delta_transition(
221 &mut self,
222 _delta: ProtocolStateDelta,
223 _tokens: &HashMap<Bytes, Token>,
224 _balances: &Balances,
225 ) -> Result<(), TransitionError> {
226 Err(TransitionError::DecodeError("Not implemented".into()))
227 }
228
229 fn clone_box(&self) -> Box<dyn ProtocolSim> {
230 Box::new(self.clone())
231 }
232
233 fn as_any(&self) -> &dyn Any {
234 self
235 }
236
237 fn as_any_mut(&mut self) -> &mut dyn Any {
238 self
239 }
240
241 fn eq(&self, other: &dyn ProtocolSim) -> bool {
242 if let Some(other_state) = other
243 .as_any()
244 .downcast_ref::<NativeState>()
245 {
246 self.base_token == other_state.base_token &&
247 self.quote_token == other_state.quote_token &&
248 self.book == other_state.book
249 } else {
250 false
251 }
252 }
253
254 fn as_indicatively_priced(&self) -> Result<&dyn IndicativelyPriced, SimulationError> {
255 Ok(self)
256 }
257}
258
259#[async_trait]
260impl IndicativelyPriced for NativeState {
261 async fn request_signed_quote(
262 &self,
263 params: GetAmountOutParams,
264 ) -> Result<SignedQuote, SimulationError> {
265 Ok(sim::quoting_client(self.client.as_ref(), "Native")?
266 .request_binding_quote(¶ms)
267 .await?)
268 }
269}
270
271all_pairs_state! {
272 NativeAllPairsState(NativeState, SignedByVenue);
278}
279
280impl RefusesQuote for NativeAllPairsState {}
281
282#[cfg(test)]
283mod tests {
284 use std::str::FromStr;
285
286 use rstest::rstest;
287 use tokio::time::Duration;
288 use tycho_common::models::Chain;
289
290 use super::*;
291 use crate::{book::levels::PriceLevel, rfq::protocols::native::models::NativeSupportedChain};
292
293 fn token(address: &str, symbol: &str, decimals: u32) -> Token {
294 Token::new(
295 &Bytes::from_str(address).unwrap(),
296 symbol,
297 decimals,
298 0,
299 &[],
300 Chain::Ethereum,
301 100,
302 )
303 }
304
305 fn state() -> NativeState {
306 let base_token = token("0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2", "WETH", 18);
307 let quote_token = token("0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48", "USDC", 6);
308 let book = NativePriceData {
309 base_address: base_token.address.clone(),
310 quote_address: quote_token.address.clone(),
311 bids: NativeBookSide {
312 levels: Levels::new(vec![PriceLevel { quantity: 1.0, price: 2_000.0 }]).unwrap(),
313 minimum_in: 100_000_000_000.0,
314 minimum_out: 0.0,
315 },
316 asks: NativeBookSide {
317 levels: Levels::new(vec![PriceLevel { quantity: 1.0, price: 2_000.0 }]).unwrap(),
318 minimum_in: 100.0,
319 minimum_out: 0.0,
320 },
321 };
322 let client = Arc::new(NativeClient::new(
323 None,
324 NativeSupportedChain::Ethereum,
325 String::new(),
326 Duration::from_secs(5),
327 ));
328
329 NativeState { base_token, quote_token, book, client: Some(client) }
330 }
331
332 #[rstest]
335 #[case::base_sell_at_minimum(true, 100_000_000_000, true)]
336 #[case::base_sell_below_minimum(true, 99_999_999_999, false)]
337 #[case::quote_sell_at_minimum(false, 100, true)]
338 #[case::quote_sell_below_minimum(false, 99, false)]
339 fn enforces_atomic_input_minimums(
340 #[case] sell_base: bool,
341 #[case] amount_in: u64,
342 #[case] expect_ok: bool,
343 ) {
344 let state = state();
345 let (token_in, token_out) = if sell_base {
346 (&state.base_token, &state.quote_token)
347 } else {
348 (&state.quote_token, &state.base_token)
349 };
350
351 let result = state.get_amount_out(BigUint::from(amount_in), token_in, token_out);
352
353 if expect_ok {
354 assert!(result.is_ok());
355 } else {
356 assert!(matches!(result, Err(SimulationError::RecoverableError(_))));
357 }
358 }
359
360 #[test]
361 fn calculates_midpoint_spot_price_in_both_directions() {
362 let mut state = state();
363 state.book.bids.levels =
364 Levels::new(vec![PriceLevel { quantity: 1.0, price: 1_900.0 }]).unwrap();
365 state.book.asks.levels =
366 Levels::new(vec![PriceLevel { quantity: 1.0, price: 2_100.0 }]).unwrap();
367
368 let direct = state
369 .spot_price(&state.base_token, &state.quote_token)
370 .unwrap();
371 let inverse = state
372 .spot_price(&state.quote_token, &state.base_token)
373 .unwrap();
374
375 assert_eq!(direct, 2_000.0);
376 assert_eq!(inverse, direct.recip());
377 }
378
379 #[test]
382 fn requires_a_finite_spot_price() {
383 let mut state = state();
384 let extreme = Levels::new(vec![PriceLevel { quantity: 1e-306, price: 1e308 }]).unwrap();
385 state.book.bids.levels = extreme.clone();
386 state.book.asks.levels = extreme;
387 assert_eq!(
388 state
389 .spot_price(&state.base_token, &state.quote_token)
390 .unwrap(),
391 1e308
392 );
393
394 let subnormal =
395 Levels::new(vec![PriceLevel { quantity: 1.0, price: f64::from_bits(1) }]).unwrap();
396 state.book.bids.levels = subnormal.clone();
397 state.book.asks.levels = subnormal;
398 assert!(matches!(
399 state.spot_price(&state.quote_token, &state.base_token),
400 Err(SimulationError::RecoverableError(message))
401 if message.contains("not positive and finite")
402 ));
403 }
404
405 #[rstest]
408 #[case::selling_base_in_the_level(true, 500_000_000_000_000_000, Some(2_000.0))]
409 #[case::selling_base_past_the_depth(true, 1_000_000_000_000_000_000, None)]
410 #[case::selling_quote_in_the_level(false, 1_000_000_000, Some(1.0 / 2_000.0))]
411 fn the_price_after_a_fill_is_the_level_where_it_stopped(
412 #[case] sell_base: bool,
413 #[case] filled: u64,
414 #[case] expected: Option<f64>,
415 ) {
416 let state = state();
417 let (token_in, token_out) = if sell_base {
418 (&state.base_token, &state.quote_token)
419 } else {
420 (&state.quote_token, &state.base_token)
421 };
422
423 let price =
424 state.marginal_price(&token_in.address, &token_out.address, &BigUint::from(filled));
425
426 match (price, expected) {
427 (Ok(price), Some(expected)) => assert_eq!(price, expected),
428 (Err(SimulationError::RecoverableError(message)), None) => {
429 assert_eq!(message, "No liquidity")
430 }
431 (price, _) => panic!("expected {expected:?}, got {price:?}"),
432 }
433 }
434
435 #[rstest]
436 #[case::sell_base(true, 2_500_000_000_000_000_000, 3_500_000_000)]
437 #[case::sell_quote(false, 8_192_000_000, 2_500_000_000_000_000_000)]
438 fn consumes_multiple_price_levels(
439 #[case] sell_base: bool,
440 #[case] amount_in: u64,
441 #[case] expected_amount_out: u64,
442 ) {
443 let mut state = state();
444 state.book.bids.levels = Levels::new(vec![
445 PriceLevel { quantity: 1.0, price: 2_000.0 },
446 PriceLevel { quantity: 2.0, price: 1_000.0 },
447 ])
448 .unwrap();
449 state.book.asks.levels = Levels::new(vec![
450 PriceLevel { quantity: 1.0, price: 2_048.0 },
451 PriceLevel { quantity: 2.0, price: 4_096.0 },
452 ])
453 .unwrap();
454 let (token_in, token_out) = if sell_base {
457 (&state.base_token, &state.quote_token)
458 } else {
459 (&state.quote_token, &state.base_token)
460 };
461
462 let result = state
463 .get_amount_out(BigUint::from(amount_in), token_in, token_out)
464 .unwrap();
465
466 assert_eq!(result.amount, BigUint::from(expected_amount_out));
467 }
468
469 #[test]
470 fn enforces_base_sell_atomic_output_minimum() {
471 let mut state = state();
472 state.book.bids.minimum_out = 1_000_000_000.0;
473 let amount_in = BigUint::from(500_000_000_000_000_000u64);
474
475 assert!(state
476 .get_amount_out(amount_in.clone(), &state.base_token, &state.quote_token)
477 .is_ok());
478
479 state.book.bids.minimum_out = 1_000_000_001.0;
480 assert!(matches!(
481 state.get_amount_out(amount_in, &state.base_token, &state.quote_token),
482 Err(SimulationError::RecoverableError(message)) if message.contains("minimum output")
483 ));
484 }
485
486 #[test]
487 fn enforces_quote_sell_atomic_output_minimum() {
488 let mut state = state();
489 state.book.asks.minimum_out = 500_000_000_000_000.0;
490 let amount_in = BigUint::from(1_000_000u64);
491
492 assert!(state
493 .get_amount_out(amount_in.clone(), &state.quote_token, &state.base_token)
494 .is_ok());
495
496 state.book.asks.minimum_out = 500_000_000_000_001.0;
497 assert!(matches!(
498 state.get_amount_out(amount_in, &state.quote_token, &state.base_token),
499 Err(SimulationError::RecoverableError(message)) if message.contains("minimum output")
500 ));
501 }
502
503 #[test]
504 fn rejects_sub_unit_partial_fill() {
505 let mut state = state();
506 state.book.bids.minimum_in = 0.0;
507 state.book.bids.levels =
508 Levels::new(vec![PriceLevel { quantity: 0.5e-18, price: 2_000.0 }]).unwrap();
509
510 let result =
511 state.get_amount_out(BigUint::from(1u64), &state.base_token, &state.quote_token);
512
513 assert!(matches!(result, Err(SimulationError::InvalidInput(_, Some(_)))));
514 }
515
516 #[rstest]
518 #[case::sell_base(true, 1_000_000_000_000_000_000, 2_000_000_000)]
519 #[case::sell_quote(false, 2_000_000_000, 1_000_000_000_000_000_000)]
520 fn gets_limits_in_both_directions(
521 #[case] sell_base: bool,
522 #[case] expected_sell_limit: u64,
523 #[case] expected_buy_limit: u64,
524 ) {
525 let state = state();
526 let (token_in, token_out) = if sell_base {
527 (&state.base_token, &state.quote_token)
528 } else {
529 (&state.quote_token, &state.base_token)
530 };
531
532 let limits = state
533 .get_limits(token_in.address.clone(), token_out.address.clone())
534 .unwrap();
535
536 assert_eq!(limits, (BigUint::from(expected_sell_limit), BigUint::from(expected_buy_limit)));
537 }
538
539 #[test]
540 fn rejects_invalid_pair() {
541 let mut state = state();
542 let other = token("0x1111111111111111111111111111111111111111", "OTHER", 18);
543
544 assert!(matches!(
545 state.get_amount_out(BigUint::from(1u64), &other, &state.quote_token),
546 Err(SimulationError::InvalidInput(_, None))
547 ));
548 assert!(matches!(
549 state.get_limits(other.address.clone(), state.quote_token.address.clone()),
550 Err(SimulationError::InvalidInput(_, None))
551 ));
552
553 state.book.bids.levels = Levels::default();
555 state.book.asks.levels = Levels::default();
556 assert!(matches!(
557 state.spot_price(&other, &state.quote_token),
558 Err(SimulationError::InvalidInput(message, None))
559 if message.contains("Invalid token addresses")
560 ));
561 }
562
563 #[test]
564 fn a_side_with_no_levels_has_nothing_to_offer() {
566 let mut state = state();
567 state.book.bids.levels = Levels::default();
568
569 assert!(matches!(
570 state.get_amount_out(
571 BigUint::from(500_000_000_000_000_000u64),
572 &state.base_token,
573 &state.quote_token,
574 ),
575 Err(SimulationError::InvalidInput(_, None))
576 ));
577 assert!(matches!(
578 state.get_limits(state.base_token.address.clone(), state.quote_token.address.clone()),
579 Err(SimulationError::RecoverableError(_))
580 ));
581 }
582
583 #[test]
585 fn rejects_a_zero_amount() {
586 let state = state();
587
588 let result = state.get_amount_out(
589 BigUint::ZERO,
590 &state.base_token.clone(),
591 &state.quote_token.clone(),
592 );
593
594 assert!(matches!(result, Err(SimulationError::InvalidInput(_, None))), "{result:?}");
595 }
596}