tycho_simulation/rfq/protocols/hashflow/
all_pairs_decoder.rs1use std::collections::HashMap;
2
3use tycho_client::feed::synchronizer::ComponentWithState;
4use tycho_common::{models::token::Token, Bytes};
5
6use super::{all_pairs_state::HashflowAllPairsState, client_builder::HashflowClientBuilder};
7use crate::{
8 protocol::{
9 errors::InvalidSnapshotError,
10 models::{DecoderContext, TryFromWithBlock},
11 },
12 rfq::{
13 constants::get_hashflow_auth,
14 models::{ComponentLayout, TimestampHeader},
15 protocols::{
16 component::{decode_all_pairs_component, DecodedAllPairs},
17 maker_price_levels::MakerPriceLevels,
18 },
19 },
20};
21
22impl TryFromWithBlock<ComponentWithState, TimestampHeader> for HashflowAllPairsState {
23 type Error = InvalidSnapshotError;
24
25 async fn try_from_with_header(
26 snapshot: ComponentWithState,
27 _timestamp_header: TimestampHeader,
28 _account_balances: &HashMap<Bytes, HashMap<Bytes, Bytes>>,
29 all_tokens: &HashMap<Bytes, Token>,
30 _decoder_context: &DecoderContext,
31 ) -> Result<Self, Self::Error> {
32 let DecodedAllPairs { books: price_levels, tokens, quote_rule } =
33 decode_all_pairs_component::<MakerPriceLevels>(&snapshot, all_tokens)?;
34
35 let auth = get_hashflow_auth().map_err(|e| {
36 InvalidSnapshotError::ValueError(format!("Failed to get Hashflow authentication: {e}"))
37 })?;
38 let mut builder = HashflowClientBuilder::new(snapshot.component.chain, auth.user, auth.key)
39 .tokens(tokens.keys().cloned().collect())
40 .component_layout(ComponentLayout::AllPairs);
41 if let Some(quote_rule) = quote_rule {
42 builder = builder.quote_rule(quote_rule);
43 }
44 let client = builder.build().map_err(|e| {
45 InvalidSnapshotError::ValueError(format!("Couldn't create HashflowClient: {e}"))
46 })?;
47
48 Ok(HashflowAllPairsState::new(price_levels, tokens, client))
49 }
50}
51
52#[cfg(test)]
53mod tests {
54 use std::env;
55
56 use num_bigint::BigUint;
57 use tycho_common::simulation::{errors::SimulationError, protocol_sim::ProtocolSim};
58
59 use super::*;
60 use crate::rfq::{
61 models::QuoteRule,
62 protocols::test_utils::{all_pairs_snapshot, decode, usdc, wbtc, weth},
63 };
64
65 #[tokio::test]
66 async fn test_decodes_price_levels() {
67 env::set_var("HASHFLOW_USER", "test_user");
69 env::set_var("HASHFLOW_KEY", "test_key");
70 let price_levels = serde_json::json!([
71 {
72 "mm": "test_market_maker",
73 "base_token": wbtc().address, "quote_token": usdc().address,
74 "levels": [{ "q": "1.5", "p": "65000.0" }, { "q": "2.0", "p": "64950.0" }]
75 },
76 {
77 "mm": "mm_b",
78 "base_token": wbtc().address, "quote_token": usdc().address,
79 "levels": [{ "q": "0.5", "p": "65100.0" }]
80 },
81 {
82 "mm": "test_market_maker",
83 "base_token": weth().address, "quote_token": usdc().address,
84 "levels": [{ "q": "10", "p": "3000.0" }]
85 }
86 ]);
87 let (snapshot, tokens) =
88 all_pairs_snapshot("rfq:hashflow", &[wbtc(), usdc(), weth()], &price_levels);
89 let state = decode::<HashflowAllPairsState>(snapshot, &tokens)
90 .await
91 .unwrap();
92
93 let wbtc_price_levels = state
94 .price_levels
95 .pair_price_levels(&wbtc().address, &usdc().address);
96 assert_eq!(wbtc_price_levels.len(), 2);
97 assert_eq!(wbtc_price_levels[0].market_maker, "mm_b");
98 assert_eq!(wbtc_price_levels[1].levels[0].quantity, 1.5);
99 assert_eq!(wbtc_price_levels[1].levels[0].price, 65000.0);
100 assert_eq!(
101 state
102 .price_levels
103 .pair_price_levels(&weth().address, &usdc().address)
104 .len(),
105 1
106 );
107 }
108
109 #[tokio::test]
112 async fn test_decodes_once_per_venue_attribute() {
113 env::set_var("HASHFLOW_USER", "test_user");
114 env::set_var("HASHFLOW_KEY", "test_key");
115 let price_levels = serde_json::json!([
116 {
117 "mm": "mm_b",
118 "base_token": wbtc().address, "quote_token": usdc().address,
119 "levels": [{ "q": "0.5", "p": "65100.0" }]
120 },
121 {
122 "mm": "test_market_maker",
123 "base_token": weth().address, "quote_token": usdc().address,
124 "levels": [{ "q": "10", "p": "3000.0" }]
125 }
126 ]);
127 let (mut snapshot, tokens) =
128 all_pairs_snapshot("rfq:hashflow", &[wbtc(), usdc(), weth()], &price_levels);
129 snapshot
130 .component
131 .static_attributes
132 .insert(
133 QuoteRule::ATTRIBUTE.to_string(),
134 QuoteRule::OncePerVenue
135 .as_str()
136 .as_bytes()
137 .into(),
138 );
139
140 let state = decode::<HashflowAllPairsState>(snapshot, &tokens)
141 .await
142 .unwrap();
143 let after_swap = state
144 .get_amount_out(BigUint::from(50_000_000u64), &wbtc(), &usdc())
145 .unwrap()
146 .new_state;
147
148 let result = after_swap.get_amount_out(
149 BigUint::from(1_000_000_000_000_000_000u64),
150 &weth(),
151 &usdc(),
152 );
153 assert!(
154 matches!(result, Err(SimulationError::RecoverableError(message)) if message.contains("already quoted in this route"))
155 );
156 }
157}