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