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
26const 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 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 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 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 fn fee(&self) -> f64 {
99 todo!()
100 }
101
102 fn spot_price(&self, base: &Token, quote: &Token) -> Result<f64, SimulationError> {
104 self.valid_direction_guard(&base.address, "e.address)?;
105 self.book
106 .average_price()
107 .ok_or(SimulationError::RecoverableError("No liquidity".into()))
108 }
109
110 fn get_amount_out(
111 &self,
112 amount_in: BigUint,
113 token_in: &Token,
114 token_out: &Token,
115 ) -> Result<GetAmountOutResult, SimulationError> {
116 sim::require_positive_amount(&amount_in)?;
119
120 self.valid_direction_guard(&token_in.address, &token_out.address)?;
121 let amount_in = sim::to_human(&amount_in, token_in.decimals);
122 let fill = self.book.levels.fill(amount_in);
123 sim::fill_result(fill, amount_in, token_out.decimals, LIQUORICE_SWAP_GAS, self)
125 }
126
127 fn get_limits(
128 &self,
129 sell_token: Bytes,
130 buy_token: Bytes,
131 ) -> Result<(BigUint, BigUint), SimulationError> {
132 self.valid_direction_guard(&sell_token, &buy_token)?;
133 if self.book.levels.is_empty() {
135 return Err(SimulationError::RecoverableError("No liquidity".into()));
136 }
137 sim::limits(&self.book.levels, self.base_token.decimals, self.quote_token.decimals)
138 }
139
140 fn as_indicatively_priced(&self) -> Result<&dyn IndicativelyPriced, SimulationError> {
141 Ok(self)
142 }
143
144 fn delta_transition(
145 &mut self,
146 _delta: ProtocolStateDelta,
147 _tokens: &HashMap<Bytes, Token>,
148 _balances: &Balances,
149 ) -> Result<(), TransitionError> {
150 todo!()
151 }
152
153 fn clone_box(&self) -> Box<dyn ProtocolSim> {
154 Box::new(self.clone())
155 }
156
157 fn as_any(&self) -> &dyn Any {
158 self
159 }
160
161 fn as_any_mut(&mut self) -> &mut dyn Any {
162 self
163 }
164
165 fn eq(&self, other: &dyn ProtocolSim) -> bool {
166 if let Some(other_state) = other
167 .as_any()
168 .downcast_ref::<LiquoriceState>()
169 {
170 self.base_token == other_state.base_token &&
171 self.quote_token == other_state.quote_token &&
172 self.market_maker == other_state.market_maker &&
173 self.book == other_state.book
174 } else {
175 false
176 }
177 }
178}
179
180#[async_trait]
181impl IndicativelyPriced for LiquoriceState {
182 async fn request_signed_quote(
183 &self,
184 params: GetAmountOutParams,
185 ) -> Result<SignedQuote, SimulationError> {
186 Ok(sim::quoting_client(self.client.as_ref(), "Liquorice")?
187 .request_binding_quote(¶ms, &self.market_maker)
188 .await?)
189 }
190}
191
192all_pairs_state! {
193 LiquoriceAllPairsState(LiquoriceState, SignedByMakers);
195}
196
197impl RefusesQuote for LiquoriceAllPairsState {}
198
199#[cfg(test)]
200mod tests {
201 use std::str::FromStr;
202
203 use rstest::rstest;
204 use tokio::time::Duration;
205 use tycho_common::models::Chain;
206
207 use super::*;
208 use crate::book::levels::{Levels, PriceLevel};
209
210 fn wbtc() -> Token {
211 Token::new(
212 &hex::decode("2260fac5e5542a773aa44fbcfedf7c193bc2c599")
213 .unwrap()
214 .into(),
215 "WBTC",
216 8,
217 0,
218 &[Some(10_000)],
219 Chain::Ethereum,
220 100,
221 )
222 }
223
224 fn usdc() -> Token {
225 Token::new(
226 &hex::decode("a0b86991c6218a76c1d19d4a2e9eb0ce3606eb48")
227 .unwrap()
228 .into(),
229 "USDC",
230 6,
231 0,
232 &[Some(10_000)],
233 Chain::Ethereum,
234 100,
235 )
236 }
237
238 fn weth() -> Token {
239 Token::new(
240 &Bytes::from_str("0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2").unwrap(),
241 "WETH",
242 18,
243 0,
244 &[],
245 Default::default(),
246 100,
247 )
248 }
249
250 fn empty_client() -> Arc<LiquoriceClient> {
251 Arc::new(LiquoriceClient::new(
252 None,
253 Chain::Ethereum.id(),
254 String::new(),
255 String::new(),
256 Duration::from_secs(30),
257 300,
258 ))
259 }
260
261 fn create_test_liquorice_state() -> LiquoriceState {
262 let base_addr = Bytes::from_str("0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2").unwrap();
263 let quote_addr = Bytes::from_str("0xa0b86991c6218a76c1d19d4a2e9eb0ce3606eb48").unwrap();
264 LiquoriceState {
265 base_token: weth(),
266 quote_token: usdc(),
267 book: LiquoriceTokenPairPrice {
268 base_token: base_addr,
269 quote_token: quote_addr,
270 levels: Levels::new(vec![
271 PriceLevel { quantity: 0.5, price: 3000.0 },
272 PriceLevel { quantity: 1.5, price: 3000.0 },
273 PriceLevel { quantity: 5.0, price: 2999.0 },
274 ])
275 .unwrap(),
276 updated_at: None,
277 },
278 market_maker: "test_mm".to_string(),
279 client: Some(empty_client()),
280 }
281 }
282
283 #[rstest]
286 #[case::in_the_first_level(250_000_000_000_000_000, Some(3000.0))]
287 #[case::on_the_second_boundary(2_000_000_000_000_000_000, Some(2999.0))]
288 #[case::past_the_depth(7_000_000_000_000_000_000, None)]
289 fn the_price_after_a_fill_is_the_level_where_it_stopped(
290 #[case] filled: u64,
291 #[case] expected: Option<f64>,
292 ) {
293 let state = create_test_liquorice_state();
294
295 let price = state.marginal_price(&weth().address, &usdc().address, &BigUint::from(filled));
296 let reverse =
297 state.marginal_price(&usdc().address, &weth().address, &BigUint::from(filled));
298
299 match (price, expected) {
300 (Ok(price), Some(expected)) => assert_eq!(price, expected),
301 (Err(SimulationError::RecoverableError(message)), None) => {
302 assert_eq!(message, "No liquidity")
303 }
304 (price, _) => panic!("expected {expected:?}, got {price:?}"),
305 }
306 assert!(matches!(reverse, Err(SimulationError::InvalidInput(_, None))), "{reverse:?}");
307 }
308
309 #[test]
312 fn rejects_tokens_outside_the_pair_and_the_reverse_direction() {
313 let state = create_test_liquorice_state();
314 let amount = BigUint::from_str("100000000").unwrap();
315 let is_invalid_pair = |result: Result<_, SimulationError>| {
316 matches!(
317 result,
318 Err(SimulationError::InvalidInput(msg, _)) if msg.contains("Invalid token addresses")
319 )
320 };
321
322 assert!(is_invalid_pair(
323 state
324 .spot_price(&wbtc(), &usdc())
325 .map(|_| ())
326 ));
327 assert!(is_invalid_pair(
328 state
329 .get_amount_out(amount.clone(), &wbtc(), &usdc())
330 .map(|_| ())
331 ));
332 assert!(is_invalid_pair(
333 state
334 .get_amount_out(amount, &usdc(), &weth())
335 .map(|_| ())
336 ));
337 assert!(is_invalid_pair(
338 state
339 .get_limits(wbtc().address.clone(), state.quote_token.address.clone())
340 .map(|_| ())
341 ));
342 }
343
344 mod spot_price {
345 use super::*;
346
347 #[test]
350 fn is_what_the_whole_ladder_pays_per_token() {
351 let state = create_test_liquorice_state();
352 let price = state
353 .spot_price(&state.base_token, &state.quote_token)
354 .unwrap();
355 assert!((price - 20995.0 / 7.0).abs() < 1e-10);
356 }
357
358 #[test]
360 fn an_empty_book_has_nothing_to_offer() {
361 let mut state = create_test_liquorice_state();
362 state.book.levels = Levels::default();
363
364 let result = state.spot_price(&state.base_token, &state.quote_token);
365 assert!(
366 matches!(&result, Err(SimulationError::RecoverableError(msg)) if msg == "No liquidity"),
367 "{result:?}"
368 );
369 assert!(matches!(
370 state.get_limits(
371 state.base_token.address.clone(),
372 state.quote_token.address.clone()
373 ),
374 Err(SimulationError::RecoverableError(_))
375 ));
376 }
377 }
378
379 mod get_amount_out {
380 use super::*;
381
382 #[test]
383 fn weth_to_usdc() {
384 let state = create_test_liquorice_state();
385
386 let amount_out_result = state
387 .get_amount_out(BigUint::from_str("1500000000000000000").unwrap(), &weth(), &usdc())
388 .unwrap();
389
390 assert_eq!(amount_out_result.amount, BigUint::from_str("4500000000").unwrap());
391 assert_eq!(amount_out_result.gas, BigUint::from(134_000u64));
392 }
393
394 #[test]
395 fn insufficient_liquidity() {
396 let state = create_test_liquorice_state();
397
398 let result = state.get_amount_out(
400 BigUint::from_str("8000000000000000000").unwrap(),
401 &weth(),
402 &usdc(),
403 );
404
405 assert!(result.is_err());
406 if let Err(SimulationError::InvalidInput(msg, _)) = result {
407 assert!(msg.contains("Pool has not enough liquidity"));
408 } else {
409 panic!("Expected InvalidInput");
410 }
411 }
412 }
413
414 mod get_limits {
415 use super::*;
416
417 #[test]
418 fn valid_limits() {
419 let state = create_test_liquorice_state();
420 let (sell_limit, buy_limit) = state
421 .get_limits(state.base_token.address.clone(), state.quote_token.address.clone())
422 .unwrap();
423
424 assert_eq!(sell_limit, BigUint::from((7.0 * 10f64.powi(18)) as u128));
425 assert_eq!(buy_limit, BigUint::from((20995.0 * 10f64.powi(6)) as u128));
426 }
427 }
428
429 #[test]
431 fn rejects_a_zero_amount() {
432 let state = create_test_liquorice_state();
433
434 let result = state.get_amount_out(
435 BigUint::ZERO,
436 &state.base_token.clone(),
437 &state.quote_token.clone(),
438 );
439
440 assert!(matches!(result, Err(SimulationError::InvalidInput(_, None))), "{result:?}");
441 }
442}