1use std::{any::Any, borrow::Cow, collections::HashMap, sync::Arc};
2
3use async_trait::async_trait;
4use num_bigint::BigUint;
5use serde::{Deserialize, Serialize};
6use tycho_common::{
7 dto::ProtocolStateDelta,
8 models::{protocol::GetAmountOutParams, token::Token},
9 simulation::{
10 errors::{SimulationError, TransitionError},
11 indicatively_priced::{IndicativelyPriced, SignedQuote},
12 protocol_sim::{Balances, GetAmountOutResult, ProtocolSim},
13 },
14 Bytes,
15};
16
17use crate::{
18 book::{
19 all_pairs::{all_pairs_state, PricesAfterFill, RefusesQuote, SignedByVenue},
20 component::PairState,
21 levels::Levels,
22 sim::{self, SwapDirection},
23 },
24 rfq::protocols::euclid::{client::EuclidClient, models::EuclidBook},
25};
26
27const EUCLID_SWAP_GAS: u64 = 120_000;
31
32#[derive(Clone, derive_more::Debug, Serialize, Deserialize)]
33pub struct EuclidState {
34 pub(super) base_token: Token,
35 pub(super) quote_token: Token,
36 #[debug(skip)]
37 pub(super) book: EuclidBook,
38 #[serde(skip)]
39 #[debug(skip)]
40 client: Option<Arc<EuclidClient>>,
41}
42
43impl EuclidState {
44 pub(super) fn new(
46 base_token: Token,
47 quote_token: Token,
48 book: EuclidBook,
49 client: Arc<EuclidClient>,
50 ) -> Self {
51 EuclidState { base_token, quote_token, book, client: Some(client) }
52 }
53
54 fn ladder(&self, direction: SwapDirection) -> Cow<'_, Levels> {
57 match direction {
58 SwapDirection::BaseToQuote => Cow::Borrowed(&self.book.bids),
59 SwapDirection::QuoteToBase => Cow::Owned(self.book.asks.invert()),
60 }
61 }
62
63 fn min_trade_quote(&self, direction: SwapDirection) -> f64 {
68 let side = match direction {
69 SwapDirection::BaseToQuote => &self.book.bids,
70 SwapDirection::QuoteToBase => &self.book.asks,
71 };
72 side.first()
73 .map_or(0.0, |level| level.price * level.quantity)
74 }
75}
76
77impl PairState for EuclidState {
78 fn base_token(&self) -> &Token {
79 &self.base_token
80 }
81
82 fn quote_token(&self) -> &Token {
83 &self.quote_token
84 }
85
86 fn directions(&self) -> Vec<(Bytes, Bytes)> {
87 sim::directions(
88 &self.base_token,
89 &self.quote_token,
90 !self.book.bids.is_empty(),
91 !self.book.asks.is_empty(),
92 )
93 }
94}
95
96impl PricesAfterFill for EuclidState {
97 fn marginal_price(
98 &self,
99 token_in: &Bytes,
100 token_out: &Bytes,
101 filled: &BigUint,
102 ) -> Result<f64, SimulationError> {
103 let direction =
104 SwapDirection::require(&self.base_token, &self.quote_token, token_in, token_out)?;
105 let (sell_decimals, _) = direction.decimals(&self.base_token, &self.quote_token);
106 sim::marginal_price(&self.ladder(direction), filled, sell_decimals)
107 }
108}
109
110#[typetag::serde]
111impl ProtocolSim for EuclidState {
112 fn fee(&self) -> f64 {
113 0.0
114 }
115
116 fn spot_price(&self, base: &Token, quote: &Token) -> Result<f64, SimulationError> {
117 let direction = SwapDirection::require(
118 &self.base_token,
119 &self.quote_token,
120 &base.address,
121 "e.address,
122 )?;
123 let best_bid = self
126 .book
127 .bids
128 .first()
129 .map(|level| level.price);
130 let best_ask = self
131 .book
132 .asks
133 .first()
134 .map(|level| level.price);
135 let mid = match (best_bid, best_ask) {
136 (Some(bid), Some(ask)) => (bid + ask) / 2.0,
137 (Some(bid), None) => bid,
138 (None, Some(ask)) => ask,
139 (None, None) => {
140 return Err(SimulationError::RecoverableError("No liquidity available".to_string()))
141 }
142 };
143 match direction {
144 SwapDirection::BaseToQuote => Ok(mid),
145 SwapDirection::QuoteToBase => Ok(1.0 / mid),
146 }
147 }
148
149 fn get_amount_out(
150 &self,
151 amount_in: BigUint,
152 token_in: &Token,
153 token_out: &Token,
154 ) -> Result<GetAmountOutResult, SimulationError> {
155 sim::require_positive_amount(&amount_in)?;
156
157 let direction = SwapDirection::require(
158 &self.base_token,
159 &self.quote_token,
160 &token_in.address,
161 &token_out.address,
162 )?;
163 let ladder = self.ladder(direction);
164 let amount_in = sim::to_human(&amount_in, token_in.decimals);
165 let fill = ladder.fill(amount_in);
166 let quote_amount = match direction {
170 SwapDirection::QuoteToBase => amount_in,
171 SwapDirection::BaseToQuote => fill.amount_out,
172 };
173 let min_trade = self.min_trade_quote(direction);
174 if fill.remaining_in < amount_in && quote_amount < min_trade {
175 return Err(SimulationError::RecoverableError(format!(
176 "Trade is worth {quote_amount} {}, below the {min_trade} Euclid quotes",
177 self.quote_token.symbol
178 )));
179 }
180 sim::fill_result(fill, amount_in, token_out.decimals, EUCLID_SWAP_GAS, self)
182 }
183
184 fn get_limits(
185 &self,
186 sell_token: Bytes,
187 buy_token: Bytes,
188 ) -> Result<(BigUint, BigUint), SimulationError> {
189 let direction =
190 SwapDirection::require(&self.base_token, &self.quote_token, &sell_token, &buy_token)?;
191 let ladder = self.ladder(direction);
192 if ladder.is_empty() {
194 return Err(SimulationError::RecoverableError("No liquidity".into()));
195 }
196 let (sell_decimals, buy_decimals) = direction.decimals(&self.base_token, &self.quote_token);
197 sim::limits(&ladder, sell_decimals, buy_decimals)
198 }
199
200 fn delta_transition(
201 &mut self,
202 _delta: ProtocolStateDelta,
203 _tokens: &HashMap<Bytes, Token>,
204 _balances: &Balances,
205 ) -> Result<(), TransitionError> {
206 Err(TransitionError::DecodeError("Not implemented".into()))
207 }
208
209 fn clone_box(&self) -> Box<dyn ProtocolSim> {
210 Box::new(self.clone())
211 }
212
213 fn as_any(&self) -> &dyn Any {
214 self
215 }
216
217 fn as_any_mut(&mut self) -> &mut dyn Any {
218 self
219 }
220
221 fn eq(&self, other: &dyn ProtocolSim) -> bool {
222 if let Some(other_state) = other
223 .as_any()
224 .downcast_ref::<EuclidState>()
225 {
226 self.base_token == other_state.base_token &&
227 self.quote_token == other_state.quote_token &&
228 self.book == other_state.book
229 } else {
230 false
231 }
232 }
233
234 fn as_indicatively_priced(&self) -> Result<&dyn IndicativelyPriced, SimulationError> {
235 Ok(self)
236 }
237}
238
239#[async_trait]
240impl IndicativelyPriced for EuclidState {
241 async fn request_signed_quote(
242 &self,
243 params: GetAmountOutParams,
244 ) -> Result<SignedQuote, SimulationError> {
245 Ok(sim::quoting_client(self.client.as_ref(), "Euclid")?
246 .request_binding_quote(¶ms)
247 .await?)
248 }
249}
250
251all_pairs_state! {
252 EuclidAllPairsState(EuclidState, SignedByVenue);
258}
259
260impl RefusesQuote for EuclidAllPairsState {}
261
262#[cfg(test)]
263mod tests {
264 use std::str::FromStr;
265
266 use tokio::time::Duration;
267 use tycho_common::models::Chain;
268
269 use super::*;
270 use crate::{
271 book::levels::PriceLevel,
272 rfq::protocols::euclid::{client::EUCLID_API_URL, models::EuclidSupportedChain},
273 };
274
275 fn token(address: &str, symbol: &str, decimals: u32) -> Token {
276 Token::new(
277 &Bytes::from_str(address).unwrap(),
278 symbol,
279 decimals,
280 0,
281 &[Some(10_000)],
282 Chain::Ethereum,
283 100,
284 )
285 }
286
287 fn weth() -> Token {
288 token("0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2", "WETH", 18)
289 }
290
291 fn usdc() -> Token {
292 token("0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48", "USDC", 6)
293 }
294
295 fn ladder(levels: &[(f64, f64)]) -> Levels {
296 Levels::new(
297 levels
298 .iter()
299 .map(|&(price, quantity)| PriceLevel { price, quantity })
300 .collect(),
301 )
302 .unwrap()
303 }
304
305 fn test_client() -> Arc<EuclidClient> {
306 Arc::new(EuclidClient::new(
307 EuclidSupportedChain::Ethereum,
308 EUCLID_API_URL,
309 Duration::from_secs(5),
310 ))
311 }
312
313 fn test_state() -> EuclidState {
317 EuclidState::new(
318 weth(),
319 usdc(),
320 EuclidBook {
321 base: weth().address,
322 quote: usdc().address,
323 updated_at_ms: 1_757_500_000_000,
324 bids: ladder(&[(3000.0, 0.001), (3000.0, 1.999), (2900.0, 2.5)]),
325 asks: ladder(&[(3100.0, 0.001), (3100.0, 1.499), (3200.0, 3.0)]),
326 },
327 test_client(),
328 )
329 }
330
331 #[test]
332 fn spot_price_is_the_mid_of_the_best_levels_either_way_round() {
333 let state = test_state();
334 assert_eq!(
335 state
336 .spot_price(&weth(), &usdc())
337 .unwrap(),
338 3050.0
339 );
340 let inverted = state
341 .spot_price(&usdc(), &weth())
342 .unwrap();
343 assert!((inverted - 1.0 / 3050.0).abs() < 1e-15);
344 }
345
346 #[test]
347 fn spot_price_falls_back_to_the_side_that_has_levels() {
348 let mut state = test_state();
349 state.book.asks = Levels::default();
350 assert_eq!(
351 state
352 .spot_price(&weth(), &usdc())
353 .unwrap(),
354 3000.0
355 );
356 state.book.bids = Levels::default();
357 assert!(matches!(
358 state.spot_price(&weth(), &usdc()),
359 Err(SimulationError::RecoverableError(_))
360 ));
361 }
362
363 #[test]
364 fn get_amount_out_walks_the_ladder_on_both_sides() {
365 let state = test_state();
366
367 let sold_base = state
369 .get_amount_out(BigUint::from_str("3000000000000000000").unwrap(), &weth(), &usdc())
370 .unwrap();
371 assert_eq!(sold_base.amount, BigUint::from_str("8900000000").unwrap());
372 assert_eq!(sold_base.gas, BigUint::from(EUCLID_SWAP_GAS));
373
374 let sold_quote = state
376 .get_amount_out(BigUint::from_str("7000000000").unwrap(), &usdc(), &weth())
377 .unwrap();
378 let expected = 1.5 + 2350.0 / 3200.0;
379 let got = sold_quote
380 .amount
381 .to_string()
382 .parse::<f64>()
383 .unwrap() /
384 1e18;
385 assert!((got - expected).abs() < 1e-12, "got {got}, expected {expected}");
386 }
387
388 #[test]
389 fn more_than_the_ladder_holds_reports_the_partial_fill() {
390 let result = test_state().get_amount_out(
391 BigUint::from_str("10000000000000000000").unwrap(),
392 &weth(),
393 &usdc(),
394 );
395 match result {
397 Err(SimulationError::InvalidInput(_, Some(partial))) => {
398 assert_eq!(partial.amount, BigUint::from_str("13250000000").unwrap());
399 }
400 other => panic!("expected a partial fill, got {other:?}"),
401 }
402 }
403
404 #[test]
407 fn a_trade_below_the_published_minimum_is_refused() {
408 let state = test_state();
409 let result =
411 state.get_amount_out(BigUint::from_str("500000000000000").unwrap(), &weth(), &usdc());
412 assert!(
413 matches!(result, Err(SimulationError::RecoverableError(ref m)) if m.contains("below the 3 Euclid")),
414 "{result:?}"
415 );
416 let result = state.get_amount_out(BigUint::from(1_000_000u64), &usdc(), &weth());
418 assert!(
419 matches!(result, Err(SimulationError::RecoverableError(ref m)) if m.contains("below the 3.1 Euclid")),
420 "{result:?}"
421 );
422 let priced = state
424 .get_amount_out(BigUint::from_str("1100000000000000").unwrap(), &weth(), &usdc())
425 .unwrap();
426 assert_eq!(priced.amount, BigUint::from(3_300_000u64));
427 }
428
429 #[test]
430 fn rejects_a_zero_amount_and_tokens_outside_the_pair() {
431 let state = test_state();
432 assert!(matches!(
433 state.get_amount_out(BigUint::ZERO, &weth(), &usdc()),
434 Err(SimulationError::InvalidInput(_, None))
435 ));
436 let dai = token("0x6b175474e89094c44da98b954eedeac495271d0f", "DAI", 18);
437 assert!(matches!(
438 state.get_amount_out(BigUint::from(1u64), &dai, &usdc()),
439 Err(SimulationError::InvalidInput(_, None))
440 ));
441 assert!(matches!(
442 state.get_limits(dai.address.clone(), usdc().address),
443 Err(SimulationError::InvalidInput(_, None))
444 ));
445 assert!(matches!(
446 state.marginal_price(&dai.address, &usdc().address, &BigUint::ZERO),
447 Err(SimulationError::InvalidInput(_, None))
448 ));
449 }
450
451 #[test]
452 fn get_limits_sum_the_ladder_a_swap_consumes() {
453 let state = test_state();
454 let (weth_in, usdc_out) = state
456 .get_limits(weth().address, usdc().address)
457 .unwrap();
458 assert_eq!(weth_in, BigUint::from_str("4500000000000000000").unwrap());
459 assert_eq!(usdc_out, BigUint::from_str("13250000000").unwrap());
460 let (usdc_in, weth_out) = state
462 .get_limits(usdc().address, weth().address)
463 .unwrap();
464 assert_eq!(usdc_in, BigUint::from_str("14250000000").unwrap());
465 assert_eq!(weth_out, BigUint::from_str("4500000000000000000").unwrap());
466 }
467
468 #[test]
471 fn marginal_price_follows_the_ladder_a_fill_has_reached() {
472 let state = test_state();
473 let (weth, usdc) = (weth().address, usdc().address);
474 assert_eq!(
475 state
476 .marginal_price(&weth, &usdc, &BigUint::ZERO)
477 .unwrap(),
478 3000.0
479 );
480 assert_eq!(
482 state
483 .marginal_price(&weth, &usdc, &BigUint::from_str("2500000000000000000").unwrap())
484 .unwrap(),
485 2900.0
486 );
487 assert!(matches!(
488 state.marginal_price(&weth, &usdc, &BigUint::from_str("5000000000000000000").unwrap()),
489 Err(SimulationError::RecoverableError(_))
490 ));
491 let per_usdc = state
493 .marginal_price(&usdc, &weth, &BigUint::ZERO)
494 .unwrap();
495 assert!((per_usdc - 1.0 / 3100.0).abs() < 1e-15, "{per_usdc}");
496 }
497
498 #[test]
499 fn a_side_with_no_levels_has_nothing_to_offer() {
500 let mut state = test_state();
501 state.book.bids = Levels::default();
502 assert_eq!(state.directions(), vec![(usdc().address, weth().address)]);
503 assert!(matches!(
504 state.get_limits(weth().address, usdc().address),
505 Err(SimulationError::RecoverableError(_))
506 ));
507 assert!(matches!(
509 state.get_amount_out(
510 BigUint::from_str("1000000000000000000").unwrap(),
511 &weth(),
512 &usdc()
513 ),
514 Err(SimulationError::InvalidInput(_, None))
515 ));
516 }
517
518 #[test]
519 fn eq_compares_the_pair_and_its_book() {
520 let state = test_state();
521 assert!(ProtocolSim::eq(&state, &test_state()));
522 let mut moved = test_state();
523 moved.book.bids = ladder(&[(2999.0, 2.0)]);
524 assert!(!ProtocolSim::eq(&state, &moved));
525 }
526
527 #[tokio::test]
528 async fn a_replayed_state_prices_but_cannot_quote() {
529 let state = test_state();
530 let replayed: EuclidState =
531 serde_json::from_str(&serde_json::to_string(&state).unwrap()).unwrap();
532
533 assert!(ProtocolSim::eq(&state, &replayed));
534 let priced = replayed
536 .get_amount_out(BigUint::from_str("1000000000000000000").unwrap(), &weth(), &usdc())
537 .unwrap();
538 assert_eq!(priced.amount, BigUint::from(3_000_000_000u64));
539
540 let params = GetAmountOutParams {
541 amount_in: BigUint::from_str("1000000000000000000").unwrap(),
542 token_in: weth().address,
543 token_out: usdc().address,
544 sender: Bytes::zero(20),
545 receiver: Bytes::zero(20),
546 origin: None,
547 };
548 assert!(matches!(
549 replayed
550 .request_signed_quote(params)
551 .await,
552 Err(SimulationError::FatalError(_))
553 ));
554 }
555}