1use std::{any::Any, collections::HashMap, sync::Arc};
2
3use async_trait::async_trait;
4use num_bigint::BigUint;
5use num_traits::FromPrimitive;
6use serde::{Deserialize, Serialize};
7use tycho_common::{
8 dto::ProtocolStateDelta,
9 models::{protocol::GetAmountOutParams, token::Token},
10 simulation::{
11 errors::{SimulationError, TransitionError},
12 indicatively_priced::{IndicativelyPriced, SignedQuote},
13 protocol_sim::{Balances, GetAmountOutResult, ProtocolSim},
14 },
15 Bytes,
16};
17
18use crate::{
19 book::{
20 all_pairs::{all_pairs_state, RefusesQuote, SignedByMakers},
21 component::PairState,
22 sim::{self, SwapDirection},
23 },
24 rfq::protocols::hashflow::{client::HashflowClient, models::HashflowMarketMakerLevels},
25};
26
27const HASHFLOW_SWAP_GAS: u64 = 151_000;
31
32#[derive(Clone, derive_more::Debug, Serialize, Deserialize)]
33pub struct HashflowState {
34 pub(super) base_token: Token,
35 pub(super) quote_token: Token,
36 #[debug(skip)]
37 pub(super) levels: HashflowMarketMakerLevels,
38 pub(super) market_maker: String,
39 #[serde(skip)]
40 #[debug(skip)]
41 client: Option<Arc<HashflowClient>>,
42}
43
44impl HashflowState {
45 pub(super) fn new(
47 base_token: Token,
48 quote_token: Token,
49 levels: HashflowMarketMakerLevels,
50 market_maker: String,
51 client: Arc<HashflowClient>,
52 ) -> Self {
53 HashflowState { base_token, quote_token, levels, market_maker, client: Some(client) }
54 }
55
56 pub fn min_amount_in(&self) -> BigUint {
66 let first_level_quantity = self
67 .levels
68 .levels
69 .first()
70 .map_or(0.0, |level| level.quantity);
71 let scaled = first_level_quantity * 10f64.powi(self.base_token.decimals as i32);
72 BigUint::from_f64(scaled).unwrap_or_default()
74 }
75 fn valid_direction_guard(
77 &self,
78 token_address_in: &Bytes,
79 token_address_out: &Bytes,
80 ) -> Result<(), SimulationError> {
81 SwapDirection::require_base_to_quote(
82 &self.base_token,
83 &self.quote_token,
84 token_address_in,
85 token_address_out,
86 )
87 }
88}
89
90impl PairState for HashflowState {
91 fn base_token(&self) -> &Token {
92 &self.base_token
93 }
94
95 fn quote_token(&self) -> &Token {
96 &self.quote_token
97 }
98
99 fn directions(&self) -> Vec<(Bytes, Bytes)> {
102 sim::directions(&self.base_token, &self.quote_token, !self.levels.levels.is_empty(), false)
103 }
104}
105
106#[typetag::serde]
107impl ProtocolSim for HashflowState {
108 fn fee(&self) -> f64 {
109 todo!()
110 }
111
112 fn spot_price(&self, base: &Token, quote: &Token) -> Result<f64, SimulationError> {
113 self.valid_direction_guard(&base.address, "e.address)?;
114 self.levels
116 .levels
117 .first()
118 .ok_or(SimulationError::RecoverableError("No liquidity".into()))
119 .map(|level| level.price)
120 }
121
122 fn get_amount_out(
123 &self,
124 amount_in: BigUint,
125 token_in: &Token,
126 token_out: &Token,
127 ) -> Result<GetAmountOutResult, SimulationError> {
128 sim::require_positive_amount(&amount_in)?;
132
133 self.valid_direction_guard(&token_in.address, &token_out.address)?;
134 let min_amount_in = self.min_amount_in();
135 if amount_in < min_amount_in {
136 return Err(SimulationError::RecoverableError(format!(
137 "Amount below minimum. Input amount: {amount_in}, min amount: {min_amount_in} \
138 (both in base units)"
139 )));
140 }
141 let amount_in = sim::to_human(&amount_in, token_in.decimals);
142 let fill = self.levels.levels.fill(amount_in);
143 sim::fill_result(fill, amount_in, token_out.decimals, HASHFLOW_SWAP_GAS, self)
145 }
146
147 fn get_limits(
148 &self,
149 sell_token: Bytes,
150 buy_token: Bytes,
151 ) -> Result<(BigUint, BigUint), SimulationError> {
152 self.valid_direction_guard(&sell_token, &buy_token)?;
153 if self.levels.levels.is_empty() {
155 return Err(SimulationError::RecoverableError("No liquidity".into()));
156 }
157 sim::limits(&self.levels.levels, self.base_token.decimals, self.quote_token.decimals)
158 }
159
160 fn as_indicatively_priced(&self) -> Result<&dyn IndicativelyPriced, SimulationError> {
161 Ok(self)
162 }
163
164 fn delta_transition(
165 &mut self,
166 _delta: ProtocolStateDelta,
167 _tokens: &HashMap<Bytes, Token>,
168 _balances: &Balances,
169 ) -> Result<(), TransitionError> {
170 todo!()
171 }
172
173 fn clone_box(&self) -> Box<dyn ProtocolSim> {
174 Box::new(self.clone())
175 }
176
177 fn as_any(&self) -> &dyn Any {
178 self
179 }
180
181 fn as_any_mut(&mut self) -> &mut dyn Any {
182 self
183 }
184
185 fn eq(&self, other: &dyn ProtocolSim) -> bool {
186 if let Some(other_state) = other
187 .as_any()
188 .downcast_ref::<HashflowState>()
189 {
190 self.base_token == other_state.base_token &&
191 self.quote_token == other_state.quote_token &&
192 self.levels == other_state.levels
193 } else {
194 false
195 }
196 }
197}
198
199#[async_trait]
200impl IndicativelyPriced for HashflowState {
201 async fn request_signed_quote(
202 &self,
203 params: GetAmountOutParams,
204 ) -> Result<SignedQuote, SimulationError> {
205 Ok(sim::quoting_client(self.client.as_ref(), "Hashflow")?
206 .request_binding_quote(¶ms, self.market_maker.clone())
207 .await?)
208 }
209}
210
211all_pairs_state! {
212 HashflowAllPairsState(HashflowState, SignedByMakers);
215}
216
217impl RefusesQuote for HashflowAllPairsState {
218 fn check_amount(
221 &self,
222 amount_in: &BigUint,
223 token_in: &Bytes,
224 token_out: &Bytes,
225 ) -> Result<(), SimulationError> {
226 match self.min_amount_in(token_in, token_out) {
227 Some(minimum) if amount_in < &minimum => {
228 Err(SimulationError::RecoverableError(format!(
229 "Amount below minimum. Input amount: {amount_in}, min amount: {minimum} \
230 (both in base units)"
231 )))
232 }
233 _ => Ok(()),
234 }
235 }
236}
237
238impl HashflowAllPairsState {
239 pub fn min_amount_in(&self, token_in: &Bytes, token_out: &Bytes) -> Option<BigUint> {
243 self.0
244 .books_pricing(token_in, token_out)
245 .map(|book| book.state.min_amount_in())
246 .min()
247 }
248}
249
250#[cfg(test)]
251mod tests {
252 use std::str::FromStr;
253
254 use tokio::time::Duration;
255 use tycho_common::models::Chain;
256
257 use super::*;
258 use crate::{
259 book::levels::{Levels, PriceLevel},
260 rfq::protocols::hashflow::models::HashflowPair,
261 };
262
263 fn wbtc() -> Token {
264 Token::new(
265 &hex::decode("2260fac5e5542a773aa44fbcfedf7c193bc2c599")
266 .unwrap()
267 .into(),
268 "WBTC",
269 8,
270 0,
271 &[Some(10_000)],
272 Chain::Ethereum,
273 100,
274 )
275 }
276
277 fn usdc() -> Token {
278 Token::new(
279 &hex::decode("a0b86991c6218a76c1d19d4a2e9eb0ce3606eb48")
280 .unwrap()
281 .into(),
282 "USDC",
283 6,
284 0,
285 &[Some(10_000)],
286 Chain::Ethereum,
287 100,
288 )
289 }
290
291 fn weth() -> Token {
292 Token::new(
293 &Bytes::from_str("0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2").unwrap(),
294 "WETH",
295 18,
296 0,
297 &[],
298 Default::default(),
299 100,
300 )
301 }
302
303 fn empty_client() -> Arc<HashflowClient> {
304 Arc::new(HashflowClient::new(
305 None,
306 1,
307 String::new(),
308 String::new(),
309 Duration::from_secs(30),
310 ))
311 }
312
313 fn create_test_hashflow_state() -> HashflowState {
314 HashflowState {
315 base_token: weth(),
316 quote_token: usdc(),
317 levels: HashflowMarketMakerLevels {
318 pair: HashflowPair {
319 base_token: Bytes::from_str("0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2")
320 .unwrap(),
321 quote_token: Bytes::from_str("0xa0b86991c6218a76c1d19d4a2e9eb0ce3606eb48")
322 .unwrap(),
323 },
324 levels: Levels::new(vec![
325 PriceLevel { quantity: 0.5, price: 3000.0 },
326 PriceLevel { quantity: 1.5, price: 3000.0 },
327 PriceLevel { quantity: 5.0, price: 2999.0 },
328 ])
329 .unwrap(),
330 },
331 market_maker: "test_mm".to_string(),
332 client: Some(empty_client()),
333 }
334 }
335
336 #[test]
344 fn the_minimum_of_a_single_level_book_is_within_its_depth() {
345 let state = HashflowState {
346 base_token: usdc(),
347 quote_token: weth(),
348 levels: HashflowMarketMakerLevels {
349 pair: HashflowPair { base_token: usdc().address, quote_token: weth().address },
350 levels: Levels::new(vec![PriceLevel {
351 quantity: 4327.8578109263835,
352 price: 0.000_25,
353 }])
354 .unwrap(),
355 },
356 market_maker: "test_mm".to_string(),
357 client: Some(empty_client()),
358 };
359
360 let minimum = state.min_amount_in();
361 let (limit, _) = state
362 .get_limits(usdc().address, weth().address)
363 .unwrap();
364
365 assert!(minimum <= limit, "minimum {minimum} is past the book's own limit {limit}");
366 let result = state.get_amount_out(minimum, &usdc(), &weth());
367 assert!(result.is_ok(), "{result:?}");
368 }
369
370 #[test]
375 fn the_advertised_minimum_is_quotable() {
376 let mut state = create_test_hashflow_state();
377 state.levels.levels =
378 Levels::new(vec![PriceLevel { quantity: 31374.751353434924, price: 3000.0 }]).unwrap();
379
380 let result = state.get_amount_out(state.min_amount_in(), &weth(), &usdc());
381
382 assert!(result.is_ok(), "{result:?}");
383 }
384
385 #[test]
386 fn rejects_tokens_outside_the_pair_and_the_reverse_direction() {
387 let state = create_test_hashflow_state();
390 let amount = BigUint::from_str("1000000000000000000").unwrap();
391 let results = [
392 state
393 .spot_price(&wbtc(), &usdc())
394 .map(|_| ()),
395 state
396 .get_amount_out(amount.clone(), &usdc(), &weth())
397 .map(|_| ()),
398 state
399 .get_amount_out(amount, &wbtc(), &usdc())
400 .map(|_| ()),
401 state
402 .get_limits(wbtc().address.clone(), usdc().address.clone())
403 .map(|_| ()),
404 ];
405
406 for result in results {
407 assert!(
408 matches!(&result, Err(SimulationError::InvalidInput(msg, None)) if msg.contains("Invalid token addresses")),
409 "{result:?}"
410 );
411 }
412 }
413
414 #[test]
415 fn an_empty_ladder_has_nothing_to_offer() {
417 let mut state = create_test_hashflow_state();
418 state.levels.levels = Levels::default();
419 let price = state.spot_price(&weth(), &usdc());
420 assert!(
421 matches!(&price, Err(SimulationError::RecoverableError(msg)) if msg == "No liquidity"),
422 "{price:?}"
423 );
424 let swap = state.get_amount_out(
425 BigUint::from_str("1000000000000000000").unwrap(),
426 &weth(),
427 &usdc(),
428 );
429 assert!(matches!(swap, Err(SimulationError::InvalidInput(_, None))), "{swap:?}");
430 assert!(matches!(
431 state.get_limits(weth().address.clone(), usdc().address.clone()),
432 Err(SimulationError::RecoverableError(_))
433 ));
434 }
435
436 #[test]
437 fn spot_price_is_the_first_level() {
438 let state = create_test_hashflow_state();
439 let price = state
440 .spot_price(&state.base_token, &state.quote_token)
441 .unwrap();
442 assert_eq!(price, 3000.0);
443 }
444
445 mod get_amount_out {
446 use super::*;
447
448 #[test]
449 fn wbtc_to_usdc() {
450 let state = create_test_hashflow_state();
451
452 let amount_out_result = state
456 .get_amount_out(
457 BigUint::from_str("1500000000000000000").unwrap(), &weth(),
459 &usdc(),
460 )
461 .unwrap();
462
463 assert_eq!(amount_out_result.amount, BigUint::from_str("4500000000").unwrap()); assert_eq!(amount_out_result.gas, BigUint::from(151_000u64));
466 }
467
468 #[test]
469 fn below_minimum() {
470 let state = create_test_hashflow_state();
471
472 let result = state.get_amount_out(
474 BigUint::from_str("250000000000000000").unwrap(), &weth(),
476 &usdc(),
477 );
478
479 assert!(result.is_err());
480 if let Err(SimulationError::RecoverableError(msg)) = result {
481 assert!(msg.contains("Amount below minimum"));
482 } else {
483 panic!("Expected RecoverableError");
484 }
485 }
486
487 #[test]
488 fn insufficient_liquidity() {
489 let state = create_test_hashflow_state();
490
491 let result = state.get_amount_out(
493 BigUint::from_str("8000000000000000000").unwrap(), &weth(),
495 &usdc(),
496 );
497
498 assert!(result.is_err());
499 if let Err(SimulationError::InvalidInput(msg, _)) = result {
500 assert!(msg.contains("Pool has not enough liquidity"));
501 } else {
502 panic!("Expected InvalidInput");
503 }
504 }
505 }
506
507 #[test]
508 fn limits_are_the_ladder_totals() {
509 let state = create_test_hashflow_state();
510 let (sell_limit, buy_limit) = state
511 .get_limits(state.base_token.address.clone(), state.quote_token.address.clone())
512 .unwrap();
513
514 assert_eq!(sell_limit, BigUint::from((7.0 * 10f64.powi(18)) as u128));
517 assert_eq!(buy_limit, BigUint::from((20995.0 * 10f64.powi(6)) as u128));
518 }
519
520 #[test]
522 fn rejects_a_zero_amount() {
523 let state = create_test_hashflow_state();
524
525 let result = state.get_amount_out(BigUint::ZERO, &weth(), &usdc());
526
527 assert!(matches!(result, Err(SimulationError::InvalidInput(_, None))), "{result:?}");
528 }
529}