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, 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
117#[typetag::serde]
118impl ProtocolSim for NativeState {
119 fn fee(&self) -> f64 {
120 0.0
121 }
122
123 fn spot_price(&self, base: &Token, quote: &Token) -> Result<f64, SimulationError> {
124 let direction = SwapDirection::require(
125 &self.base_token,
126 &self.quote_token,
127 &base.address,
128 "e.address,
129 )?;
130 let best_bid = self
131 .book
132 .bids
133 .levels
134 .first()
135 .map(|lvl| lvl.price);
136 let best_ask = self
137 .book
138 .asks
139 .levels
140 .first()
141 .map(|lvl| lvl.price);
142 let average_price = match (best_bid, best_ask) {
143 (Some(bid), Some(ask)) => bid.midpoint(ask),
144 (Some(bid), None) => bid,
145 (None, Some(ask)) => ask,
146 (None, None) => {
147 return Err(SimulationError::RecoverableError("No liquidity".to_string()))
148 }
149 };
150 let spot_price = match direction {
151 SwapDirection::BaseToQuote => average_price,
152 SwapDirection::QuoteToBase => average_price.recip(),
153 };
154 if !spot_price.is_finite() || spot_price <= 0.0 {
155 return Err(SimulationError::RecoverableError(
156 "Native spot price is not positive and finite".to_string(),
157 ))
158 }
159 Ok(spot_price)
160 }
161
162 fn get_amount_out(
163 &self,
164 amount_in: BigUint,
165 token_in: &Token,
166 token_out: &Token,
167 ) -> Result<GetAmountOutResult, SimulationError> {
168 sim::require_positive_amount(&amount_in)?;
171
172 let direction = SwapDirection::require(
173 &self.base_token,
174 &self.quote_token,
175 &token_in.address,
176 &token_out.address,
177 )?;
178 let side = self.side(direction);
179 Self::enforce_minimum(&amount_in, side.minimum_in, "input")?;
180
181 let ladder = self.ladder(direction);
182
183 let amount_in = sim::to_human(&amount_in, token_in.decimals);
184 let fill = ladder.fill(amount_in);
185 let result = sim::fill_result(fill, amount_in, token_out.decimals, NATIVE_SWAP_GAS, self)?;
186 Self::enforce_minimum(&result.amount, side.minimum_out, "output")?;
187 Ok(result)
188 }
189
190 fn get_limits(
191 &self,
192 sell_token: Bytes,
193 buy_token: Bytes,
194 ) -> Result<(BigUint, BigUint), SimulationError> {
195 let direction =
196 SwapDirection::require(&self.base_token, &self.quote_token, &sell_token, &buy_token)?;
197 let ladder = self.ladder(direction);
198 if ladder.is_empty() {
200 return Err(SimulationError::RecoverableError("No liquidity".into()));
201 }
202 let (sell_decimals, buy_decimals) = direction.decimals(&self.base_token, &self.quote_token);
203 sim::limits(&ladder, sell_decimals, buy_decimals)
204 }
205
206 fn delta_transition(
207 &mut self,
208 _delta: ProtocolStateDelta,
209 _tokens: &HashMap<Bytes, Token>,
210 _balances: &Balances,
211 ) -> Result<(), TransitionError> {
212 Err(TransitionError::DecodeError("Not implemented".into()))
213 }
214
215 fn clone_box(&self) -> Box<dyn ProtocolSim> {
216 Box::new(self.clone())
217 }
218
219 fn as_any(&self) -> &dyn Any {
220 self
221 }
222
223 fn as_any_mut(&mut self) -> &mut dyn Any {
224 self
225 }
226
227 fn eq(&self, other: &dyn ProtocolSim) -> bool {
228 if let Some(other_state) = other
229 .as_any()
230 .downcast_ref::<NativeState>()
231 {
232 self.base_token == other_state.base_token &&
233 self.quote_token == other_state.quote_token &&
234 self.book == other_state.book
235 } else {
236 false
237 }
238 }
239
240 fn as_indicatively_priced(&self) -> Result<&dyn IndicativelyPriced, SimulationError> {
241 Ok(self)
242 }
243}
244
245#[async_trait]
246impl IndicativelyPriced for NativeState {
247 async fn request_signed_quote(
248 &self,
249 params: GetAmountOutParams,
250 ) -> Result<SignedQuote, SimulationError> {
251 Ok(sim::quoting_client(self.client.as_ref(), "Native")?
252 .request_binding_quote(¶ms)
253 .await?)
254 }
255}
256
257all_pairs_state! {
258 NativeAllPairsState(NativeState, SignedByVenue);
264}
265
266impl RefusesQuote for NativeAllPairsState {}
267
268#[cfg(test)]
269mod tests {
270 use std::str::FromStr;
271
272 use rstest::rstest;
273 use tokio::time::Duration;
274 use tycho_common::models::Chain;
275
276 use super::*;
277 use crate::{book::levels::PriceLevel, rfq::protocols::native::models::NativeSupportedChain};
278
279 fn token(address: &str, symbol: &str, decimals: u32) -> Token {
280 Token::new(
281 &Bytes::from_str(address).unwrap(),
282 symbol,
283 decimals,
284 0,
285 &[],
286 Chain::Ethereum,
287 100,
288 )
289 }
290
291 fn state() -> NativeState {
292 let base_token = token("0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2", "WETH", 18);
293 let quote_token = token("0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48", "USDC", 6);
294 let book = NativePriceData {
295 base_address: base_token.address.clone(),
296 quote_address: quote_token.address.clone(),
297 bids: NativeBookSide {
298 levels: Levels::new(vec![PriceLevel { quantity: 1.0, price: 2_000.0 }]).unwrap(),
299 minimum_in: 100_000_000_000.0,
300 minimum_out: 0.0,
301 },
302 asks: NativeBookSide {
303 levels: Levels::new(vec![PriceLevel { quantity: 1.0, price: 2_000.0 }]).unwrap(),
304 minimum_in: 100.0,
305 minimum_out: 0.0,
306 },
307 };
308 let client = Arc::new(NativeClient::new(
309 None,
310 NativeSupportedChain::Ethereum,
311 String::new(),
312 Duration::from_secs(5),
313 ));
314
315 NativeState { base_token, quote_token, book, client: Some(client) }
316 }
317
318 #[rstest]
321 #[case::base_sell_at_minimum(true, 100_000_000_000, true)]
322 #[case::base_sell_below_minimum(true, 99_999_999_999, false)]
323 #[case::quote_sell_at_minimum(false, 100, true)]
324 #[case::quote_sell_below_minimum(false, 99, false)]
325 fn enforces_atomic_input_minimums(
326 #[case] sell_base: bool,
327 #[case] amount_in: u64,
328 #[case] expect_ok: bool,
329 ) {
330 let state = state();
331 let (token_in, token_out) = if sell_base {
332 (&state.base_token, &state.quote_token)
333 } else {
334 (&state.quote_token, &state.base_token)
335 };
336
337 let result = state.get_amount_out(BigUint::from(amount_in), token_in, token_out);
338
339 if expect_ok {
340 assert!(result.is_ok());
341 } else {
342 assert!(matches!(result, Err(SimulationError::RecoverableError(_))));
343 }
344 }
345
346 #[test]
347 fn calculates_midpoint_spot_price_in_both_directions() {
348 let mut state = state();
349 state.book.bids.levels =
350 Levels::new(vec![PriceLevel { quantity: 1.0, price: 1_900.0 }]).unwrap();
351 state.book.asks.levels =
352 Levels::new(vec![PriceLevel { quantity: 1.0, price: 2_100.0 }]).unwrap();
353
354 let direct = state
355 .spot_price(&state.base_token, &state.quote_token)
356 .unwrap();
357 let inverse = state
358 .spot_price(&state.quote_token, &state.base_token)
359 .unwrap();
360
361 assert_eq!(direct, 2_000.0);
362 assert_eq!(inverse, direct.recip());
363 }
364
365 #[test]
368 fn requires_a_finite_spot_price() {
369 let mut state = state();
370 let extreme = Levels::new(vec![PriceLevel { quantity: 1e-306, price: 1e308 }]).unwrap();
371 state.book.bids.levels = extreme.clone();
372 state.book.asks.levels = extreme;
373 assert_eq!(
374 state
375 .spot_price(&state.base_token, &state.quote_token)
376 .unwrap(),
377 1e308
378 );
379
380 let subnormal =
381 Levels::new(vec![PriceLevel { quantity: 1.0, price: f64::from_bits(1) }]).unwrap();
382 state.book.bids.levels = subnormal.clone();
383 state.book.asks.levels = subnormal;
384 assert!(matches!(
385 state.spot_price(&state.quote_token, &state.base_token),
386 Err(SimulationError::RecoverableError(message))
387 if message.contains("not positive and finite")
388 ));
389 }
390
391 #[rstest]
392 #[case::sell_base(true, 2_500_000_000_000_000_000, 3_500_000_000)]
393 #[case::sell_quote(false, 8_192_000_000, 2_500_000_000_000_000_000)]
394 fn consumes_multiple_price_levels(
395 #[case] sell_base: bool,
396 #[case] amount_in: u64,
397 #[case] expected_amount_out: u64,
398 ) {
399 let mut state = state();
400 state.book.bids.levels = Levels::new(vec![
401 PriceLevel { quantity: 1.0, price: 2_000.0 },
402 PriceLevel { quantity: 2.0, price: 1_000.0 },
403 ])
404 .unwrap();
405 state.book.asks.levels = Levels::new(vec![
406 PriceLevel { quantity: 1.0, price: 2_048.0 },
407 PriceLevel { quantity: 2.0, price: 4_096.0 },
408 ])
409 .unwrap();
410 let (token_in, token_out) = if sell_base {
413 (&state.base_token, &state.quote_token)
414 } else {
415 (&state.quote_token, &state.base_token)
416 };
417
418 let result = state
419 .get_amount_out(BigUint::from(amount_in), token_in, token_out)
420 .unwrap();
421
422 assert_eq!(result.amount, BigUint::from(expected_amount_out));
423 }
424
425 #[test]
426 fn enforces_base_sell_atomic_output_minimum() {
427 let mut state = state();
428 state.book.bids.minimum_out = 1_000_000_000.0;
429 let amount_in = BigUint::from(500_000_000_000_000_000u64);
430
431 assert!(state
432 .get_amount_out(amount_in.clone(), &state.base_token, &state.quote_token)
433 .is_ok());
434
435 state.book.bids.minimum_out = 1_000_000_001.0;
436 assert!(matches!(
437 state.get_amount_out(amount_in, &state.base_token, &state.quote_token),
438 Err(SimulationError::RecoverableError(message)) if message.contains("minimum output")
439 ));
440 }
441
442 #[test]
443 fn enforces_quote_sell_atomic_output_minimum() {
444 let mut state = state();
445 state.book.asks.minimum_out = 500_000_000_000_000.0;
446 let amount_in = BigUint::from(1_000_000u64);
447
448 assert!(state
449 .get_amount_out(amount_in.clone(), &state.quote_token, &state.base_token)
450 .is_ok());
451
452 state.book.asks.minimum_out = 500_000_000_000_001.0;
453 assert!(matches!(
454 state.get_amount_out(amount_in, &state.quote_token, &state.base_token),
455 Err(SimulationError::RecoverableError(message)) if message.contains("minimum output")
456 ));
457 }
458
459 #[test]
460 fn rejects_sub_unit_partial_fill() {
461 let mut state = state();
462 state.book.bids.minimum_in = 0.0;
463 state.book.bids.levels =
464 Levels::new(vec![PriceLevel { quantity: 0.5e-18, price: 2_000.0 }]).unwrap();
465
466 let result =
467 state.get_amount_out(BigUint::from(1u64), &state.base_token, &state.quote_token);
468
469 assert!(matches!(result, Err(SimulationError::InvalidInput(_, Some(_)))));
470 }
471
472 #[rstest]
474 #[case::sell_base(true, 1_000_000_000_000_000_000, 2_000_000_000)]
475 #[case::sell_quote(false, 2_000_000_000, 1_000_000_000_000_000_000)]
476 fn gets_limits_in_both_directions(
477 #[case] sell_base: bool,
478 #[case] expected_sell_limit: u64,
479 #[case] expected_buy_limit: u64,
480 ) {
481 let state = state();
482 let (token_in, token_out) = if sell_base {
483 (&state.base_token, &state.quote_token)
484 } else {
485 (&state.quote_token, &state.base_token)
486 };
487
488 let limits = state
489 .get_limits(token_in.address.clone(), token_out.address.clone())
490 .unwrap();
491
492 assert_eq!(limits, (BigUint::from(expected_sell_limit), BigUint::from(expected_buy_limit)));
493 }
494
495 #[test]
496 fn rejects_invalid_pair() {
497 let mut state = state();
498 let other = token("0x1111111111111111111111111111111111111111", "OTHER", 18);
499
500 assert!(matches!(
501 state.get_amount_out(BigUint::from(1u64), &other, &state.quote_token),
502 Err(SimulationError::InvalidInput(_, None))
503 ));
504 assert!(matches!(
505 state.get_limits(other.address.clone(), state.quote_token.address.clone()),
506 Err(SimulationError::InvalidInput(_, None))
507 ));
508
509 state.book.bids.levels = Levels::default();
511 state.book.asks.levels = Levels::default();
512 assert!(matches!(
513 state.spot_price(&other, &state.quote_token),
514 Err(SimulationError::InvalidInput(message, None))
515 if message.contains("Invalid token addresses")
516 ));
517 }
518
519 #[test]
520 fn a_side_with_no_levels_has_nothing_to_offer() {
522 let mut state = state();
523 state.book.bids.levels = Levels::default();
524
525 assert!(matches!(
526 state.get_amount_out(
527 BigUint::from(500_000_000_000_000_000u64),
528 &state.base_token,
529 &state.quote_token,
530 ),
531 Err(SimulationError::InvalidInput(_, None))
532 ));
533 assert!(matches!(
534 state.get_limits(state.base_token.address.clone(), state.quote_token.address.clone()),
535 Err(SimulationError::RecoverableError(_))
536 ));
537 }
538
539 #[test]
541 fn rejects_a_zero_amount() {
542 let state = state();
543
544 let result = state.get_amount_out(
545 BigUint::ZERO,
546 &state.base_token.clone(),
547 &state.quote_token.clone(),
548 );
549
550 assert!(matches!(result, Err(SimulationError::InvalidInput(_, None))), "{result:?}");
551 }
552}