Skip to main content

tycho_simulation/rfq/protocols/euclid/
state.rs

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
27/// Gas for one Euclid settlement: `fillOrderRFQTo` hashes the order, recovers the maker's
28/// signature, sets a bit in the maker's nonce bitmap and moves both tokens. A fill measures
29/// 120k on a mainnet fork with the tokens and the maker cold, which a route only makes cheaper.
30const 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    /// A book this venue prices, with the client its binding quotes go to.
45    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    /// The ladder a swap in `direction` consumes, in the units of the token sold: the bids as
55    /// published for selling base, the asks re-expressed per quote unit for selling quote.
56    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    /// The least the gateway signs for on the side a swap in `direction` consumes, in
64    /// quote-token units. Euclid publishes its minimum trade as the first level of each side,
65    /// at that side's best price, and declines a binding quote for less, so a book refuses to
66    /// price what the venue would not sign.
67    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            &quote.address,
122        )?;
123        // The mid of the best bid and ask, since this method does not care about the direction
124        // of a trade; one side alone stands for the price when the other is empty.
125        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        // The trade's worth is read on the quote side: the amount sold when quote is sold, and
167        // what the ladder pays otherwise. A side with no levels takes nothing at any size, which
168        // the fill below reports as the absence of liquidity it is.
169        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        // The state doesn't change after a swap.
181        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        // Nothing on this side is no swap at any size, so there is no limit to report.
193        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(&params)
247            .await?)
248    }
249}
250
251all_pairs_state! {
252    /// Euclid's books on one chain behind one component.
253    ///
254    /// Euclid signs its quotes itself from one maker inventory, so all of its books share one
255    /// turn: a route takes one quote from the venue, and the swap that takes it spends every
256    /// book behind the component.
257    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    /// WETH/USDC as the gateway publishes it: the first level of each side is the minimum
314    /// trade (3 USDC of bids, 3.1 USDC of asks), then bids 3000 x 1.999, 2900 x 2.5 and asks
315    /// 3100 x 1.499, 3200 x 3.0.
316    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        // 3 WETH -> 3000 * 2 + 2900 * 1 = 8900 USDC
368        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        // 7000 USDC -> 4650 / 3100 = 1.5 WETH, then 2350 / 3200 WETH
375        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        // All 4.5 WETH of bids fill for 13250 USDC; the rest goes unfilled.
396        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    /// The first level of each side is the least the gateway signs for; a trade worth less on
405    /// the quote side is refused, one worth at least that much is priced.
406    #[test]
407    fn a_trade_below_the_published_minimum_is_refused() {
408        let state = test_state();
409        // 0.0005 WETH sells for 1.5 USDC, under the 3 USDC first bid level.
410        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        // 1 USDC buys, under the 3.1 USDC first ask level.
417        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        // 0.0011 WETH sells for 3.3 USDC, which the gateway signs for.
423        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        // Selling WETH walks the bids: 4.5 WETH in for 3000 * 2 + 2900 * 2.5 = 13250 USDC.
455        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        // Buying WETH walks the asks: 3100 * 1.5 + 3200 * 3 = 14250 USDC in for 4.5 WETH.
461        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    /// The next unit prices at the level a fill of that much has reached, on the ladder the
469    /// direction consumes, and nothing once the ladder is spent.
470    #[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        // 2.5 WETH in: the two 3000 levels are spent, the next unit sells at 2900.
481        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        // Buying WETH: the first USDC buys at the best ask, 1 / 3100 WETH per USDC.
492        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        // Nothing fills, so no part of the amount comes back priced.
508        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        // 1 WETH sells into the two 3000 levels.
535        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}