From 9dc5da3f3409b5d9874bef725fa53d260bf6fcf3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jose=CC=81=20Duarte?= Date: Tue, 6 Jan 2026 11:36:43 +0000 Subject: [PATCH 1/4] Migrate balancer v2 sources to alloy --- .../src/boundary/liquidity/balancer/v2/mod.rs | 12 +- .../boundary/liquidity/balancer/v2/stable.rs | 11 +- .../liquidity/balancer/v2/weighted.rs | 9 +- crates/shared/Cargo.toml | 2 +- crates/shared/src/arguments.rs | 14 +- crates/shared/src/recent_block_cache.rs | 11 ++ .../src/sources/balancer_v2/graph_api.rs | 35 ++-- crates/shared/src/sources/balancer_v2/mod.rs | 2 +- .../balancer_v2/pool_fetching/aggregate.rs | 6 +- .../balancer_v2/pool_fetching/cache.rs | 16 +- .../balancer_v2/pool_fetching/internal.rs | 6 +- .../sources/balancer_v2/pool_fetching/mod.rs | 159 ++---------------- .../balancer_v2/pool_fetching/pool_storage.rs | 63 +++---- .../balancer_v2/pool_fetching/registry.rs | 33 ++-- .../src/sources/balancer_v2/pools/common.rs | 101 +++++------ .../balancer_v2/pools/composable_stable.rs | 16 +- .../pools/liquidity_bootstrapping.rs | 12 +- .../src/sources/balancer_v2/pools/mod.rs | 4 +- .../src/sources/balancer_v2/pools/stable.rs | 27 +-- .../src/sources/balancer_v2/pools/weighted.rs | 31 ++-- .../sources/balancer_v2/swap/fixed_point.rs | 69 ++++---- .../swap/fixed_point/logexpmath.rs | 89 +++++----- .../src/sources/balancer_v2/swap/math.rs | 26 +-- .../src/sources/balancer_v2/swap/mod.rs | 79 ++++----- .../sources/balancer_v2/swap/stable_math.rs | 49 +++--- .../sources/balancer_v2/swap/weighted_math.rs | 89 ++++++---- crates/shared/src/sources/mod.rs | 32 +--- crates/solver/src/liquidity/balancer_v2.rs | 5 +- .../solvers/src/boundary/liquidity/stable.rs | 11 +- .../boundary/liquidity/weighted_product.rs | 7 +- 30 files changed, 427 insertions(+), 599 deletions(-) diff --git a/crates/driver/src/boundary/liquidity/balancer/v2/mod.rs b/crates/driver/src/boundary/liquidity/balancer/v2/mod.rs index 6ffd9bbdc6..94e217eda1 100644 --- a/crates/driver/src/boundary/liquidity/balancer/v2/mod.rs +++ b/crates/driver/src/boundary/liquidity/balancer/v2/mod.rs @@ -16,10 +16,7 @@ use { BalancerV2WeightedPoolFactory, BalancerV2WeightedPoolFactoryV3, }, - ethrpc::{ - alloy::conversions::IntoLegacy, - block_stream::{BlockRetrieving, CurrentBlockWatcher}, - }, + ethrpc::block_stream::{BlockRetrieving, CurrentBlockWatcher}, shared::{ http_solver::model::TokenAmount, sources::balancer_v2::{ @@ -181,12 +178,7 @@ async fn init_liquidity( boundary::liquidity::http_client(), web3.clone(), &contracts, - config - .pool_deny_list - .iter() - .copied() - .map(IntoLegacy::into_legacy) - .collect(), + config.pool_deny_list.iter().copied().collect(), ) .await .context("failed to create balancer pool fetcher")?, diff --git a/crates/driver/src/boundary/liquidity/balancer/v2/stable.rs b/crates/driver/src/boundary/liquidity/balancer/v2/stable.rs index 03b21b48f4..cee05abfff 100644 --- a/crates/driver/src/boundary/liquidity/balancer/v2/stable.rs +++ b/crates/driver/src/boundary/liquidity/balancer/v2/stable.rs @@ -6,7 +6,6 @@ use { liquidity::{self, balancer}, }, }, - ethrpc::alloy::conversions::IntoAlloy, solver::liquidity::{StablePoolOrder, balancer_v2}, }; @@ -28,20 +27,20 @@ pub fn to_domain(id: liquidity::Id, pool: StablePoolOrder) -> Result>()?, )?, amplification_parameter: balancer::v2::stable::AmplificationParameter::new( - pool.amplification_parameter.factor().into_alloy(), - pool.amplification_parameter.precision().into_alloy(), + pool.amplification_parameter.factor(), + pool.amplification_parameter.precision(), )?, - fee: balancer::v2::Fee::from_raw(pool.fee.as_uint256().into_alloy()), + fee: balancer::v2::Fee::from_raw(pool.fee.as_uint256()), }), }) } diff --git a/crates/driver/src/boundary/liquidity/balancer/v2/weighted.rs b/crates/driver/src/boundary/liquidity/balancer/v2/weighted.rs index 4ddba4063c..f64fc7f2fa 100644 --- a/crates/driver/src/boundary/liquidity/balancer/v2/weighted.rs +++ b/crates/driver/src/boundary/liquidity/balancer/v2/weighted.rs @@ -6,7 +6,6 @@ use { liquidity::{self, balancer}, }, }, - ethrpc::alloy::conversions::IntoAlloy, shared::sources::balancer_v2::pool_fetching::WeightedPoolVersion, solver::liquidity::{WeightedProductOrder, balancer_v2}, }; @@ -29,19 +28,19 @@ pub fn to_domain(id: liquidity::Id, pool: WeightedProductOrder) -> Result>()?, )?, - fee: balancer::v2::Fee::from_raw(pool.fee.as_uint256().into_alloy()), + fee: balancer::v2::Fee::from_raw(pool.fee.as_uint256()), version: match pool.version { WeightedPoolVersion::V0 => balancer::v2::weighted::Version::V0, WeightedPoolVersion::V3Plus => balancer::v2::weighted::Version::V3Plus, diff --git a/crates/shared/Cargo.toml b/crates/shared/Cargo.toml index 611cc7e35e..811ca23b96 100644 --- a/crates/shared/Cargo.toml +++ b/crates/shared/Cargo.toml @@ -9,7 +9,7 @@ license = "MIT OR Apache-2.0" doctest = false [dependencies] -alloy = { workspace = true, features = ["sol-types", "signer-local"] } +alloy = { workspace = true, features = ["sol-types", "signer-local", "rand"] } anyhow = { workspace = true } app-data = { workspace = true } bytes-hex = { workspace = true } diff --git a/crates/shared/src/arguments.rs b/crates/shared/src/arguments.rs index f49af4b226..59e72a6d69 100644 --- a/crates/shared/src/arguments.rs +++ b/crates/shared/src/arguments.rs @@ -4,11 +4,7 @@ use { crate::{ gas_price_estimation::GasEstimatorType, - sources::{ - BaselineSource, - balancer_v2::BalancerFactoryKind, - uniswap_v2::UniV2BaselineSourceParameters, - }, + sources::{BaselineSource, uniswap_v2::UniV2BaselineSourceParameters}, tenderly_api, }, alloy::primitives::Address, @@ -218,12 +214,6 @@ pub struct Arguments { #[clap(long, env, action = clap::ArgAction::Set, default_value = "false")] pub use_internal_buffers: bool, - /// The Balancer V2 factories to consider for indexing liquidity. Allows - /// specific pool kinds to be disabled via configuration. Will use all - /// supported Balancer V2 factory kinds if not specified. - #[clap(long, env, value_enum, ignore_case = true, use_value_delimiter = true)] - pub balancer_factories: Option>, - /// Value of the authorization header for the solver competition post api. #[clap(long, env)] pub solver_competition_auth: Option, @@ -396,7 +386,6 @@ impl Display for Arguments { pool_cache_maximum_retries, pool_cache_delay_between_retries, use_internal_buffers, - balancer_factories, solver_competition_auth, network_block_interval, settlement_contract_address, @@ -439,7 +428,6 @@ impl Display for Arguments { "pool_cache_delay_between_retries: {pool_cache_delay_between_retries:?}" )?; writeln!(f, "use_internal_buffers: {use_internal_buffers}")?; - writeln!(f, "balancer_factories: {balancer_factories:?}")?; display_secret_option( f, "solver_competition_auth", diff --git a/crates/shared/src/recent_block_cache.rs b/crates/shared/src/recent_block_cache.rs index 9b6780b744..f12555c53d 100644 --- a/crates/shared/src/recent_block_cache.rs +++ b/crates/shared/src/recent_block_cache.rs @@ -26,6 +26,7 @@ use { crate::request_sharing::BoxRequestSharing, + alloy::eips::BlockId, anyhow::{Context, Result}, cached::{Cached, SizedCache}, ethcontract::BlockNumber, @@ -84,6 +85,16 @@ impl From for BlockNumber { } } +impl From for BlockId { + fn from(value: Block) -> Self { + match value { + Block::Recent => BlockId::latest(), + Block::Number(n) => BlockId::number(n), + Block::Finalized => BlockId::finalized(), + } + } +} + /// Recent block cache for arbitrary key-value pairs. /// /// Caches on-chain data for a specific number of blocks and automatically diff --git a/crates/shared/src/sources/balancer_v2/graph_api.rs b/crates/shared/src/sources/balancer_v2/graph_api.rs index bd2f133a85..a9d1943241 100644 --- a/crates/shared/src/sources/balancer_v2/graph_api.rs +++ b/crates/shared/src/sources/balancer_v2/graph_api.rs @@ -11,9 +11,8 @@ use { super::swap::fixed_point::Bfp, crate::{event_handling::MAX_REORG_BLOCK_COUNT, subgraph::SubgraphClient}, - alloy::primitives::Address, + alloy::primitives::{Address, B256}, anyhow::Result, - ethcontract::H256, reqwest::{Client, Url}, serde::Deserialize, serde_json::json, @@ -50,7 +49,7 @@ impl BalancerSubgraphClient { let block_number = self.get_safe_block().await?; let mut pools = Vec::new(); - let mut last_id = H256::default(); + let mut last_id = B256::default(); // We do paging by last ID instead of using `skip`. This is the // suggested approach to paging best performance: @@ -148,7 +147,7 @@ impl RegisteredPools { #[serde(rename_all = "camelCase")] pub struct PoolData { pub pool_type: PoolType, - pub id: H256, + pub id: B256, pub address: Address, pub factory: Address, pub swap_enabled: bool, @@ -245,7 +244,7 @@ mod tests { use { super::*, crate::sources::balancer_v2::swap::fixed_point::Bfp, - ethcontract::H256, + alloy::primitives::U256, maplit::hashmap, }; @@ -335,7 +334,7 @@ mod tests { pools: vec![ PoolData { pool_type: PoolType::Weighted, - id: H256([0x11; 32]), + id: B256::repeat_byte(0x11), address: Address::repeat_byte(0x22), factory: Address::repeat_byte(0x55), swap_enabled: true, @@ -343,18 +342,22 @@ mod tests { Token { address: Address::repeat_byte(0x33), decimals: 3, - weight: Some(Bfp::from_wei(500_000_000_000_000_000u128.into())), + weight: Some(Bfp::from_wei(U256::from( + 500_000_000_000_000_000u128 + ))), }, Token { address: Address::repeat_byte(0x44), decimals: 4, - weight: Some(Bfp::from_wei(500_000_000_000_000_000u128.into())), + weight: Some(Bfp::from_wei(U256::from( + 500_000_000_000_000_000u128 + ))), }, ], }, PoolData { pool_type: PoolType::Stable, - id: H256([0x11; 32]), + id: B256::repeat_byte(0x11), address: Address::repeat_byte(0x22), factory: Address::repeat_byte(0x55), swap_enabled: true, @@ -373,7 +376,7 @@ mod tests { }, PoolData { pool_type: PoolType::LiquidityBootstrapping, - id: H256([0x11; 32]), + id: B256::repeat_byte(0x11), address: Address::repeat_byte(0x22), factory: Address::repeat_byte(0x55), swap_enabled: true, @@ -381,18 +384,22 @@ mod tests { Token { address: Address::repeat_byte(0x33), decimals: 3, - weight: Some(Bfp::from_wei(500_000_000_000_000_000u128.into())), + weight: Some(Bfp::from_wei(U256::from( + 500_000_000_000_000_000u128 + ))), }, Token { address: Address::repeat_byte(0x44), decimals: 4, - weight: Some(Bfp::from_wei(500_000_000_000_000_000u128.into())), + weight: Some(Bfp::from_wei(U256::from( + 500_000_000_000_000_000u128 + ))), }, ], }, PoolData { pool_type: PoolType::ComposableStable, - id: H256([0x11; 32]), + id: B256::repeat_byte(0x11), address: Address::repeat_byte(0x22), factory: Address::repeat_byte(0x55), swap_enabled: true, @@ -438,7 +445,7 @@ mod tests { #[test] fn groups_pools_by_factory() { let pool = |factory: Address, id: u8| PoolData { - id: H256([id; 32]), + id: B256::repeat_byte(id), factory, pool_type: PoolType::Weighted, address: Default::default(), diff --git a/crates/shared/src/sources/balancer_v2/mod.rs b/crates/shared/src/sources/balancer_v2/mod.rs index 22b179b266..b9b4a9de5c 100644 --- a/crates/shared/src/sources/balancer_v2/mod.rs +++ b/crates/shared/src/sources/balancer_v2/mod.rs @@ -44,6 +44,6 @@ pub mod pools; pub mod swap; pub use self::{ - pool_fetching::{BalancerFactoryKind, BalancerPoolFetcher, BalancerPoolFetching}, + pool_fetching::{BalancerPoolFetcher, BalancerPoolFetching}, pools::{Pool, PoolKind}, }; diff --git a/crates/shared/src/sources/balancer_v2/pool_fetching/aggregate.rs b/crates/shared/src/sources/balancer_v2/pool_fetching/aggregate.rs index 525ca54ec9..cfa35d273a 100644 --- a/crates/shared/src/sources/balancer_v2/pool_fetching/aggregate.rs +++ b/crates/shared/src/sources/balancer_v2/pool_fetching/aggregate.rs @@ -4,8 +4,8 @@ use { super::internal::InternalPoolFetching, crate::{recent_block_cache::Block, sources::balancer_v2::pools::Pool}, + alloy::primitives::B256, anyhow::Result, - ethcontract::H256, futures::future, model::TokenPair, std::collections::HashSet, @@ -25,7 +25,7 @@ impl Aggregate { #[async_trait::async_trait] impl InternalPoolFetching for Aggregate { - async fn pool_ids_for_token_pairs(&self, token_pairs: HashSet) -> HashSet { + async fn pool_ids_for_token_pairs(&self, token_pairs: HashSet) -> HashSet { future::join_all( self.fetchers .iter() @@ -37,7 +37,7 @@ impl InternalPoolFetching for Aggregate { .collect() } - async fn pools_by_id(&self, pool_ids: HashSet, block: Block) -> Result> { + async fn pools_by_id(&self, pool_ids: HashSet, block: Block) -> Result> { Ok(future::try_join_all( self.fetchers .iter() diff --git a/crates/shared/src/sources/balancer_v2/pool_fetching/cache.rs b/crates/shared/src/sources/balancer_v2/pool_fetching/cache.rs index a79d6dd390..92cd6f9a95 100644 --- a/crates/shared/src/sources/balancer_v2/pool_fetching/cache.rs +++ b/crates/shared/src/sources/balancer_v2/pool_fetching/cache.rs @@ -9,14 +9,14 @@ use { recent_block_cache::{Block, CacheConfig, CacheFetching, CacheKey, RecentBlockCache}, sources::balancer_v2::pools::Pool, }, + alloy::primitives::B256, anyhow::Result, - ethcontract::H256, ethrpc::block_stream::CurrentBlockWatcher, std::{collections::HashSet, sync::Arc}, }; /// Internal type alias used for inner recent block cache. -type PoolCache = RecentBlockCache>; +type PoolCache = RecentBlockCache>; /// A cached pool fetcher that wraps an inner `InternalPoolFetching` /// implementation. @@ -52,18 +52,18 @@ where async fn pool_ids_for_token_pairs( &self, token_pairs: HashSet, - ) -> HashSet { + ) -> HashSet { self.inner.pool_ids_for_token_pairs(token_pairs).await } - async fn pools_by_id(&self, pool_ids: HashSet, block: Block) -> Result> { + async fn pools_by_id(&self, pool_ids: HashSet, block: Block) -> Result> { self.cache.fetch(pool_ids, block).await } } -impl CacheKey for H256 { +impl CacheKey for B256 { fn first_ord() -> Self { - H256::zero() + B256::ZERO } fn for_value(pool: &Pool) -> Self { @@ -79,11 +79,11 @@ impl CacheKey for H256 { struct CacheFetcher(Arc); #[async_trait::async_trait] -impl CacheFetching for CacheFetcher +impl CacheFetching for CacheFetcher where Inner: InternalPoolFetching, { - async fn fetch_values(&self, pool_ids: HashSet, at_block: Block) -> Result> { + async fn fetch_values(&self, pool_ids: HashSet, at_block: Block) -> Result> { self.0.pools_by_id(pool_ids, at_block).await } } diff --git a/crates/shared/src/sources/balancer_v2/pool_fetching/internal.rs b/crates/shared/src/sources/balancer_v2/pool_fetching/internal.rs index 944fa00850..6413b4c8b1 100644 --- a/crates/shared/src/sources/balancer_v2/pool_fetching/internal.rs +++ b/crates/shared/src/sources/balancer_v2/pool_fetching/internal.rs @@ -3,8 +3,8 @@ use { crate::{recent_block_cache::Block, sources::balancer_v2::pools::Pool}, + alloy::primitives::B256, anyhow::Result, - ethcontract::H256, model::TokenPair, std::collections::HashSet, }; @@ -16,8 +16,8 @@ use { #[async_trait::async_trait] pub trait InternalPoolFetching: Send + Sync + 'static { /// Retrives all pool IDs that trade the specified pairs. - async fn pool_ids_for_token_pairs(&self, token_pairs: HashSet) -> HashSet; + async fn pool_ids_for_token_pairs(&self, token_pairs: HashSet) -> HashSet; /// Fetches current pool states for the specified IDs and block. - async fn pools_by_id(&self, pool_ids: HashSet, block: Block) -> Result>; + async fn pools_by_id(&self, pool_ids: HashSet, block: Block) -> Result>; } diff --git a/crates/shared/src/sources/balancer_v2/pool_fetching/mod.rs b/crates/shared/src/sources/balancer_v2/pool_fetching/mod.rs index 1edc53cf44..1f6454693a 100644 --- a/crates/shared/src/sources/balancer_v2/pool_fetching/mod.rs +++ b/crates/shared/src/sources/balancer_v2/pool_fetching/mod.rs @@ -36,7 +36,6 @@ use { providers::{DynProvider, Provider}, }, anyhow::{Context, Result}, - clap::ValueEnum, contracts::alloy::{ BalancerV2ComposableStablePoolFactory, BalancerV2ComposableStablePoolFactoryV3, @@ -52,7 +51,6 @@ use { BalancerV2WeightedPoolFactoryV3, BalancerV2WeightedPoolFactoryV4, }, - ethcontract::H256, ethrpc::{ alloy::conversions::IntoLegacy, block_stream::{BlockRetrieving, CurrentBlockWatcher}, @@ -83,7 +81,7 @@ pub trait BalancerPoolEvaluating { #[derive(Clone, Debug)] pub struct CommonPoolState { - pub id: H256, + pub id: B256, pub address: Address, pub swap_fee: Bfp, pub paused: bool, @@ -97,7 +95,7 @@ pub struct WeightedPool { } impl WeightedPool { - pub fn new_unpaused(pool_id: H256, weighted_state: weighted::PoolState) -> Self { + pub fn new_unpaused(pool_id: B256, weighted_state: weighted::PoolState) -> Self { WeightedPool { common: CommonPoolState { id: pool_id, @@ -119,7 +117,7 @@ pub struct StablePool { } impl StablePool { - pub fn new_unpaused(pool_id: H256, stable_state: stable::PoolState) -> Self { + pub fn new_unpaused(pool_id: B256, stable_state: stable::PoolState) -> Self { StablePool { common: CommonPoolState { id: pool_id, @@ -172,25 +170,7 @@ pub struct BalancerPoolFetcher { // being problematic because their token balance becomes out of sync leading to simulation // failures. // https://forum.balancer.fi/t/medium-severity-bug-found/3161 - pool_id_deny_list: Vec, -} - -/// An enum containing all supported Balancer factory types. -#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, ValueEnum)] -#[clap(rename_all = "verbatim")] -pub enum BalancerFactoryKind { - Weighted, - WeightedV3, - WeightedV4, - Weighted2Token, - StableV2, - LiquidityBootstrapping, - NoProtocolFeeLiquidityBootstrapping, - ComposableStable, - ComposableStableV3, - ComposableStableV4, - ComposableStableV5, - ComposableStableV6, + pool_id_deny_list: Vec, } pub enum BalancerFactoryInstance { @@ -250,128 +230,12 @@ impl BalancerFactoryInstance { } } -impl BalancerFactoryKind { - /// Returns a vector with supported factories for the specified chain ID. - pub fn for_chain(chain_id: u64) -> Vec { - match chain_id { - 1 => Self::value_variants().to_owned(), - 5 => vec![ - Self::Weighted, - Self::WeightedV3, - Self::WeightedV4, - Self::Weighted2Token, - Self::StableV2, - Self::ComposableStable, - Self::ComposableStableV3, - Self::ComposableStableV4, - Self::ComposableStableV5, - Self::ComposableStableV6, - ], - 100 => vec![ - Self::WeightedV3, - Self::WeightedV4, - Self::StableV2, - Self::ComposableStableV3, - Self::ComposableStableV4, - Self::ComposableStableV5, - Self::ComposableStableV6, - ], - 11155111 => vec![ - Self::WeightedV4, - Self::ComposableStableV4, - Self::ComposableStableV5, - Self::ComposableStableV6, - Self::NoProtocolFeeLiquidityBootstrapping, - ], - _ => Default::default(), - } - } -} - /// All balancer related contracts that we expect to exist. pub struct BalancerContracts { pub vault: BalancerV2Vault::Instance, pub factories: Vec, } -impl BalancerContracts { - pub async fn try_new(web3: &Web3, factory_kinds: Vec) -> Result { - let web3 = ethrpc::instrumented::instrument_with_label(web3, "balancerV2".into()); - let vault = BalancerV2Vault::Instance::deployed(&web3.alloy) - .await - .context("Cannot retrieve balancer vault")?; - - macro_rules! instance { - ($factory:ident) => {{ - $factory::Instance::deployed(&web3.alloy) - .await - .context(format!( - "Cannot retrieve Balancer factory {}", - stringify!($factory) - ))? - }}; - } - - let mut factories = Vec::new(); - for kind in factory_kinds { - let instance = match &kind { - BalancerFactoryKind::Weighted => { - BalancerFactoryInstance::Weighted(instance!(BalancerV2WeightedPoolFactory)) - } - BalancerFactoryKind::WeightedV3 => { - BalancerFactoryInstance::WeightedV3(instance!(BalancerV2WeightedPoolFactoryV3)) - } - BalancerFactoryKind::WeightedV4 => { - BalancerFactoryInstance::WeightedV4(instance!(BalancerV2WeightedPoolFactoryV4)) - } - BalancerFactoryKind::Weighted2Token => BalancerFactoryInstance::Weighted2Token( - instance!(BalancerV2WeightedPool2TokensFactory), - ), - BalancerFactoryKind::StableV2 => { - BalancerFactoryInstance::StableV2(instance!(BalancerV2StablePoolFactoryV2)) - } - BalancerFactoryKind::LiquidityBootstrapping => { - BalancerFactoryInstance::LiquidityBootstrapping(instance!( - BalancerV2LiquidityBootstrappingPoolFactory - )) - } - BalancerFactoryKind::NoProtocolFeeLiquidityBootstrapping => { - BalancerFactoryInstance::NoProtocolFeeLiquidityBootstrapping(instance!( - BalancerV2NoProtocolFeeLiquidityBootstrappingPoolFactory - )) - } - BalancerFactoryKind::ComposableStable => BalancerFactoryInstance::ComposableStable( - instance!(BalancerV2ComposableStablePoolFactory), - ), - BalancerFactoryKind::ComposableStableV3 => { - BalancerFactoryInstance::ComposableStableV3(instance!( - BalancerV2ComposableStablePoolFactoryV3 - )) - } - BalancerFactoryKind::ComposableStableV4 => { - BalancerFactoryInstance::ComposableStableV4(instance!( - BalancerV2ComposableStablePoolFactoryV4 - )) - } - BalancerFactoryKind::ComposableStableV5 => { - BalancerFactoryInstance::ComposableStableV5(instance!( - BalancerV2ComposableStablePoolFactoryV5 - )) - } - BalancerFactoryKind::ComposableStableV6 => { - BalancerFactoryInstance::ComposableStableV6(instance!( - BalancerV2ComposableStablePoolFactoryV6 - )) - } - }; - - factories.push(instance); - } - - Ok(Self { vault, factories }) - } -} - impl BalancerPoolFetcher { #[expect(clippy::too_many_arguments)] pub async fn new( @@ -383,7 +247,7 @@ impl BalancerPoolFetcher { client: Client, web3: Web3, contracts: &BalancerContracts, - deny_listed_pool_ids: Vec, + deny_listed_pool_ids: Vec, ) -> Result { let pool_initializer = BalancerSubgraphClient::from_subgraph_url(subgraph_url, client)?; let web3 = ethrpc::instrumented::instrument_with_label(&web3, "balancerV2".into()); @@ -590,20 +454,23 @@ where /// the pool. For example the GNO-BAL pool with ID /// `0x36128d5436d2d70cab39c9af9cce146c38554ff0000200000000000000000009`: /// -fn pool_address_from_id(pool_id: H256) -> Address { - Address::from_slice(&pool_id.0[..20]) +fn pool_address_from_id(pool_id: B256) -> Address { + Address::from_slice(&pool_id.as_slice()[..20]) } #[cfg(test)] mod tests { - use {super::*, alloy::primitives::address, hex_literal::hex}; + use { + super::*, + alloy::primitives::{address, b256}, + }; #[test] fn can_extract_address_from_pool_id() { assert_eq!( - pool_address_from_id(H256(hex!( + pool_address_from_id(b256!( "36128d5436d2d70cab39c9af9cce146c38554ff0000200000000000000000009" - ))), + )), address!("36128d5436d2d70cab39c9af9cce146c38554ff0"), ); } diff --git a/crates/shared/src/sources/balancer_v2/pool_fetching/pool_storage.rs b/crates/shared/src/sources/balancer_v2/pool_fetching/pool_storage.rs index a986bbe877..a8cc176d9a 100644 --- a/crates/shared/src/sources/balancer_v2/pool_fetching/pool_storage.rs +++ b/crates/shared/src/sources/balancer_v2/pool_fetching/pool_storage.rs @@ -20,13 +20,15 @@ use { event_handling::EventStoring, sources::balancer_v2::pools::{FactoryIndexing, PoolIndexing, common}, }, - alloy::{primitives::Address, rpc::types::Log}, + alloy::{ + primitives::{Address, B256}, + rpc::types::Log, + }, anyhow::{Context, Result}, contracts::alloy::BalancerV2BasePoolFactory::BalancerV2BasePoolFactory::{ BalancerV2BasePoolFactoryEvents, PoolCreated, }, - ethcontract::H256, ethrpc::block_stream::RangeInclusive, model::TokenPair, std::{ @@ -44,9 +46,9 @@ where /// Component used to fetch pool information. pool_info_fetcher: Arc>, /// Used for O(1) access to all pool_ids for a given token - pools_by_token: HashMap>, + pools_by_token: HashMap>, /// All indexed pool infos by ID. - pools: HashMap, + pools: HashMap, /// The block the initial pools were fetched on. This block is considered /// reorg-safe and events prior to this block do not get replaced. initial_fetched_block: u64, @@ -81,7 +83,7 @@ where fn pool_ids_for_token_pair( &self, token_pair: &TokenPair, - ) -> impl Iterator + '_ + use<'_, Factory> { + ) -> impl Iterator + '_ + use<'_, Factory> { let (token0, token1) = token_pair.get(); let pools0 = self.pools_by_token.get(&token0); @@ -96,7 +98,7 @@ where /// Given a collection of `TokenPair`, returns all pools containing at least /// one of the pairs. - pub fn pool_ids_for_token_pairs(&self, token_pairs: &HashSet) -> HashSet { + pub fn pool_ids_for_token_pairs(&self, token_pairs: &HashSet) -> HashSet { token_pairs .iter() .flat_map(|pair| self.pool_ids_for_token_pair(pair)) @@ -104,12 +106,12 @@ where } /// Returns a pool by ID or none if no such pool exists. - pub fn pool_by_id(&self, pool_id: H256) -> Option<&Factory::PoolInfo> { + pub fn pool_by_id(&self, pool_id: B256) -> Option<&Factory::PoolInfo> { self.pools.get(&pool_id) } /// Returns all pool infos by their IDs. - pub fn pools_by_id(&self, pool_ids: &HashSet) -> Vec { + pub fn pools_by_id(&self, pool_ids: &HashSet) -> Vec { pool_ids .iter() .filter_map(|pool_id| self.pool_by_id(*pool_id)) @@ -233,22 +235,23 @@ mod tests { pools::{MockFactoryIndexing, common::MockPoolInfoFetching, weighted}, swap::fixed_point::Bfp, }, + alloy::primitives::U256, maplit::{hashmap, hashset}, mockall::predicate::eq, }; pub type PoolInitData = ( - Vec, + Vec, Vec
, Vec
, Vec, Vec<(PoolCreated, u64)>, ); - // This can be made cleaner by making the start and end be u8's but the H256 + // This can be made cleaner by making the start and end be u8's but theB256 // doesn't support for a from(u8) so this needs to be reviewed upon migration fn pool_init_data(start: usize, end: usize) -> PoolInitData { - let pool_ids: Vec = (start..=end) - .map(|i| H256::from_low_u64_be(i as u64)) + let pool_ids: Vec = (start..=end) + .map(|i| B256::left_padding_from(&i.to_be_bytes())) .collect(); let pool_addresses: Vec
= (start..=end) .map(|i| Address::with_last_byte(i as u8)) @@ -256,7 +259,9 @@ mod tests { let tokens: Vec
= (start..=end + 1) .map(|i| Address::with_last_byte(i as u8)) .collect(); - let weights: Vec = (start..=end + 1).map(|i| Bfp::from_wei(i.into())).collect(); + let weights: Vec = (start..=end + 1) + .map(|i| Bfp::from_wei(U256::from(i))) + .collect(); let creation_events: Vec<(PoolCreated, u64)> = (start..=end) .map(|i| { ( @@ -277,20 +282,20 @@ mod tests { vec![ weighted::PoolInfo { common: common::PoolInfo { - id: H256([1; 32]), + id: B256::repeat_byte(1), address: Address::repeat_byte(1), tokens: vec![Address::repeat_byte(0x11), Address::repeat_byte(0x22)], scaling_factors: vec![Bfp::exp10(0), Bfp::exp10(0)], block_created: 0, }, weights: vec![ - Bfp::from_wei(500_000_000_000_000_000u128.into()), - Bfp::from_wei(500_000_000_000_000_000u128.into()), + Bfp::from_wei(U256::from(500_000_000_000_000_000u128)), + Bfp::from_wei(U256::from(500_000_000_000_000_000u128)), ], }, weighted::PoolInfo { common: common::PoolInfo { - id: H256([2; 32]), + id: B256::repeat_byte(2), address: Address::repeat_byte(2), tokens: vec![ Address::repeat_byte(0x11), @@ -301,22 +306,22 @@ mod tests { block_created: 0, }, weights: vec![ - Bfp::from_wei(500_000_000_000_000_000u128.into()), - Bfp::from_wei(250_000_000_000_000_000u128.into()), - Bfp::from_wei(250_000_000_000_000_000u128.into()), + Bfp::from_wei(U256::from(500_000_000_000_000_000u128)), + Bfp::from_wei(U256::from(250_000_000_000_000_000u128)), + Bfp::from_wei(U256::from(250_000_000_000_000_000u128)), ], }, weighted::PoolInfo { common: common::PoolInfo { - id: H256([3; 32]), + id: B256::repeat_byte(3), address: Address::repeat_byte(3), tokens: vec![Address::repeat_byte(0x11), Address::repeat_byte(0x77)], scaling_factors: vec![Bfp::exp10(0), Bfp::exp10(0)], block_created: 0, }, weights: vec![ - Bfp::from_wei(500_000_000_000_000_000u128.into()), - Bfp::from_wei(500_000_000_000_000_000u128.into()), + Bfp::from_wei(U256::from(500_000_000_000_000_000u128)), + Bfp::from_wei(U256::from(500_000_000_000_000_000u128)), ], }, ], @@ -326,10 +331,10 @@ mod tests { assert_eq!( storage.pools_by_token, hashmap! { - Address::repeat_byte(0x11) => hashset![H256([1; 32]), H256([2; 32]), H256([3; 32])], - Address::repeat_byte(0x22) => hashset![H256([1; 32])], - Address::repeat_byte(0x33) => hashset![H256([2; 32])], - Address::repeat_byte(0x77) => hashset![H256([2; 32]), H256([3; 32])], + Address::repeat_byte(0x11) => hashset![B256::repeat_byte(1), B256::repeat_byte(2), B256::repeat_byte(3)], + Address::repeat_byte(0x22) => hashset![B256::repeat_byte(1)], + Address::repeat_byte(0x33) => hashset![B256::repeat_byte(2)], + Address::repeat_byte(0x77) => hashset![B256::repeat_byte(2), B256::repeat_byte(3)], } ); } @@ -438,13 +443,13 @@ mod tests { let new_pool = weighted::PoolInfo { common: common::PoolInfo { - id: H256::from_low_u64_be(43110), + id: B256::left_padding_from(&43110u64.to_be_bytes()), address: Address::with_last_byte(42), tokens: vec![Address::left_padding_from(808u64.to_be_bytes().as_slice())], scaling_factors: vec![Bfp::exp10(0)], block_created: 3, }, - weights: vec![Bfp::from_wei(1337.into())], + weights: vec![Bfp::from_wei(U256::from(1337))], }; let new_creation = PoolCreated { pool: new_pool.common.address, diff --git a/crates/shared/src/sources/balancer_v2/pool_fetching/registry.rs b/crates/shared/src/sources/balancer_v2/pool_fetching/registry.rs index 78970a2701..824822a950 100644 --- a/crates/shared/src/sources/balancer_v2/pool_fetching/registry.rs +++ b/crates/shared/src/sources/balancer_v2/pool_fetching/registry.rs @@ -14,17 +14,17 @@ use { }, BalancerV2BasePoolFactory::BalancerV2BasePoolFactory::BalancerV2BasePoolFactoryEvents, alloy::{ + primitives::B256, providers::DynProvider, rpc::types::{Filter, FilterSet, Log}, sol_types::SolEvent, }, anyhow::Result, - contracts::{ - alloy::BalancerV2BasePoolFactory::{self, BalancerV2BasePoolFactory::PoolCreated}, - errors::EthcontractErrorType, + contracts::alloy::BalancerV2BasePoolFactory::{self, BalancerV2BasePoolFactory::PoolCreated}, + ethrpc::{ + alloy::errors::ContractErrorExt, + block_stream::{BlockNumberHash, BlockRetrieving}, }, - ethcontract::{BlockId, H256, errors::MethodError}, - ethrpc::block_stream::{BlockNumberHash, BlockRetrieving}, futures::future, model::TokenPair, std::{collections::HashSet, sync::Arc}, @@ -98,7 +98,7 @@ impl InternalPoolFetching for Registry where Factory: FactoryIndexing, { - async fn pool_ids_for_token_pairs(&self, token_pairs: HashSet) -> HashSet { + async fn pool_ids_for_token_pairs(&self, token_pairs: HashSet) -> HashSet { self.updater .lock() .await @@ -106,13 +106,11 @@ where .pool_ids_for_token_pairs(&token_pairs) } - async fn pools_by_id(&self, pool_ids: HashSet, block: Block) -> Result> { - let block = BlockId::Number(block.into()); - + async fn pools_by_id(&self, pool_ids: HashSet, block: Block) -> Result> { let pool_infos = self.updater.lock().await.store().pools_by_id(&pool_ids); let pool_futures = pool_infos .into_iter() - .map(|pool_info| self.fetcher.fetch_pool(&pool_info, block)) + .map(|pool_info| self.fetcher.fetch_pool(&pool_info, block.into())) .collect::>(); let pools = future::join_all(pool_futures).await; @@ -148,20 +146,15 @@ fn collect_pool_results(pools: Vec>) -> Result> { .into_iter() .filter_map(|pool| match pool { Ok(pool) => Some(Ok(pool.active()?)), - Err(err) if is_contract_error(&err) => None, - Err(err) => Some(Err(err)), + // Error issued by the contract alloy contract calls + Err(err) => match err.downcast_ref::() { + Some(err) if err.is_contract_error() => None, + _ => Some(Err(err)), + }, }) .collect() } -fn is_contract_error(err: &anyhow::Error) -> bool { - matches!( - err.downcast_ref::() - .map(EthcontractErrorType::classify), - Some(EthcontractErrorType::Contract), - ) -} - #[cfg(test)] mod tests { use { diff --git a/crates/shared/src/sources/balancer_v2/pools/common.rs b/crates/shared/src/sources/balancer_v2/pools/common.rs index 559e23b05b..bd84d77f5f 100644 --- a/crates/shared/src/sources/balancer_v2/pools/common.rs +++ b/crates/shared/src/sources/balancer_v2/pools/common.rs @@ -9,11 +9,12 @@ use { }, token_info::TokenInfoFetching, }, - alloy::primitives::Address, + alloy::{ + eips::BlockId, + primitives::{Address, B256, U256}, + }, anyhow::{Context, Result, anyhow, ensure}, contracts::alloy::{BalancerV2BasePool, BalancerV2Vault}, - ethcontract::{BlockId, H256, U256}, - ethrpc::alloy::conversions::{IntoAlloy, IntoLegacy}, futures::{FutureExt as _, future::BoxFuture}, std::{collections::BTreeMap, future::Future, sync::Arc}, tokio::sync::oneshot, @@ -89,7 +90,7 @@ impl PoolInfoFetcher { ) -> Result { let pool = self.base_pool_at(pool_address); - let pool_id = pool.getPoolId().call().await?.into_legacy(); + let pool_id = pool.getPoolId().call().await?; let tokens = self .vault .getPoolTokens(pool_id.0.into()) @@ -112,7 +113,6 @@ impl PoolInfoFetcher { pool: &PoolInfo, block: BlockId, ) -> BoxFuture<'static, Result> { - let block = block.into_alloy(); let pool_address = pool.address; let pool_id = pool.id; let vault = self.vault.clone(); @@ -150,7 +150,7 @@ impl PoolInfoFetcher { async move { let (paused, swap_fee, pool_tokens) = futures::try_join!(fetch_paused, fetch_swap_fee, pool_tokens)?; - let swap_fee = Bfp::from_wei(swap_fee.into_legacy()); + let swap_fee = Bfp::from_wei(swap_fee); let balances = pool_tokens.balances; let tokens = pool_tokens.tokens.into_iter().collect::>(); @@ -160,7 +160,7 @@ impl PoolInfoFetcher { ( address, TokenState { - balance: balance.into_legacy(), + balance, scaling_factor, }, ) @@ -227,7 +227,7 @@ where /// Common pool data shared across all Balancer pools. #[derive(Clone, Debug, Default, Eq, PartialEq)] pub struct PoolInfo { - pub id: H256, + pub id: B256, pub address: Address, pub tokens: Vec
, pub scaling_factors: Vec, @@ -371,11 +371,9 @@ mod tests { }, anyhow::bail, contracts::alloy::BalancerV2Vault, - ethcontract::U256, maplit::{btreemap, hashmap}, mockall::predicate, std::future, - web3::types::BlockNumber, }; #[tokio::test] @@ -401,7 +399,7 @@ mod tests { &BalancerV2Vault::BalancerV2Vault::getPoolTokensReturn { tokens: tokens.to_vec(), balances: vec![], - lastChangeBlock: U256::zero().into_alloy(), + lastChangeBlock: U256::ZERO, }, ); asserter.push_success(&get_pool_tokens_response); @@ -431,7 +429,7 @@ mod tests { assert_eq!( pool_info, PoolInfo { - id: pool_id.into_legacy(), + id: pool_id, address: *pool.address(), tokens: tokens.to_vec(), scaling_factors: vec![Bfp::exp10(0), Bfp::exp10(0), Bfp::exp10(12)], @@ -442,7 +440,7 @@ mod tests { #[tokio::test] async fn fetch_common_pool_state() { - let pool_id = H256([0x90; 32]); + let pool_id = B256::repeat_byte(0x90); let tokens = [ Address::repeat_byte(1), Address::repeat_byte(2), @@ -463,14 +461,14 @@ mod tests { BalancerV2BasePool::BalancerV2BasePool::getPausedStateCall::abi_encode_returns( &BalancerV2BasePool::BalancerV2BasePool::getPausedStateReturn { paused: false, - pauseWindowEndTime: U256::zero().into_alloy(), - bufferPeriodEndTime: U256::zero().into_alloy(), + pauseWindowEndTime: U256::ZERO, + bufferPeriodEndTime: U256::ZERO, }, ); asserter.push_success(&get_paused_state_response); let get_swap_fee_percentage_response = BalancerV2BasePool::BalancerV2BasePool::getSwapFeePercentageCall::abi_encode_returns( - &bfp!("0.003").as_uint256().into_alloy(), + &bfp!("0.003").as_uint256(), ); asserter.push_success(&get_swap_fee_percentage_response); @@ -478,11 +476,8 @@ mod tests { BalancerV2Vault::BalancerV2Vault::getPoolTokensCall::abi_encode_returns( &BalancerV2Vault::BalancerV2Vault::getPoolTokensReturn { tokens: tokens.to_vec(), - balances: balances - .iter() - .map(|b| b.as_uint256().into_alloy()) - .collect(), - lastChangeBlock: U256::zero().into_alloy(), + balances: balances.iter().map(|b| b.as_uint256()).collect(), + lastChangeBlock: U256::ZERO, }, ); asserter.push_success(&get_pool_tokens_response); @@ -503,10 +498,8 @@ mod tests { }; let pool_state = { - let pool_state = pool_info_fetcher.fetch_common_pool_state( - &pool_info, - BlockId::Number(BlockNumber::Number(1.into())), - ); + let pool_state = + pool_info_fetcher.fetch_common_pool_state(&pool_info, BlockId::Number(1.into())); pool_state.await.unwrap() }; @@ -554,15 +547,15 @@ mod tests { BalancerV2BasePool::BalancerV2BasePool::getPausedStateCall::abi_encode_returns( &BalancerV2BasePool::BalancerV2BasePool::getPausedStateReturn { paused: false, - pauseWindowEndTime: U256::zero().into_alloy(), - bufferPeriodEndTime: U256::zero().into_alloy(), + pauseWindowEndTime: U256::ZERO, + bufferPeriodEndTime: U256::ZERO, }, ); asserter.push_success(&get_paused_state_response); let get_swap_fee_percentage_response = BalancerV2BasePool::BalancerV2BasePool::getSwapFeePercentageCall::abi_encode_returns( - &U256::zero().into_alloy(), + &U256::ZERO, ); asserter.push_success(&get_swap_fee_percentage_response); @@ -570,8 +563,8 @@ mod tests { BalancerV2Vault::BalancerV2Vault::getPoolTokensCall::abi_encode_returns( &BalancerV2Vault::BalancerV2Vault::getPoolTokensReturn { tokens: vec![Address::repeat_byte(1), Address::repeat_byte(4)], - balances: vec![U256::zero().into_alloy(), U256::zero().into_alloy()], - lastChangeBlock: U256::zero().into_alloy(), + balances: vec![U256::ZERO, U256::ZERO], + lastChangeBlock: U256::ZERO, }, ); asserter.push_success(&get_pool_tokens_response); @@ -592,10 +585,8 @@ mod tests { }; let pool_state = { - let pool_state = pool_info_fetcher.fetch_common_pool_state( - &pool_info, - BlockId::Number(BlockNumber::Number(1.into())), - ); + let pool_state = + pool_info_fetcher.fetch_common_pool_state(&pool_info, BlockId::Number(1.into())); pool_state.await }; @@ -619,20 +610,20 @@ mod tests { BalancerV2BasePool::BalancerV2BasePool::getPausedStateCall::abi_encode_returns( &BalancerV2BasePool::BalancerV2BasePool::getPausedStateReturn { paused: false, - pauseWindowEndTime: U256::zero().into_alloy(), - bufferPeriodEndTime: U256::zero().into_alloy(), + pauseWindowEndTime: U256::ZERO, + bufferPeriodEndTime: U256::ZERO, }, ); asserter.push_success(&get_paused_state_response); let get_swap_fee_percentage_response = BalancerV2BasePool::BalancerV2BasePool::getSwapFeePercentageCall::abi_encode_returns( - &swap_fee.as_uint256().into_alloy(), + &swap_fee.as_uint256(), ); asserter.push_success(&get_swap_fee_percentage_response); let pool_info = weighted::PoolInfo { common: PoolInfo { - id: H256([0x90; 32]), + id: B256::repeat_byte(0x90), address: *pool.address(), tokens: vec![ Address::repeat_byte(1), @@ -679,15 +670,15 @@ mod tests { balances: pool_state .tokens .values() - .map(|token| token.common.balance.into_alloy()) + .map(|token| token.common.balance) .collect(), - lastChangeBlock: U256::zero().into_alloy(), + lastChangeBlock: U256::ZERO, }, ); asserter.push_success(&get_pool_tokens_response); let mut factory = MockFactoryIndexing::new(); - let block_id = BlockId::Number(BlockNumber::Number(1.into())); + let block_id = BlockId::Number(1.into()); factory .expect_fetch_pool_state() .with( @@ -734,15 +725,15 @@ mod tests { BalancerV2BasePool::BalancerV2BasePool::getPausedStateCall::abi_encode_returns( &BalancerV2BasePool::BalancerV2BasePool::getPausedStateReturn { paused: true, - pauseWindowEndTime: U256::zero().into_alloy(), - bufferPeriodEndTime: U256::zero().into_alloy(), + pauseWindowEndTime: U256::ZERO, + bufferPeriodEndTime: U256::ZERO, }, ); asserter.push_success(&get_paused_state_response); let get_swap_fee_percentage_response = BalancerV2BasePool::BalancerV2BasePool::getSwapFeePercentageCall::abi_encode_returns( - &U256::zero().into_alloy(), + &U256::ZERO, ); asserter.push_success(&get_swap_fee_percentage_response); @@ -751,7 +742,7 @@ mod tests { &BalancerV2Vault::BalancerV2Vault::getPoolTokensReturn { tokens: vec![], balances: vec![], - lastChangeBlock: U256::zero().into_alloy(), + lastChangeBlock: U256::ZERO, }, ); asserter.push_success(&get_pool_tokens_response); @@ -791,7 +782,7 @@ mod tests { let pool_status = { pool_info_fetcher - .fetch_pool(&pool_info, BlockId::Number(BlockNumber::Number(1.into()))) + .fetch_pool(&pool_info, BlockId::Number(1.into())) .await .unwrap() }; @@ -813,15 +804,15 @@ mod tests { BalancerV2BasePool::BalancerV2BasePool::getPausedStateCall::abi_encode_returns( &BalancerV2BasePool::BalancerV2BasePool::getPausedStateReturn { paused: false, - pauseWindowEndTime: U256::zero().into_alloy(), - bufferPeriodEndTime: U256::zero().into_alloy(), + pauseWindowEndTime: U256::ZERO, + bufferPeriodEndTime: U256::ZERO, }, ); asserter.push_success(&get_paused_state_response); let get_swap_fee_percentage_response = BalancerV2BasePool::BalancerV2BasePool::getSwapFeePercentageCall::abi_encode_returns( - &U256::zero().into_alloy(), + &U256::ZERO, ); asserter.push_success(&get_swap_fee_percentage_response); @@ -830,7 +821,7 @@ mod tests { &BalancerV2Vault::BalancerV2Vault::getPoolTokensReturn { tokens: vec![], balances: vec![], - lastChangeBlock: U256::zero().into_alloy(), + lastChangeBlock: U256::ZERO, }, ); asserter.push_success(&get_pool_tokens_response); @@ -863,7 +854,7 @@ mod tests { let pool_status = { pool_info_fetcher - .fetch_pool(&pool_info, BlockId::Number(BlockNumber::Number(1.into()))) + .fetch_pool(&pool_info, BlockId::Number(1.into())) .await .unwrap() }; @@ -919,7 +910,7 @@ mod tests { fn convert_graph_pool_to_common_pool_info() { let pool = PoolData { pool_type: PoolType::Stable, - id: H256([4; 32]), + id: B256::repeat_byte(4), address: Address::repeat_byte(3), factory: Address::repeat_byte(0xfb), swap_enabled: true, @@ -940,7 +931,7 @@ mod tests { assert_eq!( PoolInfo::from_graph_data(&pool, 42).unwrap(), PoolInfo { - id: H256([4; 32]), + id: B256::repeat_byte(4), address: Address::repeat_byte(3), tokens: vec![Address::repeat_byte(0x33), Address::repeat_byte(0x44)], scaling_factors: vec![Bfp::exp10(15), Bfp::exp10(0)], @@ -953,7 +944,7 @@ mod tests { fn pool_conversion_insufficient_tokens() { let pool = PoolData { pool_type: PoolType::Weighted, - id: H256([2; 32]), + id: B256::repeat_byte(2), address: Address::repeat_byte(1), factory: Address::repeat_byte(0), swap_enabled: true, @@ -970,7 +961,7 @@ mod tests { fn pool_conversion_invalid_decimals() { let pool = PoolData { pool_type: PoolType::Weighted, - id: H256([2; 32]), + id: B256::repeat_byte(2), address: Address::repeat_byte(1), factory: Address::repeat_byte(0), swap_enabled: true, diff --git a/crates/shared/src/sources/balancer_v2/pools/composable_stable.rs b/crates/shared/src/sources/balancer_v2/pools/composable_stable.rs index 68eeb33f00..d680183ab5 100644 --- a/crates/shared/src/sources/balancer_v2/pools/composable_stable.rs +++ b/crates/shared/src/sources/balancer_v2/pools/composable_stable.rs @@ -6,10 +6,9 @@ use { graph_api::{PoolData, PoolType}, swap::fixed_point::Bfp, }, + alloy::eips::BlockId, anyhow::Result, contracts::alloy::{BalancerV2ComposableStablePool, BalancerV2ComposableStablePoolFactory}, - ethcontract::BlockId, - ethrpc::alloy::conversions::{IntoAlloy, IntoLegacy}, futures::{FutureExt as _, future::BoxFuture}, }; @@ -53,7 +52,7 @@ impl FactoryIndexing for BalancerV2ComposableStablePoolFactory::Instance { ); let fetch_common = common_pool_state.map(Result::Ok); - let scaling_factors_block = block.into_alloy(); + let scaling_factors_block = block; let amp_param_block = scaling_factors_block; let pool_contract_clone = pool_contract.clone(); let fetch_scaling_factors = async move { @@ -81,8 +80,8 @@ impl FactoryIndexing for BalancerV2ComposableStablePoolFactory::Instance { )?; let amplification_parameter = { AmplificationParameter::try_new( - amplification_parameter.value.into_legacy(), - amplification_parameter.precision.into_legacy(), + amplification_parameter.value, + amplification_parameter.precision, )? }; @@ -95,7 +94,7 @@ impl FactoryIndexing for BalancerV2ComposableStablePoolFactory::Instance { ( address, common::TokenState { - scaling_factor: Bfp::from_wei(scaling_factor.into_legacy()), + scaling_factor: Bfp::from_wei(scaling_factor), ..token }, ) @@ -114,15 +113,14 @@ mod tests { use { super::*, crate::sources::balancer_v2::graph_api::Token, - alloy::primitives::Address, - ethcontract::H256, + alloy::primitives::{Address, B256}, }; #[test] fn errors_when_converting_wrong_pool_type() { let pool = PoolData { pool_type: PoolType::Stable, - id: H256([2; 32]), + id: B256::repeat_byte(2), address: Address::repeat_byte(1), factory: Address::repeat_byte(0xfa), swap_enabled: true, diff --git a/crates/shared/src/sources/balancer_v2/pools/liquidity_bootstrapping.rs b/crates/shared/src/sources/balancer_v2/pools/liquidity_bootstrapping.rs index 8e83f29872..c194ee573d 100644 --- a/crates/shared/src/sources/balancer_v2/pools/liquidity_bootstrapping.rs +++ b/crates/shared/src/sources/balancer_v2/pools/liquidity_bootstrapping.rs @@ -6,13 +6,12 @@ use { graph_api::{PoolData, PoolType}, swap::fixed_point::Bfp, }, + alloy::eips::BlockId, anyhow::Result, contracts::alloy::{ BalancerV2LiquidityBootstrappingPool, BalancerV2LiquidityBootstrappingPoolFactory, }, - ethcontract::BlockId, - ethrpc::alloy::conversions::{IntoAlloy, IntoLegacy}, futures::{FutureExt as _, future::BoxFuture}, }; @@ -62,7 +61,7 @@ impl FactoryIndexing for BalancerV2LiquidityBootstrappingPoolFactory::Instance { let fetch_common = common_pool_state.map(Result::Ok); // Liquidity bootstrapping pools use dynamic weights, meaning that we // need to fetch them every time. - let weights_block = block.into_alloy(); + let weights_block = block; let swap_block = weights_block; let pool_contract_clone = pool_contract.clone(); let fetch_weights = async move { @@ -98,7 +97,7 @@ impl FactoryIndexing for BalancerV2LiquidityBootstrappingPoolFactory::Instance { address, TokenState { common, - weight: Bfp::from_wei(weight.into_legacy()), + weight: Bfp::from_wei(weight), }, ) }) @@ -120,15 +119,14 @@ mod tests { use { super::*, crate::sources::balancer_v2::graph_api::Token, - alloy::primitives::Address, - ethcontract::H256, + alloy::primitives::{Address, B256}, }; #[test] fn errors_when_converting_wrong_pool_type() { let pool = PoolData { pool_type: PoolType::Weighted, - id: H256([2; 32]), + id: B256::repeat_byte(2), address: Address::repeat_byte(1), factory: Address::repeat_byte(0xfa), swap_enabled: true, diff --git a/crates/shared/src/sources/balancer_v2/pools/mod.rs b/crates/shared/src/sources/balancer_v2/pools/mod.rs index d35749c778..2d3138bd85 100644 --- a/crates/shared/src/sources/balancer_v2/pools/mod.rs +++ b/crates/shared/src/sources/balancer_v2/pools/mod.rs @@ -15,8 +15,8 @@ pub mod weighted; use { super::graph_api::PoolData, + alloy::{eips::BlockId, primitives::B256}, anyhow::Result, - ethcontract::{BlockId, H256}, futures::future::BoxFuture, }; @@ -24,7 +24,7 @@ use { #[derive(Clone, Debug, Eq, PartialEq)] pub struct Pool { /// The ID of the pool. - pub id: H256, + pub id: B256, /// The pool-specific kind and state. pub kind: PoolKind, } diff --git a/crates/shared/src/sources/balancer_v2/pools/stable.rs b/crates/shared/src/sources/balancer_v2/pools/stable.rs index a236bdfa0b..9124f72fb6 100644 --- a/crates/shared/src/sources/balancer_v2/pools/stable.rs +++ b/crates/shared/src/sources/balancer_v2/pools/stable.rs @@ -9,11 +9,12 @@ use { swap::fixed_point::Bfp, }, }, - alloy::primitives::Address, + alloy::{ + eips::BlockId, + primitives::{Address, U256}, + }, anyhow::{Result, ensure}, contracts::alloy::{BalancerV2StablePool, BalancerV2StablePoolFactoryV2}, - ethcontract::{BlockId, U256}, - ethrpc::alloy::conversions::{IntoAlloy, IntoLegacy}, futures::{FutureExt as _, future::BoxFuture}, num::BigRational, std::collections::BTreeMap, @@ -101,7 +102,7 @@ impl FactoryIndexing for BalancerV2StablePoolFactoryV2::Instance { let fetch_amplification_parameter = async move { pool_contract .getAmplificationParameter() - .block(block.into_alloy()) + .block(block) .call() .await .map_err(anyhow::Error::from) @@ -112,8 +113,8 @@ impl FactoryIndexing for BalancerV2StablePoolFactoryV2::Instance { futures::try_join!(fetch_common, fetch_amplification_parameter)?; let amplification_parameter = { AmplificationParameter::try_new( - amplification_parameter.value.into_legacy(), - amplification_parameter.precision.into_legacy(), + amplification_parameter.value, + amplification_parameter.precision, )? }; @@ -129,13 +130,13 @@ impl FactoryIndexing for BalancerV2StablePoolFactoryV2::Instance { #[cfg(test)] mod tests { - use {super::*, crate::sources::balancer_v2::graph_api::Token, ethcontract::H256}; + use {super::*, crate::sources::balancer_v2::graph_api::Token, alloy::primitives::B256}; #[test] fn errors_when_converting_wrong_pool_type() { let pool = PoolData { pool_type: PoolType::Weighted, - id: H256([2; 32]), + id: B256::repeat_byte(2), address: Address::repeat_byte(1), factory: Address::repeat_byte(0xfa), swap_enabled: true, @@ -159,21 +160,21 @@ mod tests { #[test] fn amplification_parameter_conversions() { assert_eq!( - AmplificationParameter::try_new(2.into(), 3.into()) + AmplificationParameter::try_new(U256::from(2), U256::from(3)) .unwrap() - .with_base(1000.into()) + .with_base(U256::from(1000)) .unwrap(), - 666.into() + U256::from(666) ); assert_eq!( - AmplificationParameter::try_new(7.into(), 8.into()) + AmplificationParameter::try_new(U256::from(7), U256::from(8)) .unwrap() .as_big_rational(), BigRational::new(7.into(), 8.into()) ); assert_eq!( - AmplificationParameter::try_new(1.into(), 0.into()) + AmplificationParameter::try_new(U256::from(1), U256::from(0)) .unwrap_err() .to_string(), "Zero precision not allowed" diff --git a/crates/shared/src/sources/balancer_v2/pools/weighted.rs b/crates/shared/src/sources/balancer_v2/pools/weighted.rs index 5420d4dd8f..956be9336e 100644 --- a/crates/shared/src/sources/balancer_v2/pools/weighted.rs +++ b/crates/shared/src/sources/balancer_v2/pools/weighted.rs @@ -6,15 +6,13 @@ use { graph_api::{PoolData, PoolType}, swap::fixed_point::Bfp, }, - alloy::primitives::Address, + alloy::{eips::BlockId, primitives::Address}, anyhow::{Result, anyhow}, contracts::alloy::{ BalancerV2WeightedPool, BalancerV2WeightedPoolFactory, BalancerV2WeightedPoolFactoryV3, }, - ethcontract::BlockId, - ethrpc::alloy::conversions::IntoLegacy, futures::{FutureExt as _, future::BoxFuture}, std::collections::BTreeMap, }; @@ -79,7 +77,7 @@ impl FactoryIndexing for BalancerV2WeightedPoolFactory::Instance { .call() .await? .into_iter() - .map(|weight| Bfp::from_wei(weight.into_legacy())) + .map(|weight| Bfp::from_wei(weight)) .collect(); Ok(PoolInfo { @@ -149,12 +147,11 @@ mod tests { super::*, crate::sources::balancer_v2::graph_api::Token, alloy::{ - primitives::Address, + primitives::{Address, B256, U256}, providers::{Provider, ProviderBuilder, mock::Asserter}, sol_types::SolCall, }, - ethcontract::H256, - ethrpc::{Web3, alloy::conversions::IntoAlloy, mock::MockTransport}, + ethrpc::{Web3, mock::MockTransport}, futures::future, maplit::btreemap, }; @@ -163,7 +160,7 @@ mod tests { fn convert_graph_pool_to_weighted_pool_info() { let pool = PoolData { pool_type: PoolType::Weighted, - id: H256([2; 32]), + id: B256::repeat_byte(2), address: Address::repeat_byte(1), factory: Address::repeat_byte(0xfa), swap_enabled: true, @@ -185,15 +182,15 @@ mod tests { PoolInfo::from_graph_data(&pool, 42).unwrap(), PoolInfo { common: common::PoolInfo { - id: H256([2; 32]), + id: B256::repeat_byte(2), address: Address::repeat_byte(1), tokens: vec![Address::repeat_byte(0x11), Address::repeat_byte(0x22)], scaling_factors: vec![Bfp::exp10(17), Bfp::exp10(16)], block_created: 42, }, weights: vec![ - Bfp::from_wei(1_337_000_000_000_000_000u128.into()), - Bfp::from_wei(4_200_000_000_000_000_000u128.into()), + Bfp::from_wei(U256::from(1_337_000_000_000_000_000u128)), + Bfp::from_wei(U256::from(4_200_000_000_000_000_000u128)), ], }, ); @@ -203,7 +200,7 @@ mod tests { fn errors_when_converting_wrong_pool_type() { let pool = PoolData { pool_type: PoolType::Stable, - id: H256([2; 32]), + id: B256::repeat_byte(2), address: Address::repeat_byte(1), factory: Address::repeat_byte(0xfa), swap_enabled: true, @@ -242,14 +239,14 @@ mod tests { let get_normalized_weights_response = BalancerV2WeightedPool::BalancerV2WeightedPool::getNormalizedWeightsCall::abi_encode_returns( &weights.iter() - .map(|w| w.as_uint256().into_alloy()) + .map(|w| w.as_uint256()) .collect() ); asserter.push_success(&get_normalized_weights_response); let pool = factory .specialize_pool_info(common::PoolInfo { - id: H256([0x90; 32]), + id: B256::repeat_byte(0x90), tokens: vec![ Address::repeat_byte(1), Address::repeat_byte(2), @@ -273,7 +270,7 @@ mod tests { scaling_factor: Bfp::exp10(0), }, Address::repeat_byte(2) => common::TokenState { - balance: 10_000_000.into(), + balance: U256::from(10_000_000), scaling_factor: Bfp::exp10(12), }, }; @@ -288,7 +285,7 @@ mod tests { BalancerV2WeightedPoolFactory::Instance::new(Address::default(), web3.alloy.clone()); let pool_info = PoolInfo { common: common::PoolInfo { - id: H256([0x90; 32]), + id: B256::repeat_byte(0x90), address: Address::repeat_byte(0x90), tokens: tokens.keys().copied().collect(), scaling_factors: tokens.values().map(|token| token.scaling_factor).collect(), @@ -308,7 +305,7 @@ mod tests { let pool_state = factory.fetch_pool_state( &pool_info, future::ready(common_pool_state.clone()).boxed(), - BlockId::Number(ethcontract::BlockNumber::Number(block.into())), + block.into(), ); pool_state.await.unwrap() diff --git a/crates/shared/src/sources/balancer_v2/swap/fixed_point.rs b/crates/shared/src/sources/balancer_v2/swap/fixed_point.rs index 44209a0be4..557c1983a3 100644 --- a/crates/shared/src/sources/balancer_v2/swap/fixed_point.rs +++ b/crates/shared/src/sources/balancer_v2/swap/fixed_point.rs @@ -5,10 +5,10 @@ use { super::error::Error, + alloy::primitives::U256, anyhow::{Context, Result, bail, ensure}, - ethcontract::U256, num::{BigInt, BigRational}, - number::conversions::{big_int_to_u256, u256_to_big_int}, + number::conversions::alloy::{big_int_to_u256, u256_to_big_int}, std::{ convert::TryFrom, fmt::{self, Debug, Formatter}, @@ -27,13 +27,13 @@ mod logexpmath; /// including error codes, from which the name (Balancer Fixed Point). pub struct Bfp(U256); -static ONE_18: LazyLock = LazyLock::new(|| U256::exp10(18)); +static ONE_18: LazyLock = LazyLock::new(|| U256::from(10).pow(U256::from(18))); static ONE_18_BIGINT: LazyLock = LazyLock::new(|| u256_to_big_int(&ONE_18)); -static ZERO: LazyLock = LazyLock::new(|| Bfp(U256::zero())); +static ZERO: LazyLock = LazyLock::new(|| Bfp(U256::ZERO)); static ONE: LazyLock = LazyLock::new(|| Bfp(*ONE_18)); -static TWO: LazyLock = LazyLock::new(|| Bfp(*ONE_18 * 2)); -static FOUR: LazyLock = LazyLock::new(|| Bfp(*ONE_18 * 4)); -static MAX_POW_RELATIVE_ERROR: LazyLock = LazyLock::new(|| Bfp(10000_usize.into())); +static TWO: LazyLock = LazyLock::new(|| Bfp(*ONE_18 * U256::from(2))); +static FOUR: LazyLock = LazyLock::new(|| Bfp(*ONE_18 * U256::from(4))); +static MAX_POW_RELATIVE_ERROR: LazyLock = LazyLock::new(|| Bfp(U256::from(10000))); impl From for Bfp { fn from(num: usize) -> Self { @@ -72,9 +72,9 @@ impl FromStr for Bfp { if units.is_empty() || decimals.is_empty() || decimals.len() > 18 { bail!("Invalid decimal representation"); } - Ok(Bfp(U256::from_dec_str(&format!("{decimals:0<18}"))? + Ok(Bfp(U256::from_str_radix(&format!("{decimals:0<18}"), 10)? .checked_add( - U256::from_dec_str(units)? + U256::from_str_radix(units, 10)? .checked_mul(*ONE_18) .context("Too large number")?, ) @@ -88,7 +88,7 @@ impl Debug for Bfp { formatter, "{}.{:0>18}", self.0 / *ONE_18, - (self.0 % *ONE_18).as_u128() + u128::try_from(self.0 % *ONE_18).unwrap() ) } } @@ -96,7 +96,7 @@ impl Debug for Bfp { impl Bfp { #[cfg(test)] pub fn to_f64_lossy(self) -> f64 { - self.as_uint256().to_f64_lossy() / 1e18 + f64::from(self.as_uint256()) / 1e18 } pub fn as_uint256(self) -> U256 { @@ -121,7 +121,7 @@ impl Bfp { return Self::zero(); } - Self(U256::exp10(exp as _)) + Self(U256::from(10).pow(U256::from(exp))) } pub fn from_wei(num: U256) -> Self { @@ -154,7 +154,7 @@ impl Bfp { Ok(if product.is_zero() { Bfp::zero() } else { - Bfp(((product - 1) / *ONE_18) + 1) + Bfp(((product - U256::ONE) / *ONE_18) + U256::ONE) }) } @@ -177,7 +177,7 @@ impl Bfp { } else { let a_inflated = self.0.checked_mul(*ONE_18).ok_or(Error::DivInternal)?; - Ok(Self(((a_inflated - 1) / other.0) + 1)) + Ok(Self(((a_inflated - U256::ONE) / other.0) + U256::ONE)) } } @@ -191,7 +191,7 @@ impl Bfp { pub fn pow_up(self, exp: Self) -> Result { let raw = Bfp(logexpmath::pow(self.0, exp.0)?); - let max_error = raw.mul_up(*MAX_POW_RELATIVE_ERROR)?.add(Bfp(1.into()))?; + let max_error = raw.mul_up(*MAX_POW_RELATIVE_ERROR)?.add(Bfp(U256::ONE))?; raw.add(max_error) } @@ -206,7 +206,7 @@ impl Bfp { square.mul_up(square) } else { let raw = Bfp(logexpmath::pow(self.0, exp.0)?); - let max_error = raw.mul_up(*MAX_POW_RELATIVE_ERROR)?.add(Bfp(1.into()))?; + let max_error = raw.mul_up(*MAX_POW_RELATIVE_ERROR)?.add(Bfp(U256::ONE))?; raw.add(max_error) } @@ -220,22 +220,22 @@ mod tests { num::{BigInt, One, Zero}, }; - static EPSILON: LazyLock = LazyLock::new(|| Bfp(U256::one())); + static EPSILON: LazyLock = LazyLock::new(|| Bfp(U256::ONE)); #[test] fn parsing() { assert_eq!("1".parse::().unwrap(), Bfp::one()); assert_eq!( "0.1".parse::().unwrap(), - Bfp::from_wei(U256::exp10(17)) + Bfp::from_wei(U256::from(10).pow(U256::from(17))) ); assert_eq!( "1.01".parse::().unwrap(), - Bfp::from_wei(U256::exp10(18) + U256::exp10(16)) + Bfp::from_wei(U256::from(10).pow(U256::from(18)) + U256::from(10).pow(U256::from(16))) ); assert_eq!( "10.000000000000000001".parse::().unwrap(), - Bfp::from_wei(U256::exp10(19) + U256::one()) + Bfp::from_wei(U256::from(10).pow(U256::from(19)) + U256::ONE) ); assert!("10.0000000000000000001".parse::().is_err()); assert!("1.0.1".parse::().is_err()); @@ -259,7 +259,7 @@ mod tests { assert_eq!(Bfp::from(50).sub(8.into()).unwrap(), 42.into()); assert_eq!( - Bfp::one().sub(Bfp(*ONE_18 + 1)).unwrap_err(), + Bfp::one().sub(Bfp(*ONE_18 + U256::ONE)).unwrap_err(), Error::SubOverflow ); } @@ -270,15 +270,13 @@ mod tests { assert_eq!(Bfp::zero().$fn_name(Bfp::one()).unwrap(), Bfp::zero()); assert_eq!(Bfp::one().$fn_name(Bfp::zero()).unwrap(), Bfp::zero()); assert_eq!( - Bfp::one() - .$fn_name(Bfp(U256::MAX / U256::exp10(18))) - .unwrap(), - Bfp(U256::MAX / U256::exp10(18)) + Bfp::one().$fn_name(Bfp(U256::MAX / *ONE_18)).unwrap(), + Bfp(U256::MAX / *ONE_18) ); assert_eq!( Bfp::one() - .$fn_name(Bfp(U256::MAX / U256::exp10(18) + 1)) + .$fn_name(Bfp(U256::MAX / *ONE_18 + U256::ONE)) .unwrap_err(), Error::MulOverflow, ); @@ -290,14 +288,20 @@ mod tests { test_mul!(mul_down); test_mul!(mul_up); - let one_half = Bfp((5 * 10_u128.pow(17)).into()); + let one_half = Bfp(U256::from(5 * 10_u128.pow(17))); assert_eq!(EPSILON.mul_down(one_half).unwrap(), Bfp::zero()); assert_eq!(EPSILON.mul_up(one_half).unwrap(), *EPSILON); // values used in proof: // shared/src/sources/balancer/swap/weighted_math.rs#L28-L33 - let max_in_ratio = Bfp::from_wei(U256::exp10(17).checked_mul(3_u32.into()).unwrap()); - let balance_in = Bfp::from_wei(U256::MAX / (U256::exp10(17) * U256::from(3))); + let max_in_ratio = Bfp::from_wei( + U256::from(10) + .pow(U256::from(17)) + .checked_mul(U256::from(3)) + .unwrap(), + ); + let balance_in = + Bfp::from_wei(U256::MAX / (U256::from(10).pow(U256::from(17)) * U256::from(3))); assert!(balance_in.mul_down(max_in_ratio).is_ok()); assert!( (balance_in.add(Bfp::one())) @@ -317,7 +321,7 @@ mod tests { Error::ZeroDivision ); assert_eq!( - Bfp(U256::MAX / U256::exp10(18) + 1) + Bfp(U256::MAX / *ONE_18 + U256::ONE) .$fn_name(Bfp::one()) .unwrap_err(), Error::DivInternal, @@ -356,8 +360,9 @@ mod tests { ); // note: the values were chosen to get a large value from `pow` assert_eq!( - Bfp(U256::from_dec_str( - "287200000000000000000000000000000000000000000000000000000000000000000000000" + Bfp(U256::from_str_radix( + "287200000000000000000000000000000000000000000000000000000000000000000000000", + 10 ) .unwrap()) .pow_up(Bfp::one()) diff --git a/crates/shared/src/sources/balancer_v2/swap/fixed_point/logexpmath.rs b/crates/shared/src/sources/balancer_v2/swap/fixed_point/logexpmath.rs index 15375bca70..1e82da3908 100644 --- a/crates/shared/src/sources/balancer_v2/swap/fixed_point/logexpmath.rs +++ b/crates/shared/src/sources/balancer_v2/swap/fixed_point/logexpmath.rs @@ -4,7 +4,7 @@ use { super::super::error::Error, - ethcontract::{I256, U256}, + alloy::primitives::{I256, U256}, std::{convert::TryFrom, sync::LazyLock}, }; @@ -17,16 +17,22 @@ static ONE_20: LazyLock = LazyLock::new(|| I256::exp10(20)); static ONE_36: LazyLock = LazyLock::new(|| I256::exp10(36)); static UFIXED256X18_ONE: LazyLock = LazyLock::new(|| U256::try_from(*ONE_18).unwrap()); -static MAX_NATURAL_EXPONENT: LazyLock = - LazyLock::new(|| ONE_18.checked_mul(I256::from(130_i128)).unwrap()); -static MIN_NATURAL_EXPONENT: LazyLock = - LazyLock::new(|| ONE_18.checked_mul(I256::from(-41_i128)).unwrap()); +static MAX_NATURAL_EXPONENT: LazyLock = LazyLock::new(|| { + ONE_18 + .checked_mul(I256::try_from(130).expect("130 is a valid I256")) + .unwrap() +}); +static MIN_NATURAL_EXPONENT: LazyLock = LazyLock::new(|| { + ONE_18 + .checked_mul(I256::try_from(-41).expect("-41 is a valid I256")) + .unwrap() +}); static LN_36_LOWER_BOUND: LazyLock = LazyLock::new(|| ONE_18.checked_sub(I256::exp10(17)).unwrap()); static LN_36_UPPER_BOUND: LazyLock = LazyLock::new(|| ONE_18.checked_add(I256::exp10(17)).unwrap()); static MILD_EXPONENT_BOUND: LazyLock = LazyLock::new(|| { - (U256::one() << 254_u32) + (U256::ONE << 254_u32) .checked_div(U256::try_from(*ONE_20).unwrap()) .unwrap() }); @@ -45,7 +51,8 @@ fn constant_x_20(i: u32) -> I256 { 11 => 6_250_000_000_000_000_000_i128, _ => panic!("Constant not provided"), } - .into() + .try_into() + .expect("i128 fits within I256") } fn constant_x_18(i: u32) -> I256 { match i { @@ -53,7 +60,8 @@ fn constant_x_18(i: u32) -> I256 { 1 => 64_000_000_000_000_000_000_i128, _ => panic!("Constant not provided"), } - .into() + .try_into() + .expect("i128 fits within I256") } fn constant_a_20(i: u32) -> I256 { match i { @@ -69,24 +77,26 @@ fn constant_a_20(i: u32) -> I256 { 11 => 106_449_445_891_785_942_956_i128, _ => panic!("Constant not provided"), } - .into() + .try_into() + .expect("i128 fits within I256") } fn constant_a_18(i: u32) -> I256 { match i { 0 => { I256::from_dec_str("38877084059945950922200000000000000000000000000000000000").unwrap() } - 1 => 6_235_149_080_811_616_882_910_000_000_i128.into(), + 1 => I256::try_from(6_235_149_080_811_616_882_910_000_000_i128) + .expect("i128 fits within I256"), _ => panic!("Constant not provided"), } } pub fn pow(x: Ufixed256x18, y: Ufixed256x18) -> Result { - if y == U256::zero() { + if y == U256::ZERO { return Ok(*UFIXED256X18_ONE); } - if x == U256::zero() { - return Ok(U256::zero()); + if x == U256::ZERO { + return Ok(U256::ZERO); } let x_int256 = match I256::try_from(x) { @@ -120,7 +130,7 @@ fn exp(mut x: I256) -> Result { return Err(Error::InvalidExponent); } - if x < I256::zero() { + if x < I256::ZERO { return Ok((*ONE_18 * *ONE_18) / exp(-x)?); } @@ -132,10 +142,10 @@ fn exp(mut x: I256) -> Result { x -= constant_x_18(1); first_an = constant_a_18(1); } else { - first_an = 1.into(); + first_an = I256::ONE; } - x *= 100.into(); + x *= I256::try_from(100).expect("100 is a valid I256"); let mut product = *ONE_20; for i in 2..=9 { @@ -150,11 +160,13 @@ fn exp(mut x: I256) -> Result { series_sum += term; for i in 2..=12 { - term = ((term * x) / *ONE_20) / i.into(); + term = ((term * x) / *ONE_20) + / I256::try_from(i).expect("all numbers within (2..=12) are valid I256"); series_sum += term; } - Ok((((product * series_sum) / *ONE_20) * first_an) / 100.into()) + Ok((((product * series_sum) / *ONE_20) * first_an) + / I256::try_from(100).expect("100 is a valid I256")) } fn _ln(mut a: I256) -> I256 { @@ -162,7 +174,7 @@ fn _ln(mut a: I256) -> I256 { return -_ln((*ONE_18 * *ONE_18) / a); } - let mut sum = I256::zero(); + let mut sum = I256::ZERO; for i in 0..=1 { if a >= constant_a_18(i) * *ONE_18 { a /= constant_a_18(i); @@ -170,8 +182,8 @@ fn _ln(mut a: I256) -> I256 { } } - sum *= 100.into(); - a *= 100.into(); + sum *= I256::try_from(100).expect("100 is a valid I256"); + a *= I256::try_from(100).expect("100 is a valid I256"); for i in 2..=11 { if a >= constant_a_20(i) { @@ -188,12 +200,12 @@ fn _ln(mut a: I256) -> I256 { for i in (3..=11).step_by(2) { num = (num * z_squared) / *ONE_20; - series_sum += num / i.into(); + series_sum += num / I256::try_from(i).expect("all numbers within (3..=11) are valid I256"); } - series_sum *= 2.into(); + series_sum *= I256::try_from(2).expect("2 is a valid I256"); - (sum + series_sum) / 100.into() + (sum + series_sum) / I256::try_from(100).expect("100 is a valid I256") } fn _ln_36(mut x: I256) -> I256 { @@ -207,10 +219,10 @@ fn _ln_36(mut x: I256) -> I256 { for i in (3..=15).step_by(2) { num = (num * z_squared) / *ONE_36; - series_sum += num / i.into(); + series_sum += num / I256::try_from(i).expect("all numbers within (3..=15) are valid I256"); } - series_sum * 2.into() + series_sum * I256::try_from(2).expect("2 is a valid I256") } #[cfg(test)] @@ -465,8 +477,8 @@ mod tests { for (i, &o) in input.iter().zip(output.iter()) { assert_eq!( pow( - U256::from_dec_str(i[0]).unwrap(), - U256::from_dec_str(i[1]).unwrap() + U256::from_str_radix(i[0], 10).unwrap(), + U256::from_str_radix(i[1], 10).unwrap() ) .unwrap_err(), o.into() @@ -513,11 +525,11 @@ mod tests { for (i, &o) in input.iter().zip(output.iter()) { assert_eq!( pow( - U256::from_dec_str(i[0]).unwrap(), - U256::from_dec_str(i[1]).unwrap() + U256::from_str_radix(i[0], 10).unwrap(), + U256::from_str_radix(i[1], 10).unwrap() ) .unwrap(), - U256::from_dec_str(o).unwrap() + U256::from_str_radix(o, 10).unwrap() ); } } @@ -548,20 +560,11 @@ mod tests { #[test] fn pow_alternate_routes() { + assert_eq!(pow(U256::ZERO, U256::ZERO), Ok(*UFIXED256X18_ONE)); + assert_eq!(pow(U256::ZERO, U256::ONE), Ok(U256::ZERO)); assert_eq!( - pow( - U256::from_dec_str("0").unwrap(), - U256::from_dec_str("0").unwrap() - ), + pow(U256::from(10).pow(U256::from(18)), U256::ONE), Ok(*UFIXED256X18_ONE) ); - assert_eq!( - pow( - U256::from_dec_str("0").unwrap(), - U256::from_dec_str("1").unwrap() - ), - Ok(U256::zero()) - ); - assert_eq!(pow(U256::exp10(18), U256::one()), Ok(*UFIXED256X18_ONE)); } } diff --git a/crates/shared/src/sources/balancer_v2/swap/math.rs b/crates/shared/src/sources/balancer_v2/swap/math.rs index 5c8ee800d9..589bc16250 100644 --- a/crates/shared/src/sources/balancer_v2/swap/math.rs +++ b/crates/shared/src/sources/balancer_v2/swap/math.rs @@ -1,4 +1,4 @@ -use {super::error::Error, ethcontract::U256}; +use {super::error::Error, alloy::primitives::U256}; pub trait BalU256: Sized { fn bmul(self, other: Self) -> Result; @@ -33,9 +33,9 @@ impl BalU256 for U256 { return Err(Error::ZeroDivision); } if self.is_zero() { - return Ok(U256::zero()); + return Ok(U256::ZERO); } - let one = U256::one(); + let one = U256::ONE; Ok(one + (self - one) / other) } } @@ -46,8 +46,8 @@ mod tests { #[test] fn bmul_tests() { - let zero = U256::zero(); - let one = U256::one(); + let zero = U256::ZERO; + let one = U256::ONE; let max = U256::MAX; assert_eq!(zero.bmul(one).unwrap(), zero); assert_eq!(one.bmul(one).unwrap(), one); @@ -60,8 +60,8 @@ mod tests { #[test] fn badd_tests() { - let zero = U256::zero(); - let one = U256::one(); + let zero = U256::ZERO; + let one = U256::ONE; let two = U256::from(2); let max = U256::MAX; assert_eq!(zero.badd(one).unwrap(), one); @@ -75,8 +75,8 @@ mod tests { #[test] fn bsub_tests() { - let zero = U256::zero(); - let one = U256::one(); + let zero = U256::ZERO; + let one = U256::ONE; let two = U256::from(2); assert_eq!(two.bsub(zero).unwrap(), two); assert_eq!(two.bsub(one).unwrap(), one); @@ -89,8 +89,8 @@ mod tests { #[test] fn div_down_tests() { - let zero = U256::zero(); - let one = U256::one(); + let zero = U256::ZERO; + let one = U256::ONE; let two = U256::from(2); assert_eq!(zero.bdiv_down(one).unwrap(), zero); assert_eq!(two.bdiv_down(one).unwrap(), two); @@ -104,8 +104,8 @@ mod tests { #[test] fn div_up_tests() { - let zero = U256::zero(); - let one = U256::one(); + let zero = U256::ZERO; + let one = U256::ONE; let two = U256::from(2); assert_eq!(zero.bdiv_up(one).unwrap(), zero); assert_eq!(two.bdiv_up(one).unwrap(), two); diff --git a/crates/shared/src/sources/balancer_v2/swap/mod.rs b/crates/shared/src/sources/balancer_v2/swap/mod.rs index 8e1490bd58..c893d1ea27 100644 --- a/crates/shared/src/sources/balancer_v2/swap/mod.rs +++ b/crates/shared/src/sources/balancer_v2/swap/mod.rs @@ -11,10 +11,8 @@ use { WeightedTokenState, }, }, - alloy::primitives::Address, + alloy::primitives::{Address, U256}, error::Error, - ethcontract::U256, - ethrpc::alloy::conversions::{IntoAlloy, IntoLegacy}, fixed_point::Bfp, std::collections::BTreeMap, }; @@ -117,8 +115,7 @@ impl BaselineSolvable for WeightedPoolRef<'_> { out_token: Address, (in_amount, in_token): (alloy::primitives::U256, Address), ) -> Option { - self.get_amount_out_inner(out_token, in_amount.into_legacy(), in_token) - .map(IntoAlloy::into_alloy) + self.get_amount_out_inner(out_token, in_amount, in_token) } async fn get_amount_in( @@ -141,16 +138,15 @@ impl BaselineSolvable for WeightedPoolRef<'_> { in_reserves.weight, out_reserves.common.upscaled_balance().ok()?, out_reserves.weight, - out_reserves.common.upscale(out_amount.into_legacy()).ok()?, + out_reserves.common.upscale(out_amount).ok()?, ) .ok()?; let amount_in_before_fee = in_reserves.common.downscale_up(in_amount).ok()?; let in_amount = add_swap_fee_amount(amount_in_before_fee, self.swap_fee).ok()?; - converge_in_amount(in_amount, out_amount.into_legacy(), |x| { + converge_in_amount(in_amount, out_amount, |x| { self.get_amount_out_inner(out_token, x, in_token) }) - .map(IntoAlloy::into_alloy) } async fn gas_cost(&self) -> usize { @@ -298,8 +294,7 @@ impl StablePoolRef<'_> { if in_token == self.address || out_token == self.address { self.swap_with_bpt() } else { - self.regular_swap_given_in(out_token, (in_amount.into_legacy(), in_token)) - .map(IntoAlloy::into_alloy) + self.regular_swap_given_in(out_token, (in_amount, in_token)) } } } @@ -321,13 +316,10 @@ impl BaselineSolvable for StablePoolRef<'_> { if in_token == self.address || out_token == self.address { self.swap_with_bpt() } else { - let in_amount = - self.regular_swap_given_out(in_token, (out_amount.into_legacy(), out_token))?; - converge_in_amount(in_amount, out_amount.into_legacy(), |x| { - self.get_amount_out_inner(out_token, x.into_alloy(), in_token) - .map(IntoLegacy::into_legacy) + let in_amount = self.regular_swap_given_out(in_token, (out_amount, out_token))?; + converge_in_amount(in_amount, out_amount, |x| { + self.get_amount_out_inner(out_token, x, in_token) }) - .map(IntoAlloy::into_alloy) } } @@ -355,8 +347,8 @@ fn converge_in_amount( // trading price and multiply the amount to bump by 10 for each iteration. let mut bump = (exact_out_amount - out_amount) .checked_mul(in_amount)? - .ceil_div(&out_amount.max(U256::one())) - .max(U256::one()); + .ceil_div(&out_amount.max(U256::ONE)) + .max(U256::ONE); for _ in 0..6 { let bumped_in_amount = in_amount.checked_add(bump)?; @@ -365,7 +357,7 @@ fn converge_in_amount( return Some(bumped_in_amount); } - bump *= 10; + bump *= U256::from(10); } None @@ -519,7 +511,7 @@ mod tests { balance: Default::default(), scaling_factor: Bfp::exp10(12), }; - let input = Bfp::from_wei(900_546_079_866_630_330_575_i128.into()); + let input = Bfp::from_wei(U256::from(900_546_079_866_630_330_575_u128)); assert_eq!( token_state.downscale_up(input).unwrap(), U256::from(900_546_080_u128) @@ -534,17 +526,17 @@ mod tests { async fn weighted_get_amount_out() { // Values obtained from this transaction: // https://dashboard.tenderly.co/tx/main/0xa9f571c9bfd4289bd4bd270465d73e1b7e010622ed089d54d81ec63a0365ec22/debugger - let crv = ::alloy::primitives::Address::repeat_byte(21); - let sdvecrv_dao = ::alloy::primitives::Address::repeat_byte(42); + let crv = Address::repeat_byte(21); + let sdvecrv_dao = Address::repeat_byte(42); let b = create_weighted_pool_with( vec![crv, sdvecrv_dao], vec![ - 1_850_304_144_768_426_873_445_489_i128.into(), - 95_671_347_892_391_047_965_654_i128.into(), + U256::from(1_850_304_144_768_426_873_445_489_u128), + U256::from(95_671_347_892_391_047_965_654_u128), ], vec![bfp!("0.9"), bfp!("0.1")], vec![Bfp::exp10(0), Bfp::exp10(0)], - 2_000_000_000_000_000_i128.into(), + U256::from(2_000_000_000_000_000_u128), ); assert_eq!( @@ -565,14 +557,17 @@ mod tests { async fn weighted_get_amount_in() { // Values obtained from this transaction: // https://dashboard.tenderly.co/tx/main/0xafc3dd6a636a85d9c1976dfa5aee33f78e6ee902f285c9d4cf80a0014aa2a052/debugger - let weth = ::alloy::primitives::Address::repeat_byte(21); - let tusd = ::alloy::primitives::Address::repeat_byte(42); + let weth = Address::repeat_byte(21); + let tusd = Address::repeat_byte(42); let b = create_weighted_pool_with( vec![weth, tusd], - vec![60_000_000_000_000_000_i128.into(), 250_000_000_i128.into()], + vec![ + U256::from(60_000_000_000_000_000_u128), + U256::from(250_000_000_u128), + ], vec![bfp!("0.5"), bfp!("0.5")], vec![Bfp::exp10(0), Bfp::exp10(12)], - 1_000_000_000_000_000_i128.into(), + U256::from(1_000_000_000_000_000_u128), ); assert_eq!( @@ -586,13 +581,13 @@ mod tests { #[test] fn construct_balances_and_token_indices() { let tokens: Vec<_> = (1..=3).map(Address::with_last_byte).collect(); - let balances = (1..=3).map(|n| n.into()).collect(); + let balances = (1..=3).map(U256::from).collect(); let pool = create_stable_pool_with( tokens.clone(), balances, - AmplificationParameter::try_new(1.into(), 1.into()).unwrap(), + AmplificationParameter::try_new(U256::ONE, U256::ONE).unwrap(), vec![Bfp::exp10(18), Bfp::exp10(18), Bfp::exp10(18)], - 1.into(), + U256::ONE, ); for token_i in tokens.iter() { @@ -632,13 +627,13 @@ mod tests { let tokens = vec![dai, usdc, tusd]; let scaling_exps = vec![Bfp::exp10(0), Bfp::exp10(12), Bfp::exp10(12)]; let amplification_parameter = - AmplificationParameter::try_new(570000.into(), 1000.into()).unwrap(); + AmplificationParameter::try_new(U256::from(570000), U256::from(1000)).unwrap(); let balances = vec![ - 40_927_687_702_846_622_465_144_342_i128.into(), - 59_448_574_675_062_i128.into(), - 55_199_308_926_456_i128.into(), + U256::from(40_927_687_702_846_622_465_144_342_u128), + U256::from(59_448_574_675_062_u128), + U256::from(55_199_308_926_456_u128), ]; - let swap_fee_percentage = 300_000_000_000_000u128.into(); + let swap_fee_percentage = U256::from(300_000_000_000_000u128); let pool = create_stable_pool_with( tokens, balances, @@ -665,13 +660,13 @@ mod tests { let tokens = vec![dai, usdc, tusd]; let scaling_exps = vec![Bfp::exp10(0), Bfp::exp10(12), Bfp::exp10(12)]; let amplification_parameter = - AmplificationParameter::try_new(570000.into(), 1000.into()).unwrap(); + AmplificationParameter::try_new(U256::from(570000), U256::from(1000)).unwrap(); let balances = vec![ - 34_869_494_603_218_073_631_628_580_i128.into(), - 48_176_005_970_419_i128.into(), - 44_564_350_355_030_i128.into(), + U256::from(34_869_494_603_218_073_631_628_580_u128), + U256::from(48_176_005_970_419_u128), + U256::from(44_564_350_355_030_u128), ]; - let swap_fee_percentage = 300_000_000_000_000u128.into(); + let swap_fee_percentage = U256::from(300_000_000_000_000u128); let pool = create_stable_pool_with( tokens, balances, diff --git a/crates/shared/src/sources/balancer_v2/swap/stable_math.rs b/crates/shared/src/sources/balancer_v2/swap/stable_math.rs index f1860b0459..395769790e 100644 --- a/crates/shared/src/sources/balancer_v2/swap/stable_math.rs +++ b/crates/shared/src/sources/balancer_v2/swap/stable_math.rs @@ -5,7 +5,7 @@ use { super::error::Error, crate::sources::balancer_v2::swap::{fixed_point::Bfp, math::BalU256}, - ethcontract::U256, + alloy::primitives::U256, std::sync::LazyLock, }; @@ -13,7 +13,7 @@ pub static AMP_PRECISION: LazyLock = LazyLock::new(|| U256::from(1000)); /// https://github.com/balancer-labs/balancer-v2-monorepo/blob/9eb7e44a4e9ebbadfe3c6242a086118298cadc9f/pkg/pool-stable-phantom/contracts/StableMath.sol#L57-L119 fn calculate_invariant(amplification_parameter: U256, balances: &[Bfp]) -> Result { - let mut sum = U256::zero(); + let mut sum = U256::ZERO; let num_tokens_usize = balances.len(); for balance_i in balances.iter() { sum = sum.badd(balance_i.as_uint256())?; @@ -48,7 +48,7 @@ fn calculate_invariant(amplification_parameter: U256, balances: &[Bfp]) -> Resul .bsub(*AMP_PRECISION)? .bmul(invariant)? .bdiv_down(*AMP_PRECISION)? - .badd(num_tokens.badd(1.into())?.bmul(d_p)?)?; + .badd(num_tokens.badd(U256::ONE)?.bmul(d_p)?)?; invariant = numerator.bdiv_down(denominator)?; match convergence_criteria(invariant, prev_invariant) { None => continue, @@ -89,7 +89,7 @@ pub fn calc_out_given_in( balances[token_index_out] .sub(final_balance_out)? - .sub(Bfp::from_wei(1.into())) + .sub(Bfp::from_wei(U256::ONE)) } /// https://github.com/balancer-labs/balancer-v2-monorepo/blob/ad1442113b26ec22081c2047e2ec95355a7f12ba/pkg/pool-stable/contracts/StableMath.sol#L152-L190 @@ -124,7 +124,7 @@ pub fn calc_in_given_out( final_balance_in .sub(balances[token_index_in])? - .add(Bfp::from_wei(1.into())) + .add(Bfp::from_wei(U256::ONE)) } /// https://github.com/balancer-labs/balancer-v2-monorepo/blob/ad1442113b26ec22081c2047e2ec95355a7f12ba/pkg/pool-stable/contracts/StableMath.sol#L465-L516 @@ -177,10 +177,12 @@ fn get_token_balance_given_invariant_and_all_other_balances( // Math.mul(tokenBalance, tokenBalance).add(c), // Math.mul(tokenBalance, 2).add(b).sub(invariant) // ); - token_balance = token_balance - .bmul(token_balance)? - .badd(c)? - .bdiv_up(token_balance.bmul(2.into())?.badd(b)?.bsub(invariant)?)?; + token_balance = token_balance.bmul(token_balance)?.badd(c)?.bdiv_up( + token_balance + .bmul(U256::from(2))? + .badd(b)? + .bsub(invariant)?, + )?; match convergence_criteria(token_balance, prev_token_balance) { None => continue, Some(token_balance) => return Ok(Bfp::from_wei(token_balance)), @@ -190,7 +192,7 @@ fn get_token_balance_given_invariant_and_all_other_balances( } fn convergence_criteria(curr_value: U256, prev_value: U256) -> Option { - let one = U256::one(); + let one = U256::ONE; if curr_value > prev_value { if curr_value .bsub(prev_value) @@ -219,12 +221,7 @@ fn convergence_criteria(curr_value: U256, prev_value: U256) -> Option { /// Cross-reference to the TS code: https://github.com/balancer-labs/balancer-v2-monorepo/blob/stable-deployment/pvt/helpers/src/models/pools/stable/math.ts #[cfg(test)] mod tests { - use { - super::*, - crate::sources::balancer_v2::swap::fixed_point::Bfp, - ethcontract::U256, - std::str::FromStr, - }; + use {super::*, crate::sources::balancer_v2::swap::fixed_point::Bfp, std::str::FromStr}; // interpreted from // https://github.com/balancer-labs/balancer-v2-monorepo/blob/stable-deployment/pvt/helpers/src/models/pools/stable/math.ts#L53 @@ -341,7 +338,7 @@ mod tests { #[test] fn invariant_two_tokens_ok() { let amp = 100.; - let amplification_parameter = U256::from_f64_lossy(amp * AMP_PRECISION.to_f64_lossy()); + let amplification_parameter = U256::from(amp * f64::from(*AMP_PRECISION)); let balances = vec![Bfp::from(10), Bfp::from(12)]; let max_relative_error = 0.001; let expected = calculate_analytic_invariant_two_tokens( @@ -351,7 +348,7 @@ mod tests { ); let result = calculate_invariant(amplification_parameter, &balances).unwrap(); assert!( - (result.to_f64_lossy() / 1e18 - expected) + (f64::from(result) / 1e18 - expected) .abs() .le(&max_relative_error) ); @@ -364,13 +361,13 @@ mod tests { .iter() .map(|x| Bfp::from_str(x).unwrap()) .collect(); - let amplification_parameter = U256::from_f64_lossy(amp * AMP_PRECISION.to_f64_lossy()); + let amplification_parameter = U256::from(amp * f64::from(*AMP_PRECISION)); let result = calculate_invariant(amplification_parameter, balances.as_slice()).unwrap(); let float_balances = balances.iter().map(|x| x.to_f64_lossy()).collect(); let expected = calculate_invariant_approx(float_balances, amp); let max_relative_error = 0.001; assert!( - (result.to_f64_lossy() / 1e18 - expected) + (f64::from(result) / 1e18 - expected) .abs() .le(&max_relative_error) ); @@ -379,14 +376,14 @@ mod tests { #[test] fn invariant_three_tokens_ok() { let amp = 100.; - let amplification_parameter = U256::from_f64_lossy(amp * AMP_PRECISION.to_f64_lossy()); + let amplification_parameter = U256::from(amp * f64::from(*AMP_PRECISION)); let balances = vec![Bfp::from(10), Bfp::from(12), Bfp::from(14)]; let float_balances = balances.iter().map(|x| x.to_f64_lossy()).collect(); let expected = calculate_invariant_approx(float_balances, amp); let max_relative_error = 0.001; let result = calculate_invariant(amplification_parameter, &balances).unwrap(); assert!( - (result.to_f64_lossy() / 1e18 - expected) + (f64::from(result) / 1e18 - expected) .abs() .le(&max_relative_error) ); @@ -395,7 +392,7 @@ mod tests { #[test] fn in_given_out_two_tokens() { let amp = 100.; - let amplification_parameter = U256::from_f64_lossy(amp * AMP_PRECISION.to_f64_lossy()); + let amplification_parameter = U256::from(amp * f64::from(*AMP_PRECISION)); let mut balances = [Bfp::from(10), Bfp::from(12)]; let float_balances = balances.iter().map(|x| x.to_f64_lossy()).collect(); let token_index_in = 0; @@ -427,7 +424,7 @@ mod tests { #[test] fn in_given_out_three_tokens() { let amp = 100.; - let amplification_parameter = U256::from_f64_lossy(amp * AMP_PRECISION.to_f64_lossy()); + let amplification_parameter = U256::from(amp * f64::from(*AMP_PRECISION)); let mut balances = [Bfp::from(10), Bfp::from(12), Bfp::from(14)]; let float_balances = balances.iter().map(|x| x.to_f64_lossy()).collect(); let token_index_in = 0; @@ -459,7 +456,7 @@ mod tests { #[test] fn out_given_in_two_tokens() { let amp = 100.; - let amplification_parameter = U256::from_f64_lossy(amp * AMP_PRECISION.to_f64_lossy()); + let amplification_parameter = U256::from(amp * f64::from(*AMP_PRECISION)); let mut balances = [Bfp::from(10), Bfp::from(12)]; let float_balances = balances.iter().map(|x| x.to_f64_lossy()).collect(); let token_index_in = 0; @@ -491,7 +488,7 @@ mod tests { #[test] fn out_given_in_three_tokens() { let amp = 100.; - let amplification_parameter = U256::from_f64_lossy(amp * AMP_PRECISION.to_f64_lossy()); + let amplification_parameter = U256::from(amp * f64::from(*AMP_PRECISION)); let mut balances = [Bfp::from(10), Bfp::from(12), Bfp::from(14)]; let float_balances = balances.iter().map(|x| x.to_f64_lossy()).collect(); let token_index_in = 0; diff --git a/crates/shared/src/sources/balancer_v2/swap/weighted_math.rs b/crates/shared/src/sources/balancer_v2/swap/weighted_math.rs index f978eab496..8fea226e1c 100644 --- a/crates/shared/src/sources/balancer_v2/swap/weighted_math.rs +++ b/crates/shared/src/sources/balancer_v2/swap/weighted_math.rs @@ -4,15 +4,27 @@ use { super::{error::Error, fixed_point::Bfp}, - ethcontract::U256, + alloy::primitives::U256, std::sync::LazyLock, }; // https://github.com/balancer-labs/balancer-v2-monorepo/blob/6c9e24e22d0c46cca6dd15861d3d33da61a60b98/pkg/core/contracts/pools/weighted/WeightedMath.sol#L36-L37 -static MAX_IN_RATIO: LazyLock = - LazyLock::new(|| Bfp::from_wei(U256::exp10(17).checked_mul(3_u32.into()).unwrap())); -static MAX_OUT_RATIO: LazyLock = - LazyLock::new(|| Bfp::from_wei(U256::exp10(17).checked_mul(3_u32.into()).unwrap())); +static MAX_IN_RATIO: LazyLock = LazyLock::new(|| { + Bfp::from_wei( + U256::from(10) + .pow(U256::from(17)) + .checked_mul(U256::from(3)) + .unwrap(), + ) +}); +static MAX_OUT_RATIO: LazyLock = LazyLock::new(|| { + Bfp::from_wei( + U256::from(10) + .pow(U256::from(17)) + .checked_mul(U256::from(3)) + .unwrap(), + ) +}); /// https://github.com/balancer-labs/balancer-v2-monorepo/blob/6c9e24e22d0c46cca6dd15861d3d33da61a60b98/pkg/core/contracts/pools/weighted/WeightedMath.sol#L69-L100 /// It is not possible for the following addition balance_in.add(amount_in) to @@ -143,17 +155,17 @@ mod tests { fn calc_out_given_in_ok() { assert_eq!( calc_out_given_in( - Bfp::from_wei(100_000_000_000_000_000_000_000_u128.into()), - Bfp::from_wei(300_000_000_000_000_u128.into()), - Bfp::from_wei(10_000_000_000_000_000_000_u128.into()), - Bfp::from_wei(700_000_000_000_000_u128.into()), - Bfp::from_wei(10_000_000_000_000_000_u128.into()), + Bfp::from_wei(U256::from(100_000_000_000_000_000_000_000_u128)), + Bfp::from_wei(U256::from(300_000_000_000_000_u128)), + Bfp::from_wei(U256::from(10_000_000_000_000_000_000_u128)), + Bfp::from_wei(U256::from(700_000_000_000_000_u128)), + Bfp::from_wei(U256::from(10_000_000_000_000_000_u128)), ) .unwrap(), // (await weightedMath["_calcOutGivenIn"]("100000000000000000000000", // "300000000000000", "10000000000000000000", "700000000000000", // "10000000000000000")).toString() - Bfp::from_wei(428_571_297_950_u128.into()), + Bfp::from_wei(U256::from(428_571_297_950_u128)), ); } @@ -161,28 +173,29 @@ mod tests { fn calc_in_given_out_ok() { assert_eq!( calc_in_given_out( - Bfp::from_wei(100_000_000_000_000_000_000_000_u128.into()), - Bfp::from_wei(300_000_000_000_000_u128.into()), - Bfp::from_wei(10_000_000_000_000_000_000_u128.into()), - Bfp::from_wei(700_000_000_000_000_u128.into()), - Bfp::from_wei(10_000_000_000_000_000_u128.into()), + Bfp::from_wei(U256::from(100_000_000_000_000_000_000_000_u128)), + Bfp::from_wei(U256::from(300_000_000_000_000_u128)), + Bfp::from_wei(U256::from(10_000_000_000_000_000_000_u128)), + Bfp::from_wei(U256::from(700_000_000_000_000_u128)), + Bfp::from_wei(U256::from(10_000_000_000_000_000_u128)), ) .unwrap(), // (await weightedMath["_calcInGivenOut"]("100000000000000000000000", // "300000000000000", "10000000000000000000", "700000000000000", // "10000000000000000")).toString() - Bfp::from_wei(233_722_784_701_541_000_000_u128.into()), + Bfp::from_wei(U256::from(233_722_784_701_541_000_000_u128)), ); } #[test] fn calc_out_given_in_err() { - let zero = Bfp::from_wei(0.into()); - let one = Bfp::from_wei(1.into()); - let two = Bfp::from_wei(2.into()); + let zero = Bfp::from_wei(U256::from(0)); + let one = Bfp::from_wei(U256::from(1)); + let two = Bfp::from_wei(U256::from(2)); let max_u256 = Bfp::from_wei(U256::MAX); - let max_balance_in = Bfp::from_wei(U256::MAX / (U256::exp10(17) * U256::from(3))); - let mid_u256 = Bfp::from_wei(u128::MAX.into()); + let max_balance_in = + Bfp::from_wei(U256::MAX / (U256::from(10).pow(U256::from(17)) * U256::from(3))); + let mid_u256 = Bfp::from_wei(U256::from(u128::MAX)); assert_eq!( calc_out_given_in(max_u256, zero, zero, zero, two) .unwrap_err() @@ -234,12 +247,13 @@ mod tests { #[test] fn calc_in_given_out_err() { - let zero = Bfp::from_wei(0.into()); - let one = Bfp::from_wei(1.into()); - let two = Bfp::from_wei(2.into()); + let zero = Bfp::from_wei(U256::from(0)); + let one = Bfp::from_wei(U256::from(1)); + let two = Bfp::from_wei(U256::from(2)); let max_u256 = Bfp::from_wei(U256::MAX); - let max_balance = Bfp::from_wei(U256::MAX / (U256::exp10(17) * U256::from(3))); - let mid_u256 = Bfp::from_wei(u128::MAX.into()); + let max_balance = + Bfp::from_wei(U256::MAX / (U256::from(10).pow(U256::from(17)) * U256::from(3))); + let mid_u256 = Bfp::from_wei(U256::from(u128::MAX)); assert_eq!( calc_in_given_out(one, zero, max_u256, zero, two) .unwrap_err() @@ -299,10 +313,10 @@ mod tests { macro_rules! calc_with_default_pool { ($fn_name:ident, $amount: expr_2021) => { $fn_name( - Bfp::from_wei(deposit_in.into()), - Bfp::from_wei(500_000_000_000_000_u128.into()), - Bfp::from_wei(deposit_out.into()), - Bfp::from_wei(500_000_000_000_000_u128.into()), + Bfp::from_wei(U256::from(deposit_in)), + Bfp::from_wei(U256::from(500_000_000_000_000_u128)), + Bfp::from_wei(U256::from(deposit_out)), + Bfp::from_wei(U256::from(500_000_000_000_000_u128)), Bfp::from_wei($amount), ) }; @@ -314,23 +328,24 @@ mod tests { let largest_amount_in = deposit_in * 3 / 10; assert_eq!( - calc_with_default_pool!(calc_out_given_in, largest_amount_in.into()).unwrap(), + calc_with_default_pool!(calc_out_given_in, U256::from(largest_amount_in)).unwrap(), // > await calc_with_default_pool("_calcOutGivenIn", "6000000000000000000000") - Bfp::from_wei(2_307_692_307_692_230_750_000_u128.into()) + Bfp::from_wei(U256::from(2_307_692_307_692_230_750_000_u128)) ); assert_eq!( - calc_with_default_pool!(calc_out_given_in, (largest_amount_in + 1).into()).unwrap_err(), + calc_with_default_pool!(calc_out_given_in, U256::from(largest_amount_in + 1)) + .unwrap_err(), // > await calc_with_default_pool("_calcOutGivenIn", "6000000000000000000001") "304".into() ); let largest_amount_out = deposit_out * 3 / 10; assert_eq!( - calc_with_default_pool!(calc_in_given_out, largest_amount_out.into()).unwrap(), + calc_with_default_pool!(calc_in_given_out, U256::from(largest_amount_out)).unwrap(), // > await calc_with_default_pool("_calcInGivenOut", "3000000000000000000000") - Bfp::from_wei(8_571_428_571_428_857_160_000_u128.into()) + Bfp::from_wei(U256::from(8_571_428_571_428_857_160_000_u128)) ); assert_eq!( - calc_with_default_pool!(calc_in_given_out, (largest_amount_out + 1).into()) + calc_with_default_pool!(calc_in_given_out, U256::from(largest_amount_out + 1)) .unwrap_err(), // > await calc_with_default_pool("_calcInGivenOut", "3000000000000000000001") "305".into() diff --git a/crates/shared/src/sources/mod.rs b/crates/shared/src/sources/mod.rs index 0c86d7eea9..c07cd21ba1 100644 --- a/crates/shared/src/sources/mod.rs +++ b/crates/shared/src/sources/mod.rs @@ -6,16 +6,7 @@ pub mod uniswap_v2; pub mod uniswap_v3; pub mod uniswap_v3_pair_provider; -use { - self::uniswap_v2::pool_fetching::{Pool, PoolFetching}, - crate::recent_block_cache::Block, - anyhow::Result, - chain::Chain, - core::panic, - model::TokenPair, - std::{collections::HashSet, sync::Arc}, - tracing::instrument, -}; +use {chain::Chain, core::panic}; #[derive(Debug, Clone, Copy, Eq, Hash, PartialEq, clap::ValueEnum)] #[clap(rename_all = "verbatim")] @@ -75,24 +66,3 @@ pub fn defaults_for_network(chain: &Chain) -> Vec { Chain::Hardhat => panic!("unsupported baseline sources for Hardhat"), } } - -pub struct PoolAggregator { - pub pool_fetchers: Vec>, -} - -#[async_trait::async_trait] -impl PoolFetching for PoolAggregator { - #[instrument(skip_all)] - async fn fetch(&self, token_pairs: HashSet, at_block: Block) -> Result> { - // vk: Using try join means if any pool fetcher fails we fail too. Alternatively - // we could return the succeeding ones but I feel it is cleaner to - // forward the error. - let results = futures::future::try_join_all( - self.pool_fetchers - .iter() - .map(|pool_fetcher| pool_fetcher.fetch(token_pairs.clone(), at_block)), - ) - .await?; - Ok(results.into_iter().flatten().collect()) - } -} diff --git a/crates/solver/src/liquidity/balancer_v2.rs b/crates/solver/src/liquidity/balancer_v2.rs index d0f3a66c48..b22b3903ad 100644 --- a/crates/solver/src/liquidity/balancer_v2.rs +++ b/crates/solver/src/liquidity/balancer_v2.rs @@ -18,7 +18,6 @@ use { }, alloy::primitives::{Address, B256}, anyhow::Result, - ethrpc::alloy::conversions::IntoAlloy, model::TokenPair, shared::{ ethrpc::Web3, @@ -83,7 +82,7 @@ impl BalancerV2Liquidity { fee: pool.common.swap_fee, version: pool.version, settlement_handling: Arc::new(SettlementHandler { - pool_id: pool.common.id.into_alloy(), + pool_id: pool.common.id, inner: inner.clone(), }), }) @@ -97,7 +96,7 @@ impl BalancerV2Liquidity { fee: pool.common.swap_fee, amplification_parameter: pool.amplification_parameter, settlement_handling: Arc::new(SettlementHandler { - pool_id: pool.common.id.into_alloy(), + pool_id: pool.common.id, inner: inner.clone(), }), }) diff --git a/crates/solvers/src/boundary/liquidity/stable.rs b/crates/solvers/src/boundary/liquidity/stable.rs index 5cc9ecddd0..2376605f97 100644 --- a/crates/solvers/src/boundary/liquidity/stable.rs +++ b/crates/solvers/src/boundary/liquidity/stable.rs @@ -2,7 +2,6 @@ pub use shared::sources::balancer_v2::pool_fetching::StablePool as Pool; use { crate::domain::{eth, liquidity}, alloy::primitives::{Address, B256, U256}, - ethrpc::alloy::conversions::IntoLegacy, shared::sources::balancer_v2::{ pool_fetching::{AmplificationParameter, CommonPoolState, TokenState}, swap::fixed_point::Bfp, @@ -26,21 +25,21 @@ pub fn to_boundary_pool(address: Address, pool: &liquidity::stable::Pool) -> Opt Some(( reserve.asset.token.0, TokenState { - balance: reserve.asset.amount.into_legacy(), + balance: reserve.asset.amount, scaling_factor: to_fixed_point(&reserve.scale.get())?, }, )) }) .collect::>()?; let amplification_parameter = AmplificationParameter::try_new( - pool.amplification_parameter.numer().into_legacy(), - pool.amplification_parameter.denom().into_legacy(), + *pool.amplification_parameter.numer(), + *pool.amplification_parameter.denom(), ) .ok()?; Some(Pool { common: CommonPoolState { - id: id.into_legacy(), + id, address, swap_fee, paused: false, @@ -57,5 +56,5 @@ fn to_fixed_point(ratio: ð::Rational) -> Option { // this format. let base = U256::from(10).pow(U256::from(18)); let wei = ratio.numer().checked_mul(base)? / ratio.denom(); - Some(Bfp::from_wei(wei.into_legacy())) + Some(Bfp::from_wei(wei)) } diff --git a/crates/solvers/src/boundary/liquidity/weighted_product.rs b/crates/solvers/src/boundary/liquidity/weighted_product.rs index 20839258ac..7dc28818d9 100644 --- a/crates/solvers/src/boundary/liquidity/weighted_product.rs +++ b/crates/solvers/src/boundary/liquidity/weighted_product.rs @@ -2,7 +2,6 @@ pub use shared::sources::balancer_v2::pool_fetching::WeightedPool as Pool; use { crate::domain::{eth, liquidity}, alloy::primitives::{Address, B256, U256}, - ethrpc::alloy::conversions::IntoLegacy, shared::sources::balancer_v2::{ pool_fetching::{CommonPoolState, TokenState, WeightedPoolVersion, WeightedTokenState}, swap::fixed_point::Bfp, @@ -30,7 +29,7 @@ pub fn to_boundary_pool( reserve.asset.token.0, WeightedTokenState { common: TokenState { - balance: reserve.asset.amount.into_legacy(), + balance: reserve.asset.amount, scaling_factor: to_fixed_point(&reserve.scale.get())?, }, weight: to_fixed_point(&reserve.weight)?, @@ -41,7 +40,7 @@ pub fn to_boundary_pool( Some(Pool { common: CommonPoolState { - id: id.into_legacy(), + id, address, swap_fee, paused: false, @@ -61,5 +60,5 @@ fn to_fixed_point(ratio: ð::Rational) -> Option { // this format. let base = U256::from(10).pow(U256::from(18)); let wei = ratio.numer().checked_mul(base)? / ratio.denom(); - Some(Bfp::from_wei(wei.into_legacy())) + Some(Bfp::from_wei(wei)) } From a869b5fb61cc36b886e87a5ea77c67dbbd91b890 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jose=CC=81=20Duarte?= Date: Tue, 6 Jan 2026 11:59:50 +0000 Subject: [PATCH 2/4] Address CI failures --- .../src/boundary/liquidity/balancer/v2/mod.rs | 2 +- .../src/sources/balancer_v2/pools/weighted.rs | 2 +- crates/solver/src/liquidity/balancer_v2.rs | 23 +++++++++---------- 3 files changed, 13 insertions(+), 14 deletions(-) diff --git a/crates/driver/src/boundary/liquidity/balancer/v2/mod.rs b/crates/driver/src/boundary/liquidity/balancer/v2/mod.rs index 94e217eda1..0e61710b0f 100644 --- a/crates/driver/src/boundary/liquidity/balancer/v2/mod.rs +++ b/crates/driver/src/boundary/liquidity/balancer/v2/mod.rs @@ -178,7 +178,7 @@ async fn init_liquidity( boundary::liquidity::http_client(), web3.clone(), &contracts, - config.pool_deny_list.iter().copied().collect(), + config.pool_deny_list.to_vec(), ) .await .context("failed to create balancer pool fetcher")?, diff --git a/crates/shared/src/sources/balancer_v2/pools/weighted.rs b/crates/shared/src/sources/balancer_v2/pools/weighted.rs index 956be9336e..686fdc14ae 100644 --- a/crates/shared/src/sources/balancer_v2/pools/weighted.rs +++ b/crates/shared/src/sources/balancer_v2/pools/weighted.rs @@ -77,7 +77,7 @@ impl FactoryIndexing for BalancerV2WeightedPoolFactory::Instance { .call() .await? .into_iter() - .map(|weight| Bfp::from_wei(weight)) + .map(Bfp::from_wei) .collect(); Ok(PoolInfo { diff --git a/crates/solver/src/liquidity/balancer_v2.rs b/crates/solver/src/liquidity/balancer_v2.rs index b22b3903ad..3892b12b77 100644 --- a/crates/solver/src/liquidity/balancer_v2.rs +++ b/crates/solver/src/liquidity/balancer_v2.rs @@ -228,7 +228,6 @@ mod tests { crate::interactions::allowances::{Approval, MockAllowanceManaging}, alloy::primitives::U256, contracts::alloy::BalancerV2Vault, - ethrpc::alloy::conversions::IntoLegacy, maplit::{btreemap, hashmap, hashset}, mockall::predicate::*, model::TokenPair, @@ -276,7 +275,7 @@ mod tests { let weighted_pools = vec![ WeightedPool { common: CommonPoolState { - id: B256::repeat_byte(0x90).into_legacy(), + id: B256::repeat_byte(0x90), address: Address::repeat_byte(0x90), swap_fee: "0.002".parse().unwrap(), paused: true, @@ -284,21 +283,21 @@ mod tests { reserves: btreemap! { Address::repeat_byte(0x70) => WeightedTokenState { common: TokenState { - balance: 100.into(), + balance: U256::from(100), scaling_factor: Bfp::exp10(16), }, weight: "0.25".parse().unwrap(), }, Address::repeat_byte(0x71) => WeightedTokenState { common: TokenState { - balance: 1_000_000.into(), + balance: U256::from(1_000_000), scaling_factor: Bfp::exp10(12), }, weight: "0.25".parse().unwrap(), }, Address::repeat_byte(0xb0) => WeightedTokenState { common: TokenState { - balance: 1_000_000_000_000_000_000u128.into(), + balance: U256::from(1_000_000_000_000_000_000u128), scaling_factor: Bfp::exp10(0), }, weight: "0.5".parse().unwrap(), @@ -308,7 +307,7 @@ mod tests { }, WeightedPool { common: CommonPoolState { - id: B256::repeat_byte(0x91).into_legacy(), + id: B256::repeat_byte(0x91), address: Address::repeat_byte(0x91), swap_fee: "0.001".parse().unwrap(), paused: true, @@ -316,14 +315,14 @@ mod tests { reserves: btreemap! { Address::repeat_byte(0x73) => WeightedTokenState { common: TokenState { - balance: 1_000_000_000_000_000_000u128.into(), + balance: U256::from(1_000_000_000_000_000_000u128), scaling_factor: Bfp::exp10(0), }, weight: "0.5".parse().unwrap(), }, Address::repeat_byte(0xb0) => WeightedTokenState { common: TokenState { - balance: 1_000_000_000_000_000_000u128.into(), + balance: U256::from(1_000_000_000_000_000_000u128), scaling_factor: Bfp::exp10(0), }, weight: "0.5".parse().unwrap(), @@ -335,19 +334,19 @@ mod tests { let stable_pools = vec![StablePool { common: CommonPoolState { - id: B256::repeat_byte(0x92).into_legacy(), + id: B256::repeat_byte(0x92), address: Address::repeat_byte(0x92), swap_fee: "0.002".parse().unwrap(), paused: true, }, - amplification_parameter: AmplificationParameter::try_new(1.into(), 1.into()).unwrap(), + amplification_parameter: AmplificationParameter::try_new(U256::ONE, U256::ONE).unwrap(), reserves: btreemap! { Address::repeat_byte(0x73) => TokenState { - balance: 1_000_000_000_000_000_000u128.into(), + balance: U256::from(1_000_000_000_000_000_000u128), scaling_factor: Bfp::exp10(0), }, Address::repeat_byte(0xb0) => TokenState { - balance: 1_000_000_000_000_000_000u128.into(), + balance: U256::from(1_000_000_000_000_000_000u128), scaling_factor: Bfp::exp10(0), } }, From 3c8f31c5a6b320c17c2e2d5adeba0e31fde99146 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jose=CC=81=20Duarte?= Date: Wed, 7 Jan 2026 14:56:59 +0000 Subject: [PATCH 3/4] fmt and comp fix --- .../src/sources/balancer_v2/graph_api.rs | 4 +++- .../balancer_v2/pool_fetching/pool_storage.rs | 3 ++- .../src/sources/balancer_v2/pools/common.rs | 2 +- .../pools/liquidity_bootstrapping.rs | 3 ++- .../src/sources/balancer_v2/pools/weighted.rs | 4 +++- .../src/sources/balancer_v2/swap/mod.rs | 6 ++++- crates/solver/src/liquidity/balancer_v2.rs | 22 ++++++++++++++----- 7 files changed, 33 insertions(+), 11 deletions(-) diff --git a/crates/shared/src/sources/balancer_v2/graph_api.rs b/crates/shared/src/sources/balancer_v2/graph_api.rs index c6037c439d..515dbdd36d 100644 --- a/crates/shared/src/sources/balancer_v2/graph_api.rs +++ b/crates/shared/src/sources/balancer_v2/graph_api.rs @@ -242,7 +242,9 @@ mod block_number_query { #[cfg(test)] mod tests { use { - super::*, crate::sources::balancer_v2::swap::fixed_point::Bfp, alloy::primitives::U256, + super::*, + crate::sources::balancer_v2::swap::fixed_point::Bfp, + alloy::primitives::U256, maplit::hashmap, }; diff --git a/crates/shared/src/sources/balancer_v2/pool_fetching/pool_storage.rs b/crates/shared/src/sources/balancer_v2/pool_fetching/pool_storage.rs index 497c328a58..baf2ab163d 100644 --- a/crates/shared/src/sources/balancer_v2/pool_fetching/pool_storage.rs +++ b/crates/shared/src/sources/balancer_v2/pool_fetching/pool_storage.rs @@ -26,7 +26,8 @@ use { }, anyhow::{Context, Result}, contracts::alloy::BalancerV2BasePoolFactory::BalancerV2BasePoolFactory::{ - BalancerV2BasePoolFactoryEvents, PoolCreated, + BalancerV2BasePoolFactoryEvents, + PoolCreated, }, ethrpc::block_stream::RangeInclusive, model::TokenPair, diff --git a/crates/shared/src/sources/balancer_v2/pools/common.rs b/crates/shared/src/sources/balancer_v2/pools/common.rs index bb8a7d1308..bd84d77f5f 100644 --- a/crates/shared/src/sources/balancer_v2/pools/common.rs +++ b/crates/shared/src/sources/balancer_v2/pools/common.rs @@ -100,7 +100,7 @@ impl PoolInfoFetcher { let scaling_factors = self.scaling_factors(&tokens).await?; Ok(PoolInfo { - id: pool_id.into_legacy(), + id: pool_id, address: pool_address, tokens, scaling_factors, diff --git a/crates/shared/src/sources/balancer_v2/pools/liquidity_bootstrapping.rs b/crates/shared/src/sources/balancer_v2/pools/liquidity_bootstrapping.rs index 019a915cf1..c194ee573d 100644 --- a/crates/shared/src/sources/balancer_v2/pools/liquidity_bootstrapping.rs +++ b/crates/shared/src/sources/balancer_v2/pools/liquidity_bootstrapping.rs @@ -9,7 +9,8 @@ use { alloy::eips::BlockId, anyhow::Result, contracts::alloy::{ - BalancerV2LiquidityBootstrappingPool, BalancerV2LiquidityBootstrappingPoolFactory, + BalancerV2LiquidityBootstrappingPool, + BalancerV2LiquidityBootstrappingPoolFactory, }, futures::{FutureExt as _, future::BoxFuture}, }; diff --git a/crates/shared/src/sources/balancer_v2/pools/weighted.rs b/crates/shared/src/sources/balancer_v2/pools/weighted.rs index d525389e9d..3e60249538 100644 --- a/crates/shared/src/sources/balancer_v2/pools/weighted.rs +++ b/crates/shared/src/sources/balancer_v2/pools/weighted.rs @@ -9,7 +9,9 @@ use { alloy::{eips::BlockId, primitives::Address}, anyhow::{Result, anyhow}, contracts::alloy::{ - BalancerV2WeightedPool, BalancerV2WeightedPoolFactory, BalancerV2WeightedPoolFactoryV3, + BalancerV2WeightedPool, + BalancerV2WeightedPoolFactory, + BalancerV2WeightedPoolFactoryV3, }, futures::{FutureExt as _, future::BoxFuture}, std::collections::BTreeMap, diff --git a/crates/shared/src/sources/balancer_v2/swap/mod.rs b/crates/shared/src/sources/balancer_v2/swap/mod.rs index 41a6d8cdcb..ff0871d169 100644 --- a/crates/shared/src/sources/balancer_v2/swap/mod.rs +++ b/crates/shared/src/sources/balancer_v2/swap/mod.rs @@ -3,7 +3,11 @@ use { baseline_solver::BaselineSolvable, conversions::U256Ext, sources::balancer_v2::pool_fetching::{ - AmplificationParameter, StablePool, TokenState, WeightedPool, WeightedPoolVersion, + AmplificationParameter, + StablePool, + TokenState, + WeightedPool, + WeightedPoolVersion, WeightedTokenState, }, }, diff --git a/crates/solver/src/liquidity/balancer_v2.rs b/crates/solver/src/liquidity/balancer_v2.rs index a2ccbb06c0..3892b12b77 100644 --- a/crates/solver/src/liquidity/balancer_v2.rs +++ b/crates/solver/src/liquidity/balancer_v2.rs @@ -7,7 +7,11 @@ use { allowances::{AllowanceManager, AllowanceManaging, Allowances}, }, liquidity::{ - AmmOrderExecution, Liquidity, SettlementHandling, StablePoolOrder, WeightedProductOrder, + AmmOrderExecution, + Liquidity, + SettlementHandling, + StablePoolOrder, + WeightedProductOrder, }, liquidity_collector::LiquidityCollecting, settlement::SettlementEncoder, @@ -16,7 +20,9 @@ use { anyhow::Result, model::TokenPair, shared::{ - ethrpc::Web3, http_solver::model::TokenAmount, recent_block_cache::Block, + ethrpc::Web3, + http_solver::model::TokenAmount, + recent_block_cache::Block, sources::balancer_v2::pool_fetching::BalancerPoolFetching, }, std::{collections::HashSet, sync::Arc}, @@ -231,9 +237,15 @@ mod tests { interaction::Interaction, sources::balancer_v2::{ pool_fetching::{ - AmplificationParameter, CommonPoolState, FetchedBalancerPools, - MockBalancerPoolFetching, StablePool, TokenState, WeightedPool, - WeightedPoolVersion, WeightedTokenState, + AmplificationParameter, + CommonPoolState, + FetchedBalancerPools, + MockBalancerPoolFetching, + StablePool, + TokenState, + WeightedPool, + WeightedPoolVersion, + WeightedTokenState, }, swap::fixed_point::Bfp, }, From 5640967867559b6f61b2a1989c7bb4576cf6e285 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Duarte?= Date: Wed, 7 Jan 2026 16:02:16 +0000 Subject: [PATCH 4/4] Update crates/shared/src/sources/balancer_v2/pool_fetching/pool_storage.rs Co-authored-by: Marcin Szymczak --- .../src/sources/balancer_v2/pool_fetching/pool_storage.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/shared/src/sources/balancer_v2/pool_fetching/pool_storage.rs b/crates/shared/src/sources/balancer_v2/pool_fetching/pool_storage.rs index baf2ab163d..203289a30f 100644 --- a/crates/shared/src/sources/balancer_v2/pool_fetching/pool_storage.rs +++ b/crates/shared/src/sources/balancer_v2/pool_fetching/pool_storage.rs @@ -247,7 +247,7 @@ mod tests { Vec, Vec<(PoolCreated, u64)>, ); - // This can be made cleaner by making the start and end be u8's but theB256 + // This can be made cleaner by making the start and end be u8's but the B256 // doesn't support for a from(u8) so this needs to be reviewed upon migration fn pool_init_data(start: usize, end: usize) -> PoolInitData { let pool_ids: Vec = (start..=end)