Skip to main content

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::{
12    dto::{PaginationLimits, ProtocolSystemsRequestBody},
13    models::{
14        chain_config::{init_chain_registry, ChainConfigRegistry},
15        Chain, ExtractorIdentity,
16    },
17};
18
19use crate::{
20    client_metadata::serialize_client_metadata,
21    deltas::DeltasClient,
22    feed::{
23        component_tracker::ComponentFilter, synchronizer::ProtocolStateSynchronizer, BlockHeader,
24        BlockSynchronizer, BlockSynchronizerError, FeedMessage,
25    },
26    rpc::{HttpRPCClientOptions, ProtocolSystemsParams, RPCClient},
27    HttpRPCClient, WsDeltasClient,
28};
29
30#[derive(Error, Debug)]
31pub enum StreamError {
32    #[error("Error during stream set up: {0}")]
33    SetUpError(String),
34
35    #[error("WebSocket client connection error: {0}")]
36    WebSocketConnectionError(String),
37
38    #[error("BlockSynchronizer error: {0}")]
39    BlockSynchronizerError(String),
40}
41
42#[non_exhaustive]
43#[derive(Clone, Debug)]
44pub enum RetryConfiguration {
45    Constant(ConstantRetryConfiguration),
46}
47
48impl RetryConfiguration {
49    pub fn constant(max_attempts: u64, cooldown: Duration) -> Self {
50        RetryConfiguration::Constant(ConstantRetryConfiguration { max_attempts, cooldown })
51    }
52}
53
54#[derive(Clone, Debug)]
55pub struct ConstantRetryConfiguration {
56    max_attempts: u64,
57    cooldown: Duration,
58}
59
60/// Loads and validates the custom-chain config once, before the stream starts. A missing or
61/// malformed `TYCHO_CHAINS_CONFIG` fails here with an actionable error, rather than degrading to
62/// an empty registry and resurfacing later as a confusing unknown-chain error mid-stream. An unset
63/// env var yields an empty registry (Ok), so built-in-only consumers are unaffected. The validated
64/// registry is best-effort installed as the process-wide one; a prior lazy access may already have
65/// initialised it, in which case the install is a no-op.
66fn validate_chain_config() -> Result<(), StreamError> {
67    let registry = ChainConfigRegistry::load_default()
68        .map_err(|e| StreamError::SetUpError(format!("failed to load custom chain config: {e}")))?;
69    let _ = init_chain_registry(registry);
70    Ok(())
71}
72
73pub struct TychoStreamBuilder {
74    tycho_url: String,
75    chain: Chain,
76    exchanges: HashMap<String, ComponentFilter>,
77    blocklisted_ids: HashSet<String>,
78    block_time: u64,
79    timeout: u64,
80    startup_timeout: Duration,
81    max_missed_blocks: u64,
82    state_sync_retry_config: RetryConfiguration,
83    websockets_retry_config: RetryConfiguration,
84    no_state: bool,
85    auth_key: Option<String>,
86    no_tls: bool,
87    include_tvl: bool,
88    compression: bool,
89    partial_blocks: bool,
90    max_messages: Option<usize>,
91    client_metadata: HashMap<String, String>,
92}
93
94impl TychoStreamBuilder {
95    /// Creates a new `TychoStreamBuilder` with the given Tycho URL and blockchain network.
96    /// Initializes the builder with default values for block time and timeout based on the chain.
97    pub fn new(tycho_url: &str, chain: Chain) -> Self {
98        let (block_time, timeout, max_missed_blocks) = Self::default_timing(&chain);
99        Self {
100            tycho_url: tycho_url.to_string(),
101            chain,
102            exchanges: HashMap::new(),
103            blocklisted_ids: HashSet::new(),
104            block_time,
105            timeout,
106            startup_timeout: Duration::from_secs(block_time * max_missed_blocks),
107            max_missed_blocks,
108            state_sync_retry_config: RetryConfiguration::constant(
109                32,
110                Duration::from_secs(max(block_time / 4, 2)),
111            ),
112            websockets_retry_config: RetryConfiguration::constant(
113                128,
114                Duration::from_secs(max(block_time / 6, 1)),
115            ),
116            no_state: false,
117            auth_key: None,
118            no_tls: true,
119            include_tvl: false,
120            compression: true,
121            partial_blocks: false,
122            max_messages: None,
123            client_metadata: HashMap::new(),
124        }
125    }
126
127    /// Returns the default block_time, timeout and max_missed_blocks values for the given
128    /// blockchain network.
129    fn default_timing(chain: &Chain) -> (u64, u64, u64) {
130        match chain {
131            Chain::Ethereum => (12, 36, 50),
132            Chain::Starknet => (2, 8, 50),
133            Chain::ZkSync => (3, 12, 50),
134            Chain::Arbitrum => (1, 2, 100), // Typically closer to 0.25s
135            Chain::Base => (2, 12, 50),
136            Chain::Bsc => (1, 12, 50),
137            Chain::Unichain => (1, 10, 100),
138            Chain::Polygon => (2, 12, 50), // ~2s block time
139            _ => {
140                let block_time = chain.block_time_secs();
141                (block_time, block_time * 3, 50)
142            }
143        }
144    }
145
146    /// Adds an exchange and its corresponding filter to the Tycho client.
147    pub fn exchange(mut self, name: &str, filter: ComponentFilter) -> Self {
148        self.exchanges
149            .insert(name.to_string(), filter);
150        self
151    }
152
153    /// Sets the block time for the Tycho client.
154    pub fn block_time(mut self, block_time: u64) -> Self {
155        self.block_time = block_time;
156        self
157    }
158
159    /// Sets the timeout duration for network operations.
160    pub fn timeout(mut self, timeout: u64) -> Self {
161        self.timeout = timeout;
162        self
163    }
164
165    pub fn startup_timeout(mut self, timeout: Duration) -> Self {
166        self.startup_timeout = timeout;
167        self
168    }
169
170    pub fn max_missed_blocks(mut self, max_missed_blocks: u64) -> Self {
171        self.max_missed_blocks = max_missed_blocks;
172        self
173    }
174
175    pub fn websockets_retry_config(mut self, retry_config: &RetryConfiguration) -> Self {
176        self.websockets_retry_config = retry_config.clone();
177        self.warn_on_potential_timing_issues();
178        self
179    }
180
181    pub fn state_synchronizer_retry_config(mut self, retry_config: &RetryConfiguration) -> Self {
182        self.state_sync_retry_config = retry_config.clone();
183        self.warn_on_potential_timing_issues();
184        self
185    }
186
187    fn warn_on_potential_timing_issues(&self) {
188        let (RetryConfiguration::Constant(state_config), RetryConfiguration::Constant(ws_config)) =
189            (&self.state_sync_retry_config, &self.websockets_retry_config);
190
191        if ws_config.cooldown >= state_config.cooldown {
192            warn!(
193                "Websocket cooldown should be < than state syncronizer cooldown \
194                to avoid spending retries due to disconnected websocket."
195            )
196        }
197    }
198
199    /// Configures the client to exclude state updates from the stream.
200    pub fn no_state(mut self, no_state: bool) -> Self {
201        self.no_state = no_state;
202        self
203    }
204
205    /// Sets the API key for authenticating with the Tycho server.
206    ///
207    /// Optionally you can set the TYCHO_AUTH_TOKEN env var instead. Make sure to set no_tsl
208    /// to false if you do this.
209    pub fn auth_key(mut self, auth_key: Option<String>) -> Self {
210        self.auth_key = auth_key;
211        self.no_tls = false;
212        self
213    }
214
215    /// Adds client-metadata entries sent to the server in the `X-Tycho-Client-Metadata` header.
216    ///
217    /// The metadata is opaque to tycho-client; consumers supply their own keys. Accepts any
218    /// iterator of key/value pairs and inserts each entry, keeping previously set metadata. An
219    /// empty map sends no header. Invalid keys/values and oversized metadata are dropped with a
220    /// warning at `build()` time, sending no header.
221    ///
222    /// Values are self-reported and may surface in the server's metrics and logs. Do not include
223    /// secrets or personally identifiable information.
224    pub fn add_client_metadata<I, K, V>(mut self, metadata: I) -> Self
225    where
226        I: IntoIterator<Item = (K, V)>,
227        K: Into<String>,
228        V: Into<String>,
229    {
230        self.client_metadata.extend(
231            metadata
232                .into_iter()
233                .map(|(k, v)| (k.into(), v.into())),
234        );
235        self
236    }
237
238    /// Disables TLS/SSL for the connection, using `http` and `ws` protocols.
239    pub fn no_tls(mut self, no_tls: bool) -> Self {
240        self.no_tls = no_tls;
241        self
242    }
243
244    /// Configures the client to include TVL in the stream.
245    ///
246    /// If set to true, this will increase start-up time due to additional requests.
247    pub fn include_tvl(mut self, include_tvl: bool) -> Self {
248        self.include_tvl = include_tvl;
249        self
250    }
251
252    /// Disables compression for RPC and WebSocket communication.
253    /// By default, messages are compressed using zstd.
254    pub fn disable_compression(mut self) -> Self {
255        self.compression = false;
256        self
257    }
258
259    /// Enables the client to receive partial block updates (flashblocks).
260    pub fn enable_partial_blocks(mut self) -> Self {
261        self.partial_blocks = true;
262        self
263    }
264
265    /// Stops the stream after emitting this many messages. Useful for testing or
266    /// triggering a periodic restart after a fixed number of blocks.
267    pub fn max_messages(mut self, n: usize) -> Self {
268        self.max_messages = Some(n);
269        self
270    }
271
272    /// Overrides the maximum number of retry attempts for state synchronizer startup.
273    /// The retry cooldown is derived from the chain's block time and is not affected.
274    pub fn max_retries(mut self, max_retries: u64) -> Self {
275        let cooldown = match &self.state_sync_retry_config {
276            RetryConfiguration::Constant(c) => c.cooldown,
277        };
278        self.state_sync_retry_config = RetryConfiguration::constant(max_retries, cooldown);
279        self
280    }
281
282    /// Blocklist specific component IDs across all registered exchanges.
283    ///
284    /// Blocklisted components are never tracked, regardless of TVL or other
285    /// filter criteria.
286    pub fn blocklisted_ids(mut self, ids: impl IntoIterator<Item = String>) -> Self {
287        self.blocklisted_ids.extend(ids);
288        self
289    }
290
291    /// Builds and starts the Tycho client, connecting to the Tycho server and
292    /// setting up the synchronization of exchange components.
293    pub async fn build(
294        self,
295    ) -> Result<
296        (JoinHandle<()>, Receiver<Result<FeedMessage<BlockHeader>, BlockSynchronizerError>>),
297        StreamError,
298    > {
299        if self.exchanges.is_empty() {
300            return Err(StreamError::SetUpError(
301                "At least one exchange must be registered.".to_string(),
302            ));
303        }
304
305        // Serialize client metadata once, before any network I/O. Metadata is best-effort
306        // telemetry, so invalid input is dropped with a warning rather than failing the stream.
307        let metadata_header =
308            serialize_client_metadata(&self.client_metadata).unwrap_or_else(|e| {
309                warn!("Ignoring invalid client metadata: {e}");
310                None
311            });
312
313        // Fail fast on a broken custom-chain config, before any network I/O.
314        validate_chain_config()?;
315
316        // Attempt to read the authentication key from the environment variable if not provided
317        let auth_key = self
318            .auth_key
319            .clone()
320            .or_else(|| env::var("TYCHO_AUTH_TOKEN").ok());
321
322        info!("Running with version: {}", option_env!("CARGO_PKG_VERSION").unwrap_or("unknown"));
323
324        // Determine the URLs based on the TLS setting
325        let (tycho_ws_url, tycho_rpc_url) = if self.no_tls {
326            info!("Using non-secure connection: ws:// and http://");
327            let tycho_ws_url = format!("ws://{}", self.tycho_url);
328            let tycho_rpc_url = format!("http://{}", self.tycho_url);
329            (tycho_ws_url, tycho_rpc_url)
330        } else {
331            info!("Using secure connection: wss:// and https://");
332            let tycho_ws_url = format!("wss://{}", self.tycho_url);
333            let tycho_rpc_url = format!("https://{}", self.tycho_url);
334            (tycho_ws_url, tycho_rpc_url)
335        };
336
337        // Initialize the WebSocket client
338        let ws_client = match &self.websockets_retry_config {
339            RetryConfiguration::Constant(config) => WsDeltasClient::new_with_reconnects(
340                &tycho_ws_url,
341                auth_key.as_deref(),
342                config.max_attempts,
343                config.cooldown,
344            ),
345        }
346        .map_err(|e| StreamError::SetUpError(e.to_string()))?
347        .with_client_metadata_header(metadata_header.clone());
348        let rpc_client = HttpRPCClient::new(
349            &tycho_rpc_url,
350            HttpRPCClientOptions::new()
351                .with_auth_key(auth_key)
352                .with_compression(self.compression)
353                .with_client_metadata_header(metadata_header),
354        )
355        .map_err(|e| StreamError::SetUpError(e.to_string()))?;
356        let ws_jh = ws_client
357            .connect()
358            .await
359            .map_err(|e| StreamError::WebSocketConnectionError(e.to_string()))?;
360
361        // Create and configure the BlockSynchronizer
362        let mut block_sync = BlockSynchronizer::new(
363            Duration::from_secs(self.block_time),
364            Duration::from_secs(self.timeout),
365            self.max_missed_blocks,
366        );
367        if let Some(n) = self.max_messages {
368            block_sync.max_messages(n);
369        }
370
371        let requested: HashSet<_> = self.exchanges.keys().cloned().collect();
372        let info = ProtocolSystemsInfo::fetch(&rpc_client, self.chain, &requested).await;
373        info.log_other_available();
374        let dci_protocols = info.dci_protocols;
375
376        // Register each exchange with the BlockSynchronizer
377        for (name, filter) in self
378            .exchanges
379            .into_iter()
380            .map(|(name, filter)| {
381                let filter = if self.blocklisted_ids.is_empty() {
382                    filter
383                } else {
384                    filter.blocklist(self.blocklisted_ids.iter().cloned())
385                };
386                (name, filter)
387            })
388        {
389            info!("Registering exchange: {}", name);
390            let id = ExtractorIdentity { chain: self.chain, name: name.clone() };
391            let uses_dci = dci_protocols.contains(&name);
392            let sync = match &self.state_sync_retry_config {
393                RetryConfiguration::Constant(retry_config) => ProtocolStateSynchronizer::new(
394                    id.clone(),
395                    true,
396                    filter,
397                    retry_config.max_attempts,
398                    retry_config.cooldown,
399                    !self.no_state,
400                    self.include_tvl,
401                    self.compression,
402                    rpc_client.clone(),
403                    ws_client.clone(),
404                    self.block_time + self.timeout,
405                )
406                .with_dci(uses_dci)
407                .with_partial_blocks(self.partial_blocks),
408            };
409            block_sync = block_sync.register_synchronizer(id, sync);
410        }
411
412        // Start the BlockSynchronizer and monitor for disconnections
413        let (sync_jh, rx) = block_sync
414            .run()
415            .await
416            .map_err(|e| StreamError::BlockSynchronizerError(e.to_string()))?;
417
418        // Monitor WebSocket and BlockSynchronizer futures
419        let handle = tokio::spawn(async move {
420            tokio::select! {
421                res = ws_jh => {
422                    let _ = res.map_err(|e| StreamError::WebSocketConnectionError(e.to_string()));
423                }
424                res = sync_jh => {
425                    res.map_err(|e| StreamError::BlockSynchronizerError(e.to_string())).unwrap();
426                }
427            }
428            if let Err(e) = ws_client.close().await {
429                warn!(?e, "Failed to close WebSocket client");
430            }
431        });
432
433        Ok((handle, rx))
434    }
435}
436
437/// Result of fetching protocol systems: which protocols use DCI, and which
438/// available protocols on the server were not requested by the client.
439pub struct ProtocolSystemsInfo {
440    pub dci_protocols: HashSet<String>,
441    pub other_available: HashSet<String>,
442}
443
444impl ProtocolSystemsInfo {
445    /// Fetches protocol systems from the server and classifies them: which use DCI,
446    /// and which are available but not in `requested_exchanges`.
447    pub async fn fetch(
448        rpc_client: &HttpRPCClient,
449        chain: Chain,
450        requested_exchanges: &HashSet<String>,
451    ) -> Self {
452        let page_size =
453            ProtocolSystemsRequestBody::effective_max_page_size(rpc_client.compression());
454        let params = ProtocolSystemsParams::new(chain).with_pagination(0, page_size);
455        let response = rpc_client
456            .get_protocol_systems(params)
457            .await
458            .map_err(|e| {
459                warn!(
460                    "Failed to fetch protocol systems: {e}. Skipping protocol availability check."
461                );
462                e
463            })
464            .ok();
465
466        let Some(response) = response else {
467            return Self { dci_protocols: HashSet::new(), other_available: HashSet::new() };
468        };
469
470        if response.total() > page_size {
471            warn!(
472                "Server has {} protocol systems but only {} were fetched (page_size={page_size}). \
473                 Availability info may be incomplete.",
474                response.total(),
475                response.data().protocol_systems().len(),
476            );
477        }
478
479        let available: HashSet<_> = response
480            .data()
481            .protocol_systems()
482            .iter()
483            .cloned()
484            .collect();
485        let other_available = available
486            .difference(requested_exchanges)
487            .cloned()
488            .collect();
489        let mut dci_protocols: HashSet<String> = response
490            .data()
491            .dci_protocols()
492            .iter()
493            .cloned()
494            .collect();
495
496        // TODO(ENG-5302): Remove this fallback once all environments serve
497        // the `dci_protocols` field. Old servers omit the field, which
498        // deserialises as empty — causing clients to skip entrypoint
499        // fetches for DCI protocols.
500        if dci_protocols.is_empty() {
501            const LEGACY_DCI: &[&str] = &[
502                "uniswap_v4_hooks",
503                "vm:curve",
504                "vm:balancer_v2",
505                "vm:balancer_v3",
506                "fluid_v1",
507                "erc4626",
508            ];
509            for name in requested_exchanges {
510                if LEGACY_DCI.contains(&name.as_str()) {
511                    dci_protocols.insert(name.clone());
512                }
513            }
514        }
515
516        Self { dci_protocols, other_available }
517    }
518
519    /// Logs the protocols available on the server that the client didn't subscribe to.
520    pub fn log_other_available(&self) {
521        if !self.other_available.is_empty() {
522            let names: Vec<_> = self
523                .other_available
524                .iter()
525                .cloned()
526                .collect();
527            info!("Other available protocols: {}", names.join(", "));
528        }
529    }
530}
531
532#[cfg(test)]
533mod tests {
534    use super::*;
535
536    #[test]
537    fn test_validate_chain_config_errors_on_broken_file() {
538        // Relies on nextest process isolation: this mutates the process-global env var.
539        std::env::set_var("TYCHO_CHAINS_CONFIG", "/nonexistent/does-not-exist.yaml");
540        let result = validate_chain_config();
541        std::env::remove_var("TYCHO_CHAINS_CONFIG");
542
543        let err = result.expect_err("a missing config file must fail validation");
544        assert!(matches!(err, StreamError::SetUpError(_)));
545        assert!(
546            err.to_string()
547                .contains("custom chain config"),
548            "error should name the custom chain config: {err}"
549        );
550    }
551
552    #[test]
553    fn test_validate_chain_config_ok_when_env_unset() {
554        std::env::remove_var("TYCHO_CHAINS_CONFIG");
555        assert!(
556            validate_chain_config().is_ok(),
557            "an unset env var means no custom chains, which is valid"
558        );
559    }
560
561    #[test]
562    fn test_retry_configuration_constant() {
563        let config = RetryConfiguration::constant(5, Duration::from_secs(10));
564        match config {
565            RetryConfiguration::Constant(c) => {
566                assert_eq!(c.max_attempts, 5);
567                assert_eq!(c.cooldown, Duration::from_secs(10));
568            }
569        }
570    }
571
572    #[test]
573    fn test_stream_builder_retry_configs() {
574        let mut builder = TychoStreamBuilder::new("localhost:4242", Chain::Ethereum);
575        let ws_config = RetryConfiguration::constant(10, Duration::from_secs(2));
576        let state_config = RetryConfiguration::constant(20, Duration::from_secs(5));
577
578        builder = builder
579            .websockets_retry_config(&ws_config)
580            .state_synchronizer_retry_config(&state_config);
581
582        // Verify configs are stored correctly by checking they match expected values
583        match (&builder.websockets_retry_config, &builder.state_sync_retry_config) {
584            (RetryConfiguration::Constant(ws), RetryConfiguration::Constant(state)) => {
585                assert_eq!(ws.max_attempts, 10);
586                assert_eq!(ws.cooldown, Duration::from_secs(2));
587                assert_eq!(state.max_attempts, 20);
588                assert_eq!(state.cooldown, Duration::from_secs(5));
589            }
590        }
591    }
592
593    #[test]
594    fn test_default_stream_builder() {
595        let builder = TychoStreamBuilder::new("localhost:4242", Chain::Ethereum);
596        assert!(builder.compression, "Compression should be enabled by default.");
597        assert!(!builder.partial_blocks, "partial_blocks should be disabled by default.");
598    }
599
600    #[tokio::test]
601    async fn test_no_exchanges() {
602        let receiver = TychoStreamBuilder::new("localhost:4242", Chain::Ethereum)
603            .auth_key(Some("my_api_key".into()))
604            .build()
605            .await;
606        assert!(receiver.is_err(), "Client should fail to build when no exchanges are registered.");
607    }
608
609    #[test]
610    fn test_add_client_metadata_accumulates() {
611        let builder = TychoStreamBuilder::new("localhost:4242", Chain::Ethereum)
612            .add_client_metadata([("fynd_version", "0.57.0")])
613            .add_client_metadata([("preset", "best")]);
614        assert_eq!(
615            builder
616                .client_metadata
617                .get("fynd_version")
618                .map(String::as_str),
619            Some("0.57.0")
620        );
621        assert_eq!(
622            builder
623                .client_metadata
624                .get("preset")
625                .map(String::as_str),
626            Some("best")
627        );
628    }
629
630    #[ignore = "require tycho gateway"]
631    #[tokio::test]
632    async fn test_simple_build() {
633        let token = env::var("TYCHO_AUTH_TOKEN").unwrap();
634        let receiver = TychoStreamBuilder::new("tycho-beta.propellerheads.xyz", Chain::Ethereum)
635            .exchange("uniswap_v2", ComponentFilter::with_tvl_range(100.0, 100.0))
636            .auth_key(Some(token))
637            .build()
638            .await;
639
640        dbg!(&receiver);
641
642        assert!(receiver.is_ok(), "Client should build successfully with exchanges registered.");
643    }
644}