Skip to main content

tycho_simulation/rfq/protocols/hashflow/
models.rs

1use std::{collections::HashMap, fmt};
2
3use serde::{Deserialize, Serialize};
4use serde_with::{serde_as, skip_serializing_none};
5use tycho_common::{models::protocol::GetAmountOutParams, Bytes};
6
7use crate::{
8    book::{levels::Levels, wire::SkipInvalidEntries},
9    rfq::errors::RFQError,
10    serde_helpers::evm_address,
11};
12
13/// The error Hashflow reports on a rejected request, sent as an object alongside HTTP 200.
14#[derive(Debug, Clone, Serialize, Deserialize)]
15pub struct HashflowError {
16    pub code: u64,
17    pub message: String,
18}
19
20/// The codes below are the ones Hashflow has been seen to answer with. The venue publishes no
21/// catalogue of them — the numbered vocabulary in its documentation belongs to the market-maker
22/// WebSocket API, not to the taker endpoints these reach — and one code covers several
23/// conditions, so what a code not listed here means is unknown, and telling two of them apart
24/// can need the message.
25impl HashflowError {
26    /// No maker quotes the request: the one it was addressed to declined it, or is unknown to
27    /// the API.
28    const NO_MAKER_SUPPORTS_REQUEST: u64 = 82;
29
30    /// The amount asked for is above what the maker quotes.
31    const EXCEEDS_SUPPORTED_AMOUNTS: u64 = 76;
32
33    /// The amount asked for is below the maker's first level.
34    const BELOW_MINIMUM_AMOUNT: u64 = 79;
35
36    /// Whether this is a maker declining the trade rather than the request being wrong: nobody
37    /// quotes it, or the amount is outside the range the maker it went to supports. All three are
38    /// answers about one trade at one moment, which the same ladder quotes at another size.
39    pub fn declines_the_trade(&self) -> bool {
40        matches!(
41            self.code,
42            Self::NO_MAKER_SUPPORTS_REQUEST |
43                Self::EXCEEDS_SUPPORTED_AMOUNTS |
44                Self::BELOW_MINIMUM_AMOUNT
45        )
46    }
47
48    /// Whether this is Hashflow stating it does not price the chain it was asked about.
49    ///
50    /// The code it answers here with covers an unknown market maker and an unknown chain type
51    /// too, so what it refused is in the message alone.
52    pub fn refuses_the_chain(&self) -> bool {
53        self.message
54            .starts_with("Invalid chainId")
55    }
56}
57
58/// The envelope Hashflow answers a request it would not serve with, on either book endpoint.
59/// A body it does serve carries no `error` at all, so parsing one is what tells the two apart.
60#[derive(Debug, Clone, Deserialize)]
61pub struct HashflowFailure {
62    pub error: HashflowError,
63}
64
65impl fmt::Display for HashflowError {
66    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
67        write!(f, "{} (code {})", self.message, self.code)
68    }
69}
70
71#[serde_as]
72#[derive(Debug, Clone, Serialize, Deserialize)]
73pub struct HashflowPriceLevelsResponse {
74    pub status: String, // "success" or "fail"
75    #[serde_as(deserialize_as = "Option<SkipInvalidEntries>")]
76    pub levels: Option<HashMap<String, Vec<HashflowMarketMakerLevels>>>,
77    pub error: Option<HashflowError>,
78}
79
80/// One market maker's price levels for a [`HashflowPair`]: the quantities of the base token it
81/// sells, each at a price in the quote token.
82#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
83pub struct HashflowMarketMakerLevels {
84    /// The pair the levels price.
85    pub pair: HashflowPair,
86    /// Base token quantities, each at a price in quote token per base token.
87    #[serde(with = "hashflow_levels")]
88    pub levels: Levels,
89}
90
91/// Hashflow's wire form of a ladder: `{"q": "<quantity>", "p": "<price>"}` objects with decimal
92/// strings.
93mod hashflow_levels {
94    use serde::{Deserialize, Deserializer, Serialize, Serializer};
95    use serde_with::{serde_as, DisplayFromStr};
96
97    use crate::book::levels::{Levels, PriceLevel};
98
99    #[serde_as]
100    #[derive(Serialize, Deserialize)]
101    struct WireLevel {
102        #[serde_as(as = "DisplayFromStr")]
103        q: f64,
104        #[serde_as(as = "DisplayFromStr")]
105        p: f64,
106    }
107
108    pub fn serialize<S: Serializer>(levels: &Levels, serializer: S) -> Result<S::Ok, S::Error> {
109        levels
110            .iter()
111            .map(|level| WireLevel { q: level.quantity, p: level.price })
112            .collect::<Vec<_>>()
113            .serialize(serializer)
114    }
115
116    pub fn deserialize<'de, D: Deserializer<'de>>(deserializer: D) -> Result<Levels, D::Error> {
117        let levels = Vec::<WireLevel>::deserialize(deserializer)?
118            .into_iter()
119            .map(|level| PriceLevel { price: level.p, quantity: level.q })
120            .collect();
121        Levels::new(levels).map_err(serde::de::Error::custom)
122    }
123}
124
125/// The token a market maker sells and the token it prices it in.
126#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
127#[serde(rename_all = "camelCase")]
128pub struct HashflowPair {
129    /// The token the maker sells.
130    #[serde(deserialize_with = "evm_address::deserialize")]
131    pub base_token: Bytes,
132    /// The token the maker prices it in.
133    #[serde(deserialize_with = "evm_address::deserialize")]
134    pub quote_token: Bytes,
135}
136
137#[derive(Debug, Clone, Serialize, Deserialize)]
138#[serde(rename_all = "camelCase")]
139pub struct HashflowMarketMakersResponse {
140    pub market_makers: Vec<String>,
141}
142
143#[derive(Debug, Clone, Serialize, Deserialize)]
144#[serde(rename_all = "camelCase")]
145pub struct HashflowQuoteRequest {
146    pub source: String,
147    pub base_chain: HashflowChain,
148    pub quote_chain: HashflowChain,
149    pub rfqs: Vec<HashflowRFQ>,
150    pub calldata: bool,
151}
152
153#[derive(Debug, Clone, Serialize, Deserialize)]
154#[serde(rename_all = "camelCase")]
155pub struct HashflowChain {
156    chain_type: String,
157    chain_id: u64,
158}
159
160impl HashflowChain {
161    /// The chain as Hashflow's quote requests name it: an EVM chain id.
162    pub fn evm(chain_id: u64) -> Self {
163        HashflowChain { chain_type: "evm".to_string(), chain_id }
164    }
165}
166
167/// Optional fields are left out of the request rather than sent as `null`.
168#[skip_serializing_none]
169#[derive(Debug, Clone, Serialize, Deserialize)]
170#[serde(rename_all = "camelCase")]
171pub struct HashflowRFQ {
172    pub base_token: String,
173    pub quote_token: String,
174    // Decimal amount (e.g. "1000000" for 1 USDT)
175    pub base_token_amount: Option<String>,
176    // Decimal amount (e.g. "1000000" for 1 USDT)
177    pub quote_token_amount: Option<String>,
178    pub trader: String,
179    pub effective_trader: Option<String>,
180    /// The makers the RFQ goes to; a quote from any other is only possible as the API's
181    /// fallback, which `options` disables.
182    pub market_makers: Vec<String>,
183    pub options: HashflowRFQOptions,
184}
185
186#[derive(Debug, Clone, Serialize, Deserialize)]
187#[serde(rename_all = "camelCase")]
188pub struct HashflowRFQOptions {
189    /// Without it, the API answers a failed maker with the next best one. That maker's liquidity
190    /// is a component of its own, which the same route may already be filling, so its quote could
191    /// draw on the same depth twice, at a price the requesting state did not simulate.
192    pub do_not_retry_with_other_makers: bool,
193}
194
195#[derive(Debug, Clone, Serialize, Deserialize)]
196#[serde(rename_all = "camelCase")]
197pub struct HashflowQuoteResponse {
198    pub status: String,
199    pub error: Option<HashflowError>,
200    rfq_id: String,
201    internal_rfq_ids: Option<Vec<String>>,
202    pub quotes: Option<Vec<HashflowQuote>>,
203}
204
205#[derive(Debug, Clone, Serialize, Deserialize)]
206#[serde(rename_all = "camelCase")]
207pub struct HashflowQuote {
208    pub quote_data: HashflowQuoteData,
209    pub signature: Bytes,
210    pub target_contract: Option<Bytes>,
211    pub value: Option<String>,
212}
213
214impl HashflowQuote {
215    pub fn validate(
216        &self,
217        params: &GetAmountOutParams,
218        expected_effective_trader: &Bytes,
219    ) -> Result<(), RFQError> {
220        if self.quote_data.base_token != params.token_in {
221            return Err(RFQError::FatalError(format!(
222                "Base token mismatch: expected {}, got {}",
223                params.token_in, self.quote_data.base_token
224            )));
225        }
226        if self.quote_data.quote_token != params.token_out {
227            return Err(RFQError::FatalError(format!(
228                "Quote token mismatch: expected {}, got {}",
229                params.token_out, self.quote_data.quote_token
230            )));
231        }
232        if self.quote_data.trader != params.receiver {
233            return Err(RFQError::FatalError(format!(
234                "Trader address mismatch: expected {}, got {}",
235                params.receiver, self.quote_data.trader
236            )));
237        }
238        let effective_trader = self
239            .quote_data
240            .effective_trader
241            .clone()
242            .unwrap_or_else(|| self.quote_data.trader.clone());
243        if &effective_trader != expected_effective_trader {
244            return Err(RFQError::FatalError(format!(
245                "Effective trader mismatch: expected {expected_effective_trader}, got {effective_trader}"
246            )));
247        }
248        if self.quote_data.base_token_amount != params.amount_in.to_string() {
249            return Err(RFQError::FatalError(format!(
250                "Base token amount mismatch: expected {}, got {}",
251                params.amount_in, self.quote_data.base_token_amount
252            )));
253        }
254        Ok(())
255    }
256}
257
258#[derive(Debug, Clone, Serialize, Deserialize)]
259#[serde(rename_all = "camelCase")]
260pub struct HashflowQuoteData {
261    pub base_token: Bytes,
262    pub quote_token: Bytes,
263    // Decimal amount (e.g. "1000000" for 1 USDT)
264    pub base_token_amount: String,
265    // Decimal amount (e.g. "1000000" for 1 USDT)
266    pub quote_token_amount: String,
267    pub trader: Bytes,
268    pub effective_trader: Option<Bytes>,
269    #[serde(rename = "txid")]
270    pub tx_id: Bytes,
271    pub pool: Bytes,
272    pub quote_expiry: u64,
273    pub nonce: u64,
274    pub external_account: Option<Bytes>,
275}
276
277/// Every market maker's price levels as one Hashflow poll returned them, keyed by maker name.
278///
279/// The serde form follows the venue API models, so the writer and the reader must run the same
280/// tycho-simulation version.
281#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
282pub struct HashflowPrices {
283    /// Each maker's levels, one entry per pair the maker prices.
284    pub levels_by_maker: HashMap<String, Vec<HashflowMarketMakerLevels>>,
285}
286
287#[cfg(test)]
288mod tests {
289    use std::str::FromStr;
290
291    use super::*;
292    use crate::book::levels::PriceLevel;
293
294    /// A maker quoting a ladder Hashflow got wrong goes quiet for the poll; the makers that
295    /// priced their pairs correctly still publish.
296    #[test]
297    fn a_maker_with_a_malformed_ladder_does_not_cost_the_others() {
298        let json = r#"{"status":"success","levels":{
299                "mm1":[{"pair":{"baseToken":"0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2","quoteToken":"0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48"},"levels":[{"q":"1","p":"0"}]}],
300                "mm2":[{"pair":{"baseToken":"0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2","quoteToken":"0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48"},"levels":[{"q":"1","p":"3000"}]}]
301            }}"#;
302
303        let response: HashflowPriceLevelsResponse = serde_json::from_str(json).unwrap();
304
305        let levels = response.levels.unwrap();
306        assert!(levels["mm1"].is_empty());
307        assert_eq!(levels["mm2"].len(), 1);
308    }
309
310    /// Nothing readable in the response is a parsing failure, not an empty book: a published
311    /// snapshot is complete, so an empty one withdraws every pair the venue had.
312    #[test]
313    fn a_response_with_no_readable_maker_is_an_error() {
314        let json = r#"{"status":"success","levels":{"mm1":[{"pair":{"baseToken":"0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2","quoteToken":"0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48"},"levels":[{"q":"1","p":"0"}]}]}}"#;
315
316        assert!(serde_json::from_str::<HashflowPriceLevelsResponse>(json).is_err());
317    }
318
319    /// Hashflow answers a rejected RFQ with HTTP 200 and an `error` object, so the quote response
320    /// has to deserialize that shape rather than only the successful one.
321    #[test]
322    fn deserialize_rejected_quote_response() {
323        let body = r#"{"status":"fail","rfqId":"0x2250000000000000000000000000000f",
324            "error":{"code":82,"message":"No maker supports this request"}}"#;
325
326        let response: HashflowQuoteResponse = serde_json::from_str(body).unwrap();
327
328        assert_eq!(response.status, "fail");
329        assert_eq!(response.error.unwrap().to_string(), "No maker supports this request (code 82)");
330    }
331
332    #[test]
333    fn levels_round_trip_through_the_wire_form() {
334        let json = r#"{"pair":{"baseToken":"0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2","quoteToken":"0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48"},"levels":[{"q":"1","p":"3000"},{"q":"2.5","p":"2999"}]}"#;
335
336        let mm_levels: HashflowMarketMakerLevels = serde_json::from_str(json).unwrap();
337
338        assert_eq!(
339            &*mm_levels.levels,
340            &[
341                PriceLevel { quantity: 1.0, price: 3000.0 },
342                PriceLevel { quantity: 2.5, price: 2999.0 },
343            ]
344        );
345        assert_eq!(
346            mm_levels.pair.base_token,
347            Bytes::from_str("0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2").unwrap()
348        );
349        let json = serde_json::to_string(&mm_levels).unwrap();
350        assert!(json.contains(r#"{"q":"1","p":"3000"}"#), "{json}");
351
352        // The adapter hands the decoded levels to `Levels::new`, so its validation applies.
353        let invalid = json.replace(r#""p":"3000""#, r#""p":"0""#);
354        assert!(serde_json::from_str::<HashflowMarketMakerLevels>(&invalid).is_err());
355    }
356
357    #[cfg(test)]
358    mod hashflow_quote_validate_tests {
359        use num_bigint::BigUint;
360        use tycho_common::models::protocol::GetAmountOutParams;
361
362        use super::*;
363
364        fn hex_to_bytes(hex: &str) -> Bytes {
365            Bytes::from_str(hex).unwrap()
366        }
367
368        fn quote_data() -> HashflowQuoteData {
369            HashflowQuoteData {
370                base_token: hex_to_bytes("0x1111111111111111111111111111111111111111"),
371                quote_token: hex_to_bytes("0x2222222222222222222222222222222222222222"),
372                base_token_amount: "1000".to_string(),
373                quote_token_amount: "2000".to_string(),
374                trader: hex_to_bytes("0x3333333333333333333333333333333333333333"),
375                effective_trader: Some(hex_to_bytes("0x6666666666666666666666666666666666666666")),
376                tx_id: hex_to_bytes("0x4444444444444444444444444444444444444444"),
377                pool: hex_to_bytes("0x5555555555555555555555555555555555555555"),
378                quote_expiry: 123456,
379                nonce: 1,
380                external_account: None,
381            }
382        }
383
384        fn params() -> GetAmountOutParams {
385            GetAmountOutParams {
386                amount_in: BigUint::from(1000u32),
387                token_in: hex_to_bytes("0x1111111111111111111111111111111111111111"),
388                token_out: hex_to_bytes("0x2222222222222222222222222222222222222222"),
389                sender: hex_to_bytes("0x6666666666666666666666666666666666666666"),
390                receiver: hex_to_bytes("0x3333333333333333333333333333333333333333"),
391                origin: None,
392            }
393        }
394
395        fn expected_effective_trader() -> Bytes {
396            hex_to_bytes("0x6666666666666666666666666666666666666666")
397        }
398
399        fn quote() -> HashflowQuote {
400            HashflowQuote {
401                quote_data: quote_data(),
402                signature: hex_to_bytes("0x7777777777777777777777777777777777777777"),
403                target_contract: None,
404                value: None,
405            }
406        }
407
408        #[test]
409        fn validate_success() {
410            let quote = quote();
411            let params = params();
412            assert!(quote
413                .validate(&params, &expected_effective_trader())
414                .is_ok());
415        }
416
417        #[test]
418        fn validate_base_token_mismatch() {
419            let mut quote = quote();
420            quote.quote_data.base_token =
421                hex_to_bytes("0xdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef");
422            let params = params();
423            let err = quote
424                .validate(&params, &expected_effective_trader())
425                .unwrap_err();
426            assert!(format!("{err:?}").contains("Base token mismatch"));
427        }
428
429        #[test]
430        fn validate_quote_token_mismatch() {
431            let mut quote = quote();
432            quote.quote_data.quote_token =
433                hex_to_bytes("0xdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef");
434            let params = params();
435            let err = quote
436                .validate(&params, &expected_effective_trader())
437                .unwrap_err();
438            assert!(format!("{err:?}").contains("Quote token mismatch"));
439        }
440
441        #[test]
442        fn validate_trader_mismatch() {
443            let mut quote = quote();
444            quote.quote_data.trader = hex_to_bytes("0xabcdefabcdefabcdefabcdefabcdefabcdefabcd");
445            let params = params();
446            let err = quote
447                .validate(&params, &expected_effective_trader())
448                .unwrap_err();
449            assert!(format!("{err:?}").contains("Trader address mismatch"));
450        }
451
452        #[test]
453        fn validate_effective_trader_mismatch() {
454            let mut quote = quote();
455            quote.quote_data.effective_trader =
456                Some(hex_to_bytes("0xabcdefabcdefabcdefabcdefabcdefabcdefabcd"));
457            let params = params();
458            let err = quote
459                .validate(&params, &expected_effective_trader())
460                .unwrap_err();
461            assert!(format!("{err:?}").contains("Effective trader mismatch"));
462        }
463
464        #[test]
465        fn validate_effective_trader_absent() {
466            // An answer without an effectiveTrader is not tied to the address we requested
467            // (Hashflow ties it to the trader instead), so validation must reject it.
468            let mut quote = quote();
469            quote.quote_data.effective_trader = None;
470            let params = params();
471            let err = quote
472                .validate(&params, &expected_effective_trader())
473                .unwrap_err();
474            assert!(format!("{err:?}").contains("Effective trader mismatch"));
475        }
476
477        #[test]
478        fn validate_base_token_amount_mismatch() {
479            let mut quote = quote();
480            quote.quote_data.base_token_amount = "9999".to_string();
481            let params = params();
482            let err = quote
483                .validate(&params, &expected_effective_trader())
484                .unwrap_err();
485            assert!(format!("{err:?}").contains("Base token amount mismatch"));
486        }
487    }
488}