Skip to content

Commit

Permalink
Merge pull request #33 from bcnmy/dev
Browse files Browse the repository at this point in the history
sync
  • Loading branch information
AmanRaj1608 authored Jul 16, 2024
2 parents ed63519 + 70d9f6d commit f7235be
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 15 deletions.
47 changes: 34 additions & 13 deletions crates/routing-engine/src/routing_engine.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)]
Expand All @@ -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),
}
Expand Down Expand Up @@ -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?;
Expand Down Expand Up @@ -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,
Expand All @@ -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::<Vec<_>>()
Expand Down Expand Up @@ -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))
Expand Down Expand Up @@ -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
Expand All @@ -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(),
Expand Down Expand Up @@ -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(),
Expand Down Expand Up @@ -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();
Expand Down
4 changes: 2 additions & 2 deletions crates/routing-engine/src/source/bungee/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down Expand Up @@ -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);
Expand Down

0 comments on commit f7235be

Please sign in to comment.