From 49871f27ad91ae7f63954f799ba42fb7ea4b2fe0 Mon Sep 17 00:00:00 2001 From: Martin Magnus Date: Wed, 4 Dec 2024 08:00:51 +0100 Subject: [PATCH] [EASY] Delete dead code (#3146) # Description I was curious about our test coverage and noticed that the generated report can be used pretty well to find dead code that the compiler is not able to detect because the functions get exporter from the respective crates. # Changes just deletes dead code & removes some `drive` statements ## How to test no logic change => compiler is enough --- crates/app-data/src/hooks.rs | 4 - .../src/infra/blockchain/authenticator.rs | 85 -------------- crates/autopilot/src/infra/blockchain/mod.rs | 1 - .../autopilot/src/infra/solvers/dto/settle.rs | 21 +--- crates/autopilot/src/util/bytes.rs | 12 -- .../src/domain/competition/order/mod.rs | 7 -- .../src/domain/competition/order/signature.rs | 14 --- .../competition/solution/interaction.rs | 9 -- .../domain/competition/solution/settlement.rs | 5 - .../src/domain/competition/solution/trade.rs | 4 - crates/driver/src/domain/eth/gas.rs | 34 ------ crates/driver/src/infra/blockchain/mod.rs | 8 +- crates/ethrpc/src/extensions.rs | 4 +- crates/model/src/lib.rs | 1 - crates/model/src/order.rs | 21 ---- crates/model/src/quote.rs | 20 ---- crates/model/src/ratio_as_decimal.rs | 110 ------------------ crates/orderbook/src/api/get_native_price.rs | 13 +-- crates/orderbook/src/dto/auction.rs | 2 +- crates/shared/src/code_simulation.rs | 1 - crates/shared/src/external_prices.rs | 57 +-------- crates/shared/src/gas_price_estimation.rs | 2 +- crates/shared/src/http_client.rs | 45 +------ crates/shared/src/http_solver.rs | 12 +- crates/shared/src/interaction.rs | 14 +-- crates/shared/src/lib.rs | 14 --- crates/shared/src/maintenance.rs | 4 - crates/shared/src/price_estimation/mod.rs | 28 ----- crates/shared/src/trade_finding/mod.rs | 21 +--- crates/solver/src/liquidity/mod.rs | 107 ----------------- crates/solver/src/liquidity/slippage.rs | 10 -- crates/solver/src/liquidity_collector.rs | 1 - crates/solver/src/settlement/mod.rs | 26 ----- .../src/settlement/settlement_encoder.rs | 15 --- crates/solvers/src/domain/auction.rs | 4 - crates/solvers/src/domain/eth/mod.rs | 26 ----- .../src/domain/liquidity/limit_order.rs | 10 -- .../src/domain/liquidity/weighted_product.rs | 9 -- crates/solvers/src/domain/order.rs | 17 --- crates/solvers/src/domain/solution.rs | 10 -- crates/solvers/src/infra/blockchain.rs | 13 --- crates/solvers/src/infra/metrics.rs | 4 - crates/solvers/src/infra/mod.rs | 1 - crates/solvers/src/util/bytes.rs | 18 --- crates/solvers/src/util/conv.rs | 18 +-- crates/solvers/src/util/mod.rs | 1 - crates/solvers/src/util/serialize/hex.rs | 56 --------- crates/solvers/src/util/serialize/mod.rs | 1 - crates/solvers/src/util/serialize/never.rs | 25 ---- crates/solvers/src/util/serialize/str.rs | 10 -- crates/solvers/src/util/serialize/u256.rs | 13 +-- crates/solvers/src/util/url.rs | 14 --- 52 files changed, 18 insertions(+), 964 deletions(-) delete mode 100644 crates/autopilot/src/infra/blockchain/authenticator.rs delete mode 100644 crates/model/src/ratio_as_decimal.rs delete mode 100644 crates/solvers/src/infra/blockchain.rs delete mode 100644 crates/solvers/src/util/serialize/hex.rs delete mode 100644 crates/solvers/src/util/serialize/never.rs delete mode 100644 crates/solvers/src/util/serialize/str.rs diff --git a/crates/app-data/src/hooks.rs b/crates/app-data/src/hooks.rs index 6651d6c339..4ebf6dc66f 100644 --- a/crates/app-data/src/hooks.rs +++ b/crates/app-data/src/hooks.rs @@ -20,10 +20,6 @@ pub struct Hooks { } impl Hooks { - pub fn is_empty(&self) -> bool { - self.pre.is_empty() && self.post.is_empty() - } - pub fn gas_limit(&self) -> u64 { std::iter::empty() .chain(&self.pre) diff --git a/crates/autopilot/src/infra/blockchain/authenticator.rs b/crates/autopilot/src/infra/blockchain/authenticator.rs deleted file mode 100644 index bf0d72faa1..0000000000 --- a/crates/autopilot/src/infra/blockchain/authenticator.rs +++ /dev/null @@ -1,85 +0,0 @@ -use { - crate::{ - domain::{self, eth}, - infra::blockchain::contracts::{deployment_address, Contracts}, - }, - chain::Chain, - ethcontract::{dyns::DynWeb3, GasPrice}, -}; - -#[allow(dead_code)] -#[derive(Debug, Clone)] -pub struct Manager { - /// The authenticator contract that decides which solver is allowed to - /// submit settlements. - authenticator: contracts::GPv2AllowListAuthentication, - /// The safe module that is used to provide special role to EOA. - authenticator_role: contracts::Roles, - /// The EOA that is allowed to remove solvers. - authenticator_eoa: ethcontract::Account, -} - -impl Manager { - /// Creates an authenticator which can remove solvers from the allow-list - pub async fn new( - web3: DynWeb3, - chain: &Chain, - contracts: Contracts, - authenticator_pk: eth::H256, - ) -> Self { - let authenticator_role = contracts::Roles::at( - &web3, - deployment_address(contracts::Roles::raw_contract(), chain).expect("roles address"), - ); - - Self { - authenticator: contracts.authenticator().clone(), - authenticator_role, - authenticator_eoa: ethcontract::Account::Offline( - ethcontract::PrivateKey::from_raw(authenticator_pk.0).unwrap(), - None, - ), - } - } - - /// Fire and forget: Removes solver from the allow-list in the authenticator - /// contract. This solver will no longer be able to settle. - #[allow(dead_code)] - fn remove_solver(&self, solver: domain::eth::Address) { - let calldata = self - .authenticator - .methods() - .remove_solver(solver.into()) - .tx - .data - .expect("missing calldata"); - let authenticator_eoa = self.authenticator_eoa.clone(); - let authenticator_address = self.authenticator.address(); - let authenticator_role = self.authenticator_role.clone(); - tokio::task::spawn(async move { - // This value comes from the TX posted in the issue: https://github.com/cowprotocol/services/issues/2667 - let mut byte_array = [0u8; 32]; - byte_array[31] = 1; - authenticator_role - .methods() - .exec_transaction_with_role( - authenticator_address, - 0.into(), - ethcontract::Bytes(calldata.0), - 0, - ethcontract::Bytes(byte_array), - true, - ) - .from(authenticator_eoa) - .gas_price(GasPrice::Eip1559 { - // These are arbitrary high numbers that should be enough for a tx to be settled - // anytime. - max_fee_per_gas: 1000.into(), - max_priority_fee_per_gas: 5.into(), - }) - .send() - .await - .inspect_err(|err| tracing::error!(?solver, ?err, "failed to remove the solver")) - }); - } -} diff --git a/crates/autopilot/src/infra/blockchain/mod.rs b/crates/autopilot/src/infra/blockchain/mod.rs index f030cdf7eb..6b8f3234cc 100644 --- a/crates/autopilot/src/infra/blockchain/mod.rs +++ b/crates/autopilot/src/infra/blockchain/mod.rs @@ -10,7 +10,6 @@ use { url::Url, }; -pub mod authenticator; pub mod contracts; /// An Ethereum RPC connection. diff --git a/crates/autopilot/src/infra/solvers/dto/settle.rs b/crates/autopilot/src/infra/solvers/dto/settle.rs index ef7f34465a..3abdf15dbe 100644 --- a/crates/autopilot/src/infra/solvers/dto/settle.rs +++ b/crates/autopilot/src/infra/solvers/dto/settle.rs @@ -1,6 +1,5 @@ use { - primitive_types::H256, - serde::{Deserialize, Serialize}, + serde::Serialize, serde_with::{serde_as, skip_serializing_none}, }; @@ -18,21 +17,3 @@ pub struct Request { #[serde_as(as = "Option")] pub auction_id: Option, } - -#[serde_as] -#[derive(Clone, Debug, Default, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct Response { - pub calldata: Calldata, - pub tx_hash: H256, -} - -#[serde_as] -#[derive(Clone, Debug, Default, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct Calldata { - #[serde(with = "bytes_hex")] - pub internalized: Vec, - #[serde(with = "bytes_hex")] - pub uninternalized: Vec, -} diff --git a/crates/autopilot/src/util/bytes.rs b/crates/autopilot/src/util/bytes.rs index 1ff531c545..bf55ab60e5 100644 --- a/crates/autopilot/src/util/bytes.rs +++ b/crates/autopilot/src/util/bytes.rs @@ -16,15 +16,3 @@ impl From for Bytes { Self(value) } } - -impl From>> for Vec { - fn from(value: Bytes>) -> Self { - value.0 - } -} - -impl From> for [u8; N] { - fn from(value: Bytes<[u8; N]>) -> Self { - value.0 - } -} diff --git a/crates/driver/src/domain/competition/order/mod.rs b/crates/driver/src/domain/competition/order/mod.rs index 0088d36f07..5b82b1d758 100644 --- a/crates/driver/src/domain/competition/order/mod.rs +++ b/crates/driver/src/domain/competition/order/mod.rs @@ -406,13 +406,6 @@ impl Jit { } } - /// Returns the signed fee of the order. You can't set this field in - /// the API so it's enforced to be 0. This function only exists to - /// not have magic values scattered everywhere. - pub fn fee(&self) -> SellAmount { - SellAmount(0.into()) - } - /// Returns the signed partially fillable property of the order. You can't /// set this field in the API so it's enforced to be fill-or-kill. This /// function only exists to not have magic values scattered everywhere. diff --git a/crates/driver/src/domain/competition/order/signature.rs b/crates/driver/src/domain/competition/order/signature.rs index dd51692a45..2964fdc8e3 100644 --- a/crates/driver/src/domain/competition/order/signature.rs +++ b/crates/driver/src/domain/competition/order/signature.rs @@ -52,17 +52,3 @@ impl Scheme { } } } - -pub fn domain_separator( - chain_id: chain::Id, - verifying_contract: eth::ContractAddress, -) -> eth::DomainSeparator { - eth::DomainSeparator::new(ð::DomainFields { - type_hash: - b"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)", - name: b"Gnosis Protocol", - version: b"v2", - chain_id, - verifying_contract, - }) -} diff --git a/crates/driver/src/domain/competition/solution/interaction.rs b/crates/driver/src/domain/competition/solution/interaction.rs index 83fbb82af4..19e614c085 100644 --- a/crates/driver/src/domain/competition/solution/interaction.rs +++ b/crates/driver/src/domain/competition/solution/interaction.rs @@ -30,15 +30,6 @@ impl Interaction { } } - /// The assets output by this interaction. These assets are sent into the - /// settlement contract when the interaction executes. - pub fn outputs(&self) -> Vec { - match self { - Interaction::Custom(custom) => custom.outputs.clone(), - Interaction::Liquidity(liquidity) => vec![liquidity.output], - } - } - /// Returns the ERC20 approvals required for executing this interaction /// onchain. pub fn allowances(&self) -> Vec { diff --git a/crates/driver/src/domain/competition/solution/settlement.rs b/crates/driver/src/domain/competition/solution/settlement.rs index 0ea089685b..c3fc3e5b28 100644 --- a/crates/driver/src/domain/competition/solution/settlement.rs +++ b/crates/driver/src/domain/competition/solution/settlement.rs @@ -252,11 +252,6 @@ impl Settlement { self.solution.id() } - /// Address of the solver which generated this settlement. - pub fn solver(&self) -> eth::Address { - self.solution.solver().address() - } - /// The settled user orders with their in/out amounts. pub fn orders(&self) -> HashMap { let log_err = |trade: &Trade, err: error::Math, kind: &str| -> eth::TokenAmount { diff --git a/crates/driver/src/domain/competition/solution/trade.rs b/crates/driver/src/domain/competition/solution/trade.rs index 299b483502..5c24d66bf5 100644 --- a/crates/driver/src/domain/competition/solution/trade.rs +++ b/crates/driver/src/domain/competition/solution/trade.rs @@ -182,10 +182,6 @@ impl Fulfillment { &self.order } - pub fn side(&self) -> Side { - self.order.side - } - pub fn executed(&self) -> order::TargetAmount { self.executed } diff --git a/crates/driver/src/domain/eth/gas.rs b/crates/driver/src/domain/eth/gas.rs index 2ec2c5de36..e7c4fd67d9 100644 --- a/crates/driver/src/domain/eth/gas.rs +++ b/crates/driver/src/domain/eth/gas.rs @@ -1,6 +1,5 @@ use { super::{Ether, U256}, - bigdecimal::Zero, derive_more::{Display, From, Into}, std::{ops, ops::Add}, }; @@ -26,16 +25,6 @@ impl Add for Gas { } } -impl Zero for Gas { - fn zero() -> Self { - Self(U256::zero()) - } - - fn is_zero(&self) -> bool { - self.0.is_zero() - } -} - /// An EIP-1559 gas price estimate. /// /// https://eips.ethereum.org/EIPS/eip-1559#specification @@ -118,11 +107,6 @@ impl From for GasPrice { pub struct FeePerGas(pub Ether); impl FeePerGas { - /// Subtracts the given fee from this fee, saturating at zero. - pub fn saturating_sub(self, rhs: Self) -> Self { - self.0 .0.saturating_sub(rhs.0 .0).into() - } - /// Multiplies this fee by the given floating point number, rounding up. fn mul_ceil(self, rhs: f64) -> Self { U256::from_f64_lossy((self.0 .0.to_f64_lossy() * rhs).ceil()).into() @@ -174,21 +158,3 @@ impl From for U256 { value.0.into() } } - -impl Add for EffectiveGasPrice { - type Output = Self; - - fn add(self, rhs: Self) -> Self::Output { - Self(self.0 + rhs.0) - } -} - -impl Zero for EffectiveGasPrice { - fn zero() -> Self { - Self(Ether::zero()) - } - - fn is_zero(&self) -> bool { - self.0.is_zero() - } -} diff --git a/crates/driver/src/infra/blockchain/mod.rs b/crates/driver/src/infra/blockchain/mod.rs index e2c930a1a9..f6f1d9bca8 100644 --- a/crates/driver/src/infra/blockchain/mod.rs +++ b/crates/driver/src/infra/blockchain/mod.rs @@ -1,7 +1,7 @@ use { self::contracts::ContractAt, crate::{boundary, domain::eth}, - ethcontract::dyns::DynWeb3, + ethcontract::{dyns::DynWeb3, errors::ExecutionError}, ethrpc::block_stream::CurrentBlockWatcher, std::{fmt, sync::Arc}, thiserror::Error, @@ -13,8 +13,6 @@ pub mod contracts; pub mod gas; pub mod token; -use {ethcontract::errors::ExecutionError, gas_estimation::GasPriceEstimating}; - pub use self::{contracts::Contracts, gas::GasPriceEstimator}; /// An Ethereum RPC connection. @@ -169,10 +167,6 @@ impl Ethereum { Ok(access_list.into()) } - pub fn boundary_gas_estimator(&self) -> Arc { - self.inner.gas.gas.clone() - } - /// Estimate gas used by a transaction. pub async fn estimate_gas(&self, tx: ð::Tx) -> Result { self.web3 diff --git a/crates/ethrpc/src/extensions.rs b/crates/ethrpc/src/extensions.rs index 6f4cf6bdb7..78f2d77eea 100644 --- a/crates/ethrpc/src/extensions.rs +++ b/crates/ethrpc/src/extensions.rs @@ -1,7 +1,7 @@ //! Module containing Ethereum RPC extension methods. use { - serde::{Deserialize, Serialize}, + serde::Serialize, std::collections::HashMap, web3::{ self, @@ -50,7 +50,7 @@ where pub type StateOverrides = HashMap; /// State override object. -#[derive(Clone, Debug, Default, Eq, PartialEq, Deserialize, Serialize)] +#[derive(Clone, Debug, Default, Eq, PartialEq, Serialize)] #[serde(rename_all = "camelCase")] pub struct StateOverride { /// Fake balance to set for the account before executing the call. diff --git a/crates/model/src/lib.rs b/crates/model/src/lib.rs index e60f82fb01..23a13d7729 100644 --- a/crates/model/src/lib.rs +++ b/crates/model/src/lib.rs @@ -5,7 +5,6 @@ pub mod fee_policy; pub mod interaction; pub mod order; pub mod quote; -pub mod ratio_as_decimal; pub mod signature; pub mod solver_competition; pub mod time; diff --git a/crates/model/src/order.rs b/crates/model/src/order.rs index 4d3ca859a7..ec19f1caff 100644 --- a/crates/model/src/order.rs +++ b/crates/model/src/order.rs @@ -81,12 +81,6 @@ impl Order { pub fn is_limit_order(&self) -> bool { matches!(self.metadata.class, OrderClass::Limit) } - - /// For some orders the protocol doesn't precompute a fee. Instead solvers - /// are supposed to compute a reasonable fee themselves. - pub fn solver_determines_fee(&self) -> bool { - self.is_limit_order() - } } #[derive(Clone, Default, Debug)] @@ -133,11 +127,6 @@ impl OrderBuilder { self } - pub fn with_full_fee_amount(mut self, full_fee_amount: U256) -> Self { - self.0.metadata.full_fee_amount = full_fee_amount; - self - } - pub fn with_kind(mut self, kind: OrderKind) -> Self { self.0.data.kind = kind; self @@ -195,16 +184,6 @@ impl OrderBuilder { self } - pub fn with_solver_fee(mut self, fee: U256) -> Self { - self.0.metadata.solver_fee = fee; - self - } - - pub fn with_full_app_data(mut self, full_app_data: String) -> Self { - self.0.metadata.full_app_data = Some(full_app_data); - self - } - pub fn build(self) -> Order { self.0 } diff --git a/crates/model/src/quote.rs b/crates/model/src/quote.rs index 63d2409fea..0e7b2ac913 100644 --- a/crates/model/src/quote.rs +++ b/crates/model/src/quote.rs @@ -61,13 +61,6 @@ impl QuoteSigningScheme { _ => 0u64, } } - - pub fn new_eip1271_with_default_gas(onchain_order: bool) -> Self { - QuoteSigningScheme::Eip1271 { - onchain_order, - verification_gas_limit: default_verification_gas_limit(), - } - } } #[serde_as] @@ -302,19 +295,6 @@ pub struct OrderQuoteResponse { pub verified: bool, } -impl OrderQuoteRequest { - /// This method is used by the old, deprecated, fee endpoint to convert - /// {Buy, Sell}Requests - pub fn new(sell_token: H160, buy_token: H160, side: OrderQuoteSide) -> Self { - Self { - sell_token, - buy_token, - side, - ..Default::default() - } - } -} - #[cfg(test)] mod tests { use {super::*, serde_json::json, testlib::assert_json_matches}; diff --git a/crates/model/src/ratio_as_decimal.rs b/crates/model/src/ratio_as_decimal.rs deleted file mode 100644 index b19af6b3a9..0000000000 --- a/crates/model/src/ratio_as_decimal.rs +++ /dev/null @@ -1,110 +0,0 @@ -use { - bigdecimal::BigDecimal, - num::{BigInt, BigRational}, - serde::{de, Deserialize, Deserializer, Serializer}, - serde_with::{DeserializeAs, SerializeAs}, - std::{borrow::Cow, convert::TryInto, str::FromStr}, -}; - -pub struct DecimalBigRational; - -impl<'de> DeserializeAs<'de, BigRational> for DecimalBigRational { - fn deserialize_as(deserializer: D) -> Result - where - D: Deserializer<'de>, - { - deserialize(deserializer) - } -} - -impl SerializeAs for DecimalBigRational { - fn serialize_as(source: &BigRational, serializer: S) -> Result - where - S: Serializer, - { - serialize(source, serializer) - } -} - -pub fn serialize(value: &BigRational, serializer: S) -> Result -where - S: Serializer, -{ - let top_bytes = value.numer().to_bytes_le(); - let top = BigInt::from_bytes_le(top_bytes.0, &top_bytes.1); - - let bottom_bytes = value.denom().to_bytes_le(); - let bottom = BigInt::from_bytes_le(bottom_bytes.0, &bottom_bytes.1); - let decimal = BigDecimal::from(top) / BigDecimal::from(bottom); - serializer.serialize_str(&decimal.to_string()) -} - -pub fn deserialize<'de, D>(deserializer: D) -> Result -where - D: Deserializer<'de>, -{ - let big_decimal = BigDecimal::from_str(&Cow::::deserialize(deserializer)?) - .map_err(|err| de::Error::custom(format!("failed to decode decimal BigDecimal: {err}")))?; - let (x, exp) = big_decimal.into_bigint_and_exponent(); - let numerator_bytes = x.to_bytes_le(); - let base = num::bigint::BigInt::from_bytes_le(numerator_bytes.0, &numerator_bytes.1); - let ten = BigRational::new(10.into(), 1.into()); - let numerator = BigRational::new(base, 1.into()); - Ok(numerator - / ten.pow( - exp.try_into() - .map_err(|err| de::Error::custom(format!("decimal exponent overflow: {err}")))?, - )) -} - -#[cfg(test)] -mod tests { - use { - super::*, - num::{BigRational, Zero}, - serde_json::{json, value::Serializer}, - testlib::assert_json_matches, - }; - - #[test] - fn serializer() { - assert_json_matches!( - serialize(&BigRational::from_float(1.2).unwrap(), Serializer).unwrap(), - json!("1.1999999999999999555910790149937383830547332763671875") - ); - assert_json_matches!( - serialize( - &BigRational::new(1.into(), 3.into()), - Serializer - ) - .unwrap(), - json!("0.3333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333") - ); - assert_json_matches!( - serialize(&BigRational::zero(), Serializer).unwrap(), - json!("0") - ); - assert_json_matches!( - serialize(&BigRational::new((-1).into(), 1.into()), Serializer).unwrap(), - json!("-1") - ); - } - - #[test] - fn deserialize_err() { - assert!(deserialize(json!("hello")).is_err()); - } - - #[test] - fn deserialize_ok() { - assert_eq!( - deserialize(json!("1.2")).unwrap(), - BigRational::new(12.into(), 10.into()) - ); - assert_eq!(deserialize(json!("0")).unwrap(), BigRational::zero()); - assert_eq!( - deserialize(json!("-1")).unwrap(), - BigRational::new((-1).into(), 1.into()) - ); - } -} diff --git a/crates/orderbook/src/api/get_native_price.rs b/crates/orderbook/src/api/get_native_price.rs index 6b00fc8810..7b7e213236 100644 --- a/crates/orderbook/src/api/get_native_price.rs +++ b/crates/orderbook/src/api/get_native_price.rs @@ -13,12 +13,6 @@ struct PriceResponse { price: f64, } -impl From for PriceResponse { - fn from(price: f64) -> Self { - Self { price } - } -} - fn get_native_prices_request() -> impl Filter + Clone { warp::path!("v1" / "token" / H160 / "native_price").and(warp::get()) } @@ -31,10 +25,9 @@ pub fn get_native_price( async move { let result = estimator.estimate_native_price(token).await; let reply = match result { - Ok(price) => with_status( - warp::reply::json(&PriceResponse::from(price)), - StatusCode::OK, - ), + Ok(price) => { + with_status(warp::reply::json(&PriceResponse { price }), StatusCode::OK) + } Err(err) => err.into_warp_reply(), }; Result::<_, Infallible>::Ok(reply) diff --git a/crates/orderbook/src/dto/auction.rs b/crates/orderbook/src/dto/auction.rs index b169a6f599..a132bbf747 100644 --- a/crates/orderbook/src/dto/auction.rs +++ b/crates/orderbook/src/dto/auction.rs @@ -24,7 +24,7 @@ pub struct Auction { pub type AuctionId = i64; #[serde_as] -#[derive(Clone, Debug, Serialize, Deserialize)] +#[derive(Clone, Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct AuctionWithId { /// Increments whenever the backend updates the auction. diff --git a/crates/shared/src/code_simulation.rs b/crates/shared/src/code_simulation.rs index 5d720ce278..7035c2dfb6 100644 --- a/crates/shared/src/code_simulation.rs +++ b/crates/shared/src/code_simulation.rs @@ -15,7 +15,6 @@ use { }; /// Simulate a call with state overrides. -#[mockall::automock] #[async_trait::async_trait] pub trait CodeSimulating: Send + Sync + 'static { async fn simulate( diff --git a/crates/shared/src/external_prices.rs b/crates/shared/src/external_prices.rs index 16886292bd..95109e318e 100644 --- a/crates/shared/src/external_prices.rs +++ b/crates/shared/src/external_prices.rs @@ -11,7 +11,7 @@ use { ethcontract::{H160, U256}, lazy_static::lazy_static, model::order::BUY_ETH_ADDRESS, - num::{BigInt, BigRational, CheckedDiv, One as _, ToPrimitive as _}, + num::{BigInt, BigRational, One as _, ToPrimitive as _}, std::collections::{BTreeMap, HashMap}, }; @@ -64,61 +64,6 @@ impl ExternalPrices { pub fn price(&self, token: &H160) -> Option<&BigRational> { self.0.get(token) } - - /// Converts a token amount into its native asset equivalent. - /// - /// # Panic - /// - /// This method panics if the specified token does not have a price. - pub fn get_native_amount(&self, token: H160, amount: BigRational) -> BigRational { - self.try_get_native_amount(token, amount) - .unwrap_or_else(|| panic!("missing price for {token}")) - } - - /// Converts a token amount into its native asset equivalent. - /// - /// This method is similar to [`get_native_amount`] except that it will - /// return `None` if the specified token does not have a price instead of - /// panicking. - pub fn try_get_native_amount(&self, token: H160, amount: BigRational) -> Option { - Some(self.0.get(&token)? * amount) - } - - /// Converts a native asset amount into an amount of equivalent value in the - /// specified token. - /// - /// # Panic - /// - /// This method panics if the specified token does not have a price. - pub fn get_token_amount(&self, amount: &BigRational, token: H160) -> BigRational { - self.try_get_token_amount(amount, token) - .unwrap_or_else(|| panic!("missing price for {token}")) - } - - /// Converts a native asset amount into an amount of equivalent value in the - /// specified token. - /// - /// This method is similar to [`get_native_amount`] except that it will - /// return `None` if the specified token does not have a price instead of - /// panicking. - pub fn try_get_token_amount(&self, amount: &BigRational, token: H160) -> Option { - amount.checked_div(self.0.get(&token)?) - } - - /// Converts a set of external prices into prices for the HTTP solver. - /// - /// Specifically the HTTP solver expects prices to be in `f64` and there not - /// to be an entry for `BUY_ETH_ADDRESS` since orders are already normalized - /// to use the native wrapped token. - pub fn into_http_solver_prices(&self) -> HashMap { - let mut prices = self - .0 - .iter() - .filter_map(|(token, price)| Some((*token, price.to_f64()?))) - .collect::>(); - prices.remove(&BUY_ETH_ADDRESS); - prices - } } impl Default for ExternalPrices { diff --git a/crates/shared/src/gas_price_estimation.rs b/crates/shared/src/gas_price_estimation.rs index 0f821c1a24..5d4e15ff34 100644 --- a/crates/shared/src/gas_price_estimation.rs +++ b/crates/shared/src/gas_price_estimation.rs @@ -106,7 +106,7 @@ pub async fn create_priority_estimator( Ok(PriorityGasPriceEstimating::new(estimators)) } -pub fn is_mainnet(network_id: &str) -> bool { +fn is_mainnet(network_id: &str) -> bool { network_id == "1" } diff --git a/crates/shared/src/http_client.rs b/crates/shared/src/http_client.rs index 7bbbd6e2c0..59df91d89a 100644 --- a/crates/shared/src/http_client.rs +++ b/crates/shared/src/http_client.rs @@ -1,6 +1,5 @@ use { - anyhow::{anyhow, Result}, - reqwest::{Client, ClientBuilder, Response}, + reqwest::{Client, ClientBuilder}, std::{ fmt::{self, Display, Formatter}, time::Duration, @@ -74,45 +73,3 @@ impl Display for Arguments { writeln!(f, "http_timeout: {:?}", http_timeout) } } - -/// Extracts the bytes of the response up to some size limit. -/// -/// Returns an error if the byte limit was exceeded. -pub async fn response_body_with_size_limit( - response: &mut Response, - limit: usize, -) -> Result> { - let mut bytes = Vec::new(); - while let Some(chunk) = response.chunk().await? { - let slice: &[u8] = &chunk; - if bytes.len() + slice.len() > limit { - return Err(anyhow!("size limit exceeded")); - } - bytes.extend_from_slice(slice); - } - Ok(bytes) -} - -#[cfg(test)] -mod tests { - use {super::*, reqwest::Client}; - - #[tokio::test] - #[ignore] - async fn real() { - let client = Client::default(); - - let mut response = client.get("https://cow.fi").send().await.unwrap(); - let bytes = response_body_with_size_limit(&mut response, 10).await; - dbg!(&bytes); - assert!(bytes.is_err()); - - let mut response = client.get("https://cow.fi").send().await.unwrap(); - let bytes = response_body_with_size_limit(&mut response, 1_000_000) - .await - .unwrap(); - dbg!(bytes.len()); - let text = std::str::from_utf8(&bytes).unwrap(); - dbg!(text); - } -} diff --git a/crates/shared/src/http_solver.rs b/crates/shared/src/http_solver.rs index 20843f6b66..805e2d84ab 100644 --- a/crates/shared/src/http_solver.rs +++ b/crates/shared/src/http_solver.rs @@ -1,16 +1,8 @@ pub mod model { - use { - ethcontract::H160, - number::serialization::HexOrDecimalU256, - primitive_types::U256, - serde::{Deserialize, Serialize}, - serde_with::serde_as, - }; + use {ethcontract::H160, primitive_types::U256, serde::Serialize}; - #[serde_as] - #[derive(Clone, Debug, Default, Eq, PartialEq, Serialize, Deserialize)] + #[derive(Clone, Debug, Default, Eq, PartialEq)] pub struct TokenAmount { - #[serde_as(as = "HexOrDecimalU256")] pub amount: U256, pub token: H160, } diff --git a/crates/shared/src/interaction.rs b/crates/shared/src/interaction.rs index e6431f6c31..7caa026da2 100644 --- a/crates/shared/src/interaction.rs +++ b/crates/shared/src/interaction.rs @@ -1,8 +1,7 @@ use { - ethcontract::{transaction::TransactionBuilder, Bytes}, + ethcontract::Bytes, model::interaction::InteractionData, primitive_types::{H160, U256}, - web3::Transport, }; pub trait Interaction: std::fmt::Debug + Send + Sync { @@ -36,14 +35,3 @@ impl Interaction for InteractionData { (self.target, self.value, Bytes(self.call_data.clone())) } } - -pub fn for_transaction(tx: TransactionBuilder) -> InteractionData -where - T: Transport, -{ - InteractionData { - target: tx.to.unwrap(), - value: tx.value.unwrap_or_default(), - call_data: tx.data.unwrap().0, - } -} diff --git a/crates/shared/src/lib.rs b/crates/shared/src/lib.rs index ed325a2f4e..6d69e4ae11 100644 --- a/crates/shared/src/lib.rs +++ b/crates/shared/src/lib.rs @@ -40,20 +40,6 @@ pub mod trade_finding; pub mod url; pub mod zeroex_api; -use std::{ - future::Future, - time::{Duration, Instant}, -}; - -/// Run a future and callback with the time the future took. The call back can -/// for example log the time. -pub async fn measure_time(future: impl Future, timer: impl FnOnce(Duration)) -> T { - let start = Instant::now(); - let result = future.await; - timer(start.elapsed()); - result -} - /// anyhow errors are not clonable natively. This is a workaround that creates a /// new anyhow error based on formatting the error with its inner sources /// without backtrace. diff --git a/crates/shared/src/maintenance.rs b/crates/shared/src/maintenance.rs index 2775bb7048..3c489f95cd 100644 --- a/crates/shared/src/maintenance.rs +++ b/crates/shared/src/maintenance.rs @@ -25,10 +25,6 @@ impl ServiceMaintenance { } } - pub fn spawn_background_task(self, block_stream: CurrentBlockWatcher) { - tokio::task::spawn(self.run_maintenance_on_new_block(block_stream)); - } - async fn run_maintenance_for_blocks(self, blocks: impl Stream) { self.metrics .runs diff --git a/crates/shared/src/price_estimation/mod.rs b/crates/shared/src/price_estimation/mod.rs index 8355acef1c..9ba6405f9a 100644 --- a/crates/shared/src/price_estimation/mod.rs +++ b/crates/shared/src/price_estimation/mod.rs @@ -1,7 +1,6 @@ use { crate::{ arguments::{display_option, display_secret_option, ExternalSolver}, - conversions::U256Ext, trade_finding::Interaction, }, anyhow::Result, @@ -10,7 +9,6 @@ use { futures::future::BoxFuture, itertools::Itertools, model::order::{BuyTokenDestination, OrderKind, SellTokenSource}, - num::BigRational, number::nonzero::U256 as NonZeroU256, rate_limit::{RateLimiter, Strategy}, reqwest::Url, @@ -477,22 +475,6 @@ impl Estimate { } } - /// The resulting price is how many units of sell_token needs to be sold for - /// one unit of buy_token (sell_amount / buy_amount). - pub fn price_in_sell_token_rational(&self, query: &Query) -> Option { - let (sell_amount, buy_amount) = self.amounts(query); - amounts_to_price(sell_amount, buy_amount) - } - - /// The price for the estimate denominated in sell token. - /// - /// The resulting price is how many units of sell_token needs to be sold for - /// one unit of buy_token (sell_amount / buy_amount). - pub fn price_in_sell_token_f64(&self, query: &Query) -> f64 { - let (sell_amount, buy_amount) = self.amounts(query); - sell_amount.to_f64_lossy() / buy_amount.to_f64_lossy() - } - /// The price of the estimate denominated in buy token. /// /// The resulting price is how many units of buy_token are bought for one @@ -510,16 +492,6 @@ pub trait PriceEstimating: Send + Sync + 'static { fn estimate(&self, query: Arc) -> BoxFuture<'_, PriceEstimateResult>; } -pub fn amounts_to_price(sell_amount: U256, buy_amount: U256) -> Option { - if buy_amount.is_zero() { - return None; - } - Some(BigRational::new( - sell_amount.to_big_int(), - buy_amount.to_big_int(), - )) -} - pub const HEALTHY_PRICE_ESTIMATION_TIME: Duration = Duration::from_millis(5_000); pub async fn rate_limited( diff --git a/crates/shared/src/trade_finding/mod.rs b/crates/shared/src/trade_finding/mod.rs index f8e589c467..4f0fbbacf0 100644 --- a/crates/shared/src/trade_finding/mod.rs +++ b/crates/shared/src/trade_finding/mod.rs @@ -11,7 +11,7 @@ use { }, anyhow::{Context, Result}, derive_more::Debug, - ethcontract::{contract::MethodBuilder, tokens::Tokenize, web3::Transport, Bytes, H160, U256}, + ethcontract::{Bytes, H160, U256}, model::{interaction::InteractionData, order::OrderKind}, num::CheckedDiv, number::conversions::big_rational_to_u256, @@ -24,7 +24,6 @@ use { /// /// This is similar to the `PriceEstimating` interface, but it expects calldata /// to also be produced. -#[mockall::automock] #[async_trait::async_trait] pub trait TradeFinding: Send + Sync + 'static { async fn get_quote(&self, query: &Query) -> Result; @@ -97,12 +96,6 @@ impl TradeKind { } } -impl Default for TradeKind { - fn default() -> Self { - TradeKind::Legacy(LegacyTrade::default()) - } -} - /// A legacy trade. #[derive(Clone, Debug, Default, Eq, PartialEq)] pub struct LegacyTrade { @@ -185,18 +178,6 @@ pub struct Interaction { } impl Interaction { - pub fn from_call(method: MethodBuilder) -> Interaction - where - T: Transport, - R: Tokenize, - { - Interaction { - target: method.tx.to.unwrap(), - value: method.tx.value.unwrap_or_default(), - data: method.tx.data.unwrap().0, - } - } - pub fn encode(&self) -> EncodedInteraction { (self.target, self.value, Bytes(self.data.clone())) } diff --git a/crates/solver/src/liquidity/mod.rs b/crates/solver/src/liquidity/mod.rs index 6dc909c640..1af74c86d4 100644 --- a/crates/solver/src/liquidity/mod.rs +++ b/crates/solver/src/liquidity/mod.rs @@ -47,32 +47,6 @@ pub enum Liquidity { Concentrated(ConcentratedLiquidity), } -impl Liquidity { - /// Returns an iterator over all token pairs for the given liquidity. - pub fn all_token_pairs(&self) -> Vec { - match self { - Liquidity::ConstantProduct(amm) => vec![amm.tokens], - Liquidity::BalancerWeighted(amm) => token_pairs(&amm.reserves), - Liquidity::BalancerStable(amm) => token_pairs(&amm.reserves), - Liquidity::LimitOrder(order) => TokenPair::new(order.sell_token, order.buy_token) - .map(|pair| vec![pair]) - .unwrap_or_default(), - Liquidity::Concentrated(amm) => vec![amm.tokens], - } - } - - /// Returns the pool address on the blockchain containing this liquidity - pub fn address(&self) -> Option { - match self { - Liquidity::ConstantProduct(amm) => Some(amm.address), - Liquidity::BalancerWeighted(amm) => Some(amm.address), - Liquidity::BalancerStable(amm) => Some(amm.address), - Liquidity::LimitOrder(_) => None, - Liquidity::Concentrated(amm) => Some(amm.pool.address), - } - } -} - /// A trait associating some liquidity model to how it is executed and encoded /// in a settlement (through a `SettlementHandling` reference). This allows /// different liquidity types to be modeled the same way. @@ -148,19 +122,6 @@ impl Default for LimitOrderId { } } -impl LimitOrderId { - pub fn order_uid(&self) -> Option { - match self { - LimitOrderId::Market(uid) => Some(*uid), - LimitOrderId::Limit(uid) => Some(*uid), - LimitOrderId::Liquidity(order) => match order { - LiquidityOrderId::Protocol(uid) => Some(*uid), - LiquidityOrderId::ZeroEx(_) => None, - }, - } - } -} - #[cfg(test)] impl From for LimitOrderId { fn from(uid: u32) -> Self { @@ -190,16 +151,6 @@ pub struct LimitOrder { } impl LimitOrder { - pub fn is_liquidity_order(&self) -> bool { - matches!(self.id, LimitOrderId::Liquidity(_)) - } - - /// For some orders the protocol doesn't precompute a fee. Instead solvers - /// are supposed to compute a reasonable fee themselves. - pub fn solver_determines_fee(&self) -> bool { - matches!(self.id, LimitOrderId::Limit(_)) - } - /// Returns the full execution amount for the specified limit order. pub fn full_execution_amount(&self) -> U256 { match self.kind { @@ -368,19 +319,6 @@ pub struct StablePoolOrder { pub settlement_handling: Arc>, } -impl StablePoolOrder { - /// See [`shared::sources::balancer_v2::swap::StablePoolRef::reserves_without_bpt`]. - pub fn reserves_without_bpt(&self) -> impl Iterator + '_ { - shared::sources::balancer_v2::swap::StablePoolRef { - address: self.address, - reserves: &self.reserves, - swap_fee: self.fee, - amplification_parameter: self.amplification_parameter, - } - .reserves_without_bpt() - } -} - impl std::fmt::Debug for StablePoolOrder { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "Stable Pool AMM {:?}", self.reserves.keys()) @@ -406,12 +344,6 @@ pub struct AmmOrderExecution { pub internalizable: bool, } -impl ConstantProductOrder { - pub fn constant_product(&self) -> U256 { - U256::from(self.reserves.0) * U256::from(self.reserves.1) - } -} - impl Settleable for ConstantProductOrder { type Execution = AmmOrderExecution; @@ -461,45 +393,6 @@ impl Settleable for ConcentratedLiquidity { } } -#[cfg(test)] -impl Default for ConstantProductOrder { - fn default() -> Self { - ConstantProductOrder { - address: Default::default(), - tokens: Default::default(), - reserves: Default::default(), - fee: num::Zero::zero(), - settlement_handling: tests::CapturingSettlementHandler::arc(), - } - } -} - -#[cfg(test)] -impl Default for WeightedProductOrder { - fn default() -> Self { - WeightedProductOrder { - address: Default::default(), - reserves: Default::default(), - fee: Bfp::zero(), - version: Default::default(), - settlement_handling: tests::CapturingSettlementHandler::arc(), - } - } -} - -#[cfg(test)] -impl Default for StablePoolOrder { - fn default() -> Self { - StablePoolOrder { - address: Default::default(), - reserves: Default::default(), - fee: Default::default(), - amplification_parameter: AmplificationParameter::new(1.into(), 1.into()).unwrap(), - settlement_handling: tests::CapturingSettlementHandler::arc(), - } - } -} - #[cfg(test)] pub mod tests { use {super::*, maplit::btreemap, std::sync::Mutex}; diff --git a/crates/solver/src/liquidity/slippage.rs b/crates/solver/src/liquidity/slippage.rs index 0d2566fd47..a4185aa909 100644 --- a/crates/solver/src/liquidity/slippage.rs +++ b/crates/solver/src/liquidity/slippage.rs @@ -23,11 +23,6 @@ pub struct SlippageContext<'a> { } impl SlippageContext<'_> { - /// Returns the external prices used for the slippage context. - pub fn prices(&self) -> &ExternalPrices { - self.prices - } - /// Applies slippage to the specified AMM execution. pub fn apply_to_amm_execution( &self, @@ -180,11 +175,6 @@ impl SlippageAmount { Ok(Self { relative, absolute }) } - /// Reduce the specified amount by the constant slippage. - pub fn sub_from_amount(&self, amount: U256) -> U256 { - amount.saturating_sub(self.absolute) - } - /// Increase the specified amount by the constant slippage. pub fn add_to_amount(&self, amount: U256) -> U256 { amount.saturating_add(self.absolute) diff --git a/crates/solver/src/liquidity_collector.rs b/crates/solver/src/liquidity_collector.rs index 9b0b866c7f..52a3fed2bc 100644 --- a/crates/solver/src/liquidity_collector.rs +++ b/crates/solver/src/liquidity_collector.rs @@ -8,7 +8,6 @@ use { tracing::Instrument, }; -#[mockall::automock] #[async_trait::async_trait] pub trait LiquidityCollecting: Send + Sync { async fn get_liquidity( diff --git a/crates/solver/src/settlement/mod.rs b/crates/solver/src/settlement/mod.rs index 66022b317c..01dda9c696 100644 --- a/crates/solver/src/settlement/mod.rs +++ b/crates/solver/src/settlement/mod.rs @@ -126,23 +126,6 @@ impl Settlement { .encode(execution, &mut self.encoder) } - #[cfg(test)] - pub fn with_trades(clearing_prices: HashMap, trades: Vec) -> Self { - let encoder = SettlementEncoder::with_trades(clearing_prices, trades); - Self { encoder } - } - - #[cfg(test)] - pub fn with_default_prices(trades: Vec) -> Self { - let clearing_prices = trades - .iter() - .flat_map(|trade| [trade.order.data.sell_token, trade.order.data.buy_token]) - .map(|token| (token, U256::from(1_000_000_000_000_000_000_u128))) - .collect(); - let encoder = SettlementEncoder::with_trades(clearing_prices, trades); - Self { encoder } - } - /// Returns the clearing prices map. pub fn clearing_prices(&self) -> &HashMap { self.encoder.clearing_prices() @@ -171,15 +154,6 @@ impl Settlement { }) } - /// Calculates the risk level for settlement to be reverted - pub fn revertable(&self) -> Revertable { - if self.encoder.has_interactions() { - Revertable::HighRisk - } else { - Revertable::NoRisk - } - } - pub fn encode(self, internalization_strategy: InternalizationStrategy) -> EncodedSettlement { self.encoder.finish(internalization_strategy) } diff --git a/crates/solver/src/settlement/settlement_encoder.rs b/crates/solver/src/settlement/settlement_encoder.rs index 35f1b3f21c..4a901c617e 100644 --- a/crates/solver/src/settlement/settlement_encoder.rs +++ b/crates/solver/src/settlement/settlement_encoder.rs @@ -71,15 +71,6 @@ enum TokenReference { }, } -impl Default for TokenReference { - fn default() -> Self { - Self::Indexed { - sell_token_index: 0, - buy_token_index: 0, - } - } -} - /// An trade that was added to the settlement encoder. #[derive(Clone, Debug, Eq, PartialEq)] struct EncoderTrade { @@ -166,12 +157,6 @@ impl SettlementEncoder { } } - pub(crate) fn has_interactions(&self) -> bool { - self.execution_plan - .iter() - .any(|(_, internalizable)| !internalizable) - } - /// Adds an order trade using the uniform clearing prices for sell and buy /// token. Fails if any used token doesn't have a price or if executed /// amount is impossible. diff --git a/crates/solvers/src/domain/auction.rs b/crates/solvers/src/domain/auction.rs index 26ac8cc104..c8173e1a79 100644 --- a/crates/solvers/src/domain/auction.rs +++ b/crates/solvers/src/domain/auction.rs @@ -31,10 +31,6 @@ impl Tokens { pub fn reference_price(&self, token: ð::TokenAddress) -> Option { self.get(token)?.reference_price } - - pub fn decimals(&self, token: ð::TokenAddress) -> Option { - self.get(token)?.decimals - } } /// The ID of an auction. diff --git a/crates/solvers/src/domain/eth/mod.rs b/crates/solvers/src/domain/eth/mod.rs index e469fb36ad..41de18f275 100644 --- a/crates/solvers/src/domain/eth/mod.rs +++ b/crates/solvers/src/domain/eth/mod.rs @@ -33,12 +33,6 @@ pub struct Asset { #[derive(Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)] pub struct Ether(pub U256); -impl From for Ether { - fn from(value: U256) -> Self { - Self(value) - } -} - /// A token amount in wei, always representing the sell token of an order. #[derive(Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd, From)] pub struct SellTokenAmount(pub U256); @@ -57,14 +51,6 @@ impl From for SignedGas { #[derive(Clone, Copy, Debug, Default)] pub struct Gas(pub U256); -impl std::ops::Add for Gas { - type Output = Self; - - fn add(self, rhs: Self) -> Self::Output { - Self(self.0 + rhs.0) - } -} - impl std::ops::Add for Gas { type Output = Self; @@ -84,18 +70,6 @@ pub type Rational = num::rational::Ratio; #[derive(Debug, Default, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct Address(pub H160); -impl From for Address { - fn from(value: H160) -> Self { - Self(value) - } -} - -impl From
for H160 { - fn from(value: Address) -> Self { - value.0 - } -} - /// An onchain transaction. #[derive(Debug, Clone)] pub struct Tx { diff --git a/crates/solvers/src/domain/liquidity/limit_order.rs b/crates/solvers/src/domain/liquidity/limit_order.rs index 748160e30d..d2065f7a22 100644 --- a/crates/solvers/src/domain/liquidity/limit_order.rs +++ b/crates/solvers/src/domain/liquidity/limit_order.rs @@ -8,16 +8,6 @@ pub struct LimitOrder { pub fee: TakerAmount, } -impl LimitOrder { - /// Returns the fee amount as an asset. - pub fn fee(&self) -> eth::Asset { - eth::Asset { - token: self.taker.token, - amount: self.fee.0, - } - } -} - /// An amount denominated in the taker token of a [`LimitOrder`]. #[derive(Debug, Clone, Copy)] pub struct TakerAmount(pub U256); diff --git a/crates/solvers/src/domain/liquidity/weighted_product.rs b/crates/solvers/src/domain/liquidity/weighted_product.rs index e9c9bf6c4d..730369b050 100644 --- a/crates/solvers/src/domain/liquidity/weighted_product.rs +++ b/crates/solvers/src/domain/liquidity/weighted_product.rs @@ -42,15 +42,6 @@ impl Reserves { self.0.iter().cloned() } - /// Returns the reserve for the specified token. - pub fn get(&self, token: eth::TokenAddress) -> Option { - let index = self - .0 - .binary_search_by_key(&token, |reserve| reserve.asset.token) - .ok()?; - Some(self.0[index].clone()) - } - /// Returns an iterator over the tokens pairs handled by the pool reserves. pub fn token_pairs(&self) -> impl Iterator + '_ { self.0 diff --git a/crates/solvers/src/domain/order.rs b/crates/solvers/src/domain/order.rs index 54a84165bf..1696c2c87a 100644 --- a/crates/solvers/src/domain/order.rs +++ b/crates/solvers/src/domain/order.rs @@ -18,13 +18,6 @@ pub struct Order { } impl Order { - /// Returns the order's owner address. - pub fn owner(&self) -> Address { - let mut bytes = [0_u8; 20]; - bytes.copy_from_slice(&self.uid.0[32..52]); - bytes.into() - } - /// Returns `true` if the order expects a solver-computed fee. pub fn solver_determines_fee(&self) -> bool { self.class == Class::Limit @@ -110,16 +103,6 @@ pub enum Signature { PreSign, } -impl Signature { - pub fn to_bytes(&self) -> Vec { - match self { - Self::Eip712(signature) | Self::EthSign(signature) => signature.to_bytes().to_vec(), - Self::Eip1271(signature) => signature.clone(), - Self::PreSign => Vec::new(), - } - } -} - #[derive(Clone, Copy, Debug, Default)] pub struct EcdsaSignature { pub r: H256, diff --git a/crates/solvers/src/domain/solution.rs b/crates/solvers/src/domain/solution.rs index ea4e323c0f..7bd6883d6a 100644 --- a/crates/solvers/src/domain/solution.rs +++ b/crates/solvers/src/domain/solution.rs @@ -10,12 +10,6 @@ use { #[derive(Debug, Default, Copy, Clone)] pub struct Id(pub u64); -impl From for Id { - fn from(id: u64) -> Self { - Self(id) - } -} - /// A solution to an auction. #[derive(Debug, Default)] pub struct Solution { @@ -105,10 +99,6 @@ impl Solution { self } - - pub fn is_empty(&self) -> bool { - self.prices.0.is_empty() && self.trades.is_empty() && self.interactions.is_empty() - } } /// A solution for a settling a single order. diff --git a/crates/solvers/src/infra/blockchain.rs b/crates/solvers/src/infra/blockchain.rs deleted file mode 100644 index 9bed81083b..0000000000 --- a/crates/solvers/src/infra/blockchain.rs +++ /dev/null @@ -1,13 +0,0 @@ -use std::time::Duration; - -/// Creates a node RPC instance. -pub fn rpc(url: &reqwest::Url) -> ethrpc::Web3 { - ethrpc::web3( - Default::default(), - reqwest::ClientBuilder::new() - .timeout(Duration::from_secs(10)) - .user_agent("cowprotocol-solver-engine/1.0.0"), - url, - "base", - ) -} diff --git a/crates/solvers/src/infra/metrics.rs b/crates/solvers/src/infra/metrics.rs index 34cf194c1f..509c8893a0 100644 --- a/crates/solvers/src/infra/metrics.rs +++ b/crates/solvers/src/infra/metrics.rs @@ -42,10 +42,6 @@ pub fn solved(deadline: &auction::Deadline, solutions: &[solution::Solution]) { get().solutions.inc_by(solutions.len() as u64); } -pub fn solve_error(reason: &str) { - get().solve_errors.with_label_values(&[reason]).inc(); -} - /// Get the metrics instance. fn get() -> &'static Metrics { Metrics::instance(observe::metrics::get_storage_registry()) diff --git a/crates/solvers/src/infra/mod.rs b/crates/solvers/src/infra/mod.rs index d0e1cfedc7..792a13c703 100644 --- a/crates/solvers/src/infra/mod.rs +++ b/crates/solvers/src/infra/mod.rs @@ -1,4 +1,3 @@ -pub mod blockchain; pub mod cli; pub mod config; pub mod contracts; diff --git a/crates/solvers/src/util/bytes.rs b/crates/solvers/src/util/bytes.rs index 1ff531c545..83a91f06d4 100644 --- a/crates/solvers/src/util/bytes.rs +++ b/crates/solvers/src/util/bytes.rs @@ -10,21 +10,3 @@ where write!(f, "0x{}", hex::encode(&self.0)) } } - -impl From for Bytes { - fn from(value: T) -> Self { - Self(value) - } -} - -impl From>> for Vec { - fn from(value: Bytes>) -> Self { - value.0 - } -} - -impl From> for [u8; N] { - fn from(value: Bytes<[u8; N]>) -> Self { - value.0 - } -} diff --git a/crates/solvers/src/util/conv.rs b/crates/solvers/src/util/conv.rs index 509a4180d2..e679205132 100644 --- a/crates/solvers/src/util/conv.rs +++ b/crates/solvers/src/util/conv.rs @@ -2,7 +2,7 @@ use { crate::domain::eth, - bigdecimal::{num_bigint::ToBigInt, BigDecimal}, + bigdecimal::BigDecimal, ethereum_types::U256, num::{rational::Ratio, BigInt, BigUint, One}, }; @@ -45,22 +45,6 @@ pub fn u256_to_biguint(i: &U256) -> BigUint { BigUint::from_bytes_be(&bytes) } -pub fn u256_to_bigdecimal(i: &U256) -> BigDecimal { - BigDecimal::new(u256_to_biguint(i).into(), 0) -} - -pub fn bigint_to_u256(i: &BigInt) -> Option { - if i.sign() == num::bigint::Sign::Minus { - return None; - } - biguint_to_u256(i.magnitude()) -} - -pub fn bigdecimal_to_u256(d: &BigDecimal) -> Option { - let d = d.to_bigint()?; - bigint_to_u256(&d) -} - /// Converts a `BigDecimal` amount in Ether units to wei. pub fn decimal_to_ether(d: &BigDecimal) -> Option { let scaled = d * BigDecimal::new(BigInt::one(), -18); diff --git a/crates/solvers/src/util/mod.rs b/crates/solvers/src/util/mod.rs index 49e817c0b9..ce85e8add0 100644 --- a/crates/solvers/src/util/mod.rs +++ b/crates/solvers/src/util/mod.rs @@ -3,4 +3,3 @@ pub mod conv; pub mod fmt; pub mod math; pub mod serialize; -pub mod url; diff --git a/crates/solvers/src/util/serialize/hex.rs b/crates/solvers/src/util/serialize/hex.rs deleted file mode 100644 index 0875628a27..0000000000 --- a/crates/solvers/src/util/serialize/hex.rs +++ /dev/null @@ -1,56 +0,0 @@ -use { - serde::{de, Deserialize, Deserializer, Serializer}, - serde_with::{DeserializeAs, SerializeAs}, - std::borrow::Cow, -}; - -/// Serialize and deserialize binary data as a hexadecimal string. -#[derive(Debug)] -pub struct Hex; - -impl<'de> DeserializeAs<'de, Vec> for Hex { - fn deserialize_as>(deserializer: D) -> Result, D::Error> { - let s = Cow::::deserialize(deserializer)?; - let s = s - .strip_prefix("0x") - .ok_or_else( - || format!("failed to decode {s:?} as a hex string: missing \"0x\" prefix",), - ) - .map_err(de::Error::custom)?; - hex::decode(s).map_err(|err| { - de::Error::custom(format!("failed to decode {s:?} as a hex string: {err}",)) - }) - } -} - -impl SerializeAs> for Hex { - fn serialize_as(source: &Vec, serializer: S) -> Result { - let hex = hex::encode(source); - serializer.serialize_str(&format!("0x{hex}")) - } -} - -impl<'de, const N: usize> DeserializeAs<'de, [u8; N]> for Hex { - fn deserialize_as>(deserializer: D) -> Result<[u8; N], D::Error> { - let s = Cow::::deserialize(deserializer)?; - let s = s - .strip_prefix("0x") - .ok_or_else( - || format!("failed to decode {s:?} as a hex string: missing \"0x\" prefix",), - ) - .map_err(de::Error::custom)?; - - let mut buffer = [0; N]; - hex::decode_to_slice(s, &mut buffer).map_err(|err| { - de::Error::custom(format!("failed to decode {s:?} as a hex string: {err}",)) - })?; - Ok(buffer) - } -} - -impl SerializeAs<[u8; N]> for Hex { - fn serialize_as(source: &[u8; N], serializer: S) -> Result { - let hex = hex::encode(source); - serializer.serialize_str(&format!("0x{hex}")) - } -} diff --git a/crates/solvers/src/util/serialize/mod.rs b/crates/solvers/src/util/serialize/mod.rs index 40a9110f94..fdfefaeb6a 100644 --- a/crates/solvers/src/util/serialize/mod.rs +++ b/crates/solvers/src/util/serialize/mod.rs @@ -1,4 +1,3 @@ -mod hex; mod u256; pub use self::u256::U256; diff --git a/crates/solvers/src/util/serialize/never.rs b/crates/solvers/src/util/serialize/never.rs deleted file mode 100644 index 5ff667e78f..0000000000 --- a/crates/solvers/src/util/serialize/never.rs +++ /dev/null @@ -1,25 +0,0 @@ -use serde::{de, ser, Deserialize, Deserializer, Serialize, Serializer}; - -/// A type that never deserializes or serializes. -/// -/// This can be used in situations where a generic type that implements `serde` -/// traits is required, but you don't want it to actually represent any data. -pub struct Never; - -impl<'de> Deserialize<'de> for Never { - fn deserialize(_: D) -> Result - where - D: Deserializer<'de>, - { - Err(de::Error::custom("neva eva eva")) - } -} - -impl Serialize for Never { - fn serialize(&self, _: S) -> Result - where - S: Serializer, - { - Err(ser::Error::custom("neva eva eva")) - } -} diff --git a/crates/solvers/src/util/serialize/str.rs b/crates/solvers/src/util/serialize/str.rs deleted file mode 100644 index 4500a7492c..0000000000 --- a/crates/solvers/src/util/serialize/str.rs +++ /dev/null @@ -1,10 +0,0 @@ -use {serde::Serializer, serde_with::SerializeAs}; - -/// Serializes a slice of strings as a comma-separated list. -pub struct CommaSeparated; - -impl SerializeAs> for CommaSeparated { - fn serialize_as(source: &Vec, serializer: S) -> Result { - serializer.serialize_str(&source.join(",")) - } -} diff --git a/crates/solvers/src/util/serialize/u256.rs b/crates/solvers/src/util/serialize/u256.rs index 61ebf14e22..4167e1c299 100644 --- a/crates/solvers/src/util/serialize/u256.rs +++ b/crates/solvers/src/util/serialize/u256.rs @@ -1,6 +1,6 @@ use { - serde::{de, Deserialize, Deserializer, Serializer}, - serde_with::{DeserializeAs, SerializeAs}, + serde::{de, Deserialize, Deserializer}, + serde_with::DeserializeAs, std::borrow::Cow, }; @@ -17,12 +17,3 @@ impl<'de> DeserializeAs<'de, ethereum_types::U256> for U256 { .map_err(|err| de::Error::custom(format!("failed to parse {s:?} as a U256: {err}"))) } } - -impl SerializeAs for U256 { - fn serialize_as( - value: ðereum_types::U256, - serializer: S, - ) -> Result { - serializer.serialize_str(&value.to_string()) - } -} diff --git a/crates/solvers/src/util/url.rs b/crates/solvers/src/util/url.rs index 7cc53c3970..e69de29bb2 100644 --- a/crates/solvers/src/util/url.rs +++ b/crates/solvers/src/util/url.rs @@ -1,14 +0,0 @@ -use reqwest::Url; - -/// Join a path with a URL, ensuring that there is only one slash between them. -/// It doesn't matter if the URL ends with a slash or the path starts with one. -pub fn join(url: &Url, mut path: &str) -> Url { - let mut url = url.to_string(); - while url.ends_with('/') { - url.pop(); - } - while path.starts_with('/') { - path = &path[1..] - } - Url::parse(&format!("{url}/{path}")).unwrap() -}