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