From 99eca3fb7567e7e67e17f442a347dd5a84877276 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jose=CC=81=20Duarte?= Date: Thu, 11 Dec 2025 09:19:37 +0000 Subject: [PATCH 1/2] Migrate autopilot's primitive-types dependency to alloy --- Cargo.lock | 4 - Cargo.toml | 1 - crates/autopilot/Cargo.toml | 3 +- crates/autopilot/src/arguments.rs | 37 ++++---- crates/autopilot/src/database/competition.rs | 12 +-- crates/autopilot/src/domain/auction/order.rs | 18 ++-- .../domain/competition/winner_selection.rs | 4 +- crates/autopilot/src/domain/fee/mod.rs | 3 +- crates/autopilot/src/infra/blockchain/mod.rs | 7 +- .../src/infra/persistence/dto/auction.rs | 15 +-- .../src/infra/persistence/dto/order.rs | 9 +- .../autopilot/src/infra/solvers/dto/solve.rs | 53 +++++------ crates/autopilot/src/infra/solvers/mod.rs | 4 +- crates/autopilot/src/run.rs | 17 +--- crates/autopilot/src/run_loop.rs | 24 ++--- crates/autopilot/src/shadow.rs | 13 +-- crates/autopilot/src/solvable_orders.rs | 91 ++++++++++++------- crates/driver/Cargo.toml | 3 +- crates/orderbook/Cargo.toml | 2 - 19 files changed, 149 insertions(+), 171 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index e7950457df..ec6865bf74 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1238,7 +1238,6 @@ dependencies = [ "number", "observe", "order-validation", - "primitive-types", "prometheus", "prometheus-metric-storage", "rand 0.8.5", @@ -2728,7 +2727,6 @@ dependencies = [ "dashmap", "derive_more 1.0.0", "ethcontract", - "ethereum-types", "ethrpc", "futures", "gas-estimation", @@ -4875,7 +4873,6 @@ dependencies = [ "const-hex", "contracts", "database", - "ethcontract", "ethrpc", "futures", "hex-literal", @@ -4889,7 +4886,6 @@ dependencies = [ "number", "observe", "order-validation", - "primitive-types", "prometheus", "prometheus-metric-storage", "reqwest 0.11.27", diff --git a/Cargo.toml b/Cargo.toml index 66b43d6fb0..0904dbd2a4 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -20,7 +20,6 @@ tikv-jemallocator = { version = "0.6", features = ["unprefixed_malloc_on_support 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 } -ethereum-types = "0.14.1" 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/autopilot/Cargo.toml b/crates/autopilot/Cargo.toml index 6d6896c53a..2e7c95021c 100644 --- a/crates/autopilot/Cargo.toml +++ b/crates/autopilot/Cargo.toml @@ -15,7 +15,7 @@ name = "autopilot" path = "src/main.rs" [dependencies] -alloy = { workspace = true } +alloy = { workspace = true, features = ["rand"] } app-data = { workspace = true } bytes-hex = { workspace = true } # may get marked as unused but it's used with serde anyhow = { workspace = true } @@ -45,7 +45,6 @@ model = { workspace = true } num = { workspace = true } number = { workspace = true } order-validation = { workspace = true } -primitive-types = { workspace = true } prometheus = { workspace = true } prometheus-metric-storage = { workspace = true } rand = { workspace = true } diff --git a/crates/autopilot/src/arguments.rs b/crates/autopilot/src/arguments.rs index 5a8d5044b4..9ee8f1fd16 100644 --- a/crates/autopilot/src/arguments.rs +++ b/crates/autopilot/src/arguments.rs @@ -1,10 +1,9 @@ use { crate::{domain::fee::FeeFactor, infra}, - alloy::primitives::Address, + alloy::primitives::{Address, U256}, anyhow::{Context, anyhow, ensure}, chrono::{DateTime, Utc}, clap::ValueEnum, - primitive_types::{H160, U256}, shared::{ arguments::{display_list, display_option, display_secret_option}, bad_token::token_owner_finder, @@ -509,7 +508,7 @@ pub enum Account { /// AWS KMS is used to retrieve the solver public key Kms(Arn), /// Solver public key - Address(H160), + Address(Address), } // Wrapper type for AWS ARN identifiers @@ -546,14 +545,16 @@ impl FromStr for Solver { let url: Url = url.parse()?; let submission_account = match Arn::from_str(parts[2]) { Ok(value) => Account::Kms(value), - _ => Account::Address(H160::from_str(parts[2]).context("failed to parse submission")?), + _ => { + Account::Address(Address::from_str(parts[2]).context("failed to parse submission")?) + } }; let mut fairness_threshold: Option = Default::default(); let mut requested_timeout_on_problems = false; if let Some(value) = parts.get(3) { - match U256::from_dec_str(value) { + match U256::from_str_radix(value, 10) { Ok(parsed_fairness_threshold) => { fairness_threshold = Some(parsed_fairness_threshold); } @@ -744,12 +745,12 @@ impl FromStr for CowAmmConfig { .next() .context("config is missing factory")? .parse() - .context("could not parse factory as H160")?; + .context("could not parse factory as Address")?; let helper = parts .next() .context("config is missing helper")? .parse() - .context("could not parse helper as H160")?; + .context("could not parse helper as Address")?; let index_start = parts .next() .context("config is missing index_start")? @@ -770,7 +771,7 @@ impl FromStr for CowAmmConfig { #[cfg(test)] mod test { - use {super::*, hex_literal::hex}; + use {super::*, alloy::primitives::address}; #[test] fn test_fee_factor_limits() { @@ -807,9 +808,9 @@ mod test { url: Url::parse("http://localhost:8080").unwrap(), fairness_threshold: None, requested_timeout_on_problems: false, - submission_account: Account::Address(H160::from_slice(&hex!( + submission_account: Account::Address(address!( "C02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2" - ))), + )), }; assert_eq!(driver, expected); } @@ -837,10 +838,10 @@ mod test { let expected = Solver { name: "name1".into(), url: Url::parse("http://localhost:8080").unwrap(), - submission_account: Account::Address(H160::from_slice(&hex!( + submission_account: Account::Address(address!( "C02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2" - ))), - fairness_threshold: Some(U256::exp10(18)), + )), + fairness_threshold: Some(U256::from(10).pow(U256::from(18))), requested_timeout_on_problems: false, }; assert_eq!(driver, expected); @@ -854,9 +855,9 @@ mod test { let expected = Solver { name: "name1".into(), url: Url::parse("http://localhost:8080").unwrap(), - submission_account: Account::Address(H160::from_slice(&hex!( + submission_account: Account::Address(address!( "C02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2" - ))), + )), fairness_threshold: None, requested_timeout_on_problems: true, }; @@ -870,10 +871,10 @@ mod test { let expected = Solver { name: "name1".into(), url: Url::parse("http://localhost:8080").unwrap(), - submission_account: Account::Address(H160::from_slice(&hex!( + submission_account: Account::Address(address!( "C02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2" - ))), - fairness_threshold: Some(U256::exp10(18)), + )), + fairness_threshold: Some(U256::from(10).pow(U256::from(18))), requested_timeout_on_problems: true, }; assert_eq!(driver, expected); diff --git a/crates/autopilot/src/database/competition.rs b/crates/autopilot/src/database/competition.rs index ddc7923d58..c6ca77c38f 100644 --- a/crates/autopilot/src/database/competition.rs +++ b/crates/autopilot/src/database/competition.rs @@ -1,6 +1,6 @@ use { crate::domain::competition::Score, - alloy::primitives::Address, + alloy::primitives::{Address, U256}, anyhow::Context, database::{ auction::AuctionId, @@ -10,8 +10,6 @@ use { }, derive_more::Debug, model::solver_competition::SolverCompetitionDB, - number::conversions::u256_to_big_decimal, - primitive_types::{H160, U256}, std::collections::{BTreeMap, HashMap, HashSet}, }; @@ -21,9 +19,9 @@ pub struct Competition { pub reference_scores: HashMap, /// Addresses to which the CIP20 participation rewards will be payed out. /// Usually the same as the solver addresses. - pub participants: HashSet, + pub participants: HashSet
, /// External prices for auction. - pub prices: BTreeMap, + pub prices: BTreeMap, /// Winner receives performance rewards if a settlement is finalized on /// chain before this block height. pub block_deadline: u64, @@ -67,8 +65,8 @@ impl super::Postgres { .into_iter() .map(|(token, price)| AuctionPrice { auction_id: competition.auction_id, - token: ByteArray(token.0), - price: u256_to_big_decimal(&price), + token: ByteArray(token.0.0), + price: number::conversions::alloy::u256_to_big_decimal(&price), }) .collect::>() .as_slice(), diff --git a/crates/autopilot/src/domain/auction/order.rs b/crates/autopilot/src/domain/auction/order.rs index 55dcee7030..83715810f2 100644 --- a/crates/autopilot/src/domain/auction/order.rs +++ b/crates/autopilot/src/domain/auction/order.rs @@ -1,6 +1,6 @@ use { crate::domain::{self, eth, fee}, - primitive_types::{H160, H256, U256}, + alloy::primitives::{Address, B256, U256}, std::fmt::{self, Debug, Display, Formatter}, }; @@ -38,10 +38,10 @@ impl OrderUid { } /// Splits an order UID into its parts. - fn parts(&self) -> (H256, H160, u32) { + fn parts(&self) -> (B256, Address, u32) { ( - H256::from_slice(&self.0[0..32]), - H160::from_slice(&self.0[32..52]), + B256::from_slice(&self.0[0..32]), + Address::from_slice(&self.0[32..52]), u32::from_le_bytes(self.0[52..].try_into().unwrap()), ) } @@ -73,7 +73,7 @@ pub enum Side { #[derive(Clone, Debug, PartialEq)] pub struct Interaction { - pub target: H160, + pub target: Address, pub value: U256, pub call_data: Vec, } @@ -175,8 +175,8 @@ pub enum SigningScheme { #[derive(Copy, Clone, Debug, PartialEq)] pub struct EcdsaSignature { - pub r: H256, - pub s: H256, + pub r: B256, + pub s: B256, pub v: u8, } @@ -184,8 +184,8 @@ impl EcdsaSignature { /// r + s + v pub fn to_bytes(self) -> [u8; 65] { let mut bytes = [0u8; 65]; - bytes[..32].copy_from_slice(self.r.as_bytes()); - bytes[32..64].copy_from_slice(self.s.as_bytes()); + bytes[..32].copy_from_slice(self.r.as_slice()); + bytes[32..64].copy_from_slice(self.s.as_slice()); bytes[64] = self.v; bytes } diff --git a/crates/autopilot/src/domain/competition/winner_selection.rs b/crates/autopilot/src/domain/competition/winner_selection.rs index 86fdfc045b..b94ecb6a91 100644 --- a/crates/autopilot/src/domain/competition/winner_selection.rs +++ b/crates/autopilot/src/domain/competition/winner_selection.rs @@ -478,7 +478,7 @@ mod tests { }, alloy::primitives::{U256, address}, ethcontract::H160, - ethrpc::alloy::conversions::{IntoAlloy, IntoLegacy}, + ethrpc::alloy::conversions::IntoAlloy, hex_literal::hex, number::serialization::HexOrDecimalU256, serde::Deserialize, @@ -1404,7 +1404,7 @@ mod tests { url::Url::parse("http://localhost").unwrap(), solver_address.to_string(), None, - crate::arguments::Account::Address(solver_address.into_legacy()), + crate::arguments::Account::Address(solver_address), false, ) .await diff --git a/crates/autopilot/src/domain/fee/mod.rs b/crates/autopilot/src/domain/fee/mod.rs index 6bca0bd74d..d3f5d7fab2 100644 --- a/crates/autopilot/src/domain/fee/mod.rs +++ b/crates/autopilot/src/domain/fee/mod.rs @@ -16,7 +16,6 @@ use { app_data::Validator, chrono::{DateTime, Utc}, derive_more::Into, - primitive_types::H160, rust_decimal::Decimal, std::{collections::HashSet, str::FromStr}, }; @@ -75,7 +74,7 @@ impl From for Option { } } -pub type ProtocolFeeExemptAddresses = HashSet; +pub type ProtocolFeeExemptAddresses = HashSet
; pub struct ProtocolFees { fee_policies: Vec, diff --git a/crates/autopilot/src/infra/blockchain/mod.rs b/crates/autopilot/src/infra/blockchain/mod.rs index 0b8a9b9624..271190abee 100644 --- a/crates/autopilot/src/infra/blockchain/mod.rs +++ b/crates/autopilot/src/infra/blockchain/mod.rs @@ -1,7 +1,7 @@ use { self::contracts::Contracts, crate::{boundary, domain::eth}, - alloy::providers::Provider, + alloy::{primitives::U256, providers::Provider}, chain::Chain, ethrpc::{ Web3, @@ -9,7 +9,6 @@ use { block_stream::CurrentBlockWatcher, extensions::DebugNamespace, }, - primitive_types::U256, thiserror::Error, url::Url, }; @@ -134,7 +133,7 @@ impl Ethereum { .block(block_hash.into()) .await? .ok_or(Error::TransactionNotFound)?; - into_domain(transaction, receipt, traces, block.timestamp) + into_domain(transaction, receipt, traces, block.timestamp.into_alloy()) .map_err(Error::IncompleteTransactionData) } } @@ -166,7 +165,7 @@ fn into_domain( .ok_or(anyhow::anyhow!("missing effective_gas_price"))? .into_alloy() .into(), - timestamp: timestamp.as_u32(), + timestamp: u32::try_from(timestamp).expect("value should be lower than u32::MAX"), trace_calls: trace_calls.into(), }) } diff --git a/crates/autopilot/src/infra/persistence/dto/auction.rs b/crates/autopilot/src/infra/persistence/dto/auction.rs index 3fbd168416..87acc09d5d 100644 --- a/crates/autopilot/src/infra/persistence/dto/auction.rs +++ b/crates/autopilot/src/infra/persistence/dto/auction.rs @@ -1,9 +1,8 @@ use { super::order::Order, crate::domain::{self, auction::Price, eth}, - ethrpc::alloy::conversions::{IntoAlloy, IntoLegacy}, + alloy::primitives::{Address, U256}, number::serialization::HexOrDecimalU256, - primitive_types::{H160, U256}, serde::{Deserialize, Serialize}, serde_with::serde_as, std::collections::BTreeMap, @@ -20,12 +19,11 @@ pub fn from_domain(auction: domain::RawAuctionData) -> RawAuctionData { prices: auction .prices .into_iter() - .map(|(key, value)| (key.0.into_legacy(), value.get().0.into_legacy())) + .map(|(key, value)| (key.0, value.get().0)) .collect(), surplus_capturing_jit_order_owners: auction .surplus_capturing_jit_order_owners .into_iter() - .map(IntoLegacy::into_legacy) .collect(), } } @@ -37,14 +35,13 @@ pub struct RawAuctionData { pub block: u64, pub orders: Vec, #[serde_as(as = "BTreeMap<_, HexOrDecimalU256>")] - pub prices: BTreeMap, + pub prices: BTreeMap, #[serde(default)] - pub surplus_capturing_jit_order_owners: Vec, + pub surplus_capturing_jit_order_owners: Vec
, } pub type AuctionId = i64; -#[serde_as] #[derive(Clone, Debug, Deserialize)] #[serde(rename_all = "camelCase")] pub struct Auction { @@ -69,15 +66,13 @@ impl Auction { .prices .into_iter() .map(|(key, value)| { - Price::try_new(value.into_alloy().into()) - .map(|price| (eth::TokenAddress(key.into_alloy()), price)) + Price::try_new(value.into()).map(|price| (eth::TokenAddress(key), price)) }) .collect::>()?, surplus_capturing_jit_order_owners: self .auction .surplus_capturing_jit_order_owners .into_iter() - .map(IntoAlloy::into_alloy) .collect(), }) } diff --git a/crates/autopilot/src/infra/persistence/dto/order.rs b/crates/autopilot/src/infra/persistence/dto/order.rs index 241e199c74..5a68c45482 100644 --- a/crates/autopilot/src/infra/persistence/dto/order.rs +++ b/crates/autopilot/src/infra/persistence/dto/order.rs @@ -5,7 +5,6 @@ use { }, alloy::primitives::{Address, U256}, app_data::AppDataHash, - ethrpc::alloy::conversions::{IntoAlloy, IntoLegacy}, number::serialization::HexOrDecimalU256, serde::{Deserialize, Serialize}, serde_with::serde_as, @@ -147,8 +146,8 @@ impl From for domain::auction::order::Side { impl From for boundary::InteractionData { fn from(interaction: domain::auction::order::Interaction) -> Self { Self { - target: interaction.target.into_alloy(), - value: interaction.value.into_alloy(), + target: interaction.target, + value: interaction.value, call_data: interaction.call_data, } } @@ -157,8 +156,8 @@ impl From for boundary::InteractionData { impl From for domain::auction::order::Interaction { fn from(interaction: boundary::InteractionData) -> Self { Self { - target: interaction.target.into_legacy(), - value: interaction.value.into_legacy(), + target: interaction.target, + value: interaction.value, call_data: interaction.call_data, } } diff --git a/crates/autopilot/src/infra/solvers/dto/solve.rs b/crates/autopilot/src/infra/solvers/dto/solve.rs index f0fadc88d1..847d18d79d 100644 --- a/crates/autopilot/src/infra/solvers/dto/solve.rs +++ b/crates/autopilot/src/infra/solvers/dto/solve.rs @@ -4,11 +4,10 @@ use { domain::{self, eth}, infra::persistence::dto::{self, order::Order}, }, + alloy::primitives::{Address, U256}, chrono::{DateTime, Utc}, - ethrpc::alloy::conversions::{IntoAlloy, IntoLegacy}, itertools::Itertools, number::serialization::HexOrDecimalU256, - primitive_types::{H160, U256}, serde::{Deserialize, Serialize}, serde_with::{DisplayFromStr, serde_as}, std::{ @@ -34,7 +33,7 @@ impl Request { impl Request { pub fn new( auction: &domain::Auction, - trusted_tokens: &HashSet, + trusted_tokens: &HashSet
, time_limit: Duration, ) -> Self { let _timer = @@ -51,9 +50,9 @@ impl Request { .prices .iter() .map(|(address, price)| Token { - address: address.to_owned().0.into_legacy(), - price: Some(price.get().0.into_legacy()), - trusted: trusted_tokens.contains(&(address.0.into_legacy())), + address: address.to_owned().0, + price: Some(price.get().0), + trusted: trusted_tokens.contains(&(address.0)), }) .chain(trusted_tokens.iter().map(|&address| Token { address, @@ -63,12 +62,7 @@ impl Request { .unique_by(|token| token.address) .collect(), deadline: Utc::now() + chrono::Duration::from_std(time_limit).unwrap(), - surplus_capturing_jit_order_owners: auction - .surplus_capturing_jit_order_owners - .iter() - .copied() - .map(IntoLegacy::into_legacy) - .collect::>(), + surplus_capturing_jit_order_owners: auction.surplus_capturing_jit_order_owners.to_vec(), }; Self(Arc::from(serde_json::value::to_raw_value(&helper).expect( "only fails with non-string keys which we do not have", @@ -96,14 +90,14 @@ struct RequestHelper { pub tokens: Vec, pub orders: Vec, pub deadline: DateTime, - pub surplus_capturing_jit_order_owners: Vec, + pub surplus_capturing_jit_order_owners: Vec
, } #[serde_as] #[derive(Clone, Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct Token { - pub address: H160, + pub address: Address, #[serde_as(as = "Option")] pub price: Option, pub trusted: bool, @@ -115,8 +109,8 @@ impl Solution { ) -> Result { Ok(domain::competition::Solution::new( self.solution_id, - self.submission_address.into_alloy(), - domain::competition::Score::try_new(self.score.into_alloy().into())?, + self.submission_address, + domain::competition::Score::try_new(self.score.into())?, self.orders .into_iter() .map(|(o, amounts)| (o.into(), amounts.into_domain())) @@ -124,8 +118,7 @@ impl Solution { self.clearing_prices .into_iter() .map(|(token, price)| { - domain::auction::Price::try_new(price.into_alloy().into()) - .map(|price| (token.into_alloy().into(), price)) + domain::auction::Price::try_new(price.into()).map(|price| (token.into(), price)) }) .collect::>()?, )) @@ -141,13 +134,13 @@ impl Solution { #[serde(rename_all = "camelCase")] pub struct TradedOrder { side: Side, - sell_token: H160, - buy_token: H160, - #[serde_as(as = "HexOrDecimalU256")] + sell_token: Address, + buy_token: Address, /// Sell limit order amount. - limit_sell: U256, #[serde_as(as = "HexOrDecimalU256")] + limit_sell: U256, /// Buy limit order amount. + #[serde_as(as = "HexOrDecimalU256")] limit_buy: U256, /// The effective amount that left the user's wallet including all fees. #[serde_as(as = "HexOrDecimalU256")] @@ -161,19 +154,19 @@ impl TradedOrder { pub fn into_domain(self) -> domain::competition::TradedOrder { domain::competition::TradedOrder { sell: eth::Asset { - token: self.sell_token.into_alloy().into(), - amount: self.limit_sell.into_alloy().into(), + token: self.sell_token.into(), + amount: self.limit_sell.into(), }, buy: eth::Asset { - token: self.buy_token.into_alloy().into(), - amount: self.limit_buy.into_alloy().into(), + token: self.buy_token.into(), + amount: self.limit_buy.into(), }, side: match self.side { Side::Buy => domain::auction::order::Side::Buy, Side::Sell => domain::auction::order::Side::Sell, }, - executed_sell: self.executed_sell.into_alloy().into(), - executed_buy: self.executed_buy.into_alloy().into(), + executed_sell: self.executed_sell.into(), + executed_buy: self.executed_buy.into(), } } } @@ -196,10 +189,10 @@ pub struct Solution { #[serde_as(as = "HexOrDecimalU256")] pub score: U256, /// Address used by the driver to submit the settlement onchain. - pub submission_address: H160, + pub submission_address: Address, pub orders: HashMap, #[serde_as(as = "HashMap<_, HexOrDecimalU256>")] - pub clearing_prices: HashMap, + pub clearing_prices: HashMap, pub gas: Option, } diff --git a/crates/autopilot/src/infra/solvers/mod.rs b/crates/autopilot/src/infra/solvers/mod.rs index 223be66898..ae75016437 100644 --- a/crates/autopilot/src/infra/solvers/mod.rs +++ b/crates/autopilot/src/infra/solvers/mod.rs @@ -56,7 +56,7 @@ impl Driver { tracing::error!(?name, ?key_id, "Unable to load KMS account"); Error::UnableToLoadKmsAccount })?; - account.public_address() + account.public_address().into_alloy() } Account::Address(address) => address, }; @@ -76,7 +76,7 @@ impl Driver { .timeout(RESPONSE_TIME_LIMIT) .build() .map_err(Error::FailedToBuildClient)?, - submission_address: submission_address.into_alloy(), + submission_address, requested_timeout_on_problems, }) } diff --git a/crates/autopilot/src/run.rs b/crates/autopilot/src/run.rs index 732a7a0a7a..daea7346b5 100644 --- a/crates/autopilot/src/run.rs +++ b/crates/autopilot/src/run.rs @@ -24,14 +24,13 @@ use { shutdown_controller::ShutdownController, solvable_orders::SolvableOrdersCache, }, - alloy::eips::BlockNumberOrTag, + alloy::{eips::BlockNumberOrTag, primitives::Address}, chain::Chain, clap::Parser, contracts::alloy::{BalancerV2Vault, GPv2Settlement, IUniswapV3Factory, WETH9}, - ethcontract::H160, ethrpc::{ Web3, - alloy::conversions::{IntoAlloy, IntoLegacy}, + alloy::conversions::IntoLegacy, block_stream::block_number_to_block_number_hash, }, futures::StreamExt, @@ -662,10 +661,7 @@ pub async fn run(args: Arguments, shutdown_controller: ShutdownController) { infra::Driver::try_new( driver.url, driver.name.clone(), - driver - .fairness_threshold - .map(IntoAlloy::into_alloy) - .map(Into::into), + driver.fairness_threshold.map(Into::into), driver.submission_account, driver.requested_timeout_on_problems, ) @@ -722,10 +718,7 @@ async fn shadow_mode(args: Arguments) -> ! { infra::Driver::try_new( driver.url, driver.name.clone(), - driver - .fairness_threshold - .map(IntoAlloy::into_alloy) - .map(Into::into), + driver.fairness_threshold.map(Into::into), // HACK: the auction logic expects all drivers // to use a different submission address. But // in the shadow environment all drivers use @@ -734,7 +727,7 @@ async fn shadow_mode(args: Arguments) -> ! { // Luckily the shadow autopilot doesn't use // this address for anything important so we // can simply generate random addresses here. - Account::Address(H160::random()), + Account::Address(Address::random()), driver.requested_timeout_on_problems, ) .await diff --git a/crates/autopilot/src/run_loop.rs b/crates/autopilot/src/run_loop.rs index 26adb10d65..104cd3d30b 100644 --- a/crates/autopilot/src/run_loop.rs +++ b/crates/autopilot/src/run_loop.rs @@ -27,9 +27,10 @@ use { solvable_orders::SolvableOrdersCache, }, ::observe::metrics, + alloy::primitives::B256, anyhow::{Context, Result}, database::order_events::OrderEventLabel, - ethrpc::{alloy::conversions::IntoLegacy, block_stream::BlockInfo}, + ethrpc::{alloy::conversions::IntoAlloy, block_stream::BlockInfo}, futures::{FutureExt, TryFutureExt}, itertools::Itertools, model::solver_competition::{ @@ -40,7 +41,6 @@ use { SolverSettlement, }, num::ToPrimitive, - primitive_types::H256, rand::seq::SliceRandom, shared::token_list::AutoUpdatingTokenList, std::{ @@ -207,11 +207,11 @@ impl RunLoop { }); } - async fn update_caches(&self, prev_block: &mut Option, is_leader: bool) -> BlockInfo { + async fn update_caches(&self, prev_block: &mut Option, is_leader: bool) -> BlockInfo { let current_block = *self.eth.current_block().borrow(); let time_since_last_block = current_block.observed_at.elapsed(); let auction_block = if time_since_last_block > self.config.max_run_loop_delay { - if prev_block.is_some_and(|prev_block| prev_block != current_block.hash) { + if prev_block.is_some_and(|prev_block| prev_block != current_block.hash.into_alloy()) { // don't emit warning if we finished prev run loop within the same block tracing::warn!( missed_by = ?time_since_last_block - self.config.max_run_loop_delay, @@ -249,7 +249,7 @@ impl RunLoop { &self, start_block: BlockInfo, prev_auction: &mut Option, - prev_block: &mut Option, + prev_block: &mut Option, ) -> Option { // wait for appropriate time to start building the auction let auction = self.cut_auction().await?; @@ -258,7 +258,8 @@ impl RunLoop { // Only run the solvers if the auction or block has changed. let previous = prev_auction.replace(auction.clone()); if previous.as_ref() == Some(&auction) - && prev_block.replace(start_block.hash) == Some(start_block.hash) + && prev_block.replace(start_block.hash.into_alloy()) + == Some(start_block.hash.into_alloy()) { return None; } @@ -466,7 +467,7 @@ impl RunLoop { let participants = ranking .all() - .map(|participant| participant.solution().solver().into_legacy()) + .map(|participant| participant.solution().solver()) .collect::>(); let order_lookup: std::collections::HashMap<_, _> = auction .orders @@ -545,7 +546,7 @@ impl RunLoop { .prices .clone() .into_iter() - .map(|(key, value)| (key.0.into_legacy(), value.get().0.into_legacy())) + .map(|(key, value)| (key.0, value.get().0)) .collect(), block_deadline, competition_simulation_block, @@ -612,12 +613,7 @@ impl RunLoop { ) -> Vec> { let request = solve::Request::new( auction, - &self - .trusted_tokens - .all() - .into_iter() - .map(IntoLegacy::into_legacy) - .collect(), + &self.trusted_tokens.all(), self.config.solve_deadline, ); diff --git a/crates/autopilot/src/shadow.rs b/crates/autopilot/src/shadow.rs index 9e99d83609..74985b3c64 100644 --- a/crates/autopilot/src/shadow.rs +++ b/crates/autopilot/src/shadow.rs @@ -23,7 +23,7 @@ use { }, ::observe::metrics, anyhow::Context, - ethrpc::{alloy::conversions::IntoLegacy, block_stream::CurrentBlockWatcher}, + ethrpc::block_stream::CurrentBlockWatcher, itertools::Itertools, num::{CheckedSub, Saturating}, shared::token_list::AutoUpdatingTokenList, @@ -178,16 +178,7 @@ impl RunLoop { /// Runs the solver competition, making all configured drivers participate. #[instrument(skip_all)] async fn competition(&self, auction: &domain::Auction) -> Vec> { - let request = solve::Request::new( - auction, - &self - .trusted_tokens - .all() - .into_iter() - .map(IntoLegacy::into_legacy) - .collect(), - self.solve_deadline, - ); + let request = solve::Request::new(auction, &self.trusted_tokens.all(), self.solve_deadline); futures::future::join_all( self.drivers diff --git a/crates/autopilot/src/solvable_orders.rs b/crates/autopilot/src/solvable_orders.rs index bd8b411c40..0bd2d9e640 100644 --- a/crates/autopilot/src/solvable_orders.rs +++ b/crates/autopilot/src/solvable_orders.rs @@ -4,7 +4,7 @@ use { domain::{self, auction::Price, eth}, infra::{self, banned}, }, - alloy::primitives::Address, + alloy::primitives::{Address, U256}, anyhow::{Context, Result}, bigdecimal::BigDecimal, database::order_events::OrderEventLabel, @@ -18,7 +18,6 @@ use { time::now_in_epoch_seconds, }, number::conversions::alloy::u256_to_big_decimal, - primitive_types::{H256, U256}, prometheus::{Histogram, HistogramVec, IntCounter, IntCounterVec, IntGauge, IntGaugeVec}, shared::{ account_balances::{BalanceFetching, Query}, @@ -344,7 +343,7 @@ impl SolvableOrdersCache { .into_iter() .zip(fetched_balances) .filter_map(|(query, balance)| match balance { - Ok(balance) => Some((query, balance)), + Ok(balance) => Some((query, balance.into_alloy())), Err(err) => { tracing::warn!( owner = ?query.owner, @@ -512,11 +511,11 @@ async fn find_invalid_signature_orders( if let Signature::Eip1271(signature) = &order.signature { signature_check_futures.push(async { - let (H256(hash), signer, _) = order.metadata.uid.parts(); + let (hash, signer, _) = order.metadata.uid.parts(); match signature_validator .validate_signature(SignatureCheck { signer, - hash, + hash: hash.0, signature: signature.clone(), interactions: order.interactions.pre.clone(), // TODO delete balance and signature logic in the autopilot @@ -570,7 +569,7 @@ fn orders_with_balance( Some(balance) => *balance, }; - if order.data.partially_fillable && balance >= 1.into() { + if order.data.partially_fillable && balance >= U256::ONE { return true; } @@ -578,7 +577,7 @@ fn orders_with_balance( None => return false, Some(balance) => balance, }; - balance.into_alloy() >= needed_balance + balance >= needed_balance }); orders } @@ -597,9 +596,10 @@ fn filter_dust_orders(mut orders: Vec, balances: &Balances) -> Vec return false; }; - let Ok(remaining) = - remaining_amounts::Remaining::from_order_with_balance(&order.into(), balance) - else { + let Ok(remaining) = remaining_amounts::Remaining::from_order_with_balance( + &order.into(), + balance.into_legacy(), + ) else { return false; }; @@ -901,7 +901,7 @@ impl OrderFilterCounter { mod tests { use { super::*, - alloy::primitives::Address, + alloy::primitives::{Address, B256}, futures::FutureExt, maplit::{btreemap, hashset}, mockall::predicate::eq, @@ -909,7 +909,6 @@ mod tests { interaction::InteractionData, order::{Interactions, OrderBuilder, OrderData, OrderMetadata, OrderUid}, }, - primitive_types::H160, shared::{ bad_token::list_based::ListBasedDetector, price_estimation::{ @@ -1182,19 +1181,19 @@ mod tests { async fn filters_banned_users() { let banned_users = hashset!(Address::from([0xba; 20]), Address::from([0xbb; 20])); let orders = [ - H160([1; 20]), - H160([1; 20]), - H160([0xba; 20]), - H160([2; 20]), - H160([0xba; 20]), - H160([0xbb; 20]), - H160([3; 20]), + Address::repeat_byte(1), + Address::repeat_byte(1), + Address::repeat_byte(0xba), + Address::repeat_byte(2), + Address::repeat_byte(0xba), + Address::repeat_byte(0xbb), + Address::repeat_byte(3), ] .into_iter() .enumerate() .map(|(i, owner)| Order { metadata: OrderMetadata { - owner: owner.into_alloy(), + owner, uid: OrderUid([i as u8; 56]), ..Default::default() }, @@ -1223,7 +1222,11 @@ mod tests { let orders = vec![ Order { metadata: OrderMetadata { - uid: OrderUid::from_parts(H256([1; 32]), H160([11; 20]), 1), + uid: OrderUid::from_parts( + B256::repeat_byte(1).into_legacy(), + Address::repeat_byte(11).into_legacy(), + 1, + ), ..Default::default() }, interactions: Interactions { @@ -1242,7 +1245,11 @@ mod tests { }, Order { metadata: OrderMetadata { - uid: OrderUid::from_parts(H256([2; 32]), H160([22; 20]), 2), + uid: OrderUid::from_parts( + B256::repeat_byte(2).into_legacy(), + Address::repeat_byte(22).into_legacy(), + 2, + ), ..Default::default() }, signature: Signature::Eip1271(vec![2, 2]), @@ -1262,14 +1269,22 @@ mod tests { }, Order { metadata: OrderMetadata { - uid: OrderUid::from_parts(H256([3; 32]), H160([33; 20]), 3), + uid: OrderUid::from_parts( + B256::repeat_byte(3).into_legacy(), + Address::repeat_byte(33).into_legacy(), + 3, + ), ..Default::default() }, ..Default::default() }, Order { metadata: OrderMetadata { - uid: OrderUid::from_parts(H256([4; 32]), H160([44; 20]), 4), + uid: OrderUid::from_parts( + B256::repeat_byte(4).into_legacy(), + Address::repeat_byte(44).into_legacy(), + 4, + ), ..Default::default() }, signature: Signature::Eip1271(vec![4, 4, 4, 4]), @@ -1277,7 +1292,11 @@ mod tests { }, Order { metadata: OrderMetadata { - uid: OrderUid::from_parts(H256([5; 32]), H160([55; 20]), 5), + uid: OrderUid::from_parts( + B256::repeat_byte(5).into_legacy(), + Address::repeat_byte(55).into_legacy(), + 5, + ), ..Default::default() }, signature: Signature::Eip1271(vec![5, 5, 5, 5, 5]), @@ -1289,7 +1308,7 @@ mod tests { signature_validator .expect_validate_signature() .with(eq(SignatureCheck { - signer: H160([22; 20]), + signer: Address::repeat_byte(22).into_legacy(), hash: [2; 32], signature: vec![2, 2], interactions: vec![InteractionData { @@ -1303,7 +1322,7 @@ mod tests { signature_validator .expect_validate_signature() .with(eq(SignatureCheck { - signer: H160([44; 20]), + signer: Address::repeat_byte(44).into_legacy(), hash: [4; 32], signature: vec![4, 4, 4, 4], interactions: vec![], @@ -1313,7 +1332,7 @@ mod tests { signature_validator .expect_validate_signature() .with(eq(SignatureCheck { - signer: H160([55; 20]), + signer: Address::repeat_byte(55).into_legacy(), hash: [5; 32], signature: vec![5, 5, 5, 5, 5], interactions: vec![], @@ -1325,7 +1344,11 @@ mod tests { find_invalid_signature_orders(&orders, &signature_validator, false).await; assert_eq!( invalid_signature_orders, - vec![OrderUid::from_parts(H256([4; 32]), H160([44; 20]), 4)] + vec![OrderUid::from_parts( + B256::repeat_byte(4).into_legacy(), + Address::repeat_byte(44).into_legacy(), + 4 + )] ); let invalid_signature_orders_with_1271_filter_disabled = find_invalid_signature_orders(&orders, &signature_validator, true).await; @@ -1484,11 +1507,11 @@ mod tests { }, ]; let balances = [ - (Query::from_order(&orders[0]), 2.into()), - (Query::from_order(&orders[1]), 1.into()), - (Query::from_order(&orders[2]), 1.into()), - (Query::from_order(&orders[3]), 0.into()), - (Query::from_order(&orders[4]), 0.into()), + (Query::from_order(&orders[0]), U256::from(2)), + (Query::from_order(&orders[1]), U256::from(1)), + (Query::from_order(&orders[2]), U256::from(1)), + (Query::from_order(&orders[3]), U256::from(0)), + (Query::from_order(&orders[4]), U256::from(0)), ] .into_iter() .collect(); diff --git a/crates/driver/Cargo.toml b/crates/driver/Cargo.toml index abe40a0af8..0ccaa4e608 100644 --- a/crates/driver/Cargo.toml +++ b/crates/driver/Cargo.toml @@ -26,7 +26,6 @@ chrono = { workspace = true, features = ["clock"], default-features = false } cow-amm = { workspace = true } dashmap = { workspace = true } derive_more = { workspace = true } -ethereum-types = { workspace = true } ethrpc = { workspace = true } futures = { workspace = true } const-hex = { workspace = true } @@ -45,7 +44,7 @@ prometheus-metric-storage = { workspace = true } rand = { workspace = true } reqwest = { workspace = true } s3 = { workspace = true } -serde = { workspace = true } +serde = { workspace = true, features = ["derive"] } serde_json = { workspace = true } serde_with = { workspace = true } solvers-dto = { path = "../solvers-dto" } diff --git a/crates/orderbook/Cargo.toml b/crates/orderbook/Cargo.toml index 14c7e3c346..ecf16ee37b 100644 --- a/crates/orderbook/Cargo.toml +++ b/crates/orderbook/Cargo.toml @@ -27,7 +27,6 @@ chrono = { workspace = true, features = ["clock"] } clap = { workspace = true } contracts = { workspace = true } database = { workspace = true } -ethcontract = { workspace = true } ethrpc = { workspace = true } futures = { workspace = true } const-hex = { workspace = true } @@ -42,7 +41,6 @@ num = { workspace = true } number = { workspace = true } order-validation = { workspace = true } observe = { workspace = true } -primitive-types = { workspace = true } prometheus = { workspace = true } prometheus-metric-storage = { workspace = true } reqwest = { workspace = true, features = ["json"] } From 89504ed2f546b4452e2c4e452d54efbaf648bf19 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jose=CC=81=20Duarte?= Date: Thu, 11 Dec 2025 10:16:40 +0000 Subject: [PATCH 2/2] address comment --- crates/autopilot/src/infra/blockchain/mod.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/autopilot/src/infra/blockchain/mod.rs b/crates/autopilot/src/infra/blockchain/mod.rs index 271190abee..f07b2689c6 100644 --- a/crates/autopilot/src/infra/blockchain/mod.rs +++ b/crates/autopilot/src/infra/blockchain/mod.rs @@ -165,7 +165,7 @@ fn into_domain( .ok_or(anyhow::anyhow!("missing effective_gas_price"))? .into_alloy() .into(), - timestamp: u32::try_from(timestamp).expect("value should be lower than u32::MAX"), + timestamp: u32::try_from(timestamp)?, trace_calls: trace_calls.into(), }) }