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, PaginationParams, ProtocolSystemsRequestBody};
7
8use crate::{
9 deltas::DeltasClient,
10 feed::{
11 component_tracker::ComponentFilter, synchronizer::ProtocolStateSynchronizer,
12 BlockSynchronizer,
13 },
14 rpc::{HttpRPCClientOptions, RPCClient},
15 HttpRPCClient, WsDeltasClient,
16};
17
18#[derive(Parser, Debug, Clone, PartialEq)]
23#[clap(version = env!("CARGO_PKG_VERSION"))]
24struct CliArgs {
25 #[clap(long, default_value = "localhost:4242", env = "TYCHO_URL")]
27 tycho_url: String,
28
29 #[clap(short = 'k', long, env = "TYCHO_AUTH_TOKEN")]
32 auth_key: Option<String>,
33
34 #[clap(long)]
36 no_tls: bool,
37
38 #[clap(short = 'c', long, default_value = "ethereum")]
40 pub chain: String,
41
42 #[clap(short = 'e', long, number_of_values = 1)]
45 exchange: Vec<String>,
46
47 #[clap(long, default_value = "10")]
50 min_tvl: f64,
51
52 #[clap(long)]
55 remove_tvl_threshold: Option<f64>,
56
57 #[clap(long)]
60 add_tvl_threshold: Option<f64>,
61
62 #[clap(long, default_value = "600")]
69 block_time: u64,
70
71 #[clap(long, default_value = "1")]
74 timeout: u64,
75
76 #[clap(long, default_value = "logs")]
78 log_folder: String,
79
80 #[clap(long)]
82 example: bool,
83
84 #[clap(long)]
87 no_state: bool,
88
89 #[clap(short='n', long, default_value=None)]
93 max_messages: Option<usize>,
94
95 #[clap(long, default_value = "10")]
98 max_missed_blocks: u64,
99
100 #[clap(long)]
104 include_tvl: bool,
105
106 #[clap(long)]
109 disable_compression: bool,
110
111 #[clap(long)]
114 verbose: bool,
115}
116
117impl CliArgs {
118 fn validate(&self) -> Result<(), String> {
119 match (self.remove_tvl_threshold, self.add_tvl_threshold) {
121 (Some(remove), Some(add)) if remove >= add => {
122 return Err("remove_tvl_threshold must be less than add_tvl_threshold".to_string());
123 }
124 (Some(_), None) | (None, Some(_)) => {
125 return Err(
126 "Both remove_tvl_threshold and add_tvl_threshold must be set.".to_string()
127 );
128 }
129 _ => {}
130 }
131
132 Ok(())
133 }
134}
135
136pub async fn run_cli() -> Result<(), String> {
137 let args: CliArgs = CliArgs::parse();
139 args.validate()?;
140
141 let log_level = if args.verbose { "debug" } else { "info" };
143 let (non_blocking, _guard) =
144 tracing_appender::non_blocking(rolling::never(&args.log_folder, "dev_logs.log"));
145 let subscriber = tracing_subscriber::fmt()
146 .with_env_filter(
147 tracing_subscriber::EnvFilter::try_from_default_env()
148 .unwrap_or_else(|_| tracing_subscriber::EnvFilter::new(log_level)),
149 )
150 .with_writer(non_blocking)
151 .finish();
152
153 tracing::subscriber::set_global_default(subscriber)
154 .map_err(|e| format!("Failed to set up logging subscriber: {e}"))?;
155
156 let exchanges: Vec<(String, Option<String>)> = if args.example {
160 vec![
166 (
167 "uniswap_v3".to_string(),
168 Some("0x88e6a0c2ddd26feeb64f039a2c41296fcb3f5640".to_string()),
169 ),
170 (
171 "uniswap_v2".to_string(),
172 Some("0xa478c2975ab1ea89e8196811f51a7b7ade33eb11".to_string()),
173 ),
174 ]
175 } else {
176 args.exchange
177 .iter()
178 .filter_map(|e| {
179 if e.contains('-') {
180 let parts: Vec<&str> = e.split('-').collect();
181 if parts.len() == 2 {
182 Some((parts[0].to_string(), Some(parts[1].to_string())))
183 } else {
184 warn!("Ignoring invalid exchange format: {}", e);
185 None
186 }
187 } else {
188 Some((e.to_string(), None))
189 }
190 })
191 .collect()
192 };
193
194 info!("Running with exchanges: {:?}", exchanges);
195
196 run(exchanges, args).await?;
197 Ok(())
198}
199
200async fn run(exchanges: Vec<(String, Option<String>)>, args: CliArgs) -> Result<(), String> {
201 info!("Running with version: {}", option_env!("CARGO_PKG_VERSION").unwrap_or("unknown"));
202 let (tycho_ws_url, tycho_rpc_url) = if args.no_tls || args.auth_key.is_none() {
204 info!("Using non-secure connection: ws:// and http://");
205 let tycho_ws_url = format!("ws://{url}", url = &args.tycho_url);
206 let tycho_rpc_url = format!("http://{url}", url = &args.tycho_url);
207 (tycho_ws_url, tycho_rpc_url)
208 } else {
209 info!("Using secure connection: wss:// and https://");
210 let tycho_ws_url = format!("wss://{url}", url = &args.tycho_url);
211 let tycho_rpc_url = format!("https://{url}", url = &args.tycho_url);
212 (tycho_ws_url, tycho_rpc_url)
213 };
214
215 let ws_client = WsDeltasClient::new(&tycho_ws_url, args.auth_key.as_deref())
216 .map_err(|e| format!("Failed to create WebSocket client: {e}"))?;
217 let rpc_client = HttpRPCClient::new(
218 &tycho_rpc_url,
219 HttpRPCClientOptions::new()
220 .with_auth_key(args.auth_key.clone())
221 .with_compression(!args.disable_compression),
222 )
223 .map_err(|e| format!("Failed to create RPC client: {e}"))?;
224 let chain = Chain::from_str(&args.chain)
225 .map_err(|_| format!("Unknown chain: {chain}", chain = &args.chain))?;
226 let ws_jh = ws_client
227 .connect()
228 .await
229 .map_err(|e| format!("WebSocket client connection error: {e}"))?;
230
231 let mut block_sync = BlockSynchronizer::new(
232 Duration::from_secs(args.block_time),
233 Duration::from_secs(args.timeout),
234 args.max_missed_blocks,
235 );
236
237 if let Some(mm) = &args.max_messages {
238 block_sync.max_messages(*mm);
239 }
240
241 let available_protocols_set = rpc_client
242 .get_protocol_systems(&ProtocolSystemsRequestBody {
243 chain,
244 pagination: PaginationParams { page: 0, page_size: 100 },
245 })
246 .await
247 .map_err(|e| format!("Failed to get protocol systems: {e}"))?
248 .protocol_systems
249 .into_iter()
250 .collect::<HashSet<_>>();
251
252 let requested_protocol_set = exchanges
253 .iter()
254 .map(|(name, _)| name.clone())
255 .collect::<HashSet<_>>();
256
257 let not_requested_protocols = available_protocols_set
258 .difference(&requested_protocol_set)
259 .cloned()
260 .collect::<Vec<_>>();
261
262 if !not_requested_protocols.is_empty() {
263 info!("Other available protocols: {}", not_requested_protocols.join(", "));
264 }
265
266 for (name, address) in exchanges {
267 debug!("Registering exchange: {}", name);
268 let id = ExtractorIdentity { chain, name: name.clone() };
269 let filter = if let Some(address) = address {
270 ComponentFilter::Ids(vec![address])
271 } else if let (Some(remove_tvl), Some(add_tvl)) =
272 (args.remove_tvl_threshold, args.add_tvl_threshold)
273 {
274 ComponentFilter::with_tvl_range(remove_tvl, add_tvl)
275 } else {
276 ComponentFilter::with_tvl_range(args.min_tvl, args.min_tvl)
277 };
278 let sync = ProtocolStateSynchronizer::new(
279 id.clone(),
280 true,
281 filter,
282 32,
283 Duration::from_secs(args.block_time / 2),
284 !args.no_state,
285 args.include_tvl,
286 !args.disable_compression,
287 rpc_client.clone(),
288 ws_client.clone(),
289 args.block_time + args.timeout,
290 );
291 block_sync = block_sync.register_synchronizer(id, sync);
292 }
293
294 let (sync_jh, mut rx) = block_sync
295 .run()
296 .await
297 .map_err(|e| format!("Failed to start block synchronizer: {e}"))?;
298
299 let msg_printer = tokio::spawn(async move {
300 while let Some(result) = rx.recv().await {
301 let msg =
302 result.map_err(|e| format!("Message printer received synchronizer error: {e}"))?;
303
304 if let Ok(msg_json) = serde_json::to_string(&msg) {
305 println!("{msg_json}");
306 } else {
307 error!("Failed to serialize FeedMessage");
309 };
310 }
311
312 Ok::<(), String>(())
313 });
314
315 let (failed_task, shutdown_reason) = tokio::select! {
317 res = ws_jh => (
318 "WebSocket",
319 extract_nested_error(res)
320 ),
321 res = sync_jh => (
322 "BlockSynchronizer",
323 extract_nested_error::<_, _, String>(Ok(res))
324 ),
325 res = msg_printer => (
326 "MessagePrinter",
327 extract_nested_error(res)
328 )
329 };
330
331 debug!("RX closed");
332 Err(format!(
333 "{failed_task} task terminated: {}",
334 shutdown_reason.unwrap_or("unknown reason".to_string())
335 ))
336}
337
338#[inline]
339fn extract_nested_error<T, E1: ToString, E2: ToString>(
340 res: Result<Result<T, E1>, E2>,
341) -> Option<String> {
342 res.map_err(|e| e.to_string())
343 .and_then(|r| r.map_err(|e| e.to_string()))
344 .err()
345}
346
347#[cfg(test)]
348mod cli_tests {
349 use clap::Parser;
350
351 use super::CliArgs;
352
353 #[tokio::test]
354 async fn test_cli_args() {
355 let args = CliArgs::parse_from([
356 "tycho-client",
357 "--tycho-url",
358 "localhost:5000",
359 "--exchange",
360 "uniswap_v2",
361 "--min-tvl",
362 "3000",
363 "--block-time",
364 "50",
365 "--timeout",
366 "5",
367 "--log-folder",
368 "test_logs",
369 "--example",
370 "--max-messages",
371 "1",
372 ]);
373 let exchanges: Vec<String> = vec!["uniswap_v2".to_string()];
374 assert_eq!(args.tycho_url, "localhost:5000");
375 assert_eq!(args.exchange, exchanges);
376 assert_eq!(args.min_tvl, 3000.0);
377 assert_eq!(args.block_time, 50);
378 assert_eq!(args.timeout, 5);
379 assert_eq!(args.log_folder, "test_logs");
380 assert_eq!(args.max_messages, Some(1));
381 assert!(args.example);
382 assert_eq!(args.disable_compression, false);
383 }
384}