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#[derive(Parser, Debug, Clone, PartialEq)]
24#[clap(version = env!("CARGO_PKG_VERSION"))]
25struct CliArgs {
26 #[clap(long, default_value = "localhost:4242", env = "TYCHO_URL")]
28 tycho_url: String,
29
30 #[clap(short = 'k', long, env = "TYCHO_AUTH_TOKEN")]
33 auth_key: Option<String>,
34
35 #[clap(long)]
37 no_tls: bool,
38
39 #[clap(short = 'c', long, default_value = "ethereum")]
41 pub chain: String,
42
43 #[clap(short = 'e', long, number_of_values = 1)]
46 exchange: Vec<String>,
47
48 #[clap(long, default_value = "10")]
51 min_tvl: f64,
52
53 #[clap(long)]
56 remove_tvl_threshold: Option<f64>,
57
58 #[clap(long)]
61 add_tvl_threshold: Option<f64>,
62
63 #[clap(long, default_value = "600")]
70 block_time: u64,
71
72 #[clap(long, default_value = "1")]
75 timeout: u64,
76
77 #[clap(long, default_value = "logs")]
79 log_folder: String,
80
81 #[clap(long)]
83 example: bool,
84
85 #[clap(long)]
88 no_state: bool,
89
90 #[clap(short='n', long, default_value=None)]
94 max_messages: Option<usize>,
95
96 #[clap(long, default_value = "10")]
99 max_missed_blocks: u64,
100
101 #[clap(long)]
105 include_tvl: bool,
106
107 #[clap(long)]
110 disable_compression: bool,
111
112 #[clap(long)]
116 partial_blocks: bool,
117
118 #[clap(long)]
121 verbose: bool,
122
123 #[clap(long, default_value = "32")]
125 max_retries: u64,
126}
127
128impl CliArgs {
129 fn validate(&self) -> Result<(), String> {
130 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 let args: CliArgs = CliArgs::parse();
150 args.validate()?;
151
152 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 let exchanges: Vec<(String, Option<String>)> = if args.example {
171 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 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 error!("Failed to serialize FeedMessage");
307 };
308 }
309
310 Ok::<(), String>(())
311 });
312
313 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}