Skip to main content

tycho_simulation/rfq/protocols/hashflow/
state.rs

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, PricesAfterFill, RefusesQuote, SignedByMakers},
21        component::PairState,
22        sim::{self, SwapDirection},
23    },
24    rfq::protocols::hashflow::{client::HashflowClient, models::HashflowMarketMakerLevels},
25};
26
27/// Rough gas estimate for one Hashflow settlement.
28/// A quote's fresh effective trader writes a cold nonce storage slot (~22k) rather than updating
29/// a reused one (~5k), which this includes.
30const 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    /// A book this venue prices, with the client its binding quotes go to.
46    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    /// Smallest `base_token` amount, in atomic units, that Hashflow accepts for a firm quote:
57    /// the first price level's quantity, which the ladder holds in whole units of the token,
58    /// scaled and rounded down. `get_amount_out` fills smaller amounts partially against that
59    /// level, but the quote API answers them with code 79, `Below minimum amount`, so callers
60    /// size requests at or above this.
61    ///
62    /// Rounding down is what the venue signs at: measured against a live maker, it quoted ten
63    /// and ninety atomic units below its published level and refused half of it. Rounding up
64    /// would name an amount a book of a single level does not reach.
65    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` truncates, which is the rounding this wants.
73        BigUint::from_f64(scaled).unwrap_or_default()
74    }
75    /// The levels price one direction only: selling base for quote.
76    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    /// A maker's ladder prices the pair one way — a taker sells the base token it was published
100    /// under — and the venue publishes the other way round as its own book.
101    fn directions(&self) -> Vec<(Bytes, Bytes)> {
102        sim::directions(&self.base_token, &self.quote_token, !self.levels.levels.is_empty(), false)
103    }
104}
105
106impl PricesAfterFill for HashflowState {
107    fn marginal_price(
108        &self,
109        token_in: &Bytes,
110        token_out: &Bytes,
111        filled: &BigUint,
112    ) -> Result<f64, SimulationError> {
113        self.valid_direction_guard(token_in, token_out)?;
114        sim::marginal_price(&self.levels.levels, filled, self.base_token.decimals)
115    }
116}
117
118#[typetag::serde]
119impl ProtocolSim for HashflowState {
120    fn fee(&self) -> f64 {
121        todo!()
122    }
123
124    fn spot_price(&self, base: &Token, quote: &Token) -> Result<f64, SimulationError> {
125        self.valid_direction_guard(&base.address, &quote.address)?;
126        // Hashflow's levels are sorted by price, so the first level represents the best price.
127        self.levels
128            .levels
129            .first()
130            .ok_or(SimulationError::RecoverableError("No liquidity".into()))
131            .map(|level| level.price)
132    }
133
134    fn get_amount_out(
135        &self,
136        amount_in: BigUint,
137        token_in: &Token,
138        token_out: &Token,
139    ) -> Result<GetAmountOutResult, SimulationError> {
140        // Hashflow refuses a zero amount with `79 Below minimum amount`, the same code it
141        // declines any amount under its maker's first level with. The minimum below answers for
142        // a maker that is quoting; one that is not has a first level of nothing.
143        sim::require_positive_amount(&amount_in)?;
144
145        self.valid_direction_guard(&token_in.address, &token_out.address)?;
146        let min_amount_in = self.min_amount_in();
147        if amount_in < min_amount_in {
148            return Err(SimulationError::RecoverableError(format!(
149                "Amount below minimum. Input amount: {amount_in}, min amount: {min_amount_in} \
150                 (both in base units)"
151            )));
152        }
153        let amount_in = sim::to_human(&amount_in, token_in.decimals);
154        let fill = self.levels.levels.fill(amount_in);
155        // The state doesn't change after a swap.
156        sim::fill_result(fill, amount_in, token_out.decimals, HASHFLOW_SWAP_GAS, self)
157    }
158
159    fn get_limits(
160        &self,
161        sell_token: Bytes,
162        buy_token: Bytes,
163    ) -> Result<(BigUint, BigUint), SimulationError> {
164        self.valid_direction_guard(&sell_token, &buy_token)?;
165        // Nothing on this side is no swap at any size, so there is no limit to report.
166        if self.levels.levels.is_empty() {
167            return Err(SimulationError::RecoverableError("No liquidity".into()));
168        }
169        sim::limits(&self.levels.levels, self.base_token.decimals, self.quote_token.decimals)
170    }
171
172    fn as_indicatively_priced(&self) -> Result<&dyn IndicativelyPriced, SimulationError> {
173        Ok(self)
174    }
175
176    fn delta_transition(
177        &mut self,
178        _delta: ProtocolStateDelta,
179        _tokens: &HashMap<Bytes, Token>,
180        _balances: &Balances,
181    ) -> Result<(), TransitionError> {
182        todo!()
183    }
184
185    fn clone_box(&self) -> Box<dyn ProtocolSim> {
186        Box::new(self.clone())
187    }
188
189    fn as_any(&self) -> &dyn Any {
190        self
191    }
192
193    fn as_any_mut(&mut self) -> &mut dyn Any {
194        self
195    }
196
197    fn eq(&self, other: &dyn ProtocolSim) -> bool {
198        if let Some(other_state) = other
199            .as_any()
200            .downcast_ref::<HashflowState>()
201        {
202            self.base_token == other_state.base_token &&
203                self.quote_token == other_state.quote_token &&
204                self.levels == other_state.levels
205        } else {
206            false
207        }
208    }
209}
210
211#[async_trait]
212impl IndicativelyPriced for HashflowState {
213    async fn request_signed_quote(
214        &self,
215        params: GetAmountOutParams,
216    ) -> Result<SignedQuote, SimulationError> {
217        Ok(sim::quoting_client(self.client.as_ref(), "Hashflow")?
218            .request_binding_quote(&params, self.market_maker.clone())
219            .await?)
220    }
221}
222
223all_pairs_state! {
224    /// Hashflow's books on one chain behind one component: every market maker's levels on every
225    /// pair it quotes.
226    HashflowAllPairsState(HashflowState, SignedByMakers);
227}
228
229impl RefusesQuote for HashflowAllPairsState {
230    /// Every maker declines an amount below its first level, so an amount under the smallest
231    /// of their floors is one no maker here fills, and that floor is what to raise it to.
232    fn check_amount(
233        &self,
234        amount_in: &BigUint,
235        token_in: &Bytes,
236        token_out: &Bytes,
237    ) -> Result<(), SimulationError> {
238        match self.min_amount_in(token_in, token_out) {
239            Some(minimum) if amount_in < &minimum => {
240                Err(SimulationError::RecoverableError(format!(
241                    "Amount below minimum. Input amount: {amount_in}, min amount: {minimum} \
242                     (both in base units)"
243                )))
244            }
245            _ => Ok(()),
246        }
247    }
248}
249
250impl HashflowAllPairsState {
251    /// The smallest first-level minimum among the books pricing this direction, spent or not,
252    /// in atomic units, or `None` where the venue prices nothing in it. A swap goes to one
253    /// maker, and a maker declines an amount below its first level.
254    pub fn min_amount_in(&self, token_in: &Bytes, token_out: &Bytes) -> Option<BigUint> {
255        self.0
256            .books_pricing(token_in, token_out)
257            .map(|book| book.state.min_amount_in())
258            .min()
259    }
260}
261
262#[cfg(test)]
263mod tests {
264    use std::str::FromStr;
265
266    use rstest::rstest;
267    use tokio::time::Duration;
268    use tycho_common::models::Chain;
269
270    use super::*;
271    use crate::{
272        book::{
273            all_pairs::{AllPairs, MarketMaker, QuoteRule, VenueBook},
274            levels::{Levels, PriceLevel},
275        },
276        rfq::protocols::hashflow::models::HashflowPair,
277    };
278
279    fn wbtc() -> Token {
280        Token::new(
281            &hex::decode("2260fac5e5542a773aa44fbcfedf7c193bc2c599")
282                .unwrap()
283                .into(),
284            "WBTC",
285            8,
286            0,
287            &[Some(10_000)],
288            Chain::Ethereum,
289            100,
290        )
291    }
292
293    fn usdc() -> Token {
294        Token::new(
295            &hex::decode("a0b86991c6218a76c1d19d4a2e9eb0ce3606eb48")
296                .unwrap()
297                .into(),
298            "USDC",
299            6,
300            0,
301            &[Some(10_000)],
302            Chain::Ethereum,
303            100,
304        )
305    }
306
307    fn weth() -> Token {
308        Token::new(
309            &Bytes::from_str("0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2").unwrap(),
310            "WETH",
311            18,
312            0,
313            &[],
314            Default::default(),
315            100,
316        )
317    }
318
319    fn empty_client() -> Arc<HashflowClient> {
320        Arc::new(HashflowClient::new(
321            None,
322            1,
323            String::new(),
324            String::new(),
325            Duration::from_secs(30),
326        ))
327    }
328
329    fn create_test_hashflow_state() -> HashflowState {
330        HashflowState {
331            base_token: weth(),
332            quote_token: usdc(),
333            levels: HashflowMarketMakerLevels {
334                pair: HashflowPair {
335                    base_token: Bytes::from_str("0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2")
336                        .unwrap(),
337                    quote_token: Bytes::from_str("0xa0b86991c6218a76c1d19d4a2e9eb0ce3606eb48")
338                        .unwrap(),
339                },
340                levels: Levels::new(vec![
341                    PriceLevel { quantity: 0.5, price: 3000.0 },
342                    PriceLevel { quantity: 1.5, price: 3000.0 },
343                    PriceLevel { quantity: 5.0, price: 2999.0 },
344                ])
345                .unwrap(),
346            },
347            market_maker: "test_mm".to_string(),
348            client: Some(empty_client()),
349        }
350    }
351
352    /// After some input went in, the next unit is priced at the level where the fill stopped,
353    /// and a reverse swap is rejected like a token outside the pair.
354    #[rstest]
355    #[case::in_the_first_level(250_000_000_000_000_000, Some(3000.0))]
356    #[case::on_the_second_boundary(2_000_000_000_000_000_000, Some(2999.0))]
357    #[case::past_the_depth(7_000_000_000_000_000_000, None)]
358    fn the_price_after_a_fill_is_the_level_where_it_stopped(
359        #[case] filled: u64,
360        #[case] expected: Option<f64>,
361    ) {
362        let state = create_test_hashflow_state();
363
364        let price = state.marginal_price(&weth().address, &usdc().address, &BigUint::from(filled));
365        let reverse =
366            state.marginal_price(&usdc().address, &weth().address, &BigUint::from(filled));
367
368        match (price, expected) {
369            (Ok(price), Some(expected)) => assert_eq!(price, expected),
370            (Err(SimulationError::RecoverableError(message)), None) => {
371                assert_eq!(message, "No liquidity")
372            }
373            (price, _) => panic!("expected {expected:?}, got {price:?}"),
374        }
375        assert!(matches!(reverse, Err(SimulationError::InvalidInput(_, None))), "{reverse:?}");
376    }
377
378    /// The venue's minimum is checked against the whole merged swap: a chunk below it is refused
379    /// alone and accepted as the continuation of a swap that already reached it.
380    #[test]
381    fn the_minimum_applies_to_the_merged_amount() {
382        let book = VenueBook {
383            signer: MarketMaker("test_mm".to_string()),
384            updated_at: None,
385            state: create_test_hashflow_state(),
386        };
387        let venue = HashflowAllPairsState::from(AllPairs::new(vec![book], QuoteRule::OncePerMaker));
388        let minimum = venue.0.books()[0].state.min_amount_in();
389        let chunk = minimum.clone() / 5u8;
390
391        let alone = venue.get_amount_out(chunk.clone(), &weth(), &usdc());
392        let first = venue
393            .get_amount_out(minimum, &weth(), &usdc())
394            .unwrap();
395        let continued = first
396            .new_state
397            .get_amount_out(chunk, &weth(), &usdc());
398
399        assert!(
400            matches!(alone, Err(SimulationError::RecoverableError(_))),
401            "a chunk below the minimum is refused on its own: {alone:?}"
402        );
403        assert!(continued.is_ok(), "{continued:?}");
404    }
405
406    /// A book of one level advertises that level as both its minimum and its depth, so the
407    /// amount named by the minimum has to be one the same book can fill.
408    ///
409    /// How much of a unit the rounding adds is what decides whether `fill` notices. Here, four
410    /// thousand tokens of a six-decimal one, it adds 0.07 of a unit, which is 80 000 ulps of the
411    /// amount against the four a fill forgives. The same rounding on an eighteen-decimal token
412    /// adds a wei, a millionth of one ulp, and disappears.
413    #[test]
414    fn the_minimum_of_a_single_level_book_is_within_its_depth() {
415        let state = HashflowState {
416            base_token: usdc(),
417            quote_token: weth(),
418            levels: HashflowMarketMakerLevels {
419                pair: HashflowPair { base_token: usdc().address, quote_token: weth().address },
420                levels: Levels::new(vec![PriceLevel {
421                    quantity: 4327.8578109263835,
422                    price: 0.000_25,
423                }])
424                .unwrap(),
425            },
426            market_maker: "test_mm".to_string(),
427            client: Some(empty_client()),
428        };
429
430        let minimum = state.min_amount_in();
431        let (limit, _) = state
432            .get_limits(usdc().address, weth().address)
433            .unwrap();
434
435        assert!(minimum <= limit, "minimum {minimum} is past the book's own limit {limit}");
436        let result = state.get_amount_out(minimum, &usdc(), &weth());
437        assert!(result.is_ok(), "{result:?}");
438    }
439
440    /// `min_amount_in` is documented as the amount a caller sizes its request at, so quoting
441    /// exactly that amount has to work. It is the first level's quantity scaled into base
442    /// units, and for roughly 5% of 18-decimal quantities scaling it back down lands an ulp
443    /// short: 31374.751353434924 WETH comes back as 31374.75135343492.
444    #[test]
445    fn the_advertised_minimum_is_quotable() {
446        let mut state = create_test_hashflow_state();
447        state.levels.levels =
448            Levels::new(vec![PriceLevel { quantity: 31374.751353434924, price: 3000.0 }]).unwrap();
449
450        let result = state.get_amount_out(state.min_amount_in(), &weth(), &usdc());
451
452        assert!(result.is_ok(), "{result:?}");
453    }
454
455    #[test]
456    fn rejects_tokens_outside_the_pair_and_the_reverse_direction() {
457        // Hashflow's levels price one direction only and cannot be inverted, so the reverse
458        // pair is as foreign to the state as a token outside it.
459        let state = create_test_hashflow_state();
460        let amount = BigUint::from_str("1000000000000000000").unwrap();
461        let results = [
462            state
463                .spot_price(&wbtc(), &usdc())
464                .map(|_| ()),
465            state
466                .get_amount_out(amount.clone(), &usdc(), &weth())
467                .map(|_| ()),
468            state
469                .get_amount_out(amount, &wbtc(), &usdc())
470                .map(|_| ()),
471            state
472                .get_limits(wbtc().address.clone(), usdc().address.clone())
473                .map(|_| ()),
474        ];
475
476        for result in results {
477            assert!(
478                matches!(&result, Err(SimulationError::InvalidInput(msg, None)) if msg.contains("Invalid token addresses")),
479                "{result:?}"
480            );
481        }
482    }
483
484    #[test]
485    /// A maker quoting nothing has no price and no swap to offer, and no depth to report.
486    fn an_empty_ladder_has_nothing_to_offer() {
487        let mut state = create_test_hashflow_state();
488        state.levels.levels = Levels::default();
489        let price = state.spot_price(&weth(), &usdc());
490        assert!(
491            matches!(&price, Err(SimulationError::RecoverableError(msg)) if msg == "No liquidity"),
492            "{price:?}"
493        );
494        let swap = state.get_amount_out(
495            BigUint::from_str("1000000000000000000").unwrap(),
496            &weth(),
497            &usdc(),
498        );
499        assert!(matches!(swap, Err(SimulationError::InvalidInput(_, None))), "{swap:?}");
500        assert!(matches!(
501            state.get_limits(weth().address.clone(), usdc().address.clone()),
502            Err(SimulationError::RecoverableError(_))
503        ));
504    }
505
506    #[test]
507    fn spot_price_is_the_first_level() {
508        let state = create_test_hashflow_state();
509        let price = state
510            .spot_price(&state.base_token, &state.quote_token)
511            .unwrap();
512        assert_eq!(price, 3000.0);
513    }
514
515    mod get_amount_out {
516        use super::*;
517
518        #[test]
519        fn wbtc_to_usdc() {
520            let state = create_test_hashflow_state();
521
522            // Test swapping 1.5 WETH -> USDC
523            // Should consume first level (0.5 WETH at 3000) + partial second level (1.0 WETH at
524            // 3000)
525            let amount_out_result = state
526                .get_amount_out(
527                    BigUint::from_str("1500000000000000000").unwrap(), // 1.5 WETH (18 decimals)
528                    &weth(),
529                    &usdc(),
530                )
531                .unwrap();
532
533            // Expected: (0.5 * 3000) + (1.0 * 3000) = 1500 + 3000 = 4500 USDC
534            assert_eq!(amount_out_result.amount, BigUint::from_str("4500000000").unwrap()); // 6 decimals
535            assert_eq!(amount_out_result.gas, BigUint::from(151_000u64));
536        }
537
538        #[test]
539        fn below_minimum() {
540            let state = create_test_hashflow_state();
541
542            // Test with amount below minimum (first level quantity is 0.5 WETH)
543            let result = state.get_amount_out(
544                BigUint::from_str("250000000000000000").unwrap(), // 0.25 WETH (18 decimals)
545                &weth(),
546                &usdc(),
547            );
548
549            assert!(result.is_err());
550            if let Err(SimulationError::RecoverableError(msg)) = result {
551                assert!(msg.contains("Amount below minimum"));
552            } else {
553                panic!("Expected RecoverableError");
554            }
555        }
556
557        #[test]
558        fn insufficient_liquidity() {
559            let state = create_test_hashflow_state();
560
561            // Test with amount exceeding total liquidity (total is 7.0 WETH)
562            let result = state.get_amount_out(
563                BigUint::from_str("8000000000000000000").unwrap(), // 8.0 WETH (18 decimals)
564                &weth(),
565                &usdc(),
566            );
567
568            assert!(result.is_err());
569            if let Err(SimulationError::InvalidInput(msg, _)) = result {
570                assert!(msg.contains("Pool has not enough liquidity"));
571            } else {
572                panic!("Expected InvalidInput");
573            }
574        }
575    }
576
577    #[test]
578    fn limits_are_the_ladder_totals() {
579        let state = create_test_hashflow_state();
580        let (sell_limit, buy_limit) = state
581            .get_limits(state.base_token.address.clone(), state.quote_token.address.clone())
582            .unwrap();
583
584        // Total sell: 0.5 + 1.5 + 5.0 = 7.0 WETH (18 decimals)
585        // Total buy: (0.5+1.5)*3000 + 5.0*2999 = 20995 USDC (6 decimals)
586        assert_eq!(sell_limit, BigUint::from((7.0 * 10f64.powi(18)) as u128));
587        assert_eq!(buy_limit, BigUint::from((20995.0 * 10f64.powi(6)) as u128));
588    }
589
590    /// The venue refuses a swap of nothing, so simulating one must not report a fill.
591    #[test]
592    fn rejects_a_zero_amount() {
593        let state = create_test_hashflow_state();
594
595        let result = state.get_amount_out(BigUint::ZERO, &weth(), &usdc());
596
597        assert!(matches!(result, Err(SimulationError::InvalidInput(_, None))), "{result:?}");
598    }
599}