use std::{
collections::{HashMap, HashSet},
fs,
path::Path,
};
use tracing::info;
use tycho_client::{
rpc::{AllTokensParams, HttpRPCClientOptions, RPCClient, RPC_CLIENT_CONCURRENCY},
HttpRPCClient, RPCError,
};
use tycho_common::{
models::{token::Token, Chain},
simulation::errors::SimulationError,
Bytes,
};
pub(crate) fn decimals_exponent(
from_decimals: u32,
to_decimals: u32,
) -> Result<i32, SimulationError> {
i32::try_from(i64::from(from_decimals) - i64::from(to_decimals)).map_err(|e| {
SimulationError::InvalidInput(
format!("Decimals exponent {from_decimals} - {to_decimals} out of range: {e}"),
None,
)
})
}
pub(crate) fn decimals_i32(decimals: u32) -> Result<i32, SimulationError> {
i32::try_from(decimals).map_err(|e| {
SimulationError::InvalidInput(format!("Decimals {decimals} out of range: {e}"), None)
})
}
pub(crate) fn decimals_scale(decimals: u32) -> f64 {
decimals_i32(decimals).map_or(f64::INFINITY, |exponent| 10f64.powi(exponent))
}
pub fn hexstring_to_vec(hexstring: &str) -> Result<Vec<u8>, SimulationError> {
let hexstring_no_prefix =
if let Some(stripped) = hexstring.strip_prefix("0x") { stripped } else { hexstring };
let bytes = hex::decode(hexstring_no_prefix).map_err(|err| {
SimulationError::FatalError(format!("Invalid hex string `{hexstring}`: {err}"))
})?;
Ok(bytes)
}
pub async fn load_all_tokens(
tycho_url: &str,
no_tls: bool,
auth_key: Option<&str>,
compression: bool,
chain: Chain,
min_quality: Option<i32>,
max_days_since_last_trade: Option<u64>,
) -> Result<HashMap<Bytes, Token>, SimulationError> {
info!("Loading tokens from Tycho...");
let rpc_url =
if no_tls { format!("http://{tycho_url}") } else { format!("https://{tycho_url}") };
let rpc_options = HttpRPCClientOptions::new()
.with_auth_key(auth_key.map(|s| s.to_string()))
.with_compression(compression);
let rpc_client = HttpRPCClient::new(rpc_url.as_str(), rpc_options)
.map_err(|err| map_rpc_error(&err, "Failed to create Tycho RPC client"))?;
let default_min_days = HashMap::from([(Chain::Base, 7_u64), (Chain::Ethereum, 30_u64)]);
let min_q = min_quality.or(Some(100));
let traded = max_days_since_last_trade.or_else(|| {
default_min_days
.get(&chain)
.or(Some(&42))
.copied()
});
let mut token_params = AllTokensParams::new(chain, RPC_CLIENT_CONCURRENCY);
if let Some(q) = min_q {
token_params = token_params.with_min_quality(q);
}
if let Some(d) = traded {
token_params = token_params.with_traded_n_days_ago(d);
}
let tokens = rpc_client
.get_all_tokens(token_params)
.await
.map_err(|err| map_rpc_error(&err, "Unable to load tokens"))?;
tokens
.into_iter()
.map(|token| Ok((token.address.clone(), token)))
.collect()
}
pub fn get_default_url(chain: &Chain) -> Option<String> {
match chain {
Chain::Ethereum => Some("tycho-beta.propellerheads.xyz".to_string()),
Chain::Base => Some("tycho-base-beta.propellerheads.xyz".to_string()),
Chain::Unichain => Some("tycho-unichain-beta.propellerheads.xyz".to_string()),
Chain::Bsc => Some("tycho-bsc-beta.propellerheads.xyz".to_string()),
Chain::Arbitrum => Some("tycho-arbitrum-beta.propellerheads.xyz".to_string()),
Chain::Polygon => Some("tycho-polygon-beta.propellerheads.xyz".to_string()),
Chain::Robinhood => Some("tycho-robinhood-beta.propellerheads.xyz".to_string()),
Chain::Starknet | Chain::ZkSync | Chain::Plasma | Chain::Arc | Chain::Custom(_) | _ => None,
}
}
pub fn load_blocklist(path: Option<&Path>) -> Result<HashSet<String>, SimulationError> {
let Some(path) = path else {
return Ok(default_blocklist());
};
let contents = fs::read_to_string(path).map_err(|e| {
SimulationError::FatalError(format!("Failed to read blocklist {:?}: {e}", path))
})?;
parse_blocklist(&contents).map_err(|e| {
SimulationError::FatalError(format!("Failed to parse blocklist {:?}: {e}", path))
})
}
pub fn default_blocklist() -> HashSet<String> {
parse_blocklist(include_str!("../blocklist.toml"))
.expect("embedded blocklist.toml is valid TOML")
}
fn parse_blocklist(contents: &str) -> Result<HashSet<String>, toml::de::Error> {
#[derive(Default, serde::Deserialize)]
struct Blocklist {
#[serde(default)]
components: HashSet<String>,
}
#[derive(serde::Deserialize)]
struct BlocklistConfig {
#[serde(default)]
blocklist: Blocklist,
}
let config: BlocklistConfig = toml::from_str(contents)?;
Ok(config.blocklist.components)
}
fn map_rpc_error(err: &RPCError, context: &str) -> SimulationError {
let message = format!("{context}: {err}", err = err,);
match err {
RPCError::UrlParsing(_, _) | RPCError::FormatRequest(_) => {
SimulationError::InvalidInput(message, None)
}
RPCError::HttpClient(..) |
RPCError::ParseResponse(_) |
RPCError::StaleBlock(_) |
RPCError::UnknownExtractor(_) |
RPCError::Fatal(_) |
RPCError::RateLimited(_) |
RPCError::ServerUnreachable(_) => SimulationError::FatalError(message),
}
}