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 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 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), Chain::Base => (2, 12, 50),
106 Chain::Bsc => (1, 12, 50),
107 Chain::Unichain => (1, 10, 100),
108 }
109 }
110
111 pub fn exchange(mut self, name: &str, filter: ComponentFilter) -> Self {
113 self.exchanges
114 .insert(name.to_string(), filter);
115 self
116 }
117
118 pub fn block_time(mut self, block_time: u64) -> Self {
120 self.block_time = block_time;
121 self
122 }
123
124 pub fn timeout(mut self, timeout: u64) -> Self {
126 self.timeout = timeout;
127 self
128 }
129
130 pub fn startup_timeout(mut self, timeout: Duration) -> Self {
131 self.startup_timeout = timeout;
132 self
133 }
134
135 pub fn max_missed_blocks(mut self, max_missed_blocks: u64) -> Self {
136 self.max_missed_blocks = max_missed_blocks;
137 self
138 }
139
140 pub fn websockets_retry_config(mut self, retry_config: &RetryConfiguration) -> Self {
141 self.websockets_retry_config = retry_config.clone();
142 self.warn_on_potential_timing_issues();
143 self
144 }
145
146 pub fn state_synchronizer_retry_config(mut self, retry_config: &RetryConfiguration) -> Self {
147 self.state_sync_retry_config = retry_config.clone();
148 self.warn_on_potential_timing_issues();
149 self
150 }
151
152 fn warn_on_potential_timing_issues(&self) {
153 let (RetryConfiguration::Constant(state_config), RetryConfiguration::Constant(ws_config)) =
154 (&self.state_sync_retry_config, &self.websockets_retry_config);
155
156 if ws_config.cooldown >= state_config.cooldown {
157 warn!(
158 "Websocket cooldown should be < than state syncronizer cooldown \
159 to avoid spending retries due to disconnected websocket."
160 )
161 }
162 }
163
164 pub fn no_state(mut self, no_state: bool) -> Self {
166 self.no_state = no_state;
167 self
168 }
169
170 pub fn auth_key(mut self, auth_key: Option<String>) -> Self {
175 self.auth_key = auth_key;
176 self.no_tls = false;
177 self
178 }
179
180 pub fn no_tls(mut self, no_tls: bool) -> Self {
182 self.no_tls = no_tls;
183 self
184 }
185
186 pub fn include_tvl(mut self, include_tvl: bool) -> Self {
190 self.include_tvl = include_tvl;
191 self
192 }
193
194 pub async fn build(
197 self,
198 ) -> Result<
199 (JoinHandle<()>, Receiver<Result<FeedMessage<BlockHeader>, BlockSynchronizerError>>),
200 StreamError,
201 > {
202 if self.exchanges.is_empty() {
203 return Err(StreamError::SetUpError(
204 "At least one exchange must be registered.".to_string(),
205 ));
206 }
207
208 let auth_key = self
210 .auth_key
211 .clone()
212 .or_else(|| env::var("TYCHO_AUTH_TOKEN").ok());
213
214 info!("Running with version: {}", option_env!("CARGO_PKG_VERSION").unwrap_or("unknown"));
215
216 let (tycho_ws_url, tycho_rpc_url) = if self.no_tls {
218 info!("Using non-secure connection: ws:// and http://");
219 let tycho_ws_url = format!("ws://{}", self.tycho_url);
220 let tycho_rpc_url = format!("http://{}", self.tycho_url);
221 (tycho_ws_url, tycho_rpc_url)
222 } else {
223 info!("Using secure connection: wss:// and https://");
224 let tycho_ws_url = format!("wss://{}", self.tycho_url);
225 let tycho_rpc_url = format!("https://{}", self.tycho_url);
226 (tycho_ws_url, tycho_rpc_url)
227 };
228
229 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 .map_err(|e| StreamError::SetUpError(e.to_string()))?;
239 let rpc_client = HttpRPCClient::new(&tycho_rpc_url, auth_key.as_deref())
240 .map_err(|e| StreamError::SetUpError(e.to_string()))?;
241 let ws_jh = ws_client
242 .connect()
243 .await
244 .map_err(|e| StreamError::WebSocketConnectionError(e.to_string()))?;
245
246 let mut block_sync = BlockSynchronizer::new(
248 Duration::from_secs(self.block_time),
249 Duration::from_secs(self.timeout),
250 self.max_missed_blocks,
251 );
252
253 self.display_available_protocols(&rpc_client)
254 .await;
255
256 for (name, filter) in self.exchanges {
258 info!("Registering exchange: {}", name);
259 let id = ExtractorIdentity { chain: self.chain, name: name.clone() };
260 let sync = match &self.state_sync_retry_config {
261 RetryConfiguration::Constant(retry_config) => ProtocolStateSynchronizer::new(
262 id.clone(),
263 true,
264 filter,
265 retry_config.max_attempts,
266 retry_config.cooldown,
267 !self.no_state,
268 self.include_tvl,
269 rpc_client.clone(),
270 ws_client.clone(),
271 self.block_time + self.timeout,
272 ),
273 };
274 block_sync = block_sync.register_synchronizer(id, sync);
275 }
276
277 let (sync_jh, rx) = block_sync
279 .run()
280 .await
281 .map_err(|e| StreamError::BlockSynchronizerError(e.to_string()))?;
282
283 let handle = tokio::spawn(async move {
285 tokio::select! {
286 res = ws_jh => {
287 let _ = res.map_err(|e| StreamError::WebSocketConnectionError(e.to_string()));
288 }
289 res = sync_jh => {
290 res.map_err(|e| StreamError::BlockSynchronizerError(e.to_string())).unwrap();
291 }
292 }
293 if let Err(e) = ws_client.close().await {
294 warn!(?e, "Failed to close WebSocket client");
295 }
296 });
297
298 Ok((handle, rx))
299 }
300
301 async fn display_available_protocols(&self, rpc_client: &HttpRPCClient) {
304 let available_protocols_set = rpc_client
305 .get_protocol_systems(&ProtocolSystemsRequestBody {
306 chain: self.chain,
307 pagination: PaginationParams { page: 0, page_size: 100 },
308 })
309 .await
310 .map(|resp| {
311 resp.protocol_systems
312 .into_iter()
313 .collect::<HashSet<_>>()
314 })
315 .map_err(|e| {
316 warn!(
317 "Failed to fetch protocol systems: {e}. Skipping protocol availability check."
318 );
319 e
320 })
321 .ok();
322
323 if let Some(not_requested_protocols) = available_protocols_set
324 .map(|available_protocols_set| {
325 let requested_protocol_set = self
326 .exchanges
327 .keys()
328 .cloned()
329 .collect::<HashSet<_>>();
330
331 available_protocols_set
332 .difference(&requested_protocol_set)
333 .cloned()
334 .collect::<Vec<_>>()
335 })
336 .filter(|not_requested_protocols| !not_requested_protocols.is_empty())
337 {
338 info!("Other available protocols: {}", not_requested_protocols.join(", "))
339 }
340 }
341}
342
343#[cfg(test)]
344mod tests {
345 use super::*;
346
347 #[test]
348 fn test_retry_configuration_constant() {
349 let config = RetryConfiguration::constant(5, Duration::from_secs(10));
350 match config {
351 RetryConfiguration::Constant(c) => {
352 assert_eq!(c.max_attempts, 5);
353 assert_eq!(c.cooldown, Duration::from_secs(10));
354 }
355 }
356 }
357
358 #[test]
359 fn test_stream_builder_retry_configs() {
360 let mut builder = TychoStreamBuilder::new("localhost:4242", Chain::Ethereum);
361 let ws_config = RetryConfiguration::constant(10, Duration::from_secs(2));
362 let state_config = RetryConfiguration::constant(20, Duration::from_secs(5));
363
364 builder = builder
365 .websockets_retry_config(&ws_config)
366 .state_synchronizer_retry_config(&state_config);
367
368 match (&builder.websockets_retry_config, &builder.state_sync_retry_config) {
370 (RetryConfiguration::Constant(ws), RetryConfiguration::Constant(state)) => {
371 assert_eq!(ws.max_attempts, 10);
372 assert_eq!(ws.cooldown, Duration::from_secs(2));
373 assert_eq!(state.max_attempts, 20);
374 assert_eq!(state.cooldown, Duration::from_secs(5));
375 }
376 }
377 }
378
379 #[tokio::test]
380 async fn test_no_exchanges() {
381 let receiver = TychoStreamBuilder::new("localhost:4242", Chain::Ethereum)
382 .auth_key(Some("my_api_key".into()))
383 .build()
384 .await;
385 assert!(receiver.is_err(), "Client should fail to build when no exchanges are registered.");
386 }
387
388 #[ignore = "require tycho gateway"]
389 #[tokio::test]
390 async fn teat_simple_build() {
391 let token = env::var("TYCHO_AUTH_TOKEN").unwrap();
392 let receiver = TychoStreamBuilder::new("tycho-beta.propellerheads.xyz", Chain::Ethereum)
393 .exchange("uniswap_v2", ComponentFilter::with_tvl_range(100.0, 100.0))
394 .auth_key(Some(token))
395 .build()
396 .await;
397
398 dbg!(&receiver);
399
400 assert!(receiver.is_ok(), "Client should build successfully with exchanges registered.");
401 }
402}