Skip to main content

tycho_simulation/rfq/
stream.rs

1use std::collections::HashMap;
2
3use futures::{stream::select_all, StreamExt};
4use tycho_client::feed::{synchronizer::ComponentWithState, FeedMessage};
5use tycho_common::{
6    models::token::Token,
7    simulation::{errors::SimulationError, protocol_sim::ProtocolSim},
8    Bytes,
9};
10
11use crate::{
12    evm::decoder::TychoStreamDecoder,
13    protocol::{
14        errors::InvalidSnapshotError,
15        models::{TryFromWithBlock, Update},
16    },
17    rfq::{client::RFQClient, models::TimestampHeader},
18};
19
20/// `RFQStreamBuilder` is a utility for constructing and managing a merged stream of RFQ (Request
21/// For Quote) providers in Tycho.
22///
23/// It allows you to:
24/// - Register multiple `RFQClient` implementations, each providing its own stream of RFQ price
25///   updates.
26/// - Dynamically decode incoming updates into `Update` objects using `TychoStreamDecoder`.
27///
28/// The `build` method consumes the builder and runs the event loop, sending decoded `Update`s
29/// through the provided `mpsc::Sender`. It returns an error if decoding an update or forwarding
30/// it to the channel fails.
31///
32/// ### Error Handling:
33/// - Each `RFQClient`'s stream is expected to yield `Result<(String, StateSyncMessage), RFQError>`.
34/// - If a client's stream returns an `Err` (e.g., `RFQError::FatalError`), the client is
35///   **removed** from the merged stream, and the system continues running without it.
36#[derive(Default)]
37pub struct RFQStreamBuilder {
38    clients: Vec<Box<dyn RFQClient>>,
39    decoder: TychoStreamDecoder<TimestampHeader>,
40}
41
42impl RFQStreamBuilder {
43    pub fn new() -> Self {
44        Self { clients: Vec::new(), decoder: TychoStreamDecoder::new() }
45    }
46
47    pub fn add_client<T>(mut self, name: &str, provider: Box<dyn RFQClient>) -> Self
48    where
49        T: ProtocolSim
50            + TryFromWithBlock<ComponentWithState, TimestampHeader, Error = InvalidSnapshotError>
51            + Send
52            + 'static,
53    {
54        self.clients.push(provider);
55        self.decoder.register_decoder::<T>(name);
56        self
57    }
58
59    pub async fn build(self, tx: tokio::sync::mpsc::Sender<Update>) -> Result<(), SimulationError> {
60        let streams: Vec<_> = self
61            .clients
62            .into_iter()
63            .map(|provider| provider.stream())
64            .collect();
65
66        let mut merged = select_all(streams);
67
68        while let Some(next) = merged.next().await {
69            match next {
70                Ok((provider, msg)) => {
71                    let update = self
72                        .decoder
73                        .decode(&FeedMessage {
74                            state_msgs: HashMap::from([(provider.clone(), msg)]),
75                            sync_states: HashMap::new(),
76                        })
77                        .await
78                        .map_err(|e| {
79                            SimulationError::RecoverableError(format!("Decoding error: {e}"))
80                        })?;
81                    tx.send(update).await.map_err(|e| {
82                        SimulationError::RecoverableError(format!(
83                            "Failed to send update through channel: {e}"
84                        ))
85                    })?;
86                }
87                Err(e) => {
88                    tracing::error!(
89                        "RFQ stream fatal error: {e}. Assuming this stream will not emit more messages."
90                    );
91                }
92            }
93        }
94
95        Ok(())
96    }
97
98    /// Sets the currently known tokens which to be considered during decoding.
99    ///
100    /// Protocol components containing tokens which are not included in this initial list, or
101    /// added when applying deltas, will not be decoded.
102    pub async fn set_tokens(self, tokens: HashMap<Bytes, Token>) -> Self {
103        self.decoder.set_tokens(tokens).await;
104        self
105    }
106}
107
108#[cfg(test)]
109mod tests {
110    use std::{any::Any, time::Duration};
111
112    use async_trait::async_trait;
113    use futures::stream::BoxStream;
114    use num_bigint::BigUint;
115    use serde::{Deserialize, Serialize};
116    use tokio::sync::mpsc;
117    use tokio_stream::wrappers::IntervalStream;
118    use tycho_client::feed::synchronizer::{Snapshot, StateSyncMessage};
119    use tycho_common::{
120        dto::{ProtocolComponent, ProtocolStateDelta, ResponseProtocolState},
121        models::{protocol::GetAmountOutParams, token::Token},
122        simulation::{
123            errors::{SimulationError, TransitionError},
124            indicatively_priced::SignedQuote,
125            protocol_sim::{Balances, GetAmountOutResult},
126        },
127        Bytes,
128    };
129
130    use super::*;
131    use crate::{protocol::models::DecoderContext, rfq::errors::RFQError};
132
133    #[derive(Clone, Debug, Serialize, Deserialize)]
134    pub struct DummyProtocol;
135
136    #[typetag::serde]
137    impl ProtocolSim for DummyProtocol {
138        fn fee(&self) -> f64 {
139            unimplemented!("Not needed for this test")
140        }
141
142        fn spot_price(&self, _base: &Token, _quote: &Token) -> Result<f64, SimulationError> {
143            unimplemented!("Not needed for this test")
144        }
145
146        fn get_amount_out(
147            &self,
148            _amount_in: BigUint,
149            _token_in: &Token,
150            _token_out: &Token,
151        ) -> Result<GetAmountOutResult, SimulationError> {
152            unimplemented!("Not needed for this test")
153        }
154
155        fn get_limits(
156            &self,
157            _sell_token: Bytes,
158            _buy_token: Bytes,
159        ) -> Result<(BigUint, BigUint), SimulationError> {
160            unimplemented!("Not needed for this test")
161        }
162
163        fn delta_transition(
164            &mut self,
165            _delta: ProtocolStateDelta,
166            _tokens: &HashMap<Bytes, Token>,
167            _balances: &Balances,
168        ) -> Result<(), TransitionError> {
169            unimplemented!("Not needed for this test")
170        }
171
172        fn clone_box(&self) -> Box<dyn ProtocolSim> {
173            Box::new(self.clone())
174        }
175
176        fn as_any(&self) -> &dyn Any {
177            self
178        }
179
180        fn as_any_mut(&mut self) -> &mut dyn Any {
181            self
182        }
183        fn eq(&self, _other: &dyn ProtocolSim) -> bool {
184            unimplemented!("Not needed for this test")
185        }
186    }
187
188    impl TryFromWithBlock<ComponentWithState, TimestampHeader> for DummyProtocol {
189        type Error = InvalidSnapshotError;
190        async fn try_from_with_header(
191            _value: ComponentWithState,
192            _header: TimestampHeader,
193            _account_balances: &HashMap<Bytes, HashMap<Bytes, Bytes>>,
194            _all_tokens: &HashMap<Bytes, Token>,
195            _decoder_context: &DecoderContext,
196        ) -> Result<Self, Self::Error> {
197            Ok(DummyProtocol)
198        }
199    }
200
201    pub struct MockRFQClient {
202        name: String,
203        interval: Duration,
204        error_at_time: Option<u128>,
205    }
206
207    impl MockRFQClient {
208        pub fn new(name: &str, interval: Duration, error_at_time: Option<u128>) -> Self {
209            Self { name: name.to_string(), interval, error_at_time }
210        }
211    }
212
213    #[async_trait]
214    impl RFQClient for MockRFQClient {
215        fn stream(
216            &self,
217        ) -> BoxStream<'static, Result<(String, StateSyncMessage<TimestampHeader>), RFQError>>
218        {
219            let name = self.name.clone();
220            let error_at_time = self.error_at_time;
221            let mut current_time: u128 = 0;
222            let interval = self.interval;
223            let interval =
224                IntervalStream::new(tokio::time::interval(self.interval)).map(move |_| {
225                    if let Some(error_at_time) = error_at_time {
226                        if error_at_time == current_time {
227                            return Err(RFQError::FatalError(format!(
228                                "{name} stream is dying and can't go on"
229                            )));
230                        };
231                    };
232                    let protocol_component =
233                        ProtocolComponent { protocol_system: name.clone(), ..Default::default() };
234
235                    let snapshot = Snapshot {
236                        states: HashMap::from([(
237                            name.clone(),
238                            ComponentWithState {
239                                state: ResponseProtocolState {
240                                    component_id: name.clone(),
241                                    attributes: HashMap::new(),
242                                    balances: HashMap::new(),
243                                },
244                                component: protocol_component,
245                                component_tvl: None,
246                                entrypoints: vec![],
247                            },
248                        )]),
249                        vm_storage: HashMap::new(),
250                    };
251
252                    let msg = StateSyncMessage {
253                        header: TimestampHeader { timestamp: current_time as u64 },
254                        snapshots: snapshot,
255                        ..Default::default()
256                    };
257
258                    current_time += interval.as_millis();
259                    Ok((name.clone(), msg))
260                });
261            Box::pin(interval)
262        }
263
264        async fn request_binding_quote(
265            &self,
266            _params: &GetAmountOutParams,
267        ) -> Result<SignedQuote, RFQError> {
268            unimplemented!("Not needed for this test")
269        }
270    }
271
272    #[tokio::test]
273    async fn test_rfq_stream_builder() {
274        // This test has two mocked RFQ clients
275        // 1. Bebop client that emits a message every 100ms
276        // 2. Hashflow client that emits a message every 200m
277        let (tx, mut rx) = mpsc::channel::<Update>(10);
278
279        let builder = RFQStreamBuilder::new()
280            .add_client::<DummyProtocol>(
281                "bebop",
282                Box::new(MockRFQClient::new("bebop", Duration::from_millis(100), Some(300))),
283            )
284            .add_client::<DummyProtocol>(
285                "hashflow",
286                Box::new(MockRFQClient::new("hashflow", Duration::from_millis(200), None)),
287            );
288
289        tokio::spawn(builder.build(tx));
290
291        // Collect only the first 10 messages
292        let mut updates = Vec::new();
293        for _ in 0..6 {
294            let update = rx.recv().await.unwrap();
295            updates.push(update);
296        }
297
298        // Collect all timestamps per provider
299        let bebop_updates: Vec<_> = updates
300            .iter()
301            .filter(|u| u.new_pairs.contains_key("bebop"))
302            .collect();
303        let hashflow_updates: Vec<_> = updates
304            .iter()
305            .filter(|u| u.new_pairs.contains_key("hashflow"))
306            .collect();
307
308        assert_eq!(bebop_updates[0].block_number_or_timestamp, 0,);
309        assert_eq!(hashflow_updates[0].block_number_or_timestamp, 0,);
310        assert_eq!(bebop_updates[1].block_number_or_timestamp, 100);
311        assert_eq!(bebop_updates[2].block_number_or_timestamp, 200);
312        assert_eq!(hashflow_updates[1].block_number_or_timestamp, 200);
313        // At this point the bebop stream dies, and we shouldn't have any more bebop updates, only
314        // hashflow
315        assert_eq!(bebop_updates.len(), 3);
316        assert_eq!(hashflow_updates[2].block_number_or_timestamp, 400);
317    }
318}