diff --git a/crates/driver/src/boundary/liquidity/balancer/v2/mod.rs b/crates/driver/src/boundary/liquidity/balancer/v2/mod.rs index 6ffd9bbdc6..0e61710b0f 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.to_vec(), ) .await .context("failed to create balancer pool fetcher")?, 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 faf32d7160..515dbdd36d 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, @@ -246,7 +245,6 @@ mod tests { super::*, crate::sources::balancer_v2::swap::fixed_point::Bfp, alloy::primitives::U256, - ethcontract::H256, maplit::hashmap, }; @@ -336,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, @@ -359,7 +357,7 @@ mod tests { }, 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, @@ -378,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, @@ -401,7 +399,7 @@ mod tests { }, 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, @@ -447,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 122c23b834..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 @@ -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)) @@ -239,17 +241,17 @@ mod tests { }; 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 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) - .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)) @@ -280,7 +282,7 @@ 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)], @@ -293,7 +295,7 @@ mod tests { }, 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), @@ -311,7 +313,7 @@ mod tests { }, 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)], @@ -329,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)], } ); } @@ -441,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(U256::from(1337u64))], + 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 6790656ec9..c542c5c334 100644 --- a/crates/shared/src/sources/balancer_v2/pool_fetching/registry.rs +++ b/crates/shared/src/sources/balancer_v2/pool_fetching/registry.rs @@ -14,13 +14,13 @@ 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}, - ethcontract::{BlockId, H256}, ethrpc::{ alloy::errors::ContractErrorExt, block_stream::{BlockNumberHash, BlockRetrieving}, @@ -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; diff --git a/crates/shared/src/sources/balancer_v2/pools/common.rs b/crates/shared/src/sources/balancer_v2/pools/common.rs index 12e056b88f..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, U256}, + alloy::{ + eips::BlockId, + primitives::{Address, B256, U256}, + }, anyhow::{Context, Result, anyhow, ensure}, contracts::alloy::{BalancerV2BasePool, BalancerV2Vault}, - ethcontract::{BlockId, H256}, - ethrpc::alloy::conversions::{IntoAlloy, IntoLegacy}, futures::{FutureExt as _, future::BoxFuture}, std::{collections::BTreeMap, future::Future, sync::Arc}, tokio::sync::oneshot, @@ -99,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, @@ -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(); @@ -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, @@ -374,7 +374,6 @@ mod tests { maplit::{btreemap, hashmap}, mockall::predicate, std::future, - web3::types::BlockNumber, }; #[tokio::test] @@ -430,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)], @@ -441,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), @@ -499,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() }; @@ -588,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 }; @@ -628,7 +623,7 @@ mod tests { 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), @@ -683,7 +678,7 @@ mod tests { 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( @@ -787,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() }; @@ -859,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() }; @@ -915,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, @@ -936,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)], @@ -949,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, @@ -966,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 a5573bd220..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, 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 { @@ -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 b2b8229f5d..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, 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 { @@ -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 be9f1f262a..e9b370ef31 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, U256}, + alloy::{ + eips::BlockId, + primitives::{Address, U256}, + }, anyhow::{Result, ensure}, contracts::alloy::{BalancerV2StablePool, BalancerV2StablePoolFactoryV2}, - ethcontract::BlockId, - ethrpc::alloy::conversions::IntoAlloy, 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) @@ -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(U256::from(2u64), U256::from(3u64)) + AmplificationParameter::try_new(U256::from(2), U256::from(3)) .unwrap() - .with_base(U256::from(1000u64)) + .with_base(U256::from(1000)) .unwrap(), - U256::from(666u64) + U256::from(666) ); assert_eq!( - AmplificationParameter::try_new(U256::from(7u64), U256::from(8u64)) + AmplificationParameter::try_new(U256::from(7), U256::from(8)) .unwrap() .as_big_rational(), BigRational::new(7.into(), 8.into()) ); assert_eq!( - AmplificationParameter::try_new(U256::from(1u64), U256::from(0u64)) + AmplificationParameter::try_new(U256::ONE, U256::ZERO) .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 1a7f31e231..3e60249538 100644 --- a/crates/shared/src/sources/balancer_v2/pools/weighted.rs +++ b/crates/shared/src/sources/balancer_v2/pools/weighted.rs @@ -6,14 +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, futures::{FutureExt as _, future::BoxFuture}, std::collections::BTreeMap, }; @@ -148,11 +147,10 @@ mod tests { super::*, crate::sources::balancer_v2::graph_api::Token, alloy::{ - primitives::{Address, U256}, + primitives::{Address, B256, U256}, providers::{Provider, ProviderBuilder, mock::Asserter}, sol_types::SolCall, }, - ethcontract::H256, ethrpc::{Web3, mock::MockTransport}, futures::future, maplit::btreemap, @@ -162,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, @@ -184,7 +182,7 @@ 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)], @@ -202,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, @@ -248,7 +246,7 @@ mod tests { 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), @@ -272,7 +270,7 @@ mod tests { scaling_factor: Bfp::exp10(0), }, Address::repeat_byte(2) => common::TokenState { - balance: U256::from(10_000_000u64), + balance: U256::from(10_000_000), scaling_factor: Bfp::exp10(12), }, }; @@ -287,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(), @@ -307,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 80e43e0860..c55af870b4 100644 --- a/crates/shared/src/sources/balancer_v2/swap/fixed_point.rs +++ b/crates/shared/src/sources/balancer_v2/swap/fixed_point.rs @@ -88,8 +88,12 @@ impl FromStr for Bfp { impl Debug for Bfp { fn fmt(&self, formatter: &mut Formatter) -> fmt::Result { - let low: u128 = u128::try_from(self.0 % *ONE_18).unwrap(); - write!(formatter, "{}.{:0>18}", self.0 / *ONE_18, low) + write!( + formatter, + "{}.{:0>18}", + self.0 / *ONE_18, + u128::try_from(self.0 % *ONE_18).unwrap() + ) } } @@ -121,7 +125,7 @@ impl Bfp { return Self::zero(); } - Self(U256::from(10u64).pow(U256::from(exp))) + Self(U256::from(10).pow(U256::from(exp))) } pub fn from_wei(num: U256) -> Self { @@ -220,12 +224,12 @@ mod tests { num::{BigInt, One, Zero}, }; + static EPSILON: LazyLock = LazyLock::new(|| Bfp(U256::ONE)); + fn test_exp10(n: u8) -> U256 { U256::from(10u64).pow(U256::from(n)) } - static EPSILON: LazyLock = LazyLock::new(|| Bfp(U256::from(1u64))); - #[test] fn parsing() { assert_eq!("1".parse::().unwrap(), Bfp::one()); @@ -271,15 +275,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 / test_exp10(18))) - .unwrap(), - Bfp(U256::MAX / test_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 / test_exp10(18) + U256::ONE)) + .$fn_name(Bfp(U256::MAX / *ONE_18 + U256::ONE)) .unwrap_err(), Error::MulOverflow, ); @@ -291,7 +293,7 @@ mod tests { test_mul!(mul_down); test_mul!(mul_up); - let one_half = Bfp(U256::from(5u64) * U256::from(10u64).pow(U256::from(17u64))); + 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); @@ -318,7 +320,7 @@ mod tests { Error::ZeroDivision ); assert_eq!( - Bfp(U256::MAX / test_exp10(18) + U256::ONE) + Bfp(U256::MAX / *ONE_18 + U256::ONE) .$fn_name(Bfp::one()) .unwrap_err(), Error::DivInternal, 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 24447a2fae..89f7137cf4 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 @@ -149,10 +149,10 @@ fn exp(mut x: I256) -> Result { x -= constant_x_18(1); first_an = constant_a_18(1); } else { - first_an = I256::try_from(1i64).expect("1 fits in I256"); + first_an = I256::ONE; } - x *= I256::try_from(100i64).expect("100 fits in I256"); + x *= I256::try_from(100).expect("100 fits in I256"); let mut product = *ONE_20; for i in 2..=9 { @@ -172,7 +172,7 @@ fn exp(mut x: I256) -> Result { } Ok((((product * series_sum) / *ONE_20) * first_an) - / I256::try_from(100i64).expect("100 fits in I256")) + / I256::try_from(100).expect("100 fits in I256")) } fn _ln(mut a: I256) -> I256 { @@ -188,8 +188,8 @@ fn _ln(mut a: I256) -> I256 { } } - sum *= I256::try_from(100i64).expect("100 fits in I256"); - a *= I256::try_from(100i64).expect("100 fits in I256"); + sum *= I256::try_from(100).expect("100 fits in I256"); + a *= I256::try_from(100).expect("100 fits in I256"); for i in 2..=11 { if a >= constant_a_20(i) { @@ -209,9 +209,9 @@ fn _ln(mut a: I256) -> I256 { series_sum += num / I256::try_from(i).expect("loop index fits in I256"); } - series_sum *= I256::try_from(2i64).expect("2 fits in I256"); + series_sum *= I256::try_from(2).expect("2 fits in I256"); - (sum + series_sum) / I256::try_from(100i64).expect("100 fits in I256") + (sum + series_sum) / I256::try_from(100).expect("100 fits in I256") } fn _ln_36(mut x: I256) -> I256 { @@ -228,7 +228,7 @@ fn _ln_36(mut x: I256) -> I256 { series_sum += num / I256::try_from(i).expect("loop index fits in I256"); } - series_sum * I256::try_from(2i64).expect("2 fits in I256") + series_sum * I256::try_from(2).expect("2 fits in I256") } #[cfg(test)] @@ -566,22 +566,12 @@ 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::ZERO, U256::ZERO), Ok(*UFIXED256X18_ONE)); + assert_eq!(pow(U256::ZERO, U256::ONE), Ok(U256::ZERO)); assert_eq!( - pow( - U256::from_str_radix("0", 10).unwrap(), - U256::from_str_radix("0", 10).unwrap() - ), - Ok(*UFIXED256X18_ONE) - ); - assert_eq!( - pow( - U256::from_str_radix("0", 10).unwrap(), - U256::from_str_radix("1", 10).unwrap() - ), - Ok(U256::ZERO) - ); - assert_eq!( - pow(U256::from(10u64).pow(U256::from(18u64)), U256::from(1u64)), + pow(U256::from(10u64).pow(U256::from(18u64)), 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 3a6fc2cc66..589bc16250 100644 --- a/crates/shared/src/sources/balancer_v2/swap/math.rs +++ b/crates/shared/src/sources/balancer_v2/swap/math.rs @@ -35,7 +35,7 @@ impl BalU256 for U256 { if self.is_zero() { return Ok(U256::ZERO); } - let one = U256::from(1u64); + let one = U256::ONE; Ok(one + (self - one) / other) } } @@ -47,7 +47,7 @@ mod tests { #[test] fn bmul_tests() { let zero = U256::ZERO; - let one = U256::from(1u64); + let one = U256::ONE; let max = U256::MAX; assert_eq!(zero.bmul(one).unwrap(), zero); assert_eq!(one.bmul(one).unwrap(), one); @@ -61,8 +61,8 @@ mod tests { #[test] fn badd_tests() { let zero = U256::ZERO; - let one = U256::from(1u64); - let two = U256::from(2u64); + let one = U256::ONE; + let two = U256::from(2); let max = U256::MAX; assert_eq!(zero.badd(one).unwrap(), one); assert_eq!(one.badd(one).unwrap(), two); @@ -76,8 +76,8 @@ mod tests { #[test] fn bsub_tests() { let zero = U256::ZERO; - let one = U256::from(1u64); - let two = U256::from(2u64); + let one = U256::ONE; + let two = U256::from(2); assert_eq!(two.bsub(zero).unwrap(), two); assert_eq!(two.bsub(one).unwrap(), one); assert_eq!(two.bsub(two).unwrap(), zero); @@ -90,8 +90,8 @@ mod tests { #[test] fn div_down_tests() { let zero = U256::ZERO; - let one = U256::from(1u64); - let two = U256::from(2u64); + 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); assert_eq!(two.bdiv_down(two).unwrap(), one); @@ -105,8 +105,8 @@ mod tests { #[test] fn div_up_tests() { let zero = U256::ZERO; - let one = U256::from(1u64); - let two = U256::from(2u64); + 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); assert_eq!(two.bdiv_up(two).unwrap(), one); diff --git a/crates/shared/src/sources/balancer_v2/swap/mod.rs b/crates/shared/src/sources/balancer_v2/swap/mod.rs index 21115da39e..ff0871d169 100644 --- a/crates/shared/src/sources/balancer_v2/swap/mod.rs +++ b/crates/shared/src/sources/balancer_v2/swap/mod.rs @@ -347,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::from(1u64))) - .max(U256::from(1u64)); + .ceil_div(&out_amount.max(U256::ONE)) + .max(U256::ONE); for _ in 0..6 { let bumped_in_amount = in_amount.checked_add(bump)?; @@ -357,7 +357,7 @@ fn converge_in_amount( return Some(bumped_in_amount); } - bump *= U256::from(10u64); + bump *= U256::from(10); } None @@ -526,8 +526,8 @@ 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![ @@ -557,8 +557,8 @@ 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![ @@ -581,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| U256::from(n)).collect(); + let balances = (1..=3).map(U256::from).collect(); let pool = create_stable_pool_with( tokens.clone(), balances, - AmplificationParameter::try_new(U256::from(1u64), U256::from(1u64)).unwrap(), + AmplificationParameter::try_new(U256::ONE, U256::ONE).unwrap(), vec![Bfp::exp10(18), Bfp::exp10(18), Bfp::exp10(18)], - U256::from(1u64), + U256::ONE, ); for token_i in tokens.iter() { @@ -627,7 +627,7 @@ 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(U256::from(570000u64), U256::from(1000u64)).unwrap(); + AmplificationParameter::try_new(U256::from(570000), U256::from(1000)).unwrap(); let balances = vec![ U256::from(40_927_687_702_846_622_465_144_342_u128), U256::from(59_448_574_675_062_u128), @@ -660,7 +660,7 @@ 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(U256::from(570000u64), U256::from(1000u64)).unwrap(); + AmplificationParameter::try_new(U256::from(570000), U256::from(1000)).unwrap(); let balances = vec![ U256::from(34_869_494_603_218_073_631_628_580_u128), U256::from(48_176_005_970_419_u128), 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 0d59421d84..72c77856db 100644 --- a/crates/shared/src/sources/balancer_v2/swap/stable_math.rs +++ b/crates/shared/src/sources/balancer_v2/swap/stable_math.rs @@ -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(U256::from(1u64))?.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(U256::from(1u64))) + .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(U256::from(1u64))) + .add(Bfp::from_wei(U256::ONE)) } /// https://github.com/balancer-labs/balancer-v2-monorepo/blob/ad1442113b26ec22081c2047e2ec95355a7f12ba/pkg/pool-stable/contracts/StableMath.sol#L465-L516 @@ -179,7 +179,7 @@ fn get_token_balance_given_invariant_and_all_other_balances( // ); token_balance = token_balance.bmul(token_balance)?.badd(c)?.bdiv_up( token_balance - .bmul(U256::from(2u64))? + .bmul(U256::from(2))? .badd(b)? .bsub(invariant)?, )?; @@ -192,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::from(1u64); + let one = U256::ONE; if curr_value > prev_value { if curr_value .bsub(prev_value) @@ -221,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, - alloy::primitives::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 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 658f3025cb..58aab4d830 100644 --- a/crates/shared/src/sources/balancer_v2/swap/weighted_math.rs +++ b/crates/shared/src/sources/balancer_v2/swap/weighted_math.rs @@ -181,11 +181,11 @@ mod tests { #[test] fn calc_out_given_in_err() { - let zero = Bfp::from_wei(U256::from(0u64)); - let one = Bfp::from_wei(U256::from(1u64)); - let two = Bfp::from_wei(U256::from(2u64)); + let zero = Bfp::from_wei(U256::ZERO); + let one = Bfp::from_wei(U256::ONE); + 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 / (exp10(17) * U256::from(3u64))); + let max_balance_in = Bfp::from_wei(U256::MAX / (exp10(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) @@ -238,11 +238,11 @@ mod tests { #[test] fn calc_in_given_out_err() { - let zero = Bfp::from_wei(U256::from(0u64)); - let one = Bfp::from_wei(U256::from(1u64)); - let two = Bfp::from_wei(U256::from(2u64)); + let zero = Bfp::from_wei(U256::ZERO); + let one = Bfp::from_wei(U256::ONE); + let two = Bfp::from_wei(U256::from(2)); let max_u256 = Bfp::from_wei(U256::MAX); - let max_balance = Bfp::from_wei(U256::MAX / (exp10(17) * U256::from(3u64))); + let max_balance = Bfp::from_wei(U256::MAX / (exp10(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) 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 b81d0ee9a7..3892b12b77 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(), }), }) @@ -229,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, @@ -277,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, @@ -309,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, @@ -336,13 +334,12 @@ 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(U256::from(1), U256::from(1)) - .unwrap(), + amplification_parameter: AmplificationParameter::try_new(U256::ONE, U256::ONE).unwrap(), reserves: btreemap! { Address::repeat_byte(0x73) => TokenState { balance: U256::from(1_000_000_000_000_000_000u128), diff --git a/crates/solvers/src/boundary/liquidity/stable.rs b/crates/solvers/src/boundary/liquidity/stable.rs index a0479aa4f3..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, @@ -40,7 +39,7 @@ pub fn to_boundary_pool(address: Address, pool: &liquidity::stable::Pool) -> Opt Some(Pool { common: CommonPoolState { - id: id.into_legacy(), + id, address, swap_fee, paused: false, diff --git a/crates/solvers/src/boundary/liquidity/weighted_product.rs b/crates/solvers/src/boundary/liquidity/weighted_product.rs index d96cc1faa8..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, @@ -41,7 +40,7 @@ pub fn to_boundary_pool( Some(Pool { common: CommonPoolState { - id: id.into_legacy(), + id, address, swap_fee, paused: false,