From 14db9e46531efc71e4deb3b396d2d630f1df33a4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jose=CC=81=20Duarte?= Date: Fri, 12 Dec 2025 13:36:03 +0000 Subject: [PATCH 1/3] Migrate "shared" and model ethcontract/primitive-types usages into alloy --- Cargo.lock | 2 - .../src/database/onchain_order_events/mod.rs | 2 +- crates/autopilot/src/run.rs | 5 +- crates/autopilot/src/solvable_orders.rs | 12 +- crates/cow-amm/src/amm.rs | 3 +- .../src/boundary/liquidity/uniswap/v3.rs | 14 +- .../src/domain/competition/pre_processing.rs | 6 +- crates/driver/src/infra/blockchain/mod.rs | 4 +- .../e2e/src/setup/onchain_components/mod.rs | 35 ----- crates/e2e/src/setup/solver/solution.rs | 5 +- crates/e2e/tests/e2e/jit_orders.rs | 4 +- crates/model/Cargo.toml | 1 - crates/model/src/signature.rs | 7 +- crates/number/src/serialization.rs | 124 +----------------- crates/orderbook/src/orderbook.rs | 3 +- crates/orderbook/src/run.rs | 7 +- crates/shared/src/account_balances/cached.rs | 30 ++--- crates/shared/src/account_balances/mod.rs | 35 +++-- .../shared/src/account_balances/simulation.rs | 53 ++++---- crates/shared/src/encoded_settlement.rs | 24 ++-- .../shared/src/gas_price_estimation/driver.rs | 8 +- crates/shared/src/order_quoting.rs | 26 ++-- crates/shared/src/order_validation.rs | 31 +++-- .../src/price_estimation/native/oneinch.rs | 5 +- .../price_estimation/trade_verifier/mod.rs | 43 +++--- crates/shared/src/signature_validator/mod.rs | 11 +- .../src/signature_validator/simulation.rs | 4 +- crates/shared/src/sources/uniswap_v2/mod.rs | 50 +++---- .../src/sources/uniswap_v3/graph_api.rs | 52 ++++---- .../src/sources/uniswap_v3/pool_fetching.rs | 78 ++++++----- crates/shared/src/trade_finding/external.rs | 63 +++++---- crates/solver/src/liquidity/uniswap_v3.rs | 12 +- crates/solver/src/settlement/mod.rs | 5 +- .../src/settlement/settlement_encoder.rs | 12 +- crates/solvers/Cargo.toml | 1 - 35 files changed, 284 insertions(+), 493 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 9c473f09ab..67acbdec62 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4431,7 +4431,6 @@ dependencies = [ "maplit", "num", "number", - "primitive-types", "secp256k1 0.27.0", "serde", "serde_json", @@ -6509,7 +6508,6 @@ dependencies = [ "const-hex", "contracts", "derive_more 1.0.0", - "ethcontract", "ethrpc", "futures", "hex-literal", diff --git a/crates/autopilot/src/database/onchain_order_events/mod.rs b/crates/autopilot/src/database/onchain_order_events/mod.rs index a85fd822bc..5fdf9e2c54 100644 --- a/crates/autopilot/src/database/onchain_order_events/mod.rs +++ b/crates/autopilot/src/database/onchain_order_events/mod.rs @@ -574,7 +574,7 @@ async fn get_quote( quoter, ¶meters.clone(), Some(*quote_id), - Some(order_data.fee_amount.into_legacy()), + Some(order_data.fee_amount), ) .await .map_err(|err| match err { diff --git a/crates/autopilot/src/run.rs b/crates/autopilot/src/run.rs index daea7346b5..7f92a5f00d 100644 --- a/crates/autopilot/src/run.rs +++ b/crates/autopilot/src/run.rs @@ -229,8 +229,7 @@ pub async fn run(args: Arguments, shutdown_controller: ShutdownController) { .vaultRelayer() .call() .await - .expect("Couldn't get vault relayer address") - .into_legacy(); + .expect("Couldn't get vault relayer address"); let vault_address = args.shared.balancer_v2_vault_address.or_else(|| { let chain_id = chain.id(); @@ -271,7 +270,7 @@ pub async fn run(args: Arguments, shutdown_controller: ShutdownController) { eth.contracts().settlement().clone(), eth.contracts().balances().clone(), vault_relayer, - vault_address.map(IntoLegacy::into_legacy), + vault_address, balance_overrider, ), eth.current_block().clone(), diff --git a/crates/autopilot/src/solvable_orders.rs b/crates/autopilot/src/solvable_orders.rs index 3ba20c30e8..1184164686 100644 --- a/crates/autopilot/src/solvable_orders.rs +++ b/crates/autopilot/src/solvable_orders.rs @@ -8,7 +8,6 @@ use { anyhow::{Context, Result}, bigdecimal::BigDecimal, database::order_events::OrderEventLabel, - ethrpc::alloy::conversions::{IntoAlloy, IntoLegacy}, futures::{FutureExt, StreamExt, future::join_all, stream::FuturesUnordered}, indexmap::IndexSet, itertools::Itertools, @@ -343,7 +342,7 @@ impl SolvableOrdersCache { .into_iter() .zip(fetched_balances) .filter_map(|(query, balance)| match balance { - Ok(balance) => Some((query, balance.into_alloy())), + Ok(balance) => Some((query, balance)), Err(err) => { tracing::warn!( owner = ?query.owner, @@ -514,7 +513,7 @@ async fn find_invalid_signature_orders( let (hash, signer, _) = order.metadata.uid.parts(); match signature_validator .validate_signature(SignatureCheck { - signer: signer.into_legacy(), + signer, hash: hash.0, signature: signature.clone(), interactions: order.interactions.pre.clone(), @@ -901,7 +900,6 @@ mod tests { use { super::*, alloy::primitives::{Address, B256}, - ethrpc::alloy::conversions::IntoLegacy, futures::FutureExt, maplit::{btreemap, hashset}, mockall::predicate::eq, @@ -1288,7 +1286,7 @@ mod tests { signature_validator .expect_validate_signature() .with(eq(SignatureCheck { - signer: Address::repeat_byte(22).into_legacy(), + signer: Address::repeat_byte(22), hash: [2; 32], signature: vec![2, 2], interactions: vec![InteractionData { @@ -1302,7 +1300,7 @@ mod tests { signature_validator .expect_validate_signature() .with(eq(SignatureCheck { - signer: Address::repeat_byte(44).into_legacy(), + signer: Address::repeat_byte(44), hash: [4; 32], signature: vec![4, 4, 4, 4], interactions: vec![], @@ -1312,7 +1310,7 @@ mod tests { signature_validator .expect_validate_signature() .with(eq(SignatureCheck { - signer: Address::repeat_byte(55).into_legacy(), + signer: Address::repeat_byte(55), hash: [5; 32], signature: vec![5, 5, 5, 5, 5], interactions: vec![], diff --git a/crates/cow-amm/src/amm.rs b/crates/cow-amm/src/amm.rs index c1a9286a86..48685db1f5 100644 --- a/crates/cow-amm/src/amm.rs +++ b/crates/cow-amm/src/amm.rs @@ -7,7 +7,6 @@ use { CowAmmLegacyHelper::CowAmmLegacyHelper::orderReturn, }, database::byte_array::ByteArray, - ethrpc::alloy::conversions::IntoLegacy, model::{ DomainSeparator, interaction::InteractionData, @@ -72,7 +71,7 @@ impl Amm { let hash = hashed_eip712_message(domain_separator, &template.order.hash_struct()); validator .validate_signature_and_get_additional_gas(SignatureCheck { - signer: self.address.into_legacy(), + signer: self.address, hash, signature: template.signature.to_bytes(), interactions: template.pre_interactions.clone(), diff --git a/crates/driver/src/boundary/liquidity/uniswap/v3.rs b/crates/driver/src/boundary/liquidity/uniswap/v3.rs index b68358ea05..f6d41df6b8 100644 --- a/crates/driver/src/boundary/liquidity/uniswap/v3.rs +++ b/crates/driver/src/boundary/liquidity/uniswap/v3.rs @@ -11,7 +11,7 @@ use { infra::{self, blockchain::Ethereum}, }, anyhow::Context, - ethrpc::{alloy::conversions::IntoAlloy, block_stream::BlockRetrieving}, + ethrpc::block_stream::BlockRetrieving, shared::{ http_solver::model::TokenAmount, interaction::Interaction, @@ -46,16 +46,16 @@ pub fn to_domain(id: liquidity::Id, pool: ConcentratedLiquidity) -> Result {{ - const NAME: &str = stringify!($call); - $call - .from($acc.clone()) - .value($value) - .send() - .await - .expect(&format!("{} failed", NAME)) - }}; -} - -#[macro_export] -macro_rules! tx { - ($acc:expr_2021, $call:expr_2021) => { - $crate::tx_value!($acc, ethcontract::U256::zero(), $call) - }; -} - -#[macro_export] -macro_rules! deploy { - ($web3:expr, $contract:ident) => { deploy!($web3, $contract ()) }; - ($web3:expr, $contract:ident ( $($param:expr_2021),* $(,)? )) => { - deploy!($web3, $contract ($($param),*) as stringify!($contract)) - }; - ($web3:expr, $contract:ident ( $($param:expr_2021),* $(,)? ) as $name:expr_2021) => {{ - let name = $name; - $contract::builder(&$web3 $(, $param)*) - .deploy() - .await - .unwrap_or_else(|e| panic!("failed to deploy {name}: {e:?}")) - }}; -} - #[derive(Clone, Debug)] pub struct TestAccount { account: Account, diff --git a/crates/e2e/src/setup/solver/solution.rs b/crates/e2e/src/setup/solver/solution.rs index 7930948677..134dd1c41b 100644 --- a/crates/e2e/src/setup/solver/solution.rs +++ b/crates/e2e/src/setup/solver/solution.rs @@ -1,7 +1,6 @@ use { + alloy::primitives::Address, app_data::AppDataHash, - ethcontract::common::abi::ethereum_types::Address, - ethrpc::alloy::conversions::IntoAlloy, model::{ DomainSeparator, order::{BuyTokenDestination, OrderData, OrderKind, OrderUid, SellTokenSource}, @@ -28,7 +27,7 @@ impl JitOrder { OrderData { sell_token: self.sell.token, buy_token: self.buy.token, - receiver: Some(self.receiver.into_alloy()), + receiver: Some(self.receiver), sell_amount: self.sell.amount, buy_amount: self.buy.amount, valid_to: self.valid_to, diff --git a/crates/e2e/tests/e2e/jit_orders.rs b/crates/e2e/tests/e2e/jit_orders.rs index 0185b44db9..5e5506b752 100644 --- a/crates/e2e/tests/e2e/jit_orders.rs +++ b/crates/e2e/tests/e2e/jit_orders.rs @@ -137,7 +137,7 @@ async fn single_limit_order_test(web3: Web3) { assert_eq!(limit_order.metadata.class, OrderClass::Limit); let (jit_order, jit_order_uid) = JitOrder { - owner: trader.address().into_legacy(), + owner: trader.address(), sell: Asset { amount: 10u64.eth(), token: *token.address(), @@ -150,7 +150,7 @@ async fn single_limit_order_test(web3: Web3) { partially_fillable: false, valid_to: model::time::now_in_epoch_seconds() + 300, app_data: Default::default(), - receiver: solver.address().into_legacy(), + receiver: solver.address(), } .sign( EcdsaSigningScheme::Eip712, diff --git a/crates/model/Cargo.toml b/crates/model/Cargo.toml index 7ec7e17123..d0005fc1e0 100644 --- a/crates/model/Cargo.toml +++ b/crates/model/Cargo.toml @@ -20,7 +20,6 @@ derive_more = { workspace = true } hex-literal = { workspace = true } num = { workspace = true } number = { workspace = true } -primitive-types = { workspace = true } secp256k1 = { workspace = true } serde = { workspace = true } serde_json = { workspace = true } diff --git a/crates/model/src/signature.rs b/crates/model/src/signature.rs index 040b9034b3..4df708ddf6 100644 --- a/crates/model/src/signature.rs +++ b/crates/model/src/signature.rs @@ -2,7 +2,6 @@ use { crate::{DomainSeparator, quote::QuoteSigningScheme}, alloy::primitives::{Address, B256}, anyhow::{Context as _, Result, ensure}, - primitive_types::H160, serde::{Deserialize, Serialize, de}, std::{ convert::TryInto as _, @@ -159,11 +158,11 @@ impl Signature { } } - pub fn encode_for_settlement(&self, owner: H160) -> Vec { + pub fn encode_for_settlement(&self, owner: Address) -> Vec { match self { Self::Eip712(signature) | Self::EthSign(signature) => signature.to_bytes().to_vec(), - Self::Eip1271(signature) => [owner.as_bytes(), signature].concat(), - Self::PreSign => owner.as_bytes().to_vec(), + Self::Eip1271(signature) => [owner.as_slice(), signature].concat(), + Self::PreSign => owner.to_vec(), } } diff --git a/crates/number/src/serialization.rs b/crates/number/src/serialization.rs index b30a9107e1..7e4cdb6aef 100644 --- a/crates/number/src/serialization.rs +++ b/crates/number/src/serialization.rs @@ -1,140 +1,28 @@ use { - primitive_types::U256, - serde::{Deserializer, Serializer, de}, + alloy::primitives::U256, + serde::{Deserialize, Deserializer, Serializer}, serde_with::{DeserializeAs, SerializeAs}, - std::fmt, }; /// (De)serialization structure able to deserialize decimal and hexadecimal /// numbers, serializes as decimal. pub struct HexOrDecimalU256; -impl<'de> DeserializeAs<'de, alloy::primitives::U256> for HexOrDecimalU256 { - fn deserialize_as(deserializer: D) -> Result - where - D: Deserializer<'de>, - { - struct Visitor {} - impl de::Visitor<'_> for Visitor { - type Value = alloy::primitives::U256; - - fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - write!( - formatter, - "a u256 encoded either as 0x hex prefixed or decimal encoded string" - ) - } - - fn visit_str(self, s: &str) -> Result - where - E: de::Error, - { - if s.trim().starts_with("0x") { - alloy::primitives::U256::from_str_radix(s, 16).map_err(|err| { - de::Error::custom(format!("failed to decode {s:?} as hex u256: {err}")) - }) - } else { - alloy::primitives::U256::from_str_radix(s, 10).map_err(|err| { - de::Error::custom(format!("failed to decode {s:?} as decimal u256: {err}")) - }) - } - } - } - - deserializer.deserialize_str(Visitor {}) - } -} - -impl SerializeAs for HexOrDecimalU256 { - fn serialize_as(source: &U256, serializer: S) -> Result - where - S: Serializer, - { - serialize(source, serializer) - } -} - impl<'de> DeserializeAs<'de, U256> for HexOrDecimalU256 { fn deserialize_as(deserializer: D) -> Result where D: Deserializer<'de>, { - deserialize(deserializer) + U256::deserialize(deserializer) } } -impl SerializeAs for HexOrDecimalU256 { - fn serialize_as(source: &alloy::primitives::U256, serializer: S) -> Result +impl SerializeAs for HexOrDecimalU256 { + fn serialize_as(source: &U256, serializer: S) -> Result where S: Serializer, { + // alloy::primitives::U256 serializes as hex, this gives us decimals instead serializer.serialize_str(&source.to_string()) } } - -pub fn serialize(value: &U256, serializer: S) -> Result -where - S: Serializer, -{ - // `primitive_types::U256::to_string()` is so slow that - // it's still faster to first convert to alloy's U256 - // and convert that to string... - let mut buf = [0u8; 32]; - value.to_big_endian(&mut buf); - let value = alloy::primitives::U256::from_be_bytes(buf); - serializer.serialize_str(&value.to_string()) -} - -pub fn deserialize<'de, D>(deserializer: D) -> Result -where - D: Deserializer<'de>, -{ - struct Visitor {} - impl de::Visitor<'_> for Visitor { - type Value = U256; - - fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - write!( - formatter, - "a u256 encoded either as 0x hex prefixed or decimal encoded string" - ) - } - - fn visit_str(self, s: &str) -> Result - where - E: de::Error, - { - if s.trim().starts_with("0x") { - U256::from_str_radix(s, 16).map_err(|err| { - de::Error::custom(format!("failed to decode {s:?} as hex u256: {err}")) - }) - } else { - U256::from_dec_str(s).map_err(|err| { - de::Error::custom(format!("failed to decode {s:?} as decimal u256: {err}")) - }) - } - } - } - - deserializer.deserialize_str(Visitor {}) -} - -#[cfg(test)] -mod tests { - use { - super::*, - serde::de::{ - IntoDeserializer, - value::{Error as ValueError, StrDeserializer}, - }, - }; - - #[test] - fn test_deserialization() { - let deserializer: StrDeserializer = "0x10".into_deserializer(); - assert_eq!(deserialize(deserializer), Ok(16.into())); - - let deserializer: StrDeserializer = "10".into_deserializer(); - assert_eq!(deserialize(deserializer), Ok(10.into())); - } -} diff --git a/crates/orderbook/src/orderbook.rs b/crates/orderbook/src/orderbook.rs index 6be5a605e0..3c77c6515a 100644 --- a/crates/orderbook/src/orderbook.rs +++ b/crates/orderbook/src/orderbook.rs @@ -13,7 +13,6 @@ use { bigdecimal::ToPrimitive, chrono::Utc, database::order_events::OrderEventLabel, - ethrpc::alloy::conversions::IntoLegacy, model::{ DomainSeparator, order::{ @@ -286,7 +285,7 @@ impl Orderbook { .validate_and_construct_order( payload, &self.domain_separator, - self.settlement_contract.into_legacy(), + self.settlement_contract, full_app_data_override, ) .await?; diff --git a/crates/orderbook/src/run.rs b/crates/orderbook/src/run.rs index cc9fd2f761..95c343f52a 100644 --- a/crates/orderbook/src/run.rs +++ b/crates/orderbook/src/run.rs @@ -22,7 +22,6 @@ use { WETH9, support::Balances, }, - ethrpc::alloy::conversions::IntoLegacy, futures::{FutureExt, StreamExt}, model::{DomainSeparator, order::BUY_ETH_ADDRESS}, num::ToPrimitive, @@ -142,7 +141,7 @@ pub async fn run(args: Arguments) { signature_validator::Contracts { settlement: settlement_contract.clone(), signatures: signatures_contract, - vault_relayer: vault_relayer.into_legacy(), + vault_relayer, }, balance_overrider.clone(), ); @@ -190,8 +189,8 @@ pub async fn run(args: Arguments) { BalanceSimulator::new( settlement_contract.clone(), balances_contract.clone(), - vault_relayer.into_legacy(), - vault_address.map(IntoLegacy::into_legacy), + vault_relayer, + vault_address, balance_overrider, ), ); diff --git a/crates/shared/src/account_balances/cached.rs b/crates/shared/src/account_balances/cached.rs index 101d5d0a1e..e04adcdc33 100644 --- a/crates/shared/src/account_balances/cached.rs +++ b/crates/shared/src/account_balances/cached.rs @@ -1,10 +1,10 @@ use { crate::account_balances::{BalanceFetching, Query, TransferSimulationError}, + alloy::primitives::U256, anyhow::Result, ethrpc::block_stream::{CurrentBlockWatcher, into_stream}, futures::StreamExt, itertools::Itertools, - primitive_types::U256, std::{ collections::HashMap, sync::{Arc, Mutex}, @@ -224,15 +224,15 @@ mod tests { .expect_get_balances() .times(1) .withf(|arg| arg == [query(1)]) - .returning(|_| vec![Ok(1.into())]); + .returning(|_| vec![Ok(U256::ONE)]); let fetcher = Balances::new(Arc::new(inner)); // 1st call to `inner`. let result = fetcher.get_balances(&[query(1)]).await; - assert_eq!(result[0].as_ref().unwrap(), &1.into()); + assert_eq!(result[0].as_ref().unwrap(), &U256::ONE); // Fetches balance from cache and skips calling `inner`. let result = fetcher.get_balances(&[query(1)]).await; - assert_eq!(result[0].as_ref().unwrap(), &1.into()); + assert_eq!(result[0].as_ref().unwrap(), &U256::ONE); } #[tokio::test] @@ -261,14 +261,14 @@ mod tests { .expect_get_balances() .times(2) .withf(|arg| arg == [query(1)]) - .returning(|_| vec![Ok(U256::one())]); + .returning(|_| vec![Ok(U256::ONE)]); let fetcher = Balances::new(Arc::new(inner)); fetcher.spawn_background_task(receiver); // 1st call to `inner`. Balance gets cached. let result = fetcher.get_balances(&[query(1)]).await; - assert_eq!(result[0].as_ref().unwrap(), &1.into()); + assert_eq!(result[0].as_ref().unwrap(), &U256::ONE); // New block gets detected. sender @@ -283,7 +283,7 @@ mod tests { // Balance was already updated so this will hit the cache and skip calling // `inner`. let result = fetcher.get_balances(&[query(1)]).await; - assert_eq!(result[0].as_ref().unwrap(), &1.into()); + assert_eq!(result[0].as_ref().unwrap(), &U256::ONE); } #[tokio::test] @@ -293,26 +293,26 @@ mod tests { .expect_get_balances() .times(1) .withf(|arg| arg == [query(1)]) - .returning(|_| vec![Ok(1.into())]); + .returning(|_| vec![Ok(U256::ONE)]); inner .expect_get_balances() .times(1) .withf(|arg| arg == [query(2)]) - .returning(|_| vec![Ok(2.into())]); + .returning(|_| vec![Ok(U256::from(2))]); let fetcher = Balances::new(Arc::new(inner)); // 1st call to `inner` putting balance 1 into the cache. let result = fetcher.get_balances(&[query(1)]).await; - assert_eq!(result[0].as_ref().unwrap(), &1.into()); + assert_eq!(result[0].as_ref().unwrap(), &U256::ONE); // Fetches balance 1 from cache and balance 2 fresh. (2nd call to `inner`) let result = fetcher.get_balances(&[query(1), query(2)]).await; - assert_eq!(result[0].as_ref().unwrap(), &1.into()); - assert_eq!(result[1].as_ref().unwrap(), &2.into()); + assert_eq!(result[0].as_ref().unwrap(), &U256::ONE); + assert_eq!(result[1].as_ref().unwrap(), &U256::from(2)); // Now balance 2 is also in the cache. Skipping call to `inner`. let result = fetcher.get_balances(&[query(2)]).await; - assert_eq!(result[0].as_ref().unwrap(), &2.into()); + assert_eq!(result[0].as_ref().unwrap(), &U256::from(2)); } #[tokio::test] @@ -324,7 +324,7 @@ mod tests { inner .expect_get_balances() .times(7) - .returning(|_| vec![Ok(U256::one())]); + .returning(|_| vec![Ok(U256::ONE)]); let fetcher = Balances::new(Arc::new(inner)); fetcher.spawn_background_task(receiver); @@ -337,7 +337,7 @@ mod tests { assert!(cached_entry().is_none()); // 1st call to `inner`. Balance gets cached. let result = fetcher.get_balances(&[query(1)]).await; - assert_eq!(result[0].as_ref().unwrap(), &1.into()); + assert_eq!(result[0].as_ref().unwrap(), &U256::ONE); for block in 1..=EVICTION_TIME + 1 { assert!(cached_entry().is_some()); diff --git a/crates/shared/src/account_balances/mod.rs b/crates/shared/src/account_balances/mod.rs index e61eb89d94..312842136e 100644 --- a/crates/shared/src/account_balances/mod.rs +++ b/crates/shared/src/account_balances/mod.rs @@ -4,7 +4,7 @@ use { BalanceOverriding, }, alloy::{ - primitives::Address, + primitives::{Address, U256}, sol_types::{SolCall, SolType, sol_data}, }, contracts::alloy::{GPv2Settlement, support::Balances}, @@ -14,7 +14,6 @@ use { interaction::InteractionData, order::{Order, SellTokenSource}, }, - primitive_types::{H160, U256}, std::sync::Arc, thiserror::Error, }; @@ -99,8 +98,8 @@ pub fn cached( pub struct BalanceSimulator { settlement: GPv2Settlement::Instance, balances: Balances::Instance, - vault_relayer: H160, - vault: H160, + vault_relayer: Address, + vault: Address, balance_overrider: Arc, } @@ -108,8 +107,8 @@ impl BalanceSimulator { pub fn new( settlement: GPv2Settlement::Instance, balances: Balances::Instance, - vault_relayer: H160, - vault: Option, + vault_relayer: Address, + vault: Option
, balance_overrider: Arc, ) -> Self { Self { @@ -121,18 +120,18 @@ impl BalanceSimulator { } } - pub fn vault_relayer(&self) -> H160 { + pub fn vault_relayer(&self) -> Address { self.vault_relayer } - pub fn vault(&self) -> H160 { + pub fn vault(&self) -> Address { self.vault } pub async fn simulate( &self, - owner: H160, - token: H160, + owner: Address, + token: Address, source: SellTokenSource, interactions: &[InteractionData], amount: Option, @@ -157,12 +156,12 @@ impl BalanceSimulator { let balance_call = Balances::Balances::balanceCall { contracts: Balances::Balances::Contracts { settlement: *self.settlement.address(), - vaultRelayer: self.vault_relayer.into_alloy(), - vault: self.vault.into_alloy(), + vaultRelayer: self.vault_relayer, + vault: self.vault, }, - trader: owner.into_alloy(), - token: token.into_alloy(), - amount: amount.unwrap_or_default().into_alloy(), + trader: owner, + token, + amount: amount.unwrap_or_default(), source: source.as_bytes().into(), interactions: interactions .iter() @@ -196,9 +195,9 @@ impl BalanceSimulator { })?; let simulation = Simulation { - token_balance: U256::from_little_endian(&token_balance.as_le_bytes()), - allowance: U256::from_little_endian(&allowance.as_le_bytes()), - effective_balance: U256::from_little_endian(&effective_balance.as_le_bytes()), + token_balance: U256::from_le_slice(&token_balance.as_le_bytes()), + allowance: U256::from_le_slice(&allowance.as_le_bytes()), + effective_balance: U256::from_le_slice(&effective_balance.as_le_bytes()), can_transfer, }; diff --git a/crates/shared/src/account_balances/simulation.rs b/crates/shared/src/account_balances/simulation.rs index e453ac95af..7f5a70a6cf 100644 --- a/crates/shared/src/account_balances/simulation.rs +++ b/crates/shared/src/account_balances/simulation.rs @@ -5,13 +5,10 @@ use { super::{BalanceFetching, Query, TransferSimulationError}, crate::account_balances::BalanceSimulator, + alloy::primitives::{Address, U256}, anyhow::Result, contracts::alloy::{BalancerV2Vault::BalancerV2Vault, ERC20}, - ethcontract::{H160, U256}, - ethrpc::{ - Web3, - alloy::conversions::{IntoAlloy, IntoLegacy}, - }, + ethrpc::Web3, futures::future, model::order::SellTokenSource, tracing::instrument, @@ -39,11 +36,11 @@ impl Balances { } } - fn vault_relayer(&self) -> H160 { + fn vault_relayer(&self) -> Address { self.balance_simulator.vault_relayer } - fn vault(&self) -> H160 { + fn vault(&self) -> Address { self.balance_simulator.vault } @@ -51,8 +48,8 @@ impl Balances { let simulation = self .balance_simulator .simulate( - query.owner.into_legacy(), - query.token.into_legacy(), + query.owner, + query.token, query.source, &query.interactions, None, @@ -62,7 +59,7 @@ impl Balances { Ok(if simulation.can_transfer { simulation.effective_balance } else { - U256::zero() + U256::ZERO }) } @@ -74,19 +71,18 @@ impl Balances { let usable_balance = match query.source { SellTokenSource::Erc20 => { let balance = token.balanceOf(query.owner); - let allowance = token.allowance(query.owner, self.vault_relayer().into_alloy()); + let allowance = token.allowance(query.owner, self.vault_relayer()); let (balance, allowance) = futures::try_join!( balance.call().into_future(), allowance.call().into_future() )?; - std::cmp::min(balance, allowance).into_legacy() + std::cmp::min(balance, allowance) } SellTokenSource::External => { - let vault = BalancerV2Vault::new(self.vault().into_alloy(), &self.web3.alloy); + let vault = BalancerV2Vault::new(self.vault(), &self.web3.alloy); let balance = token.balanceOf(query.owner); - let approved = - vault.hasApprovedRelayer(query.owner, self.vault_relayer().into_alloy()); - let allowance = token.allowance(query.owner, self.vault().into_alloy()); + let approved = vault.hasApprovedRelayer(query.owner, self.vault_relayer()); + let allowance = token.allowance(query.owner, self.vault()); let (balance, approved, allowance) = futures::try_join!( balance.call().into_future(), approved.call().into_future(), @@ -96,13 +92,11 @@ impl Balances { true => std::cmp::min(balance, allowance), false => alloy::primitives::U256::ZERO, } - .into_legacy() } SellTokenSource::Internal => { - let vault = BalancerV2Vault::new(self.vault().into_alloy(), &self.web3.alloy); + let vault = BalancerV2Vault::new(self.vault(), &self.web3.alloy); let balance = vault.getInternalBalance(query.owner, vec![query.token]); - let approved = - vault.hasApprovedRelayer(query.owner, self.vault_relayer().into_alloy()); + let approved = vault.hasApprovedRelayer(query.owner, self.vault_relayer()); let (balance, approved) = futures::try_join!( balance.call().into_future(), approved.call().into_future() @@ -111,7 +105,6 @@ impl Balances { true => balance[0], // internal approvals are always U256::MAX false => alloy::primitives::U256::ZERO, } - .into_legacy() } }; Ok(usable_balance) @@ -146,8 +139,8 @@ impl BalanceFetching for Balances { let simulation = self .balance_simulator .simulate( - query.owner.into_legacy(), - query.token.into_legacy(), + query.owner, + query.token, query.source, &query.interactions, Some(amount), @@ -199,22 +192,22 @@ mod tests { BalanceSimulator::new( settlement, balances, - addr!("C92E8bdf79f0507f65a392b0ab4667716BFE0110"), - Some(addr!("BA12222222228d8Ba445958a75a0704d566BF2C8")), + address!("C92E8bdf79f0507f65a392b0ab4667716BFE0110"), + Some(address!("BA12222222228d8Ba445958a75a0704d566BF2C8")), Arc::new(DummyOverrider), ), ); - let owner = addr!("b0a4e99371dfb0734f002ae274933b4888f618ef"); - let token = addr!("d909c5862cdb164adb949d92622082f0092efc3d"); - let amount = 50000000000000000000000_u128.into(); + let owner = address!("b0a4e99371dfb0734f002ae274933b4888f618ef"); + let token = address!("d909c5862cdb164adb949d92622082f0092efc3d"); + let amount = U256::from(50000000000000000000000_u128); let source = SellTokenSource::Erc20; balances .can_transfer( &Query { - owner: owner.into_alloy(), - token: token.into_alloy(), + owner, + token, source, interactions: vec![], balance_override: None, diff --git a/crates/shared/src/encoded_settlement.rs b/crates/shared/src/encoded_settlement.rs index bfb64135f8..83442f74ff 100644 --- a/crates/shared/src/encoded_settlement.rs +++ b/crates/shared/src/encoded_settlement.rs @@ -1,19 +1,17 @@ use { crate::interaction::EncodedInteraction, - alloy::primitives::Address, + alloy::primitives::{Address, U256}, ethcontract::Bytes, - ethrpc::alloy::conversions::IntoLegacy, model::{ order::{BuyTokenDestination, OrderData, OrderKind, SellTokenSource}, signature::{Signature, SigningScheme}, }, - primitive_types::{H160, U256}, }; pub type EncodedTrade = ( U256, // sellTokenIndex U256, // buyTokenIndex - H160, // receiver + Address, // receiver U256, // sellAmount U256, // buyAmount u32, // validTo @@ -28,20 +26,20 @@ pub type EncodedTrade = ( pub fn encode_trade( order: &OrderData, signature: &Signature, - owner: H160, + owner: Address, sell_token_index: usize, buy_token_index: usize, executed_amount: U256, ) -> EncodedTrade { ( - sell_token_index.into(), - buy_token_index.into(), - order.receiver.unwrap_or(Address::ZERO).into_legacy(), - order.sell_amount.into_legacy(), - order.buy_amount.into_legacy(), + U256::from(sell_token_index), + U256::from(buy_token_index), + order.receiver.unwrap_or(Address::ZERO), + order.sell_amount, + order.buy_amount, order.valid_to, Bytes(order.app_data.0), - order.fee_amount.into_legacy(), + order.fee_amount, order_flags(order, signature), executed_amount, Bytes(signature.encode_for_settlement(owner).to_vec()), @@ -75,7 +73,7 @@ fn order_flags(order: &OrderData, signature: &Signature) -> U256 { SigningScheme::Eip1271 => 0b10, SigningScheme::PreSign => 0b11, } << 5; - result.into() + U256::from(result) } #[derive(Clone, Debug, Default, PartialEq, Eq)] @@ -183,7 +181,7 @@ mod tests { #[test] fn trade_signature_encoding() { - let owner = H160([1; 20]); + let owner = Address::repeat_byte(1); for (signature, bytes) in [ (Signature::Eip712(Default::default()), vec![0; 65]), ( diff --git a/crates/shared/src/gas_price_estimation/driver.rs b/crates/shared/src/gas_price_estimation/driver.rs index 00cd114901..6d38349dfd 100644 --- a/crates/shared/src/gas_price_estimation/driver.rs +++ b/crates/shared/src/gas_price_estimation/driver.rs @@ -1,8 +1,8 @@ use { + alloy::primitives::U256, anyhow::{Context, Result}, gas_estimation::{GasPrice1559, GasPriceEstimating}, number::serialization::HexOrDecimalU256, - primitive_types::U256, reqwest::Url, serde::Deserialize, serde_with::serde_as, @@ -68,9 +68,9 @@ impl DriverGasEstimator { .context("failed to parse driver response")?; Ok(GasPrice1559 { - base_fee_per_gas: response.base_fee_per_gas.to_f64_lossy(), - max_fee_per_gas: response.max_fee_per_gas.to_f64_lossy(), - max_priority_fee_per_gas: response.max_priority_fee_per_gas.to_f64_lossy(), + base_fee_per_gas: f64::from(response.base_fee_per_gas), + max_fee_per_gas: f64::from(response.max_fee_per_gas), + max_priority_fee_per_gas: f64::from(response.max_priority_fee_per_gas), }) } diff --git a/crates/shared/src/order_quoting.rs b/crates/shared/src/order_quoting.rs index 77a00386c6..4d33778c9c 100644 --- a/crates/shared/src/order_quoting.rs +++ b/crates/shared/src/order_quoting.rs @@ -581,10 +581,7 @@ impl OrderQuoter { balance_override: None, }; let mut balances = self.balance_fetcher.get_balances(&[query]).await; - balances - .pop() - .map(|head| head.map(IntoAlloy::into_alloy)) - .context("missing balance result")? + balances.pop().context("missing balance result")? } } @@ -796,7 +793,6 @@ mod tests { U256 as AlloyU256, chrono::Utc, ethcontract::H160, - ethrpc::alloy::conversions::IntoLegacy, futures::FutureExt, gas_estimation::GasPrice1559, mockall::{Sequence, predicate::eq}, @@ -806,12 +802,8 @@ mod tests { fn mock_balance_fetcher() -> Arc { let mut mock = MockBalanceFetching::new(); - mock.expect_get_balances().returning(|addresses| { - addresses - .iter() - .map(|_| Ok(U256::MAX.into_legacy())) - .collect() - }); + mock.expect_get_balances() + .returning(|addresses| addresses.iter().map(|_| Ok(U256::MAX)).collect()); Arc::new(mock) } @@ -1774,12 +1766,12 @@ mod tests { }, ], jit_orders: vec![dto::JitOrder { - buy_token: H160([4; 20]), - sell_token: H160([5; 20]), - sell_amount: U256::from(10).into_legacy(), - buy_amount: U256::from(20).into_legacy(), - executed_amount: U256::from(11).into_legacy(), - receiver: H160([6; 20]), + buy_token: Address::repeat_byte(4), + sell_token: Address::repeat_byte(5), + sell_amount: U256::from(10), + buy_amount: U256::from(20), + executed_amount: U256::from(11), + receiver: Address::repeat_byte(6), valid_to: 1734084318, app_data: Default::default(), side: dto::Side::Sell, diff --git a/crates/shared/src/order_validation.rs b/crates/shared/src/order_validation.rs index c163d5d37f..ef6230e53f 100644 --- a/crates/shared/src/order_validation.rs +++ b/crates/shared/src/order_validation.rs @@ -18,12 +18,11 @@ use { signature_validator::{SignatureCheck, SignatureValidating, SignatureValidationError}, trade_finding, }, - alloy::primitives::Address, + alloy::primitives::{Address, B256, U256}, anyhow::{Result, anyhow}, app_data::{AppDataHash, Hook, Hooks, ValidatedAppData, Validator}, async_trait::async_trait, contracts::alloy::{HooksTrampoline, WETH9}, - ethcontract::{H160, H256, U256}, ethrpc::alloy::conversions::{IntoAlloy, IntoLegacy}, model::{ DomainSeparator, @@ -99,7 +98,7 @@ pub trait OrderValidating: Send + Sync { &self, order: OrderCreation, domain_separator: &DomainSeparator, - settlement_contract: H160, + settlement_contract: Address, full_app_data_override: Option, ) -> Result<(Order, Option), ValidationError>; } @@ -155,7 +154,7 @@ pub enum ValidationError { WrongOwner(signature::Recovered), /// An invalid EIP-1271 signature, where the on-chain validation check /// reverted or did not return the expected value. - InvalidEip1271Signature(H256), + InvalidEip1271Signature(B256), ZeroAmount, IncompatibleSigningScheme, TooManyLimitOrders, @@ -375,7 +374,7 @@ impl OrderValidator { async fn ensure_token_is_transferable( &self, order: &OrderCreation, - owner: H160, + owner: Address, app_data: &OrderAppData, ) -> Result<(), ValidationError> { let mut res = Ok(()); @@ -394,7 +393,7 @@ impl OrderValidator { .can_transfer( &account_balances::Query { token: order.data().sell_token, - owner: owner.into_alloy(), + owner, source: order.data().sell_token_balance, interactions: app_data.interactions.pre.clone(), balance_override: app_data.inner.protocol.flashloan.as_ref().map(|loan| { @@ -569,7 +568,7 @@ impl OrderValidating for OrderValidator { &self, order: OrderCreation, domain_separator: &DomainSeparator, - settlement_contract: H160, + settlement_contract: Address, full_app_data_override: Option, ) -> Result<(Order, Option), ValidationError> { // Happens before signature verification because a miscalculated app data hash @@ -596,7 +595,7 @@ impl OrderValidating for OrderValidator { let hash = hashed_eip712_message(domain_separator, &data.hash_struct()); self.signature_validator .validate_signature_and_get_additional_gas(SignatureCheck { - signer: owner.into_legacy(), + signer: owner, hash, signature: signature.to_owned(), interactions: app_data.interactions.pre.clone(), @@ -611,7 +610,7 @@ impl OrderValidating for OrderValidator { .await .map_err(|err| match err { SignatureValidationError::Invalid => { - ValidationError::InvalidEip1271Signature(H256(hash)) + ValidationError::InvalidEip1271Signature(B256::new(hash)) } SignatureValidationError::Other(err) => ValidationError::Other(err), })? @@ -657,7 +656,7 @@ impl OrderValidating for OrderValidator { verification, }; - self.ensure_token_is_transferable(&order, owner.into_legacy(), &app_data) + self.ensure_token_is_transferable(&order, owner, &app_data) .await?; // Check if we need to re-classify the market order if it is outside the market @@ -670,7 +669,7 @@ impl OrderValidating for OrderValidator { &*self.quoter, "e_parameters, order.quote_id, - Some(data.fee_amount.into_legacy()), + Some(data.fee_amount), ) .await?; tracing::debug!( @@ -772,7 +771,7 @@ impl OrderValidating for OrderValidator { owner, creation_date: chrono::offset::Utc::now(), uid, - settlement_contract: settlement_contract.into_alloy(), + settlement_contract, class, full_app_data: match order.app_data { OrderCreationAppData::Both { full, .. } @@ -1438,7 +1437,7 @@ mod tests { signature_validator .expect_validate_signature_and_get_additional_gas() .with(eq(SignatureCheck { - signer: creation.from.unwrap().into_legacy(), + signer: creation.from.unwrap(), hash: order_hash, signature: vec![1, 2, 3], interactions: pre_interactions.clone(), @@ -1467,7 +1466,7 @@ mod tests { signature_validator .expect_validate_signature_and_get_additional_gas() .with(eq(SignatureCheck { - signer: creation.from.unwrap().into_legacy(), + signer: creation.from.unwrap(), hash: order_hash, signature: vec![1, 2, 3], interactions: pre_interactions.clone(), @@ -2261,7 +2260,7 @@ mod tests { fee_amount: alloy::primitives::U256::from(6), ..Default::default() }; - let fee_amount = 0.into(); + let fee_amount = U256::ZERO; let quote_id = Some(42); order_quoter .expect_find_quote() @@ -2310,7 +2309,7 @@ mod tests { fee_amount: alloy::primitives::U256::from(6), ..Default::default() }; - let fee_amount = 0.into(); + let fee_amount = U256::ZERO; order_quoter .expect_calculate_quote() .with(eq(QuoteParameters { diff --git a/crates/shared/src/price_estimation/native/oneinch.rs b/crates/shared/src/price_estimation/native/oneinch.rs index 6f0959d3de..78efcf32e1 100644 --- a/crates/shared/src/price_estimation/native/oneinch.rs +++ b/crates/shared/src/price_estimation/native/oneinch.rs @@ -1,13 +1,12 @@ use { super::{NativePrice, NativePriceEstimateResult, NativePriceEstimating}, crate::{price_estimation::PriceEstimationError, token_info::TokenInfoFetching}, - alloy::primitives::Address, + alloy::primitives::{Address, U256}, anyhow::{Context, Result, anyhow}, ethrpc::block_stream::{CurrentBlockWatcher, into_stream}, futures::{FutureExt, StreamExt, future::BoxFuture}, num::ToPrimitive, - number::{conversions::u256_to_big_rational, serialization::HexOrDecimalU256}, - primitive_types::U256, + number::{conversions::alloy::u256_to_big_rational, serialization::HexOrDecimalU256}, reqwest::{Client, header::AUTHORIZATION}, serde::Deserialize, serde_with::serde_as, diff --git a/crates/shared/src/price_estimation/trade_verifier/mod.rs b/crates/shared/src/price_estimation/trade_verifier/mod.rs index 914ba05de5..c5c02065f2 100644 --- a/crates/shared/src/price_estimation/trade_verifier/mod.rs +++ b/crates/shared/src/price_estimation/trade_verifier/mod.rs @@ -438,16 +438,16 @@ fn legacy_settlement_to_alloy( .trades .into_iter() .map(|t| GPv2Settlement::GPv2Trade::Data { - sellTokenIndex: t.0.into_alloy(), - buyTokenIndex: t.1.into_alloy(), - receiver: t.2.into_alloy(), - sellAmount: t.3.into_alloy(), - buyAmount: t.4.into_alloy(), + sellTokenIndex: t.0, + buyTokenIndex: t.1, + receiver: t.2, + sellAmount: t.3, + buyAmount: t.4, validTo: t.5, appData: t.6.0.into(), - feeAmount: t.7.into_alloy(), - flags: t.8.into_alloy(), - executedAmount: t.9.into_alloy(), + feeAmount: t.7, + flags: t.8, + executedAmount: t.9, signature: t.10.into_alloy(), }) .collect(), @@ -639,7 +639,7 @@ fn encode_fake_trade( let encoded_trade = encode_trade( &fake_order, &fake_signature, - verification.from.into_legacy(), + verification.from, // the tokens set length is small so the linear search is acceptable tokens .iter() @@ -649,7 +649,7 @@ fn encode_fake_trade( .iter() .position(|token| token == &query.buy_token) .context("missing buy token index")?, - query.in_amount.get().into_legacy(), + query.in_amount.get(), ); Ok(encoded_trade) @@ -664,11 +664,11 @@ fn encode_jit_orders( .iter() .map(|jit_order| { let order_data = OrderData { - sell_token: jit_order.sell_token.into_alloy(), - buy_token: jit_order.buy_token.into_alloy(), - receiver: Some(jit_order.receiver.into_alloy()), - sell_amount: jit_order.sell_amount.into_alloy(), - buy_amount: jit_order.buy_amount.into_alloy(), + sell_token: jit_order.sell_token, + buy_token: jit_order.buy_token, + receiver: Some(jit_order.receiver), + sell_amount: jit_order.sell_amount, + buy_amount: jit_order.buy_amount, valid_to: jit_order.valid_to, app_data: jit_order.app_data, fee_amount: alloy::primitives::U256::ZERO, @@ -690,11 +690,11 @@ fn encode_jit_orders( // the tokens set length is small so the linear search is acceptable tokens .iter() - .position(|token| token.into_legacy() == jit_order.sell_token) + .position(|token| *token == jit_order.sell_token) .context("missing jit order sell token index")?, tokens .iter() - .position(|token| token.into_legacy() == jit_order.buy_token) + .position(|token| *token == jit_order.buy_token) .context("missing jit order buy token index")?, jit_order.executed_amount, )) @@ -707,16 +707,16 @@ fn recover_jit_order_owner( jit_order: &JitOrder, order_data: &OrderData, domain_separator: &DomainSeparator, -) -> Result<(H160, Signature), Error> { +) -> Result<(Address, Signature), Error> { let (owner, signature) = match jit_order.signing_scheme { SigningScheme::Eip1271 => { let (owner, signature) = jit_order.signature.split_at(20); - let owner = H160::from_slice(owner); + let owner = Address::from_slice(owner); let signature = Signature::from_bytes(jit_order.signing_scheme, signature)?; (owner, signature) } SigningScheme::PreSign => { - let owner = H160::from_slice(&jit_order.signature); + let owner = Address::from_slice(&jit_order.signature); let signature = Signature::from_bytes(jit_order.signing_scheme, Vec::new().as_slice())?; (owner, signature) } @@ -725,8 +725,7 @@ fn recover_jit_order_owner( let owner = signature .recover(domain_separator, &order_data.hash_struct())? .context("could not recover the owner")? - .signer - .into_legacy(); + .signer; (owner, signature) } }; diff --git a/crates/shared/src/signature_validator/mod.rs b/crates/shared/src/signature_validator/mod.rs index a415ba3347..39f48e01ef 100644 --- a/crates/shared/src/signature_validator/mod.rs +++ b/crates/shared/src/signature_validator/mod.rs @@ -3,12 +3,11 @@ use { BalanceOverrideRequest, BalanceOverriding, }, - alloy::primitives::FixedBytes, + alloy::primitives::{Address, FixedBytes}, contracts::alloy::GPv2Settlement, - ethrpc::{Web3, alloy::conversions::IntoAlloy}, + ethrpc::Web3, hex_literal::hex, model::interaction::InteractionData, - primitive_types::H160, std::sync::Arc, thiserror::Error, }; @@ -18,7 +17,7 @@ mod simulation; /// Structure used to represent a signature. #[derive(Clone, Eq, PartialEq)] pub struct SignatureCheck { - pub signer: H160, + pub signer: Address, pub hash: [u8; 32], pub signature: Vec, pub interactions: Vec, @@ -97,7 +96,7 @@ pub fn check_erc1271_result(result: FixedBytes<4>) -> Result<(), SignatureValida pub struct Contracts { pub settlement: GPv2Settlement::Instance, pub signatures: contracts::alloy::support::Signatures::Instance, - pub vault_relayer: H160, + pub vault_relayer: Address, } /// Creates the default [`SignatureValidating`] instance. @@ -110,7 +109,7 @@ pub fn validator( web3, contracts.settlement, *contracts.signatures.address(), - contracts.vault_relayer.into_alloy(), + contracts.vault_relayer, balance_overrider, )) } diff --git a/crates/shared/src/signature_validator/simulation.rs b/crates/shared/src/signature_validator/simulation.rs index 4b1c56817f..d2fc5376c5 100644 --- a/crates/shared/src/signature_validator/simulation.rs +++ b/crates/shared/src/signature_validator/simulation.rs @@ -67,7 +67,7 @@ impl Validator { // change), the order's validity can be directly determined by whether // the signature matches the expected hash of the order data, checked // with isValidSignature method called on the owner's contract - let contract = ERC1271SignatureValidator::new(check.signer.into_alloy(), &self.web3.alloy); + let contract = ERC1271SignatureValidator::new(check.signer, &self.web3.alloy); let magic_bytes = contract .isValidSignature(check.hash.into(), check.signature.clone().into()) .call() @@ -118,7 +118,7 @@ impl Validator { settlement: *self.settlement.address(), vaultRelayer: self.vault_relayer, }, - signer: check.signer.into_alloy(), + signer: check.signer, order: check.hash.into(), signature: check.signature.clone().into(), interactions: check diff --git a/crates/shared/src/sources/uniswap_v2/mod.rs b/crates/shared/src/sources/uniswap_v2/mod.rs index 6636f19ac5..21cc73fa11 100644 --- a/crates/shared/src/sources/uniswap_v2/mod.rs +++ b/crates/shared/src/sources/uniswap_v2/mod.rs @@ -13,10 +13,9 @@ use { ethrpc::Web3, sources::{BaselineSource, swapr::SwaprPoolReader}, }, + alloy::primitives::{Address, B256}, anyhow::{Context, Result}, contracts::alloy::IUniswapLikeRouter, - ethcontract::{H160, H256}, - ethrpc::alloy::conversions::{IntoAlloy, IntoLegacy}, hex_literal::hex, std::{fmt::Display, str::FromStr, sync::Arc}, }; @@ -42,13 +41,6 @@ pub const SWAPR_INIT: [u8; 32] = pub const TESTNET_UNISWAP_INIT: [u8; 32] = hex!("0efd7612822d579e24a8851501d8c2ad854264a1050e3dfcee8afcca08f80a86"); -#[derive(Debug, Clone, Copy)] -pub struct UniV2BaselineSourceParameters { - router: H160, - init_code_digest: H256, - pool_reading: PoolReadingStyle, -} - #[derive(Clone, Copy, Debug, strum::EnumString, strum::Display)] enum PoolReadingStyle { Default, @@ -61,6 +53,13 @@ pub struct UniV2BaselineSource { pub pool_fetching: Arc, } +#[derive(Debug, Clone, Copy)] +pub struct UniV2BaselineSourceParameters { + router: Address, + init_code_digest: B256, + pool_reading: PoolReadingStyle, +} + impl UniV2BaselineSourceParameters { pub fn from_baseline_source(source: BaselineSource, chain: &str) -> Option { use BaselineSource as BS; @@ -70,38 +69,32 @@ impl UniV2BaselineSourceParameters { match source { BS::None | BS::BalancerV2 | BS::ZeroEx | BS::UniswapV3 => None, BS::UniswapV2 => Some(Self { - router: contracts::alloy::UniswapV2Router02::deployment_address(&chain_id) - .map(IntoLegacy::into_legacy)?, + router: contracts::alloy::UniswapV2Router02::deployment_address(&chain_id)?, init_code_digest: UNISWAP_INIT.into(), pool_reading: PoolReadingStyle::Default, }), BS::Honeyswap => Some(Self { - router: contracts::alloy::HoneyswapRouter::deployment_address(&chain_id) - .map(IntoLegacy::into_legacy)?, + router: contracts::alloy::HoneyswapRouter::deployment_address(&chain_id)?, init_code_digest: HONEYSWAP_INIT.into(), pool_reading: PoolReadingStyle::Default, }), BS::SushiSwap => Some(Self { - router: contracts::alloy::SushiSwapRouter::deployment_address(&chain_id) - .map(IntoLegacy::into_legacy)?, + router: contracts::alloy::SushiSwapRouter::deployment_address(&chain_id)?, init_code_digest: SUSHISWAP_INIT.into(), pool_reading: PoolReadingStyle::Default, }), BS::Swapr => Some(Self { - router: contracts::alloy::SwaprRouter::deployment_address(&chain_id) - .map(IntoLegacy::into_legacy)?, + router: contracts::alloy::SwaprRouter::deployment_address(&chain_id)?, init_code_digest: SWAPR_INIT.into(), pool_reading: PoolReadingStyle::Swapr, }), BS::TestnetUniswapV2 => Some(Self { - router: contracts::alloy::TestnetUniswapV2Router02::deployment_address(&chain_id) - .map(IntoLegacy::into_legacy)?, + router: contracts::alloy::TestnetUniswapV2Router02::deployment_address(&chain_id)?, init_code_digest: TESTNET_UNISWAP_INIT.into(), pool_reading: PoolReadingStyle::Default, }), BS::Baoswap => Some(Self { - router: contracts::alloy::BaoswapRouter::deployment_address(&chain_id) - .map(IntoLegacy::into_legacy)?, + router: contracts::alloy::BaoswapRouter::deployment_address(&chain_id)?, init_code_digest: BAOSWAP_INIT.into(), pool_reading: PoolReadingStyle::Default, }), @@ -110,10 +103,8 @@ impl UniV2BaselineSourceParameters { pub async fn into_source(&self, web3: &Web3) -> Result { let web3 = ethrpc::instrumented::instrument_with_label(web3, "uniswapV2".into()); - let router = contracts::alloy::IUniswapLikeRouter::Instance::new( - self.router.into_alloy(), - web3.alloy.clone(), - ); + let router = + contracts::alloy::IUniswapLikeRouter::Instance::new(self.router, web3.alloy.clone()); let factory = router.factory().call().await.context("factory")?; let pair_provider = pair_provider::PairProvider { factory, @@ -149,12 +140,12 @@ impl FromStr for UniV2BaselineSourceParameters { fn from_str(s: &str) -> Result { let mut parts = s.split('|'); - let router: H160 = parts + let router: Address = parts .next() .context("no factory address")? .parse() .context("parse factory address")?; - let init_code_digest: H256 = parts + let init_code_digest: B256 = parts .next() .context("no init code digest")? .parse() @@ -178,7 +169,7 @@ mod tests { super::*, crate::recent_block_cache::Block, alloy::{ - primitives::{Address, address}, + primitives::{Address, B256, address}, providers::Provider, }, maplit::hashset, @@ -189,8 +180,7 @@ mod tests { fn parse_address_init() { let arg = "0x0000000000000000000000000000000000000001|0x0000000000000000000000000000000000000000000000000000000000000002"; let parsed = UniV2BaselineSourceParameters::from_str(arg).unwrap(); - assert_eq!(parsed.router, H160::from_low_u64_be(1)); - assert_eq!(parsed.init_code_digest, H256::from_low_u64_be(2)); + assert_eq!(parsed.init_code_digest, B256::with_last_byte(2)); } #[test] diff --git a/crates/shared/src/sources/uniswap_v3/graph_api.rs b/crates/shared/src/sources/uniswap_v3/graph_api.rs index a032683c14..ebb79f38c8 100644 --- a/crates/shared/src/sources/uniswap_v3/graph_api.rs +++ b/crates/shared/src/sources/uniswap_v3/graph_api.rs @@ -6,8 +6,8 @@ use { event_handling::MAX_REORG_BLOCK_COUNT, subgraph::{ContainsId, SubgraphClient}, }, + alloy::primitives::{Address, U256}, anyhow::Result, - ethcontract::{H160, U256}, num::BigInt, number::serialization::HexOrDecimalU256, reqwest::{Client, Url}, @@ -106,7 +106,7 @@ impl UniV3SubgraphClient { .paginated_query(&query, variables) .await? .into_iter() - .filter(|pool: &PoolData| pool.liquidity > U256::zero()) + .filter(|pool: &PoolData| pool.liquidity > U256::ZERO) .collect()) } @@ -126,7 +126,7 @@ impl UniV3SubgraphClient { async fn get_pools_by_pool_ids( &self, - pool_ids: &[H160], + pool_ids: &[Address], block_number: u64, ) -> Result> { let variables = json_map! { @@ -141,7 +141,7 @@ impl UniV3SubgraphClient { /// Retrieves the ticks data for pools with given pool ids async fn get_ticks_by_pools_ids( &self, - pool_ids: &[H160], + pool_ids: &[Address], block_number: u64, ) -> Result> { let mut all = Vec::new(); @@ -166,7 +166,7 @@ impl UniV3SubgraphClient { /// Retrieves the pool data and ticks data for pools with given pool ids pub async fn get_pools_with_ticks_by_ids( &self, - ids: &[H160], + ids: &[Address], block_number: u64, ) -> Result> { let (pools, ticks) = futures::try_join!( @@ -291,7 +291,7 @@ pub struct RegisteredPools { #[derive(Debug, Clone, Deserialize, Default, PartialEq)] #[serde(rename_all = "camelCase")] pub struct PoolData { - pub id: H160, + pub id: Address, pub token0: Token, pub token1: Token, #[serde_as(as = "HexOrDecimalU256")] @@ -321,7 +321,7 @@ pub struct TickData { pub tick_idx: BigInt, #[serde_as(as = "DisplayFromStr")] pub liquidity_net: BigInt, - pub pool_address: H160, + pub pool_address: Address, } impl ContainsId for TickData { @@ -334,7 +334,7 @@ impl ContainsId for TickData { #[derive(Debug, Clone, Default, Deserialize, Eq, PartialEq, Serialize)] #[serde(rename_all = "camelCase")] pub struct Token { - pub id: H160, + pub id: Address, #[serde_as(as = "DisplayFromStr")] pub decimals: u8, } @@ -367,7 +367,7 @@ mod block_number_query { #[cfg(test)] mod tests { - use {super::*, crate::subgraph::Data, serde_json::json, std::str::FromStr}; + use {super::*, crate::subgraph::Data, alloy::primitives::address, serde_json::json}; #[test] fn decode_pools_data() { @@ -414,38 +414,34 @@ mod tests { Data { inner: vec![ PoolData { - id: H160::from_str("0x0001fcbba8eb491c3ccfeddc5a5caba1a98c4c28").unwrap(), + id: address!("0x0001fcbba8eb491c3ccfeddc5a5caba1a98c4c28"), token0: Token { - id: H160::from_str("0xbef81556ef066ec840a540595c8d12f516b6378f") - .unwrap(), + id: address!("0xbef81556ef066ec840a540595c8d12f516b6378f"), decimals: 18, }, token1: Token { - id: H160::from_str("0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2") - .unwrap(), + id: address!("0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2"), decimals: 18, }, - fee_tier: U256::from_dec_str("10000").unwrap(), - liquidity: U256::from_dec_str("303015134493562686441").unwrap(), - sqrt_price: U256::from_dec_str("792216481398733702759960397").unwrap(), + fee_tier: U256::from(10000), + liquidity: U256::from(303015134493562686441_u128), + sqrt_price: U256::from(792216481398733702759960397_u128), tick: BigInt::from(-92110), ticks: None, }, PoolData { - id: H160::from_str("0x0002e63328169d7feea121f1e32e4f620abf0352").unwrap(), + id: address!("0x0002e63328169d7feea121f1e32e4f620abf0352"), token0: Token { - id: H160::from_str("0x0d438f3b5175bebc262bf23753c1e53d03432bde") - .unwrap(), + id: address!("0x0d438f3b5175bebc262bf23753c1e53d03432bde"), decimals: 18, }, token1: Token { - id: H160::from_str("0x903bef1736cddf2a537176cf3c64579c3867a881") - .unwrap(), + id: address!("0x903bef1736cddf2a537176cf3c64579c3867a881"), decimals: 9, }, - fee_tier: U256::from_dec_str("3000").unwrap(), - liquidity: U256::from_dec_str("3125586395511534995").unwrap(), - sqrt_price: U256::from_dec_str("5986323062404391218190509").unwrap(), + fee_tier: U256::from(3000), + liquidity: U256::from(3125586395511534995_u128), + sqrt_price: U256::from(5986323062404391218190509_u128), tick: BigInt::from(-189822), ticks: None, }, @@ -480,15 +476,13 @@ mod tests { id: "0x0001fcbba8eb491c3ccfeddc5a5caba1a98c4c28#0".to_string(), tick_idx: BigInt::from(0), liquidity_net: BigInt::from(-303015134493562686441i128), - pool_address: H160::from_str("0x0001fcbba8eb491c3ccfeddc5a5caba1a98c4c28") - .unwrap(), + pool_address: address!("0x0001fcbba8eb491c3ccfeddc5a5caba1a98c4c28") }, TickData { id: "0x0001fcbba8eb491c3ccfeddc5a5caba1a98c4c28#-92200".to_string(), tick_idx: BigInt::from(-92200), liquidity_net: BigInt::from(303015134493562686441i128), - pool_address: H160::from_str("0x0001fcbba8eb491c3ccfeddc5a5caba1a98c4c28") - .unwrap(), + pool_address: address!("0x0001fcbba8eb491c3ccfeddc5a5caba1a98c4c28") }, ], } diff --git a/crates/shared/src/sources/uniswap_v3/pool_fetching.rs b/crates/shared/src/sources/uniswap_v3/pool_fetching.rs index e5d464037b..2fb71beb57 100644 --- a/crates/shared/src/sources/uniswap_v3/pool_fetching.rs +++ b/crates/shared/src/sources/uniswap_v3/pool_fetching.rs @@ -9,16 +9,17 @@ use { recent_block_cache::Block, sources::uniswap_v3::event_fetching::WithAddress, }, - alloy::rpc::types::Log, + alloy::{ + primitives::{Address, U256}, + rpc::types::Log, + }, anyhow::{Context, Result}, contracts::alloy::UniswapV3Pool::UniswapV3Pool::{ UniswapV3PoolEvents as AlloyUniswapV3PoolEvents, UniswapV3PoolEvents, }, - ethcontract::{H160, U256}, ethrpc::{ Web3, - alloy::conversions::{IntoAlloy, IntoLegacy}, block_stream::{BlockRetrieving, RangeInclusive}, }, itertools::{Either, Itertools}, @@ -51,7 +52,7 @@ pub struct PoolInfo { /// Skip serializing address since it's redundant (already serialized /// outside of this struct) #[serde(skip_serializing)] - pub address: H160, + pub address: Address, pub tokens: Vec, pub state: PoolState, pub gas_stats: PoolStats, @@ -106,7 +107,7 @@ impl TryFrom for PoolInfo { } }) .collect(), - fee: Ratio::new(pool.fee_tier.as_u32(), 1_000_000u32), + fee: Ratio::new(u32::try_from(pool.fee_tier)?, 1_000_000u32), }, gas_stats: PoolStats { mean_gas: U256::from(108_163), // as estimated by https://dune.com/queries/1044812 @@ -118,18 +119,18 @@ impl TryFrom for PoolInfo { #[derive(Default)] struct PoolsCheckpoint { /// Pools state. - pools: HashMap, + pools: HashMap, /// Block number for which `pools` field was populated. block_number: u64, /// Pools that don't exist in `pools` field, therefore need to be /// initialized and moved to `pools` in the next maintainance run - missing_pools: HashSet, + missing_pools: HashSet
, } struct PoolsCheckpointHandler { graph_api: UniV3SubgraphClient, - /// H160 is pool id while TokenPair is a pair or tokens for each pool. - pools_by_token_pair: HashMap>, + /// Address is pool id while TokenPair is a pair or tokens for each pool. + pools_by_token_pair: HashMap>, /// Pools state on a specific block number in history considered reorg safe pools_checkpoint: Mutex, } @@ -153,10 +154,10 @@ impl PoolsCheckpointHandler { "initialized registered pools", ); - let mut pools_by_token_pair: HashMap> = HashMap::new(); + let mut pools_by_token_pair: HashMap> = HashMap::new(); for pool in ®istered_pools.pools { - let pair = TokenPair::new(pool.token0.id.into_alloy(), pool.token1.id.into_alloy()) - .context("cant create pair")?; + let pair = + TokenPair::new(pool.token0.id, pool.token1.id).context("cant create pair")?; pools_by_token_pair.entry(pair).or_default().insert(pool.id); } @@ -196,7 +197,7 @@ impl PoolsCheckpointHandler { /// For a given list of token pairs, fetches the pools for the ones that /// exist in the checkpoint. For the ones that don't exist, flag as /// missing and expect to exist after the next maintenance run. - fn get(&self, token_pairs: &HashSet) -> (HashMap, u64) { + fn get(&self, token_pairs: &HashSet) -> (HashMap, u64) { let mut pool_ids = token_pairs .iter() .filter_map(|pair| self.pools_by_token_pair.get(pair)) @@ -208,7 +209,7 @@ impl PoolsCheckpointHandler { match pool_ids.peek() { Some(_) => { let mut pools_checkpoint = self.pools_checkpoint.lock().unwrap(); - let (existing_pools, missing_pools): (HashMap, Vec) = + let (existing_pools, missing_pools): (HashMap, Vec
) = pool_ids.partition_map(|pool_id| match pools_checkpoint.pools.get(pool_id) { Some(entry) => Either::Left((*pool_id, entry.clone())), _ => Either::Right(pool_id), @@ -407,21 +408,18 @@ impl PoolFetching for UniswapV3PoolFetcher { // return only pools which current liquidity is positive Ok(checkpoint .into_values() - .filter(|pool| pool.state.liquidity > U256::zero()) + .filter(|pool| pool.state.liquidity > U256::ZERO) .collect()) } } /// For a given checkpoint, append events to get a new checkpoint fn append_events( - pools: &mut HashMap, + pools: &mut HashMap, events: Vec>, ) { for event in events { - if let Some(pool) = pools - .get_mut(&event.address().into_legacy()) - .map(|pool| &mut pool.state) - { + if let Some(pool) = pools.get_mut(&event.address()).map(|pool| &mut pool.state) { match event.inner() { UniswapV3PoolEvents::Burn(burn) => { let tick_lower = BigInt::from(burn.tickLower.as_i32()); @@ -430,7 +428,7 @@ fn append_events( // liquidity tracks the liquidity on recent tick, // only need to update it if the new position includes the recent tick. if tick_lower <= pool.tick && pool.tick < tick_upper { - pool.liquidity -= burn.amount.into(); + pool.liquidity -= U256::from(burn.amount); } pool.liquidity_net @@ -459,7 +457,7 @@ fn append_events( // liquidity tracks the liquidity on recent tick, // only need to update it if the new position includes the recent tick. if tick_lower <= pool.tick && pool.tick < tick_upper { - pool.liquidity += mint.amount.into(); + pool.liquidity += U256::from(mint.amount); } pool.liquidity_net @@ -483,9 +481,8 @@ fn append_events( } UniswapV3PoolEvents::Swap(swap) => { pool.tick = BigInt::from(swap.tick.as_i32()); - pool.liquidity = swap.liquidity.into(); - pool.sqrt_price = - alloy::primitives::U256::from(swap.sqrtPriceX96).into_legacy(); + pool.liquidity = U256::from(swap.liquidity); + pool.sqrt_price = U256::from(swap.sqrtPriceX96); } _ => continue, } @@ -522,9 +519,8 @@ impl Maintaining for UniswapV3PoolFetcher { mod tests { use { super::*, - alloy::primitives::{U160, aliases::I24}, + alloy::primitives::{U160, address, aliases::I24}, contracts::alloy::UniswapV3Pool::UniswapV3Pool::{Burn, Mint, Swap}, - ethrpc::alloy::conversions::IntoAlloy, serde_json::json, std::str::FromStr, testlib::assert_json_matches, @@ -561,20 +557,20 @@ mod tests { }); let pool = PoolInfo { - address: H160::from_str("0x0001fcbba8eb491c3ccfeddc5a5caba1a98c4c28").unwrap(), + address: address!("0x0001fcbba8eb491c3ccfeddc5a5caba1a98c4c28"), tokens: vec![ Token { - id: H160::from_str("0xbef81556ef066ec840a540595c8d12f516b6378f").unwrap(), + id: address!("0xbef81556ef066ec840a540595c8d12f516b6378f"), decimals: 18, }, Token { - id: H160::from_str("0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2").unwrap(), + id: address!("0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2"), decimals: 18, }, ], state: PoolState { - sqrt_price: U256::from_dec_str("792216481398733702759960397").unwrap(), - liquidity: U256::from_dec_str("303015134493562686441").unwrap(), + sqrt_price: U256::from(792216481398733702759960397_u128), + liquidity: U256::from(303015134493562686441_u128), tick: BigInt::from_str("-92110").unwrap(), liquidity_net: BTreeMap::from([ ( @@ -603,7 +599,7 @@ mod tests { #[test] fn append_events_test_empty() { - let pools = HashMap::from([(H160::from_low_u64_be(1), Default::default())]); + let pools = HashMap::from([(Address::with_last_byte(1), Default::default())]); let mut new_pools = pools.clone(); let events = vec![]; append_events(&mut new_pools, events); @@ -612,7 +608,7 @@ mod tests { #[test] fn append_events_test_swap() { - let address = H160::from_low_u64_be(1); + let address = Address::with_last_byte(1); let pool = PoolInfo { address, ..Default::default() @@ -629,7 +625,7 @@ mod tests { amount0: Default::default(), amount1: Default::default(), }), - address.into_alloy(), + address, ); append_events(&mut pools, vec![event]); @@ -640,7 +636,7 @@ mod tests { #[test] fn append_events_test_burn() { - let address = H160::from_low_u64_be(1); + let address = Address::with_last_byte(1); let pool = PoolInfo { address, ..Default::default() @@ -657,7 +653,7 @@ mod tests { amount0: Default::default(), amount1: Default::default(), }), - address.into_alloy(), + address, ); append_events(&mut pools, vec![event]); assert_eq!( @@ -678,7 +674,7 @@ mod tests { amount0: Default::default(), amount1: Default::default(), }), - address.into_alloy(), + address, ); append_events(&mut pools, vec![event]); assert_eq!( @@ -693,7 +689,7 @@ mod tests { #[test] fn append_events_test_mint() { - let address = H160::from_low_u64_be(1); + let address = Address::with_last_byte(1); let pool = PoolInfo { address, ..Default::default() @@ -711,7 +707,7 @@ mod tests { amount1: Default::default(), sender: Default::default(), }), - address.into_alloy(), + address, ); append_events(&mut pools, vec![event]); assert_eq!( @@ -733,7 +729,7 @@ mod tests { amount1: Default::default(), sender: Default::default(), }), - address.into_alloy(), + address, ); append_events(&mut pools, vec![event]); assert_eq!( diff --git a/crates/shared/src/trade_finding/external.rs b/crates/shared/src/trade_finding/external.rs index 5d5962dc49..fdb7125788 100644 --- a/crates/shared/src/trade_finding/external.rs +++ b/crates/shared/src/trade_finding/external.rs @@ -17,10 +17,7 @@ use { }, }, anyhow::{Context, anyhow}, - ethrpc::{ - alloy::conversions::{IntoAlloy, IntoLegacy}, - block_stream::CurrentBlockWatcher, - }, + ethrpc::block_stream::CurrentBlockWatcher, futures::FutureExt, observe::tracing::tracing_headers, reqwest::{Client, header}, @@ -59,9 +56,9 @@ impl ExternalTradeFinder { async fn shared_query(&self, query: &Query) -> Result { let fut = move |query: &Query| { let order = dto::Order { - sell_token: query.sell_token.into_legacy(), - buy_token: query.buy_token.into_legacy(), - amount: query.in_amount.get().into_legacy(), + sell_token: query.sell_token, + buy_token: query.buy_token, + amount: query.in_amount.get(), kind: query.kind, deadline: chrono::Utc::now() + query.timeout, }; @@ -133,19 +130,19 @@ impl From for TradeKind { impl From for LegacyTrade { fn from(quote: dto::LegacyQuote) -> Self { Self { - out_amount: quote.amount.into_alloy(), + out_amount: quote.amount, gas_estimate: quote.gas, interactions: quote .interactions .into_iter() .map(|interaction| Interaction { - target: interaction.target.into_alloy(), - value: interaction.value.into_alloy(), + target: interaction.target, + value: interaction.value, data: interaction.call_data, }) .collect(), - solver: quote.solver.into_alloy(), - tx_origin: quote.tx_origin.map(IntoAlloy::into_alloy), + solver: quote.solver, + tx_origin: quote.tx_origin, } } } @@ -156,15 +153,15 @@ impl From for Trade { clearing_prices: quote .clearing_prices .into_iter() - .map(|(k, v)| (k.into_alloy(), v.into_alloy())) + .map(|(k, v)| (k, v)) .collect(), gas_estimate: quote.gas, pre_interactions: quote .pre_interactions .into_iter() .map(|interaction| Interaction { - target: interaction.target.into_alloy(), - value: interaction.value.into_alloy(), + target: interaction.target, + value: interaction.value, data: interaction.call_data, }) .collect(), @@ -172,13 +169,13 @@ impl From for Trade { .interactions .into_iter() .map(|interaction| Interaction { - target: interaction.target.into_alloy(), - value: interaction.value.into_alloy(), + target: interaction.target, + value: interaction.value, data: interaction.call_data, }) .collect(), - solver: quote.solver.into_alloy(), - tx_origin: quote.tx_origin.map(IntoAlloy::into_alloy), + solver: quote.solver, + tx_origin: quote.tx_origin, jit_orders: quote.jit_orders, } } @@ -196,8 +193,8 @@ impl From for PriceEstimationError { impl From for Interaction { fn from(interaction: dto::Interaction) -> Self { Self { - target: interaction.target.into_alloy(), - value: interaction.value.into_alloy(), + target: interaction.target, + value: interaction.value, data: interaction.call_data, } } @@ -241,9 +238,9 @@ impl TradeFinding for ExternalTradeFinder { pub(crate) mod dto { use { + alloy::primitives::{Address, U256}, app_data::AppDataHash, bytes_hex::BytesHex, - ethcontract::{H160, U256}, model::{ order::{BuyTokenDestination, OrderKind, SellTokenSource}, signature::SigningScheme, @@ -258,8 +255,8 @@ pub(crate) mod dto { #[derive(Clone, Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct Order { - pub sell_token: H160, - pub buy_token: H160, + pub sell_token: Address, + pub buy_token: Address, #[serde_as(as = "HexOrDecimalU256")] pub amount: U256, pub kind: OrderKind, @@ -281,10 +278,10 @@ pub(crate) mod dto { #[serde_as(as = "HexOrDecimalU256")] pub amount: U256, pub interactions: Vec, - pub solver: H160, + pub solver: Address, pub gas: Option, #[serde(default)] - pub tx_origin: Option, + pub tx_origin: Option
, } #[serde_as] @@ -292,14 +289,14 @@ pub(crate) mod dto { #[serde(rename_all = "camelCase")] pub struct Quote { #[serde_as(as = "HashMap<_, HexOrDecimalU256>")] - pub clearing_prices: HashMap, + pub clearing_prices: HashMap, #[serde(default)] pub pre_interactions: Vec, #[serde(default)] pub interactions: Vec, - pub solver: H160, + pub solver: Address, pub gas: Option, - pub tx_origin: Option, + pub tx_origin: Option
, #[serde(default)] pub jit_orders: Vec, } @@ -308,7 +305,7 @@ pub(crate) mod dto { #[derive(Clone, Debug, Deserialize)] #[serde(rename_all = "camelCase")] pub struct Interaction { - pub target: H160, + pub target: Address, #[serde_as(as = "HexOrDecimalU256")] pub value: U256, #[serde_as(as = "BytesHex")] @@ -319,15 +316,15 @@ pub(crate) mod dto { #[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct JitOrder { - pub buy_token: H160, - pub sell_token: H160, + pub buy_token: Address, + pub sell_token: Address, #[serde_as(as = "HexOrDecimalU256")] pub sell_amount: U256, #[serde_as(as = "HexOrDecimalU256")] pub buy_amount: U256, #[serde_as(as = "HexOrDecimalU256")] pub executed_amount: U256, - pub receiver: H160, + pub receiver: Address, pub valid_to: u32, pub app_data: AppDataHash, pub side: Side, diff --git a/crates/solver/src/liquidity/uniswap_v3.rs b/crates/solver/src/liquidity/uniswap_v3.rs index 46b4b8f58a..cd3d2b4f02 100644 --- a/crates/solver/src/liquidity/uniswap_v3.rs +++ b/crates/solver/src/liquidity/uniswap_v3.rs @@ -12,7 +12,6 @@ use { alloy::primitives::Address, anyhow::{Context, Result, ensure}, contracts::alloy::UniswapV3SwapRouterV2::IV3SwapRouter::ExactOutputSingleParams, - ethrpc::alloy::conversions::IntoAlloy, model::TokenPair, num::{CheckedMul, rational::Ratio}, shared::{ @@ -130,14 +129,11 @@ impl LiquidityCollecting for UniswapV3Liquidity { pool.tokens.len() == 2, "two tokens required for uniswap v3 pools" ); - let token_pair = TokenPair::new( - pool.tokens[0].id.into_alloy(), - pool.tokens[1].id.into_alloy(), - ) - .context("cant create pair")?; + let token_pair = + TokenPair::new(pool.tokens[0].id, pool.tokens[1].id).context("cant create pair")?; - tokens.insert(pool.tokens[0].id.into_alloy()); - tokens.insert(pool.tokens[1].id.into_alloy()); + tokens.insert(pool.tokens[0].id); + tokens.insert(pool.tokens[1].id); result.push(Liquidity::Concentrated(ConcentratedLiquidity { tokens: token_pair, diff --git a/crates/solver/src/settlement/mod.rs b/crates/solver/src/settlement/mod.rs index 50870bc999..05f49c9db3 100644 --- a/crates/solver/src/settlement/mod.rs +++ b/crates/solver/src/settlement/mod.rs @@ -4,7 +4,6 @@ use { crate::liquidity::Settleable, alloy::primitives::{Address, U256}, anyhow::Result, - ethrpc::alloy::conversions::IntoLegacy, model::order::{Order, OrderKind}, shared::{ conversions::U256Ext as _, @@ -91,10 +90,10 @@ impl Trade { encode_trade( &self.order.data, &self.order.signature, - self.order.metadata.owner.into_legacy(), + self.order.metadata.owner, sell_token_index, buy_token_index, - self.executed_amount.into_legacy(), + self.executed_amount, ) } } diff --git a/crates/solver/src/settlement/settlement_encoder.rs b/crates/solver/src/settlement/settlement_encoder.rs index 5e132d9cc7..9b2a1de270 100644 --- a/crates/solver/src/settlement/settlement_encoder.rs +++ b/crates/solver/src/settlement/settlement_encoder.rs @@ -701,11 +701,11 @@ pub mod tests { ); assert_eq!( finished_settlement.trades[1].1, // <-- is the buy token index of liquidity order - 3.into() + U256::from(3) ); assert_eq!( finished_settlement.trades[0].1, // <-- is the buy token index of normal order - 1.into() + U256::ONE ); } @@ -745,11 +745,11 @@ pub mod tests { ); assert_eq!( finished_settlement.trades[0].0, // <-- is the sell token index of liquidity order - 0.into() + U256::ZERO ); assert_eq!( finished_settlement.trades[0].1, // <-- is the buy token index of liquidity order - 1.into() + U256::ONE ); } @@ -986,11 +986,11 @@ pub mod tests { // dropping unnecessary tokens did not change the sell_token_index let updated_sell_token_index = encoded_trade.0; - assert_eq!(updated_sell_token_index, 0.into()); + assert_eq!(updated_sell_token_index, U256::ZERO); // dropping unnecessary tokens decreased the buy_token_index by one let updated_buy_token_index = encoded_trade.1; - assert_eq!(updated_buy_token_index, 1.into()); + assert_eq!(updated_buy_token_index, U256::ONE); } #[derive(Debug)] diff --git a/crates/solvers/Cargo.toml b/crates/solvers/Cargo.toml index 6d9e50d8d7..82a416785e 100644 --- a/crates/solvers/Cargo.toml +++ b/crates/solvers/Cargo.toml @@ -56,7 +56,6 @@ tracing = { workspace = true } [dev-dependencies] tempfile = { workspace = true } -ethcontract = { workspace = true } [build-dependencies] anyhow = { workspace = true } From 65607e1b520a121751629d870603915eeed7a133 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jose=CC=81=20Duarte?= Date: Fri, 12 Dec 2025 13:59:06 +0000 Subject: [PATCH 2/3] fix lint --- crates/shared/src/trade_finding/external.rs | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/crates/shared/src/trade_finding/external.rs b/crates/shared/src/trade_finding/external.rs index fdb7125788..ca180729dc 100644 --- a/crates/shared/src/trade_finding/external.rs +++ b/crates/shared/src/trade_finding/external.rs @@ -150,11 +150,7 @@ impl From for LegacyTrade { impl From for Trade { fn from(quote: dto::Quote) -> Self { Self { - clearing_prices: quote - .clearing_prices - .into_iter() - .map(|(k, v)| (k, v)) - .collect(), + clearing_prices: quote.clearing_prices, gas_estimate: quote.gas, pre_interactions: quote .pre_interactions From 166e27123d37c72e197f614cdc4c4a9cfb2c688b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jose=CC=81=20Duarte?= Date: Fri, 12 Dec 2025 17:03:22 +0000 Subject: [PATCH 3/3] Remove ethcontract-mock --- Cargo.lock | 107 ++---------------- Cargo.toml | 1 - crates/ethrpc/src/mock.rs | 15 +++ crates/shared/Cargo.toml | 1 - .../src/sources/balancer_v2/pools/weighted.rs | 18 ++- 5 files changed, 30 insertions(+), 112 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 67acbdec62..76ef1e4e71 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1232,7 +1232,7 @@ dependencies = [ "itertools 0.14.0", "maplit", "mimalloc", - "mockall 0.12.1", + "mockall", "model", "num", "number", @@ -2668,12 +2668,6 @@ dependencies = [ "unicode-xid", ] -[[package]] -name = "difflib" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6184e33543162437515c2e2b48714794e37845ec9851711914eec9d308f6ebe8" - [[package]] name = "digest" version = "0.9.0" @@ -2967,7 +2961,6 @@ dependencies = [ "aws-config", "aws-sdk-kms", "ethcontract-common", - "ethcontract-derive", "futures", "futures-timer", "hex", @@ -2999,19 +2992,6 @@ dependencies = [ "web3", ] -[[package]] -name = "ethcontract-derive" -version = "0.25.9" -source = "git+https://github.com/cowprotocol/ethcontract-rs?rev=8e112a88988040cde6110379ee6d1be768a13244#8e112a88988040cde6110379ee6d1be768a13244" -dependencies = [ - "anyhow", - "ethcontract-common", - "ethcontract-generate", - "proc-macro2", - "quote", - "syn 2.0.108", -] - [[package]] name = "ethcontract-generate" version = "0.25.9" @@ -3027,18 +3007,6 @@ dependencies = [ "url", ] -[[package]] -name = "ethcontract-mock" -version = "0.25.9" -source = "git+https://github.com/cowprotocol/ethcontract-rs?rev=8e112a88988040cde6110379ee6d1be768a13244#8e112a88988040cde6110379ee6d1be768a13244" -dependencies = [ - "ethcontract", - "hex", - "mockall 0.11.4", - "predicates 3.1.0", - "rlp", -] - [[package]] name = "ethereum-types" version = "0.14.1" @@ -3066,7 +3034,7 @@ dependencies = [ "hex-literal", "itertools 0.14.0", "maplit", - "mockall 0.12.1", + "mockall", "observe", "primitive-types", "prometheus", @@ -3172,15 +3140,6 @@ dependencies = [ "miniz_oxide", ] -[[package]] -name = "float-cmp" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "98de4bbd547a563b716d8dfa9aad1cb19bfab00f4fa09a6a4ed21dbcf44ce9c4" -dependencies = [ - "num-traits", -] - [[package]] name = "flume" version = "0.11.0" @@ -4361,21 +4320,6 @@ dependencies = [ "windows-sys 0.59.0", ] -[[package]] -name = "mockall" -version = "0.11.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4c84490118f2ee2d74570d114f3d0493cbf02790df303d2707606c3e14e07c96" -dependencies = [ - "cfg-if", - "downcast", - "fragile", - "lazy_static", - "mockall_derive 0.11.4", - "predicates 2.1.5", - "predicates-tree", -] - [[package]] name = "mockall" version = "0.12.1" @@ -4386,23 +4330,11 @@ dependencies = [ "downcast", "fragile", "lazy_static", - "mockall_derive 0.12.1", - "predicates 3.1.0", + "mockall_derive", + "predicates", "predicates-tree", ] -[[package]] -name = "mockall_derive" -version = "0.11.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "22ce75669015c4f47b289fd4d4f56e894e4c96003ffdf3ac51313126f94c6cbb" -dependencies = [ - "cfg-if", - "proc-macro2", - "quote", - "syn 1.0.109", -] - [[package]] name = "mockall_derive" version = "0.12.1" @@ -4500,12 +4432,6 @@ dependencies = [ "minimal-lexical", ] -[[package]] -name = "normalize-line-endings" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "61807f77802ff30975e01f4f071c8ba10c022052f98b3294119f3e615d13e5be" - [[package]] name = "nu-ansi-term" version = "0.46.0" @@ -4877,7 +4803,7 @@ dependencies = [ "humantime", "hyper 0.14.29", "mimalloc", - "mockall 0.12.1", + "mockall", "model", "multibase", "num", @@ -5112,20 +5038,6 @@ version = "0.2.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5b40af805b3121feab8a3c29f04d8ad262fa8e0561883e7653e024ae4479e6de" -[[package]] -name = "predicates" -version = "2.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "59230a63c37f3e18569bdb90e4a89cbf5bf8b06fea0b84e65ea10cc4df47addd" -dependencies = [ - "difflib", - "float-cmp", - "itertools 0.10.5", - "normalize-line-endings", - "predicates-core", - "regex", -] - [[package]] name = "predicates" version = "3.1.0" @@ -5133,11 +5045,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "68b87bfd4605926cdfefc1c3b5f8fe560e3feca9d5552cf68c466d3d8236c7e8" dependencies = [ "anstyle", - "difflib", - "float-cmp", - "normalize-line-endings", "predicates-core", - "regex", ] [[package]] @@ -6356,7 +6264,6 @@ dependencies = [ "derivative", "derive_more 1.0.0", "ethcontract", - "ethcontract-mock", "ethrpc", "futures", "gas-estimation", @@ -6365,7 +6272,7 @@ dependencies = [ "indexmap 2.10.0", "itertools 0.14.0", "maplit", - "mockall 0.12.1", + "mockall", "model", "num", "number", @@ -6478,7 +6385,7 @@ dependencies = [ "hex-literal", "itertools 0.14.0", "maplit", - "mockall 0.12.1", + "mockall", "model", "num", "number", diff --git a/Cargo.toml b/Cargo.toml index 0904dbd2a4..3f3bbd3f21 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -19,7 +19,6 @@ mimalloc = "0.1.43" tikv-jemallocator = { version = "0.6", features = ["unprefixed_malloc_on_supported_platforms", "profiling"] } jemalloc_pprof = { version = "0.8", features = ["symbolize"] } ethcontract-generate = { git = "https://github.com/cowprotocol/ethcontract-rs", rev = "8e112a88988040cde6110379ee6d1be768a13244", default-features = false } -ethcontract-mock = { git = "https://github.com/cowprotocol/ethcontract-rs", rev = "8e112a88988040cde6110379ee6d1be768a13244", default-features = false } flate2 = "1.0.30" futures = "0.3.30" gas-estimation = { git = "https://github.com/cowprotocol/gas-estimation", tag = "v0.7.3", features = ["web3_", "tokio_"] } diff --git a/crates/ethrpc/src/mock.rs b/crates/ethrpc/src/mock.rs index 9a3c6c35a6..6ba9d3ac7a 100644 --- a/crates/ethrpc/src/mock.rs +++ b/crates/ethrpc/src/mock.rs @@ -20,6 +20,21 @@ use { }, }; +impl Web3 { + pub fn with_asserter(asserter: Asserter) -> Self { + Web3 { + legacy: web3::Web3::new(MockTransport::new()), + // this will not behave like the original mock transport but it's only used + // in one place so let's keep this for now and fix it when we switch to + // alloy in the 1 place that uses the mock provider. + alloy: ProviderBuilder::new() + .connect_mocked_client(asserter) + .erased(), + wallet: MutWallet::default(), + } + } +} + pub fn web3() -> Web3 { Web3 { legacy: web3::Web3::new(MockTransport::new()), diff --git a/crates/shared/Cargo.toml b/crates/shared/Cargo.toml index e34b048538..7bbfcaa060 100644 --- a/crates/shared/Cargo.toml +++ b/crates/shared/Cargo.toml @@ -64,7 +64,6 @@ mockall = { workspace = true, optional = true } alloy = { workspace = true, features = ["rand"] } app-data = { workspace = true, features = ["test_helpers"] } async-stream = { workspace = true } -ethcontract-mock = { workspace = true } ethrpc = { workspace = true, features = ["test-util"] } mockall = { workspace = true } regex = { workspace = true } diff --git a/crates/shared/src/sources/balancer_v2/pools/weighted.rs b/crates/shared/src/sources/balancer_v2/pools/weighted.rs index c6b8757abd..5420d4dd8f 100644 --- a/crates/shared/src/sources/balancer_v2/pools/weighted.rs +++ b/crates/shared/src/sources/balancer_v2/pools/weighted.rs @@ -154,8 +154,7 @@ mod tests { sol_types::SolCall, }, ethcontract::H256, - ethcontract_mock::Mock, - ethrpc::alloy::conversions::IntoAlloy, + ethrpc::{Web3, alloy::conversions::IntoAlloy, mock::MockTransport}, futures::future, maplit::btreemap, }; @@ -281,13 +280,12 @@ mod tests { let weights = [bfp!("0.8"), bfp!("0.2")]; let swap_fee = bfp!("0.003"); - let mock = Mock::new(42); - let web3 = mock.web3(); + let asserter = Asserter::new(); + asserter.push_success(&10); + let web3 = Web3::::with_asserter(asserter); - let factory = BalancerV2WeightedPoolFactory::Instance::new( - Address::default(), - ethrpc::mock::web3().alloy, - ); + let factory = + BalancerV2WeightedPoolFactory::Instance::new(Address::default(), web3.alloy.clone()); let pool_info = PoolInfo { common: common::PoolInfo { id: H256([0x90; 32]), @@ -305,12 +303,12 @@ mod tests { }; let pool_state = { - let block = web3.eth().block_number().await.unwrap(); + let block = web3.alloy.get_block_number().await.unwrap(); let pool_state = factory.fetch_pool_state( &pool_info, future::ready(common_pool_state.clone()).boxed(), - block.into(), + BlockId::Number(ethcontract::BlockNumber::Number(block.into())), ); pool_state.await.unwrap()