tycho_simulation/
utils.rs1use std::{
2 collections::{HashMap, HashSet},
3 fs,
4 path::Path,
5};
6
7use tracing::info;
8use tycho_client::{
9 rpc::{AllTokensParams, HttpRPCClientOptions, RPCClient, RPC_CLIENT_CONCURRENCY},
10 HttpRPCClient, RPCError,
11};
12use tycho_common::{
13 models::{token::Token, Chain},
14 simulation::errors::SimulationError,
15 Bytes,
16};
17
18pub(crate) fn decimals_exponent(
21 from_decimals: u32,
22 to_decimals: u32,
23) -> Result<i32, SimulationError> {
24 i32::try_from(i64::from(from_decimals) - i64::from(to_decimals)).map_err(|e| {
25 SimulationError::InvalidInput(
26 format!("Decimals exponent {from_decimals} - {to_decimals} out of range: {e}"),
27 None,
28 )
29 })
30}
31
32pub(crate) fn decimals_i32(decimals: u32) -> Result<i32, SimulationError> {
34 i32::try_from(decimals).map_err(|e| {
35 SimulationError::InvalidInput(format!("Decimals {decimals} out of range: {e}"), None)
36 })
37}
38
39pub(crate) fn decimals_scale(decimals: u32) -> f64 {
42 decimals_i32(decimals).map_or(f64::INFINITY, |exponent| 10f64.powi(exponent))
43}
44
45pub fn hexstring_to_vec(hexstring: &str) -> Result<Vec<u8>, SimulationError> {
68 let hexstring_no_prefix =
69 if let Some(stripped) = hexstring.strip_prefix("0x") { stripped } else { hexstring };
70 let bytes = hex::decode(hexstring_no_prefix).map_err(|err| {
71 SimulationError::FatalError(format!("Invalid hex string `{hexstring}`: {err}"))
72 })?;
73 Ok(bytes)
74}
75
76pub async fn load_all_tokens(
93 tycho_url: &str,
94 no_tls: bool,
95 auth_key: Option<&str>,
96 compression: bool,
97 chain: Chain,
98 min_quality: Option<i32>,
99 max_days_since_last_trade: Option<u64>,
100) -> Result<HashMap<Bytes, Token>, SimulationError> {
101 info!("Loading tokens from Tycho...");
102 let rpc_url =
103 if no_tls { format!("http://{tycho_url}") } else { format!("https://{tycho_url}") };
104
105 let rpc_options = HttpRPCClientOptions::new()
106 .with_auth_key(auth_key.map(|s| s.to_string()))
107 .with_compression(compression);
108
109 let rpc_client = HttpRPCClient::new(rpc_url.as_str(), rpc_options)
110 .map_err(|err| map_rpc_error(&err, "Failed to create Tycho RPC client"))?;
111
112 let default_min_days = HashMap::from([(Chain::Base, 7_u64), (Chain::Ethereum, 30_u64)]);
114
115 let min_q = min_quality.or(Some(100));
116 let traded = max_days_since_last_trade.or_else(|| {
117 default_min_days
118 .get(&chain)
119 .or(Some(&42))
120 .copied()
121 });
122 let mut token_params = AllTokensParams::new(chain, RPC_CLIENT_CONCURRENCY);
123 if let Some(q) = min_q {
124 token_params = token_params.with_min_quality(q);
125 }
126 if let Some(d) = traded {
127 token_params = token_params.with_traded_n_days_ago(d);
128 }
129 let tokens = rpc_client
130 .get_all_tokens(token_params)
131 .await
132 .map_err(|err| map_rpc_error(&err, "Unable to load tokens"))?;
133
134 tokens
135 .into_iter()
136 .map(|token| Ok((token.address.clone(), token)))
137 .collect()
138}
139
140pub fn get_default_url(chain: &Chain) -> Option<String> {
142 match chain {
143 Chain::Ethereum => Some("tycho-beta.propellerheads.xyz".to_string()),
144 Chain::Base => Some("tycho-base-beta.propellerheads.xyz".to_string()),
145 Chain::Unichain => Some("tycho-unichain-beta.propellerheads.xyz".to_string()),
146 Chain::Bsc => Some("tycho-bsc-beta.propellerheads.xyz".to_string()),
147 Chain::Arbitrum => Some("tycho-arbitrum-beta.propellerheads.xyz".to_string()),
148 Chain::Polygon => Some("tycho-polygon-beta.propellerheads.xyz".to_string()),
149 Chain::Robinhood => Some("tycho-robinhood-beta.propellerheads.xyz".to_string()),
150 Chain::Starknet | Chain::ZkSync | Chain::Plasma | Chain::Arc | Chain::Custom(_) | _ => None,
151 }
152}
153
154pub fn load_blocklist(path: Option<&Path>) -> Result<HashSet<String>, SimulationError> {
160 let Some(path) = path else {
161 return Ok(default_blocklist());
162 };
163 let contents = fs::read_to_string(path).map_err(|e| {
164 SimulationError::FatalError(format!("Failed to read blocklist {:?}: {e}", path))
165 })?;
166 parse_blocklist(&contents).map_err(|e| {
167 SimulationError::FatalError(format!("Failed to parse blocklist {:?}: {e}", path))
168 })
169}
170
171pub fn default_blocklist() -> HashSet<String> {
172 parse_blocklist(include_str!("../blocklist.toml"))
173 .expect("embedded blocklist.toml is valid TOML")
174}
175
176fn parse_blocklist(contents: &str) -> Result<HashSet<String>, toml::de::Error> {
177 #[derive(Default, serde::Deserialize)]
178 struct Blocklist {
179 #[serde(default)]
180 components: HashSet<String>,
181 }
182
183 #[derive(serde::Deserialize)]
184 struct BlocklistConfig {
185 #[serde(default)]
186 blocklist: Blocklist,
187 }
188
189 let config: BlocklistConfig = toml::from_str(contents)?;
190 Ok(config.blocklist.components)
191}
192
193fn map_rpc_error(err: &RPCError, context: &str) -> SimulationError {
194 let message = format!("{context}: {err}", err = err,);
195 match err {
196 RPCError::UrlParsing(_, _) | RPCError::FormatRequest(_) => {
197 SimulationError::InvalidInput(message, None)
198 }
199 RPCError::HttpClient(..) |
200 RPCError::ParseResponse(_) |
201 RPCError::StaleBlock(_) |
202 RPCError::UnknownExtractor(_) |
203 RPCError::Fatal(_) |
204 RPCError::RateLimited(_) |
205 RPCError::ServerUnreachable(_) => SimulationError::FatalError(message),
206 }
207}