Skip to main content

tycho_simulation/rfq/protocols/liquorice/
state.rs

1use std::{any::Any, 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, SignedByMakers},
20        component::PairState,
21        sim::{self, SwapDirection},
22    },
23    rfq::protocols::liquorice::{client::LiquoriceClient, models::LiquoriceTokenPairPrice},
24};
25
26/// Rough gas estimate for one Liquorice settlement.
27const LIQUORICE_SWAP_GAS: u64 = 134_000;
28
29#[derive(Clone, derive_more::Debug, Serialize, Deserialize)]
30pub struct LiquoriceState {
31    pub(super) base_token: Token,
32    pub(super) quote_token: Token,
33    #[debug(skip)]
34    pub(super) book: LiquoriceTokenPairPrice,
35    pub(super) market_maker: String,
36    #[serde(skip)]
37    #[debug(skip)]
38    client: Option<Arc<LiquoriceClient>>,
39}
40
41impl LiquoriceState {
42    /// A book this venue prices, with the client its binding quotes go to.
43    pub(super) fn new(
44        base_token: Token,
45        quote_token: Token,
46        book: LiquoriceTokenPairPrice,
47        market_maker: String,
48        client: Arc<LiquoriceClient>,
49    ) -> Self {
50        LiquoriceState { base_token, quote_token, book, market_maker, client: Some(client) }
51    }
52
53    /// The levels price one direction only: selling base for quote.
54    fn valid_direction_guard(
55        &self,
56        token_address_in: &Bytes,
57        token_address_out: &Bytes,
58    ) -> Result<(), SimulationError> {
59        SwapDirection::require_base_to_quote(
60            &self.base_token,
61            &self.quote_token,
62            token_address_in,
63            token_address_out,
64        )
65    }
66}
67
68impl PairState for LiquoriceState {
69    fn base_token(&self) -> &Token {
70        &self.base_token
71    }
72
73    fn quote_token(&self) -> &Token {
74        &self.quote_token
75    }
76
77    /// A maker's ladder prices the pair one way — a taker sells the base token it was published
78    /// under — and the venue publishes the other way round as its own book.
79    fn directions(&self) -> Vec<(Bytes, Bytes)> {
80        sim::directions(&self.base_token, &self.quote_token, !self.book.levels.is_empty(), false)
81    }
82}
83
84impl PricesAfterFill for LiquoriceState {
85    fn marginal_price(
86        &self,
87        token_in: &Bytes,
88        token_out: &Bytes,
89        filled: &BigUint,
90    ) -> Result<f64, SimulationError> {
91        self.valid_direction_guard(token_in, token_out)?;
92        sim::marginal_price(&self.book.levels, filled, self.base_token.decimals)
93    }
94}
95
96#[typetag::serde]
97impl ProtocolSim for LiquoriceState {
98    #[expect(
99        clippy::todo,
100        reason = "the trait method returns no error, and a book has no separate fee to report"
101    )]
102    fn fee(&self) -> f64 {
103        todo!()
104    }
105
106    /// What the maker pays on average over the whole of its ladder.
107    fn spot_price(&self, base: &Token, quote: &Token) -> Result<f64, SimulationError> {
108        self.valid_direction_guard(&base.address, &quote.address)?;
109        self.book
110            .average_price()
111            .ok_or(SimulationError::RecoverableError("No liquidity".into()))
112    }
113
114    fn get_amount_out(
115        &self,
116        amount_in: BigUint,
117        token_in: &Token,
118        token_out: &Token,
119    ) -> Result<GetAmountOutResult, SimulationError> {
120        // Liquorice refuses a zero amount with `invalid_request: Token amount is less than or
121        // equal to zero`.
122        sim::require_positive_amount(&amount_in)?;
123
124        self.valid_direction_guard(&token_in.address, &token_out.address)?;
125        let amount_in = sim::to_human(&amount_in, token_in.decimals);
126        let fill = self.book.levels.fill(amount_in);
127        // The state doesn't change after a swap.
128        sim::fill_result(fill, amount_in, token_out.decimals, LIQUORICE_SWAP_GAS, self)
129    }
130
131    fn get_limits(
132        &self,
133        sell_token: Bytes,
134        buy_token: Bytes,
135    ) -> Result<(BigUint, BigUint), SimulationError> {
136        self.valid_direction_guard(&sell_token, &buy_token)?;
137        // Nothing on this side is no swap at any size, so there is no limit to report.
138        if self.book.levels.is_empty() {
139            return Err(SimulationError::RecoverableError("No liquidity".into()));
140        }
141        sim::limits(&self.book.levels, self.base_token.decimals, self.quote_token.decimals)
142    }
143
144    fn as_indicatively_priced(&self) -> Result<&dyn IndicativelyPriced, SimulationError> {
145        Ok(self)
146    }
147
148    fn delta_transition(
149        &mut self,
150        _delta: ProtocolStateDelta,
151        _tokens: &HashMap<Bytes, Token>,
152        _balances: &Balances,
153    ) -> Result<(), TransitionError> {
154        Err(TransitionError::DecodeError(
155            "Liquorice state is snapshot-based and does not support deltas".into(),
156        ))
157    }
158
159    fn clone_box(&self) -> Box<dyn ProtocolSim> {
160        Box::new(self.clone())
161    }
162
163    fn as_any(&self) -> &dyn Any {
164        self
165    }
166
167    fn as_any_mut(&mut self) -> &mut dyn Any {
168        self
169    }
170
171    fn eq(&self, other: &dyn ProtocolSim) -> bool {
172        if let Some(other_state) = other
173            .as_any()
174            .downcast_ref::<LiquoriceState>()
175        {
176            self.base_token == other_state.base_token &&
177                self.quote_token == other_state.quote_token &&
178                self.market_maker == other_state.market_maker &&
179                self.book == other_state.book
180        } else {
181            false
182        }
183    }
184}
185
186#[async_trait]
187impl IndicativelyPriced for LiquoriceState {
188    async fn request_signed_quote(
189        &self,
190        params: GetAmountOutParams,
191    ) -> Result<SignedQuote, SimulationError> {
192        Ok(sim::quoting_client(self.client.as_ref(), "Liquorice")?
193            .request_binding_quote(&params, &self.market_maker)
194            .await?)
195    }
196}
197
198all_pairs_state! {
199    /// Liquorice's books on one chain behind one component: one book per market maker and pair.
200    LiquoriceAllPairsState(LiquoriceState, SignedByMakers);
201}
202
203impl RefusesQuote for LiquoriceAllPairsState {}
204
205#[cfg(test)]
206mod tests {
207    use std::str::FromStr;
208
209    use rstest::rstest;
210    use tokio::time::Duration;
211    use tycho_common::models::Chain;
212
213    use super::*;
214    use crate::book::levels::{Levels, PriceLevel};
215
216    fn wbtc() -> Token {
217        Token::new(
218            &hex::decode("2260fac5e5542a773aa44fbcfedf7c193bc2c599")
219                .unwrap()
220                .into(),
221            "WBTC",
222            8,
223            0,
224            &[Some(10_000)],
225            Chain::Ethereum,
226            100,
227        )
228    }
229
230    fn usdc() -> Token {
231        Token::new(
232            &hex::decode("a0b86991c6218a76c1d19d4a2e9eb0ce3606eb48")
233                .unwrap()
234                .into(),
235            "USDC",
236            6,
237            0,
238            &[Some(10_000)],
239            Chain::Ethereum,
240            100,
241        )
242    }
243
244    fn weth() -> Token {
245        Token::new(
246            &Bytes::from_str("0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2").unwrap(),
247            "WETH",
248            18,
249            0,
250            &[],
251            Default::default(),
252            100,
253        )
254    }
255
256    fn empty_client() -> Arc<LiquoriceClient> {
257        Arc::new(LiquoriceClient::new(
258            None,
259            Chain::Ethereum.id(),
260            String::new(),
261            String::new(),
262            Duration::from_secs(30),
263            300,
264        ))
265    }
266
267    fn create_test_liquorice_state() -> LiquoriceState {
268        let base_addr = Bytes::from_str("0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2").unwrap();
269        let quote_addr = Bytes::from_str("0xa0b86991c6218a76c1d19d4a2e9eb0ce3606eb48").unwrap();
270        LiquoriceState {
271            base_token: weth(),
272            quote_token: usdc(),
273            book: LiquoriceTokenPairPrice {
274                base_token: base_addr,
275                quote_token: quote_addr,
276                levels: Levels::new(vec![
277                    PriceLevel { quantity: 0.5, price: 3000.0 },
278                    PriceLevel { quantity: 1.5, price: 3000.0 },
279                    PriceLevel { quantity: 5.0, price: 2999.0 },
280                ])
281                .unwrap(),
282                updated_at: None,
283            },
284            market_maker: "test_mm".to_string(),
285            client: Some(empty_client()),
286        }
287    }
288
289    /// After some input went in, the next unit is priced at the level where the fill stopped,
290    /// and a reverse swap is rejected like a token outside the pair.
291    #[rstest]
292    #[case::in_the_first_level(250_000_000_000_000_000, Some(3000.0))]
293    #[case::on_the_second_boundary(2_000_000_000_000_000_000, Some(2999.0))]
294    #[case::past_the_depth(7_000_000_000_000_000_000, None)]
295    fn the_price_after_a_fill_is_the_level_where_it_stopped(
296        #[case] filled: u64,
297        #[case] expected: Option<f64>,
298    ) {
299        let state = create_test_liquorice_state();
300
301        let price = state.marginal_price(&weth().address, &usdc().address, &BigUint::from(filled));
302        let reverse =
303            state.marginal_price(&usdc().address, &weth().address, &BigUint::from(filled));
304
305        match (price, expected) {
306            (Ok(price), Some(expected)) => assert_eq!(price, expected),
307            (Err(SimulationError::RecoverableError(message)), None) => {
308                assert_eq!(message, "No liquidity")
309            }
310            (price, _) => panic!("expected {expected:?}, got {price:?}"),
311        }
312        assert!(matches!(reverse, Err(SimulationError::InvalidInput(_, None))), "{reverse:?}");
313    }
314
315    /// A Liquorice book prices one direction, so the reverse direction is rejected like a token
316    /// outside the pair, by every method.
317    #[test]
318    fn rejects_tokens_outside_the_pair_and_the_reverse_direction() {
319        let state = create_test_liquorice_state();
320        let amount = BigUint::from_str("100000000").unwrap();
321        let is_invalid_pair = |result: Result<_, SimulationError>| {
322            matches!(
323                result,
324                Err(SimulationError::InvalidInput(msg, _)) if msg.contains("Invalid token addresses")
325            )
326        };
327
328        assert!(is_invalid_pair(
329            state
330                .spot_price(&wbtc(), &usdc())
331                .map(|_| ())
332        ));
333        assert!(is_invalid_pair(
334            state
335                .get_amount_out(amount.clone(), &wbtc(), &usdc())
336                .map(|_| ())
337        ));
338        assert!(is_invalid_pair(
339            state
340                .get_amount_out(amount, &usdc(), &weth())
341                .map(|_| ())
342        ));
343        assert!(is_invalid_pair(
344            state
345                .get_limits(wbtc().address, state.quote_token.address.clone())
346                .map(|_| ())
347        ));
348    }
349
350    mod spot_price {
351        use super::*;
352
353        /// 0.5 and 1.5 WETH at 3000 USDC and 5 more at 2999 is 20 995 USDC for the 7 WETH the
354        /// ladder holds.
355        #[test]
356        fn is_what_the_whole_ladder_pays_per_token() {
357            let state = create_test_liquorice_state();
358            let price = state
359                .spot_price(&state.base_token, &state.quote_token)
360                .unwrap();
361            assert!((price - 20995.0 / 7.0).abs() < 1e-10);
362        }
363
364        /// A maker quoting nothing leaves no price to report, and no depth either.
365        #[test]
366        fn an_empty_book_has_nothing_to_offer() {
367            let mut state = create_test_liquorice_state();
368            state.book.levels = Levels::default();
369
370            let result = state.spot_price(&state.base_token, &state.quote_token);
371            assert!(
372                matches!(&result, Err(SimulationError::RecoverableError(msg)) if msg == "No liquidity"),
373                "{result:?}"
374            );
375            assert!(matches!(
376                state.get_limits(
377                    state.base_token.address.clone(),
378                    state.quote_token.address.clone()
379                ),
380                Err(SimulationError::RecoverableError(_))
381            ));
382        }
383    }
384
385    mod get_amount_out {
386        use super::*;
387
388        #[test]
389        fn weth_to_usdc() {
390            let state = create_test_liquorice_state();
391
392            let amount_out_result = state
393                .get_amount_out(BigUint::from_str("1500000000000000000").unwrap(), &weth(), &usdc())
394                .unwrap();
395
396            assert_eq!(amount_out_result.amount, BigUint::from_str("4500000000").unwrap());
397            assert_eq!(amount_out_result.gas, BigUint::from(134_000u64));
398        }
399
400        #[test]
401        fn insufficient_liquidity() {
402            let state = create_test_liquorice_state();
403
404            // The maker's ladder holds 7 WETH, so 8 exceeds it.
405            let result = state.get_amount_out(
406                BigUint::from_str("8000000000000000000").unwrap(),
407                &weth(),
408                &usdc(),
409            );
410
411            assert!(result.is_err());
412            if let Err(SimulationError::InvalidInput(msg, _)) = result {
413                assert!(msg.contains("Pool has not enough liquidity"));
414            } else {
415                panic!("Expected InvalidInput");
416            }
417        }
418    }
419
420    mod get_limits {
421        use super::*;
422
423        #[test]
424        fn valid_limits() {
425            let state = create_test_liquorice_state();
426            let (sell_limit, buy_limit) = state
427                .get_limits(state.base_token.address.clone(), state.quote_token.address.clone())
428                .unwrap();
429
430            assert_eq!(sell_limit, BigUint::from(7_000_000_000_000_000_000u128));
431            assert_eq!(buy_limit, BigUint::from(20_995_000_000u128));
432        }
433    }
434
435    /// The venue refuses a swap of nothing, so simulating one must not report a fill.
436    #[test]
437    fn rejects_a_zero_amount() {
438        let state = create_test_liquorice_state();
439
440        let result = state.get_amount_out(
441            BigUint::ZERO,
442            &state.base_token.clone(),
443            &state.quote_token.clone(),
444        );
445
446        assert!(matches!(result, Err(SimulationError::InvalidInput(_, None))), "{result:?}");
447    }
448}