Skip to main content

tycho_client/
cli.rs

1use std::{collections::HashSet, str::FromStr, time::Duration};
2
3use clap::Parser;
4use tracing::{debug, error, info, warn};
5use tracing_appender::rolling;
6use tycho_common::dto::{Chain, ExtractorIdentity};
7
8use crate::{
9    deltas::DeltasClient,
10    feed::{
11        component_tracker::ComponentFilter, synchronizer::ProtocolStateSynchronizer,
12        BlockSynchronizer,
13    },
14    rpc::HttpRPCClientOptions,
15    stream::ProtocolSystemsInfo,
16    HttpRPCClient, WsDeltasClient,
17};
18
19/// Tycho Client CLI - A tool for indexing and tracking blockchain protocol data
20///
21/// This CLI tool connects to a Tycho server and tracks various blockchain protocols,
22/// providing real-time updates about their state.
23#[derive(Parser, Debug, Clone, PartialEq)]
24#[clap(version = env!("CARGO_PKG_VERSION"))]
25struct CliArgs {
26    /// Tycho server URL, without protocol. Example: localhost:4242
27    #[clap(long, default_value = "localhost:4242", env = "TYCHO_URL")]
28    tycho_url: String,
29
30    /// Tycho gateway API key, used as authentication for both websocket and http connections.
31    /// Can be set with TYCHO_AUTH_TOKEN env variable.
32    #[clap(short = 'k', long, env = "TYCHO_AUTH_TOKEN")]
33    auth_key: Option<String>,
34
35    /// If set, use unsecured transports: http and ws instead of https and wss.
36    #[clap(long)]
37    no_tls: bool,
38
39    /// The blockchain to index on
40    #[clap(short = 'c', long, default_value = "ethereum")]
41    pub chain: String,
42
43    /// Specifies exchanges. Optionally also supply a pool address in the format
44    /// {exchange}-{pool_address}
45    #[clap(short = 'e', long, number_of_values = 1)]
46    exchange: Vec<String>,
47
48    /// Specifies the minimum TVL to filter the components. Denoted in the native token (e.g.
49    /// Mainnet -> ETH). Ignored if addresses or range tvl values are provided.
50    #[clap(long, default_value = "10")]
51    min_tvl: f64,
52
53    /// Specifies the lower bound of the TVL threshold range. Denoted in the native token (e.g.
54    /// Mainnet -> ETH). Components below this TVL will be removed from tracking.
55    #[clap(long)]
56    remove_tvl_threshold: Option<f64>,
57
58    /// Specifies the upper bound of the TVL threshold range. Denoted in the native token (e.g.
59    /// Mainnet -> ETH). Components above this TVL will be added to tracking.
60    #[clap(long)]
61    add_tvl_threshold: Option<f64>,
62
63    /// Expected block time in seconds. For blockchains with consistent intervals,
64    /// set to the average block time (e.g., "600" for a 10-minute interval).
65    ///
66    /// Adjusting `block_time` helps balance efficiency and responsiveness:
67    /// - **Low values**: Increase sync frequency but may waste resources on retries.
68    /// - **High values**: Reduce sync frequency but may delay updates on faster chains.
69    #[clap(long, default_value = "600")]
70    block_time: u64,
71
72    /// Maximum wait time in seconds beyond the block time. Useful for handling
73    /// chains with variable block intervals or network delays.
74    #[clap(long, default_value = "1")]
75    timeout: u64,
76
77    /// Logging folder path.
78    #[clap(long, default_value = "logs")]
79    log_folder: String,
80
81    /// Run the example on a single block with UniswapV2 and UniswapV3.
82    #[clap(long)]
83    example: bool,
84
85    /// If set, only component and tokens are streamed, any snapshots or state updates
86    /// are omitted from the stream.
87    #[clap(long)]
88    no_state: bool,
89
90    /// Maximum amount of messages to process before exiting. Useful for debugging e.g.
91    /// to easily get a state sync messages for a fixture. Alternatively this may be
92    /// used to trigger a regular restart or resync.
93    #[clap(short='n', long, default_value=None)]
94    max_messages: Option<usize>,
95
96    /// Maximum blocks an exchange can be absent for before it is marked as stale. Used
97    /// in conjunction with block_time to calculate a timeout: block_time * max_missed_blocks.
98    #[clap(long, default_value = "10")]
99    max_missed_blocks: u64,
100
101    /// If set, the synchronizer will include TVL in the messages.
102    /// Enabling this option will increase the number of network requests made during start-up,
103    /// which may result in increased start-up latency.
104    #[clap(long)]
105    include_tvl: bool,
106
107    /// If set, disable compression for WebSocket messages.
108    /// By default, messages are compressed using zstd.
109    #[clap(long)]
110    disable_compression: bool,
111
112    /// If set, enables receiving partial block updates (flashblocks).
113    /// This allows the client to receive incremental updates within a block, allowing for
114    /// lower latency.
115    #[clap(long)]
116    partial_blocks: bool,
117
118    /// Enable verbose logging. This will show more detailed information about the
119    /// synchronization process and any errors that occur.
120    #[clap(long)]
121    verbose: bool,
122
123    /// Maximum number of retry attempts for failed startups
124    #[clap(long, default_value = "32")]
125    max_retries: u64,
126}
127
128impl CliArgs {
129    fn validate(&self) -> Result<(), String> {
130        // TVL thresholds must be set together - either both or neither
131        match (self.remove_tvl_threshold, self.add_tvl_threshold) {
132            (Some(remove), Some(add)) if remove >= add => {
133                return Err("remove_tvl_threshold must be less than add_tvl_threshold".to_string());
134            }
135            (Some(_), None) | (None, Some(_)) => {
136                return Err(
137                    "Both remove_tvl_threshold and add_tvl_threshold must be set.".to_string()
138                );
139            }
140            _ => {}
141        }
142
143        Ok(())
144    }
145}
146
147pub async fn run_cli() -> Result<(), String> {
148    // Parse CLI Args
149    let args: CliArgs = CliArgs::parse();
150    args.validate()?;
151
152    // Setup Logging
153    let log_level = if args.verbose { "debug" } else { "info" };
154    let (non_blocking, _guard) =
155        tracing_appender::non_blocking(rolling::never(&args.log_folder, "dev_logs.log"));
156    let subscriber = tracing_subscriber::fmt()
157        .with_env_filter(
158            tracing_subscriber::EnvFilter::try_from_default_env()
159                .unwrap_or_else(|_| tracing_subscriber::EnvFilter::new(log_level)),
160        )
161        .with_writer(non_blocking)
162        .finish();
163
164    tracing::subscriber::set_global_default(subscriber)
165        .map_err(|e| format!("Failed to set up logging subscriber: {e}"))?;
166
167    // Build the list of exchanges.  When --example is provided, we seed the list with a fixed
168    // pair of well-known pools, otherwise we parse user supplied values (either plain exchange
169    // names or exchange-pool pairs in the {exchange}-{pool_address} format).
170    let exchanges: Vec<(String, Option<String>)> = if args.example {
171        // You will need to port-forward tycho to run the example:
172        //
173        // ```bash
174        // kubectl port-forward -n dev-tycho deploy/tycho-indexer 8888:4242
175        // ```
176        vec![
177            (
178                "uniswap_v3".to_string(),
179                Some("0x88e6a0c2ddd26feeb64f039a2c41296fcb3f5640".to_string()),
180            ),
181            (
182                "uniswap_v2".to_string(),
183                Some("0xa478c2975ab1ea89e8196811f51a7b7ade33eb11".to_string()),
184            ),
185        ]
186    } else {
187        args.exchange
188            .iter()
189            .filter_map(|e| {
190                if e.contains('-') {
191                    let parts: Vec<&str> = e.split('-').collect();
192                    if parts.len() == 2 {
193                        Some((parts[0].to_string(), Some(parts[1].to_string())))
194                    } else {
195                        warn!("Ignoring invalid exchange format: {}", e);
196                        None
197                    }
198                } else {
199                    Some((e.to_string(), None))
200                }
201            })
202            .collect()
203    };
204
205    info!("Running with exchanges: {:?}", exchanges);
206
207    run(exchanges, args).await?;
208    Ok(())
209}
210
211async fn run(exchanges: Vec<(String, Option<String>)>, args: CliArgs) -> Result<(), String> {
212    info!("Running with version: {}", option_env!("CARGO_PKG_VERSION").unwrap_or("unknown"));
213    //TODO: remove "or args.auth_key.is_none()" when our internal client use the no_tls flag
214    let (tycho_ws_url, tycho_rpc_url) = if args.no_tls || args.auth_key.is_none() {
215        info!("Using non-secure connection: ws:// and http://");
216        let tycho_ws_url = format!("ws://{url}", url = &args.tycho_url);
217        let tycho_rpc_url = format!("http://{url}", url = &args.tycho_url);
218        (tycho_ws_url, tycho_rpc_url)
219    } else {
220        info!("Using secure connection: wss:// and https://");
221        let tycho_ws_url = format!("wss://{url}", url = &args.tycho_url);
222        let tycho_rpc_url = format!("https://{url}", url = &args.tycho_url);
223        (tycho_ws_url, tycho_rpc_url)
224    };
225
226    let ws_client = WsDeltasClient::new(&tycho_ws_url, args.auth_key.as_deref())
227        .map_err(|e| format!("Failed to create WebSocket client: {e}"))?;
228    let rpc_client = HttpRPCClient::new(
229        &tycho_rpc_url,
230        HttpRPCClientOptions::new()
231            .with_auth_key(args.auth_key.clone())
232            .with_compression(!args.disable_compression),
233    )
234    .map_err(|e| format!("Failed to create RPC client: {e}"))?;
235    let chain = Chain::from_str(&args.chain)
236        .map_err(|_| format!("Unknown chain: {chain}", chain = &args.chain))?;
237    let ws_jh = ws_client
238        .connect()
239        .await
240        .map_err(|e| format!("WebSocket client connection error: {e}"))?;
241
242    let mut block_sync = BlockSynchronizer::new(
243        Duration::from_secs(args.block_time),
244        Duration::from_secs(args.timeout),
245        args.max_missed_blocks,
246    );
247
248    if let Some(mm) = &args.max_messages {
249        block_sync.max_messages(*mm);
250    }
251
252    let requested_protocol_set: HashSet<_> = exchanges
253        .iter()
254        .map(|(name, _)| name.clone())
255        .collect();
256    let protocol_info =
257        ProtocolSystemsInfo::fetch(&rpc_client, chain, &requested_protocol_set).await;
258    protocol_info.log_other_available();
259    let dci_protocols = protocol_info.dci_protocols;
260
261    for (name, address) in exchanges {
262        debug!("Registering exchange: {}", name);
263        let id = ExtractorIdentity { chain, name: name.clone() };
264        let filter = if let Some(address) = address {
265            ComponentFilter::Ids(vec![address])
266        } else if let (Some(remove_tvl), Some(add_tvl)) =
267            (args.remove_tvl_threshold, args.add_tvl_threshold)
268        {
269            ComponentFilter::with_tvl_range(remove_tvl, add_tvl)
270        } else {
271            ComponentFilter::with_tvl_range(args.min_tvl, args.min_tvl)
272        };
273        let uses_dci = dci_protocols.contains(&name);
274        let sync = ProtocolStateSynchronizer::new(
275            id.clone(),
276            true,
277            filter,
278            args.max_retries,
279            Duration::from_secs(args.block_time / 2),
280            !args.no_state,
281            args.include_tvl,
282            !args.disable_compression,
283            rpc_client.clone(),
284            ws_client.clone(),
285            args.block_time + args.timeout,
286        )
287        .with_dci(uses_dci)
288        .with_partial_blocks(args.partial_blocks);
289        block_sync = block_sync.register_synchronizer(id, sync);
290    }
291
292    let (sync_jh, mut rx) = block_sync
293        .run()
294        .await
295        .map_err(|e| format!("Failed to start block synchronizer: {e}"))?;
296
297    let msg_printer = tokio::spawn(async move {
298        while let Some(result) = rx.recv().await {
299            let msg =
300                result.map_err(|e| format!("Message printer received synchronizer error: {e}"))?;
301
302            if let Ok(msg_json) = serde_json::to_string(&msg) {
303                println!("{msg_json}");
304            } else {
305                // Log the error but continue processing further messages.
306                error!("Failed to serialize FeedMessage");
307            };
308        }
309
310        Ok::<(), String>(())
311    });
312
313    // Monitor the WebSocket, BlockSynchronizer and message printer futures.
314    let (failed_task, shutdown_reason) = tokio::select! {
315        res = ws_jh => (
316            "WebSocket",
317            extract_nested_error(res)
318        ),
319        res = sync_jh => (
320            "BlockSynchronizer",
321            extract_nested_error::<_, _, String>(Ok(res))
322            ),
323        res = msg_printer => (
324            "MessagePrinter",
325            extract_nested_error(res)
326        )
327    };
328
329    debug!("RX closed");
330    Err(format!(
331        "{failed_task} task terminated: {}",
332        shutdown_reason.unwrap_or("unknown reason".to_string())
333    ))
334}
335
336#[inline]
337fn extract_nested_error<T, E1: ToString, E2: ToString>(
338    res: Result<Result<T, E1>, E2>,
339) -> Option<String> {
340    res.map_err(|e| e.to_string())
341        .and_then(|r| r.map_err(|e| e.to_string()))
342        .err()
343}
344
345#[cfg(test)]
346mod cli_tests {
347    use clap::Parser;
348
349    use super::CliArgs;
350
351    #[tokio::test]
352    async fn test_cli_args() {
353        let args = CliArgs::parse_from([
354            "tycho-client",
355            "--tycho-url",
356            "localhost:5000",
357            "--exchange",
358            "uniswap_v2",
359            "--min-tvl",
360            "3000",
361            "--block-time",
362            "50",
363            "--timeout",
364            "5",
365            "--log-folder",
366            "test_logs",
367            "--example",
368            "--max-messages",
369            "1",
370        ]);
371        let exchanges: Vec<String> = vec!["uniswap_v2".to_string()];
372        assert_eq!(args.tycho_url, "localhost:5000");
373        assert_eq!(args.exchange, exchanges);
374        assert_eq!(args.min_tvl, 3000.0);
375        assert_eq!(args.block_time, 50);
376        assert_eq!(args.timeout, 5);
377        assert_eq!(args.log_folder, "test_logs");
378        assert_eq!(args.max_messages, Some(1));
379        assert!(args.example);
380        assert_eq!(args.disable_compression, false);
381        assert_eq!(args.partial_blocks, false);
382    }
383}