tycho_client/
stream.rs

1use std::{
2    cmp::max,
3    collections::{HashMap, HashSet},
4    env,
5    time::Duration,
6};
7
8use thiserror::Error;
9use tokio::{sync::mpsc::Receiver, task::JoinHandle};
10use tracing::{info, warn};
11use tycho_common::dto::{Chain, ExtractorIdentity, PaginationParams, ProtocolSystemsRequestBody};
12
13use crate::{
14    deltas::DeltasClient,
15    feed::{
16        component_tracker::ComponentFilter, synchronizer::ProtocolStateSynchronizer, BlockHeader,
17        BlockSynchronizer, BlockSynchronizerError, FeedMessage,
18    },
19    rpc::RPCClient,
20    HttpRPCClient, WsDeltasClient,
21};
22
23#[derive(Error, Debug)]
24pub enum StreamError {
25    #[error("Error during stream set up: {0}")]
26    SetUpError(String),
27
28    #[error("WebSocket client connection error: {0}")]
29    WebSocketConnectionError(String),
30
31    #[error("BlockSynchronizer error: {0}")]
32    BlockSynchronizerError(String),
33}
34
35#[non_exhaustive]
36#[derive(Clone, Debug)]
37pub enum RetryConfiguration {
38    Constant(ConstantRetryConfiguration),
39}
40
41impl RetryConfiguration {
42    pub fn constant(max_attempts: u64, cooldown: Duration) -> Self {
43        RetryConfiguration::Constant(ConstantRetryConfiguration { max_attempts, cooldown })
44    }
45}
46
47#[derive(Clone, Debug)]
48pub struct ConstantRetryConfiguration {
49    max_attempts: u64,
50    cooldown: Duration,
51}
52
53pub struct TychoStreamBuilder {
54    tycho_url: String,
55    chain: Chain,
56    exchanges: HashMap<String, ComponentFilter>,
57    block_time: u64,
58    timeout: u64,
59    startup_timeout: Duration,
60    max_missed_blocks: u64,
61    state_sync_retry_config: RetryConfiguration,
62    websockets_retry_config: RetryConfiguration,
63    no_state: bool,
64    auth_key: Option<String>,
65    no_tls: bool,
66    include_tvl: bool,
67}
68
69impl TychoStreamBuilder {
70    /// Creates a new `TychoStreamBuilder` with the given Tycho URL and blockchain network.
71    /// Initializes the builder with default values for block time and timeout based on the chain.
72    pub fn new(tycho_url: &str, chain: Chain) -> Self {
73        let (block_time, timeout, max_missed_blocks) = Self::default_timing(&chain);
74        Self {
75            tycho_url: tycho_url.to_string(),
76            chain,
77            exchanges: HashMap::new(),
78            block_time,
79            timeout,
80            startup_timeout: Duration::from_secs(block_time * max_missed_blocks),
81            max_missed_blocks,
82            state_sync_retry_config: RetryConfiguration::constant(
83                32,
84                Duration::from_secs(max(block_time / 4, 2)),
85            ),
86            websockets_retry_config: RetryConfiguration::constant(
87                128,
88                Duration::from_secs(max(block_time / 6, 1)),
89            ),
90            no_state: false,
91            auth_key: None,
92            no_tls: true,
93            include_tvl: false,
94        }
95    }
96
97    /// Returns the default block_time, timeout and max_missed_blocks values for the given
98    /// blockchain network.
99    fn default_timing(chain: &Chain) -> (u64, u64, u64) {
100        match chain {
101            Chain::Ethereum => (12, 36, 50),
102            Chain::Starknet => (2, 8, 50),
103            Chain::ZkSync => (3, 12, 50),
104            Chain::Arbitrum => (1, 2, 100), // Typically closer to 0.25s
105            Chain::Base => (2, 12, 50),
106            Chain::Unichain => (1, 10, 100),
107        }
108    }
109
110    /// Adds an exchange and its corresponding filter to the Tycho client.
111    pub fn exchange(mut self, name: &str, filter: ComponentFilter) -> Self {
112        self.exchanges
113            .insert(name.to_string(), filter);
114        self
115    }
116
117    /// Sets the block time for the Tycho client.
118    pub fn block_time(mut self, block_time: u64) -> Self {
119        self.block_time = block_time;
120        self
121    }
122
123    /// Sets the timeout duration for network operations.
124    pub fn timeout(mut self, timeout: u64) -> Self {
125        self.timeout = timeout;
126        self
127    }
128
129    pub fn startup_timeout(mut self, timeout: Duration) -> Self {
130        self.startup_timeout = timeout;
131        self
132    }
133
134    pub fn max_missed_blocks(mut self, max_missed_blocks: u64) -> Self {
135        self.max_missed_blocks = max_missed_blocks;
136        self
137    }
138
139    pub fn websockets_retry_config(mut self, retry_config: &RetryConfiguration) -> Self {
140        self.websockets_retry_config = retry_config.clone();
141        self.warn_on_potential_timing_issues();
142        self
143    }
144
145    pub fn state_synchronizer_retry_config(mut self, retry_config: &RetryConfiguration) -> Self {
146        self.state_sync_retry_config = retry_config.clone();
147        self.warn_on_potential_timing_issues();
148        self
149    }
150
151    fn warn_on_potential_timing_issues(&self) {
152        let (RetryConfiguration::Constant(state_config), RetryConfiguration::Constant(ws_config)) =
153            (&self.state_sync_retry_config, &self.websockets_retry_config);
154
155        if ws_config.cooldown >= state_config.cooldown {
156            warn!(
157                "Websocket cooldown should be < than state syncronizer cooldown \
158                to avoid spending retries due to disconnected websocket."
159            )
160        }
161    }
162
163    /// Configures the client to exclude state updates from the stream.
164    pub fn no_state(mut self, no_state: bool) -> Self {
165        self.no_state = no_state;
166        self
167    }
168
169    /// Sets the API key for authenticating with the Tycho server.
170    ///
171    /// Optionally you can set the TYCHO_AUTH_TOKEN env var instead. Make sure to set no_tsl
172    /// to false if you do this.
173    pub fn auth_key(mut self, auth_key: Option<String>) -> Self {
174        self.auth_key = auth_key;
175        self.no_tls = false;
176        self
177    }
178
179    /// Disables TLS/SSL for the connection, using `http` and `ws` protocols.
180    pub fn no_tls(mut self, no_tls: bool) -> Self {
181        self.no_tls = no_tls;
182        self
183    }
184
185    /// Configures the client to include TVL in the stream.
186    ///
187    /// If set to true, this will increase start-up time due to additional requests.
188    pub fn include_tvl(mut self, include_tvl: bool) -> Self {
189        self.include_tvl = include_tvl;
190        self
191    }
192
193    /// Builds and starts the Tycho client, connecting to the Tycho server and
194    /// setting up the synchronization of exchange components.
195    pub async fn build(
196        self,
197    ) -> Result<
198        (JoinHandle<()>, Receiver<Result<FeedMessage<BlockHeader>, BlockSynchronizerError>>),
199        StreamError,
200    > {
201        if self.exchanges.is_empty() {
202            return Err(StreamError::SetUpError(
203                "At least one exchange must be registered.".to_string(),
204            ));
205        }
206
207        // Attempt to read the authentication key from the environment variable if not provided
208        let auth_key = self
209            .auth_key
210            .clone()
211            .or_else(|| env::var("TYCHO_AUTH_TOKEN").ok());
212
213        info!("Running with version: {}", option_env!("CARGO_PKG_VERSION").unwrap_or("unknown"));
214
215        // Determine the URLs based on the TLS setting
216        let (tycho_ws_url, tycho_rpc_url) = if self.no_tls {
217            info!("Using non-secure connection: ws:// and http://");
218            let tycho_ws_url = format!("ws://{}", self.tycho_url);
219            let tycho_rpc_url = format!("http://{}", self.tycho_url);
220            (tycho_ws_url, tycho_rpc_url)
221        } else {
222            info!("Using secure connection: wss:// and https://");
223            let tycho_ws_url = format!("wss://{}", self.tycho_url);
224            let tycho_rpc_url = format!("https://{}", self.tycho_url);
225            (tycho_ws_url, tycho_rpc_url)
226        };
227
228        // Initialize the WebSocket client
229        #[allow(unreachable_patterns)]
230        let ws_client = match &self.websockets_retry_config {
231            RetryConfiguration::Constant(config) => WsDeltasClient::new_with_reconnects(
232                &tycho_ws_url,
233                auth_key.as_deref(),
234                config.max_attempts,
235                config.cooldown,
236            ),
237            _ => {
238                return Err(StreamError::SetUpError(
239                    "Unknown websocket configuration variant!".to_string(),
240                ));
241            }
242        }
243        .map_err(|e| StreamError::SetUpError(e.to_string()))?;
244        let rpc_client = HttpRPCClient::new(&tycho_rpc_url, auth_key.as_deref())
245            .map_err(|e| StreamError::SetUpError(e.to_string()))?;
246        let ws_jh = ws_client
247            .connect()
248            .await
249            .map_err(|e| StreamError::WebSocketConnectionError(e.to_string()))?;
250
251        // Create and configure the BlockSynchronizer
252        let mut block_sync = BlockSynchronizer::new(
253            Duration::from_secs(self.block_time),
254            Duration::from_secs(self.timeout),
255            self.max_missed_blocks,
256        );
257
258        self.display_available_protocols(&rpc_client)
259            .await;
260
261        // Register each exchange with the BlockSynchronizer
262        for (name, filter) in self.exchanges {
263            info!("Registering exchange: {}", name);
264            let id = ExtractorIdentity { chain: self.chain, name: name.clone() };
265            #[allow(unreachable_patterns)]
266            let sync = match &self.state_sync_retry_config {
267                RetryConfiguration::Constant(retry_config) => ProtocolStateSynchronizer::new(
268                    id.clone(),
269                    true,
270                    filter,
271                    retry_config.max_attempts,
272                    retry_config.cooldown,
273                    !self.no_state,
274                    self.include_tvl,
275                    rpc_client.clone(),
276                    ws_client.clone(),
277                    self.block_time + self.timeout,
278                ),
279                _ => {
280                    return Err(StreamError::SetUpError(
281                        "Unknown state synchronizer configuration variant!".to_string(),
282                    ));
283                }
284            };
285            block_sync = block_sync.register_synchronizer(id, sync);
286        }
287
288        // Start the BlockSynchronizer and monitor for disconnections
289        let (sync_jh, rx) = block_sync
290            .run()
291            .await
292            .map_err(|e| StreamError::BlockSynchronizerError(e.to_string()))?;
293
294        // Monitor WebSocket and BlockSynchronizer futures
295        let handle = tokio::spawn(async move {
296            tokio::select! {
297                res = ws_jh => {
298                    let _ = res.map_err(|e| StreamError::WebSocketConnectionError(e.to_string()));
299                }
300                res = sync_jh => {
301                    res.map_err(|e| StreamError::BlockSynchronizerError(e.to_string())).unwrap();
302                }
303            }
304            if let Err(e) = ws_client.close().await {
305                warn!(?e, "Failed to close WebSocket client");
306            }
307        });
308
309        Ok((handle, rx))
310    }
311
312    /// Displays the other available protocols not registered to within this stream builder, for the
313    /// given chain.
314    async fn display_available_protocols(&self, rpc_client: &HttpRPCClient) {
315        let available_protocols_set = rpc_client
316            .get_protocol_systems(&ProtocolSystemsRequestBody {
317                chain: self.chain,
318                pagination: PaginationParams { page: 0, page_size: 100 },
319            })
320            .await
321            .map(|resp| {
322                resp.protocol_systems
323                    .into_iter()
324                    .collect::<HashSet<_>>()
325            })
326            .map_err(|e| {
327                warn!(
328                    "Failed to fetch protocol systems: {e}. Skipping protocol availability check."
329                );
330                e
331            })
332            .ok();
333
334        if let Some(not_requested_protocols) = available_protocols_set
335            .map(|available_protocols_set| {
336                let requested_protocol_set = self
337                    .exchanges
338                    .keys()
339                    .cloned()
340                    .collect::<HashSet<_>>();
341
342                available_protocols_set
343                    .difference(&requested_protocol_set)
344                    .cloned()
345                    .collect::<Vec<_>>()
346            })
347            .filter(|not_requested_protocols| !not_requested_protocols.is_empty())
348        {
349            info!("Other available protocols: {}", not_requested_protocols.join(", "))
350        }
351    }
352}
353
354#[cfg(test)]
355mod tests {
356    use super::*;
357
358    #[test]
359    fn test_retry_configuration_constant() {
360        let config = RetryConfiguration::constant(5, Duration::from_secs(10));
361        match config {
362            RetryConfiguration::Constant(c) => {
363                assert_eq!(c.max_attempts, 5);
364                assert_eq!(c.cooldown, Duration::from_secs(10));
365            }
366        }
367    }
368
369    #[test]
370    fn test_stream_builder_retry_configs() {
371        let mut builder = TychoStreamBuilder::new("localhost:4242", Chain::Ethereum);
372        let ws_config = RetryConfiguration::constant(10, Duration::from_secs(2));
373        let state_config = RetryConfiguration::constant(20, Duration::from_secs(5));
374
375        builder = builder
376            .websockets_retry_config(&ws_config)
377            .state_synchronizer_retry_config(&state_config);
378
379        // Verify configs are stored correctly by checking they match expected values
380        match (&builder.websockets_retry_config, &builder.state_sync_retry_config) {
381            (RetryConfiguration::Constant(ws), RetryConfiguration::Constant(state)) => {
382                assert_eq!(ws.max_attempts, 10);
383                assert_eq!(ws.cooldown, Duration::from_secs(2));
384                assert_eq!(state.max_attempts, 20);
385                assert_eq!(state.cooldown, Duration::from_secs(5));
386            }
387        }
388    }
389
390    #[tokio::test]
391    async fn test_no_exchanges() {
392        let receiver = TychoStreamBuilder::new("localhost:4242", Chain::Ethereum)
393            .auth_key(Some("my_api_key".into()))
394            .build()
395            .await;
396        assert!(receiver.is_err(), "Client should fail to build when no exchanges are registered.");
397    }
398
399    #[ignore = "require tycho gateway"]
400    #[tokio::test]
401    async fn teat_simple_build() {
402        let token = env::var("TYCHO_AUTH_TOKEN").unwrap();
403        let receiver = TychoStreamBuilder::new("tycho-beta.propellerheads.xyz", Chain::Ethereum)
404            .exchange("uniswap_v2", ComponentFilter::with_tvl_range(100.0, 100.0))
405            .auth_key(Some(token))
406            .build()
407            .await;
408
409        dbg!(&receiver);
410
411        assert!(receiver.is_ok(), "Client should build successfully with exchanges registered.");
412    }
413}