Skip to main content

tycho_simulation/rfq/protocols/native/
client_builder.rs

1use std::collections::HashSet;
2
3use tokio::time::Duration;
4use tycho_common::{models::Chain, Bytes};
5
6use super::client::NativeClient;
7use crate::rfq::{
8    constants::get_native_auth, errors::RFQError, models::ComponentLayout,
9    protocols::utils::default_quote_tokens_for_chain,
10};
11
12pub struct NativeClientBuilder {
13    chain: Chain,
14    api_key: String,
15    tokens: HashSet<Bytes>,
16    tvl: f64,
17    quote_tokens: Option<HashSet<Bytes>>,
18    poll_time: Duration,
19    quote_timeout: Duration,
20    component_layout: ComponentLayout,
21}
22
23impl NativeClientBuilder {
24    pub fn new(chain: Chain, api_key: String) -> Self {
25        Self {
26            chain,
27            api_key,
28            tokens: HashSet::new(),
29            tvl: 100.0,
30            quote_tokens: None,
31            poll_time: Duration::from_secs(5),
32            quote_timeout: Duration::from_secs(5),
33            component_layout: ComponentLayout::PerPair,
34        }
35    }
36
37    pub fn from_env(chain: Chain) -> Result<Self, RFQError> {
38        let auth = get_native_auth()?;
39        Ok(Self::new(chain, auth.key))
40    }
41
42    pub fn tokens(mut self, tokens: HashSet<Bytes>) -> Self {
43        self.tokens = tokens;
44        self
45    }
46
47    pub fn tvl_threshold(mut self, tvl: f64) -> Self {
48        self.tvl = tvl;
49        self
50    }
51
52    pub fn quote_tokens(mut self, quote_tokens: HashSet<Bytes>) -> Self {
53        self.quote_tokens = Some(quote_tokens);
54        self
55    }
56
57    pub fn poll_time(mut self, poll_time: Duration) -> Self {
58        self.poll_time = poll_time;
59        self
60    }
61
62    /// The components the client streams. One per pair, by default. Register a `PerPair` client
63    /// with `NativeState` and a `AllPairs` client with `NativeAllPairsState`.
64    pub fn component_layout(mut self, component_layout: ComponentLayout) -> Self {
65        self.component_layout = component_layout;
66        self
67    }
68
69    pub fn quote_timeout(mut self, quote_timeout: Duration) -> Self {
70        self.quote_timeout = quote_timeout;
71        self
72    }
73
74    pub fn build(self) -> Result<NativeClient, RFQError> {
75        let quote_tokens = match self.quote_tokens {
76            Some(tokens) => tokens,
77            None => default_quote_tokens_for_chain(&self.chain)?,
78        };
79
80        NativeClient::new(
81            self.chain,
82            self.api_key,
83            self.tokens,
84            self.tvl,
85            quote_tokens,
86            self.poll_time,
87            self.quote_timeout,
88        )
89        .map(|client| client.with_component_layout(self.component_layout))
90    }
91}