diff --git a/crates/routing-engine/src/routing_engine.rs b/crates/routing-engine/src/routing_engine.rs index 712ea71..c2c8d6a 100644 --- a/crates/routing-engine/src/routing_engine.rs +++ b/crates/routing-engine/src/routing_engine.rs @@ -8,13 +8,14 @@ use thiserror::Error; use tokio::sync::RwLock; use account_aggregation::{service::AccountAggregationService, types::TokenWithBalance}; -use config::{ChainConfig, config::BucketConfig, SolverConfig, TokenConfig}; +use config::{ChainConfig, Config, config::BucketConfig, SolverConfig, TokenConfig}; use storage::{KeyValueStore, RedisClient, RedisClientError}; use crate::{ BridgeResult, BridgeResultVecWrapper, estimator::{Estimator, LinearRegressionEstimator}, Route, }; +use crate::token_price::utils::get_token_price; /// (from_chain, to_chain, from_token, to_token) #[derive(Debug)] @@ -31,6 +32,9 @@ pub enum RoutingEngineError { #[error("Cache error: {0}")] CacheError(String), + #[error("Bucket not found error: chain {0} -> {1}, token: {2} -> {3}, amount: {4}")] + BucketNotFoundError(u32, u32, String, String, f64), + #[error("User balance fetch error: {0}")] UserBalanceFetchError(String), } @@ -111,6 +115,8 @@ impl RoutingEngine { debug!("Direct assets: {:?}", direct_assets); debug!("Non-direct assets: {:?}", non_direct_assets); + // let to_value_usd = + let (mut selected_routes, total_amount_needed, mut total_cost) = self .generate_optimal_routes(direct_assets, to_chain, to_token, to_value, account) .await?; @@ -153,8 +159,10 @@ impl RoutingEngine { let y = self.estimates.y_value; let mut assets_sorted_by_bridging_cost: Vec<(TokenWithBalance, f64)> = stream::iter(assets.into_iter()) - .then(|balance| async move { - let balance_taken = cmp::min_by(to_value_usd, balance.amount_in_usd, |a, b| a.partial_cmp(b).unwrap_or_else(|| cmp::Ordering::Less)); + .then(|mut balance| async move { + let balance_taken = cmp::min_by(to_value_usd, balance.amount_in_usd, |a, b| { + a.partial_cmp(b).unwrap_or_else(|| cmp::Ordering::Less) + }); let fee_cost = self .estimate_bridging_cost( balance_taken, @@ -166,6 +174,13 @@ impl RoutingEngine { ), ) .await; + + if balance.token == "ETH" { + balance.amount_in_usd -= 1.0; + } + if balance.amount_in_usd < 0.0 { + balance.amount_in_usd = 0.0; + } (balance, fee_cost) }) .collect::>() @@ -239,15 +254,21 @@ impl RoutingEngine { matches_path && matches_amount }) .ok_or_else(|| { - RoutingEngineError::CacheError("No matching bucket found".to_string()) + RoutingEngineError::BucketNotFoundError( + path.0, + path.1, + path.2.clone(), + path.3.clone(), + target_amount_in_usd, + ) })?; let key = bucket.get_hash().to_string(); let cache = self.cache.read().await; - let value = cache - .get(&key) - .ok_or_else(|| RoutingEngineError::CacheError(format!("No cached value found for {}", key)))?; + let value = cache.get(&key).ok_or_else(|| { + RoutingEngineError::CacheError(format!("No cached value found for {}", key)) + })?; let estimator: LinearRegressionEstimator = serde_json::from_str(value)?; Ok(estimator.estimate(target_amount_in_usd)) @@ -361,7 +382,7 @@ mod tests { DataPoint { x: 1.0, y: 1.0 }, DataPoint { x: 2.0, y: 2.0 }, ]) - .unwrap(); + .unwrap(); let serialized_estimator = serde_json::to_string(&dummy_estimator)?; // Create a cache with a dummy bucket @@ -376,8 +397,8 @@ mod tests { "test".to_string(), true, ) - .await - .unwrap(); + .await + .unwrap(); let aas_client = Arc::new(AccountAggregationService::new( user_db_provider.clone(), @@ -426,8 +447,8 @@ mod tests { "test".to_string(), true, ) - .await - .unwrap(); + .await + .unwrap(); let aas_client = Arc::new(AccountAggregationService::new( user_db_provider.clone(), user_db_provider.clone(), @@ -462,7 +483,7 @@ mod tests { DataPoint { x: 1.0, y: 1.0 }, DataPoint { x: 2.0, y: 2.0 }, ]) - .unwrap(); + .unwrap(); let serialized_estimator = serde_json::to_string(&dummy_estimator)?; // Create a cache with a dummy bucket let key1 = buckets[0].get_hash().to_string(); diff --git a/crates/routing-engine/src/source/bungee/mod.rs b/crates/routing-engine/src/source/bungee/mod.rs index efa0310..8e8f02d 100644 --- a/crates/routing-engine/src/source/bungee/mod.rs +++ b/crates/routing-engine/src/source/bungee/mod.rs @@ -147,7 +147,7 @@ impl RouteSource for BungeeClient { recipient_address: Option<&String>, estimation_type: &CostType, ) -> Result<(Self::BaseRouteType, f64), Self::FetchRouteCostError> { - info!("Fetching least route cost in USD for route {:?} with token amount {} and estimation type {}", route, from_token_amount, estimation_type); + info!("Fetching least route cost in USD for route {} with token amount {} and estimation type {}", route, from_token_amount, estimation_type); // Build GetQuoteRequest let from_token = route.from_token.by_chain.get(&route.from_chain.id); @@ -281,7 +281,7 @@ impl RouteSource for BungeeClient { let transactions = vec![EthereumTransaction { from_address: sender_address.clone(), - from_chain: route.to_chain.id, + from_chain: route.from_chain.id, to: tx.tx_target, value: Uint::from_str(&tx.value).map_err(|err| { error!("Error while parsing tx data: {}", err);