From 49def689b967a33794553bcb40f352cddcda82eb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jose=CC=81=20Duarte?= Date: Thu, 11 Dec 2025 10:32:08 +0000 Subject: [PATCH] Migrate NonZeroU256 to alloy --- crates/driver/src/domain/eth/mod.rs | 2 +- crates/e2e/tests/e2e/app_data.rs | 7 +-- crates/e2e/tests/e2e/banned_users.rs | 4 +- crates/e2e/tests/e2e/cow_amm.rs | 6 +- crates/e2e/tests/e2e/eth_integration.rs | 5 +- crates/e2e/tests/e2e/ethflow.rs | 9 +-- crates/e2e/tests/e2e/hooks.rs | 9 ++- crates/e2e/tests/e2e/limit_orders.rs | 6 +- crates/e2e/tests/e2e/order_cancellation.rs | 10 ++-- .../e2e/tests/e2e/place_order_with_quote.rs | 6 +- crates/e2e/tests/e2e/quote_verification.rs | 22 +++---- crates/e2e/tests/e2e/quoting.rs | 13 +++-- crates/e2e/tests/e2e/refunder.rs | 13 ++--- crates/e2e/tests/e2e/wrapper.rs | 4 +- crates/model/src/quote.rs | 4 +- crates/number/Cargo.toml | 2 +- crates/number/src/nonzero.rs | 44 +++++++------- crates/orderbook/src/api/post_quote.rs | 2 +- crates/orderbook/src/quoter.rs | 57 +++++++++---------- crates/shared/src/encoded_settlement.rs | 6 +- crates/shared/src/order_quoting.rs | 7 +-- crates/shared/src/order_validation.rs | 9 +-- .../src/price_estimation/competition/mod.rs | 2 +- crates/shared/src/price_estimation/factory.rs | 19 +++---- .../src/price_estimation/instrumented.rs | 2 +- crates/shared/src/price_estimation/mod.rs | 7 +-- .../shared/src/price_estimation/native/mod.rs | 15 ++--- .../shared/src/price_estimation/sanitized.rs | 25 ++++---- .../price_estimation/trade_verifier/mod.rs | 35 ++++++------ crates/shared/src/trade_finding/external.rs | 4 +- crates/solver/src/settlement/mod.rs | 2 +- 31 files changed, 162 insertions(+), 196 deletions(-) diff --git a/crates/driver/src/domain/eth/mod.rs b/crates/driver/src/domain/eth/mod.rs index 792a006e9c..07838bde11 100644 --- a/crates/driver/src/domain/eth/mod.rs +++ b/crates/driver/src/domain/eth/mod.rs @@ -20,7 +20,7 @@ pub use { alloy::primitives::{Address, U256}, eip712::DomainSeparator, gas::{EffectiveGasPrice, FeePerGas, Gas, GasPrice}, - number::nonzero::U256 as NonZeroU256, + number::nonzero::NonZeroU256, primitive_types::{H256, U512}, }; diff --git a/crates/e2e/tests/e2e/app_data.rs b/crates/e2e/tests/e2e/app_data.rs index cae06951f4..cc613588d3 100644 --- a/crates/e2e/tests/e2e/app_data.rs +++ b/crates/e2e/tests/e2e/app_data.rs @@ -1,10 +1,7 @@ use { app_data::{AppDataHash, hash_full_app_data}, e2e::setup::{eth, *}, - ethrpc::alloy::{ - CallBuilderExt, - conversions::{IntoAlloy, IntoLegacy}, - }, + ethrpc::alloy::{CallBuilderExt, conversions::IntoAlloy}, model::{ order::{OrderCreation, OrderCreationAppData, OrderKind}, quote::{OrderQuoteRequest, OrderQuoteSide, SellAmount}, @@ -118,7 +115,7 @@ async fn app_data(web3: Web3) { buy_token: order3.buy_token, side: OrderQuoteSide::Sell { sell_amount: SellAmount::AfterFee { - value: order3.sell_amount.into_legacy().try_into().unwrap(), + value: order3.sell_amount.try_into().unwrap(), }, }, app_data: OrderCreationAppData::Hash { diff --git a/crates/e2e/tests/e2e/banned_users.rs b/crates/e2e/tests/e2e/banned_users.rs index 21027604d9..8230470e08 100644 --- a/crates/e2e/tests/e2e/banned_users.rs +++ b/crates/e2e/tests/e2e/banned_users.rs @@ -1,6 +1,6 @@ use { alloy::{ - primitives::{Address, address}, + primitives::{Address, U256, address, utils::Unit}, providers::ext::{AnvilApi, ImpersonateConfig}, }, contracts::alloy::ERC20, @@ -96,7 +96,7 @@ async fn forked_mainnet_onchain_banned_user_test(web3: Web3) { buy_token: *token_usdt.address(), side: OrderQuoteSide::Sell { sell_amount: SellAmount::BeforeFee { - value: to_wei_with_exp(1000, 18).try_into().unwrap(), + value: (U256::from(1000) * Unit::ETHER.wei()).try_into().unwrap(), }, }, from: BANNED_USER, diff --git a/crates/e2e/tests/e2e/cow_amm.rs b/crates/e2e/tests/e2e/cow_amm.rs index 22c81968e8..4d9aaf0669 100644 --- a/crates/e2e/tests/e2e/cow_amm.rs +++ b/crates/e2e/tests/e2e/cow_amm.rs @@ -1,6 +1,6 @@ use { alloy::{ - primitives::{Address, Bytes, FixedBytes, U256, address}, + primitives::{Address, Bytes, FixedBytes, U256, address, utils::Unit}, providers::ext::{AnvilApi, ImpersonateConfig}, }, contracts::alloy::{ @@ -602,7 +602,7 @@ factory = "0xf76c421bAb7df8548604E60deCCcE50477C10462" buy_token: *usdt.address(), side: OrderQuoteSide::Sell { sell_amount: SellAmount::BeforeFee { - value: to_wei_with_exp(1000, 6).try_into().unwrap(), + value: (U256::from(1000) * Unit::MWEI.wei()).try_into().unwrap(), }, }, ..Default::default() @@ -983,7 +983,7 @@ async fn cow_amm_opposite_direction(web3: Web3) { buy_token: *onchain.contracts().weth.address(), side: OrderQuoteSide::Sell { sell_amount: SellAmount::AfterFee { - value: NonZeroU256::try_from(executed_amount.into_legacy()).unwrap(), + value: NonZeroU256::try_from(executed_amount).unwrap(), }, }, ..Default::default() diff --git a/crates/e2e/tests/e2e/eth_integration.rs b/crates/e2e/tests/e2e/eth_integration.rs index 4d5960e38c..fd9a891fb9 100644 --- a/crates/e2e/tests/e2e/eth_integration.rs +++ b/crates/e2e/tests/e2e/eth_integration.rs @@ -1,4 +1,5 @@ use { + ::alloy::primitives::{U256, utils::Unit}, e2e::setup::{eth, *}, ethcontract::prelude::Address, ethrpc::alloy::{ @@ -10,7 +11,7 @@ use { quote::{OrderQuoteRequest, OrderQuoteSide, SellAmount}, signature::EcdsaSigningScheme, }, - number::nonzero::U256 as NonZeroU256, + number::nonzero::NonZeroU256, secp256k1::SecretKey, shared::ethrpc::Web3, web3::signing::SecretKeyRef, @@ -69,7 +70,7 @@ async fn eth_integration(web3: Web3) { from: Address::default().into_alloy(), side: OrderQuoteSide::Sell { sell_amount: SellAmount::AfterFee { - value: NonZeroU256::try_from(to_wei(43)).unwrap(), + value: NonZeroU256::try_from(U256::from(43) * Unit::ETHER.wei()).unwrap(), }, }, ..Default::default() diff --git a/crates/e2e/tests/e2e/ethflow.rs b/crates/e2e/tests/e2e/ethflow.rs index fea85147fe..35a12b078c 100644 --- a/crates/e2e/tests/e2e/ethflow.rs +++ b/crates/e2e/tests/e2e/ethflow.rs @@ -55,7 +55,7 @@ use { signature::{Signature, hashed_eip712_message}, trade::Trade, }, - number::nonzero::U256 as NonZeroU256, + number::nonzero::NonZeroU256, refunder::refund_service::{INVALIDATED_OWNER, NO_OWNER}, reqwest::Client, shared::signature_validator::check_erc1271_result, @@ -434,10 +434,7 @@ async fn test_submit_quote( panic!("untested!"); }; - assert_eq!( - response.quote.sell_amount, - sell_amount_after_fees.get().into_alloy() - ); + assert_eq!(response.quote.sell_amount, sell_amount_after_fees.get()); response } @@ -862,7 +859,7 @@ impl EthFlowTradeIntent { }, side: OrderQuoteSide::Sell { sell_amount: model::quote::SellAmount::AfterFee { - value: NonZeroU256::try_from(self.sell_amount.into_legacy()).unwrap(), + value: NonZeroU256::try_from(self.sell_amount).unwrap(), }, }, buy_token_balance: BuyTokenDestination::Erc20, diff --git a/crates/e2e/tests/e2e/hooks.rs b/crates/e2e/tests/e2e/hooks.rs index c8ee68160c..fc04a8c4d5 100644 --- a/crates/e2e/tests/e2e/hooks.rs +++ b/crates/e2e/tests/e2e/hooks.rs @@ -1,5 +1,8 @@ use { - alloy::providers::Provider, + alloy::{ + primitives::{U256, utils::Unit}, + providers::Provider, + }, app_data::Hook, e2e::setup::{ OnchainComponents, @@ -21,7 +24,7 @@ use { quote::{OrderQuoteRequest, OrderQuoteSide, SellAmount}, signature::{EcdsaSigningScheme, Signature, hashed_eip712_message}, }, - number::nonzero::U256 as NonZeroU256, + number::nonzero::NonZeroU256, reqwest::StatusCode, secp256k1::SecretKey, serde_json::json, @@ -614,7 +617,7 @@ async fn quote_verification(web3: Web3) { buy_token: *onchain.contracts().weth.address(), side: OrderQuoteSide::Sell { sell_amount: SellAmount::BeforeFee { - value: NonZeroU256::try_from(to_wei(5)).unwrap(), + value: NonZeroU256::try_from(U256::from(5) * Unit::ETHER.wei()).unwrap(), }, }, app_data: OrderCreationAppData::Full { diff --git a/crates/e2e/tests/e2e/limit_orders.rs b/crates/e2e/tests/e2e/limit_orders.rs index ad8f4666bf..f8f15119d8 100644 --- a/crates/e2e/tests/e2e/limit_orders.rs +++ b/crates/e2e/tests/e2e/limit_orders.rs @@ -1,7 +1,7 @@ use { crate::database::AuctionTransaction, ::alloy::{ - primitives::{Address, U256, address}, + primitives::{Address, U256, address, utils::Unit}, providers::ext::{AnvilApi, ImpersonateConfig}, }, bigdecimal::BigDecimal, @@ -715,7 +715,7 @@ async fn limit_does_not_apply_to_in_market_orders_test(web3: Web3) { buy_token: *onchain.contracts().weth.address(), side: OrderQuoteSide::Sell { sell_amount: SellAmount::BeforeFee { - value: NonZeroU256::try_from(to_wei(5)).unwrap(), + value: NonZeroU256::try_from(U256::from(5) * Unit::ETHER.wei()).unwrap(), }, }, ..Default::default() @@ -871,7 +871,7 @@ async fn forked_mainnet_single_limit_order_test(web3: Web3) { buy_token: *token_usdt.address(), side: OrderQuoteSide::Sell { sell_amount: SellAmount::BeforeFee { - value: to_wei_with_exp(1000, 6).try_into().unwrap(), + value: (U256::from(1000) * Unit::MWEI.wei()).try_into().unwrap(), }, }, ..Default::default() diff --git a/crates/e2e/tests/e2e/order_cancellation.rs b/crates/e2e/tests/e2e/order_cancellation.rs index 7baa8e2509..3fc1cbfc32 100644 --- a/crates/e2e/tests/e2e/order_cancellation.rs +++ b/crates/e2e/tests/e2e/order_cancellation.rs @@ -1,5 +1,5 @@ use { - ::alloy::primitives::U256 as AlloyU256, + ::alloy::primitives::{U256, utils::Unit}, database::order_events::OrderEventLabel, e2e::setup::{eth, *}, ethrpc::alloy::{CallBuilderExt, conversions::IntoAlloy}, @@ -17,7 +17,7 @@ use { quote::{OrderQuoteRequest, OrderQuoteSide, SellAmount}, signature::{EcdsaSignature, EcdsaSigningScheme}, }, - number::nonzero::U256 as NonZeroU256, + number::nonzero::NonZeroU256, secp256k1::SecretKey, serde_json::json, shared::ethrpc::Web3, @@ -95,7 +95,7 @@ async fn order_cancellation(web3: Web3) { buy_token: *onchain.contracts().weth.address(), side: OrderQuoteSide::Sell { sell_amount: SellAmount::AfterFee { - value: NonZeroU256::try_from(to_wei(1)).unwrap(), + value: NonZeroU256::try_from(U256::ONE * Unit::ETHER.wei()).unwrap(), }, }, app_data: OrderCreationAppData::Full { @@ -110,9 +110,9 @@ async fn order_cancellation(web3: Web3) { kind: quote.kind, sell_token: quote.sell_token, sell_amount: quote.sell_amount, - fee_amount: ::alloy::primitives::U256::ZERO, + fee_amount: U256::ZERO, buy_token: quote.buy_token, - buy_amount: ((quote.buy_amount * AlloyU256::from(99)) / AlloyU256::from(100)), + buy_amount: ((quote.buy_amount * U256::from(99)) / U256::from(100)), valid_to: quote.valid_to, app_data: quote.app_data, ..Default::default() diff --git a/crates/e2e/tests/e2e/place_order_with_quote.rs b/crates/e2e/tests/e2e/place_order_with_quote.rs index f375426587..1fc1b48c87 100644 --- a/crates/e2e/tests/e2e/place_order_with_quote.rs +++ b/crates/e2e/tests/e2e/place_order_with_quote.rs @@ -1,5 +1,5 @@ use { - ::alloy::primitives::U256, + ::alloy::primitives::{U256, utils::Unit}, driver::domain::eth::NonZeroU256, e2e::{nodes::local_node::TestNodeApi, setup::*}, ethrpc::alloy::{CallBuilderExt, conversions::IntoAlloy}, @@ -58,7 +58,7 @@ async fn place_order_with_quote(web3: Web3) { .expect("Must be able to disable automine"); tracing::info!("Quoting"); - let quote_sell_amount = to_wei(1); + let quote_sell_amount = U256::ONE * Unit::ETHER.wei(); let quote_request = OrderQuoteRequest { from: trader.address(), sell_token: *onchain.contracts().weth.address(), @@ -86,7 +86,7 @@ async fn place_order_with_quote(web3: Web3) { let order = OrderCreation { quote_id: quote_response.id, sell_token: *onchain.contracts().weth.address(), - sell_amount: quote_sell_amount.into_alloy(), + sell_amount: quote_sell_amount, buy_token: *token.address(), buy_amount: quote_response.quote.buy_amount, valid_to: model::time::now_in_epoch_seconds() + 300, diff --git a/crates/e2e/tests/e2e/quote_verification.rs b/crates/e2e/tests/e2e/quote_verification.rs index 2839af1c30..a1db55bf09 100644 --- a/crates/e2e/tests/e2e/quote_verification.rs +++ b/crates/e2e/tests/e2e/quote_verification.rs @@ -1,6 +1,6 @@ use { ::alloy::{ - primitives::{Address, U256, address}, + primitives::{Address, U256, address, utils::Unit}, providers::Provider, }, bigdecimal::{BigDecimal, Zero}, @@ -15,7 +15,7 @@ use { order::{BuyTokenDestination, OrderKind, SellTokenSource}, quote::{OrderQuoteRequest, OrderQuoteSide, SellAmount}, }, - number::nonzero::U256 as NonZeroU256, + number::nonzero::NonZeroU256, serde_json::json, shared::{ price_estimation::{ @@ -113,7 +113,7 @@ async fn standard_verified_quote(web3: Web3) { buy_token: *onchain.contracts().weth.address(), side: OrderQuoteSide::Sell { sell_amount: SellAmount::BeforeFee { - value: to_wei(1).try_into().unwrap(), + value: (U256::ONE * Unit::ETHER.wei()).try_into().unwrap(), }, }, ..Default::default() @@ -169,7 +169,7 @@ async fn test_bypass_verification_for_rfq_quotes(web3: Web3) { sell_token: address!("0x2260fac5e5542a773aa44fbcfedf7c193bc2c599"), buy_token: address!("0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2"), kind: OrderKind::Sell, - in_amount: NonZeroU256::new(12.into()).unwrap(), + in_amount: NonZeroU256::new(U256::from(12)).unwrap(), }, &Verification { from: address!("0x73688c2b34bf6c09c125fed02fe92d17a94b897a"), @@ -268,7 +268,7 @@ async fn verified_quote_eth_balance(web3: Web3) { buy_token: *token.address(), side: OrderQuoteSide::Sell { sell_amount: SellAmount::BeforeFee { - value: to_wei(1).try_into().unwrap(), + value: (U256::ONE * Unit::ETHER.wei()).try_into().unwrap(), }, }, ..Default::default() @@ -305,7 +305,7 @@ async fn verified_quote_for_settlement_contract(web3: Web3) { buy_token: *token.address(), side: OrderQuoteSide::Sell { sell_amount: SellAmount::BeforeFee { - value: to_wei(3).try_into().unwrap(), + value: (U256::from(3) * Unit::ETHER.wei()).try_into().unwrap(), }, }, ..Default::default() @@ -410,7 +410,7 @@ async fn verified_quote_with_simulated_balance(web3: Web3) { buy_token: *weth.address(), side: OrderQuoteSide::Sell { sell_amount: SellAmount::BeforeFee { - value: to_wei(1).try_into().unwrap(), + value: (U256::ONE * Unit::ETHER.wei()).try_into().unwrap(), }, }, ..Default::default() @@ -450,7 +450,7 @@ async fn verified_quote_with_simulated_balance(web3: Web3) { buy_token: *token.address(), side: OrderQuoteSide::Sell { sell_amount: SellAmount::BeforeFee { - value: to_wei(1).try_into().unwrap(), + value: (U256::ONE * Unit::ETHER.wei()).try_into().unwrap(), }, }, ..Default::default() @@ -468,7 +468,7 @@ async fn verified_quote_with_simulated_balance(web3: Web3) { buy_token: *token.address(), side: OrderQuoteSide::Sell { sell_amount: SellAmount::BeforeFee { - value: to_wei(1).try_into().unwrap(), + value: (U256::ONE * Unit::ETHER.wei()).try_into().unwrap(), }, }, ..Default::default() @@ -486,7 +486,7 @@ async fn verified_quote_with_simulated_balance(web3: Web3) { buy_token: *token.address(), side: OrderQuoteSide::Sell { sell_amount: SellAmount::BeforeFee { - value: to_wei(1).try_into().unwrap(), + value: (U256::ONE * Unit::ETHER.wei()).try_into().unwrap(), }, }, app_data: model::order::OrderCreationAppData::Full { @@ -540,7 +540,7 @@ async fn usdt_quote_verification(web3: Web3) { buy_token: usdc, side: OrderQuoteSide::Sell { sell_amount: SellAmount::BeforeFee { - value: to_wei_with_exp(1000, 18).try_into().unwrap(), + value: (U256::from(1000) * Unit::ETHER.wei()).try_into().unwrap(), }, }, ..Default::default() diff --git a/crates/e2e/tests/e2e/quoting.rs b/crates/e2e/tests/e2e/quoting.rs index da2cd9a3e1..bcd00fb887 100644 --- a/crates/e2e/tests/e2e/quoting.rs +++ b/crates/e2e/tests/e2e/quoting.rs @@ -1,4 +1,5 @@ use { + ::alloy::primitives::{U256, utils::Unit}, e2e::setup::{colocation::SolverEngine, eth, mock::Mock, *}, ethrpc::alloy::{CallBuilderExt, conversions::IntoAlloy}, futures::FutureExt, @@ -7,7 +8,7 @@ use { quote::{OrderQuoteRequest, OrderQuoteSide, QuoteSigningScheme, SellAmount}, signature::EcdsaSigningScheme, }, - number::nonzero::U256 as NonZeroU256, + number::nonzero::NonZeroU256, secp256k1::SecretKey, serde_json::json, shared::ethrpc::Web3, @@ -93,7 +94,7 @@ async fn test(web3: Web3) { buy_token: *token.address(), side: OrderQuoteSide::Sell { sell_amount: SellAmount::BeforeFee { - value: NonZeroU256::try_from(to_wei(1)).unwrap(), + value: NonZeroU256::try_from(U256::ONE * Unit::ETHER.wei()).unwrap(), }, }, ..Default::default() @@ -231,7 +232,7 @@ async fn uses_stale_liquidity(web3: Web3) { buy_token: *token.address(), side: OrderQuoteSide::Sell { sell_amount: SellAmount::AfterFee { - value: NonZeroU256::new(to_wei(1)).unwrap(), + value: NonZeroU256::new(U256::ONE * Unit::ETHER.wei()).unwrap(), }, }, ..Default::default() @@ -332,7 +333,7 @@ async fn quote_timeout(web3: Web3) { buy_token: *sell_token.address(), side: OrderQuoteSide::Sell { sell_amount: SellAmount::BeforeFee { - value: NonZeroU256::try_from(to_wei(1)).unwrap(), + value: NonZeroU256::try_from(U256::ONE * Unit::ETHER.wei()).unwrap(), }, }, timeout, @@ -462,7 +463,7 @@ async fn volume_fee(web3: Web3) { buy_token: *token.address(), side: OrderQuoteSide::Sell { sell_amount: SellAmount::BeforeFee { - value: NonZeroU256::try_from(to_wei(1)).unwrap(), + value: NonZeroU256::try_from(U256::ONE * Unit::ETHER.wei()).unwrap(), }, }, ..Default::default() @@ -480,7 +481,7 @@ async fn volume_fee(web3: Web3) { sell_token: *onchain.contracts().weth.address(), buy_token: *token.address(), side: OrderQuoteSide::Buy { - buy_amount_after_fee: NonZeroU256::try_from(to_wei(1)).unwrap(), + buy_amount_after_fee: NonZeroU256::try_from(U256::ONE * Unit::ETHER.wei()).unwrap(), }, ..Default::default() }; diff --git a/crates/e2e/tests/e2e/refunder.rs b/crates/e2e/tests/e2e/refunder.rs index 98de58b547..7881eef9a6 100644 --- a/crates/e2e/tests/e2e/refunder.rs +++ b/crates/e2e/tests/e2e/refunder.rs @@ -3,14 +3,13 @@ use { ::alloy::primitives::Address, chrono::{TimeZone, Utc}, e2e::{nodes::local_node::TestNodeApi, setup::*}, - ethcontract::U256, ethrpc::{ Web3, alloy::conversions::TryIntoAlloyAsync, block_stream::timestamp_of_current_block_in_seconds, }, model::quote::{OrderQuoteRequest, OrderQuoteSide, QuoteSigningScheme, Validity}, - number::nonzero::U256 as NonZeroU256, + number::nonzero::NonZeroU256, refunder::refund_service::RefundService, sqlx::PgPool, }; @@ -36,7 +35,7 @@ async fn refunder_tx(web3: Web3) { // Get quote id for order placement let buy_token = *token.address(); let receiver = Some(Address::repeat_byte(42)); - let sell_amount = U256::from("3000000000000000"); + let sell_amount = NonZeroU256::try_from(3000000000000000u128).unwrap(); let ethflow_contract = onchain.contracts().ethflows.first().unwrap(); let quote = OrderQuoteRequest { @@ -50,9 +49,7 @@ async fn refunder_tx(web3: Web3) { verification_gas_limit: 0, }, side: OrderQuoteSide::Sell { - sell_amount: model::quote::SellAmount::AfterFee { - value: NonZeroU256::try_from(sell_amount).unwrap(), - }, + sell_amount: model::quote::SellAmount::AfterFee { value: sell_amount }, }, ..Default::default() }; @@ -82,9 +79,7 @@ async fn refunder_tx(web3: Web3) { verification_gas_limit: 0, }, side: OrderQuoteSide::Sell { - sell_amount: model::quote::SellAmount::AfterFee { - value: NonZeroU256::try_from(sell_amount).unwrap(), - }, + sell_amount: model::quote::SellAmount::AfterFee { value: sell_amount }, }, ..Default::default() }; diff --git a/crates/e2e/tests/e2e/wrapper.rs b/crates/e2e/tests/e2e/wrapper.rs index 8a46b901cc..aabae6e68a 100644 --- a/crates/e2e/tests/e2e/wrapper.rs +++ b/crates/e2e/tests/e2e/wrapper.rs @@ -1,6 +1,6 @@ use { ::alloy::{ - primitives::{Address, address}, + primitives::{Address, U256, address, utils::Unit}, providers::{ Provider, ext::{AnvilApi, DebugApi, ImpersonateConfig}, @@ -137,7 +137,7 @@ async fn forked_mainnet_wrapper_test(web3: Web3) { buy_token: *token_usdc.address(), side: OrderQuoteSide::Sell { sell_amount: SellAmount::BeforeFee { - value: to_wei(1).try_into().unwrap(), + value: (U256::ONE * Unit::ETHER.wei()).try_into().unwrap(), }, }, app_data: OrderCreationAppData::Both { diff --git a/crates/model/src/quote.rs b/crates/model/src/quote.rs index c1dc2dd05c..6de58cddf9 100644 --- a/crates/model/src/quote.rs +++ b/crates/model/src/quote.rs @@ -8,7 +8,7 @@ use { anyhow::bail, app_data::AppDataHash, chrono::{DateTime, Utc}, - number::{nonzero::U256 as NonZeroU256, serialization::HexOrDecimalU256}, + number::{nonzero::NonZeroU256, serialization::HexOrDecimalU256}, serde::{ Deserialize, Deserializer, @@ -162,7 +162,7 @@ pub enum OrderQuoteSide { impl Default for OrderQuoteSide { fn default() -> Self { Self::Buy { - buy_amount_after_fee: NonZeroU256::one(), + buy_amount_after_fee: NonZeroU256::ONE, } } } diff --git a/crates/number/Cargo.toml b/crates/number/Cargo.toml index ef84a0a375..2839bc5749 100644 --- a/crates/number/Cargo.toml +++ b/crates/number/Cargo.toml @@ -7,7 +7,7 @@ license = "MIT OR Apache-2.0" [dependencies] anyhow = { workspace = true } -alloy = { workspace = true } +alloy = { workspace = true, features = ["serde"] } bigdecimal = { workspace = true } num = { workspace = true } primitive-types = { workspace = true } diff --git a/crates/number/src/nonzero.rs b/crates/number/src/nonzero.rs index 36408f3a58..92daf2b1d2 100644 --- a/crates/number/src/nonzero.rs +++ b/crates/number/src/nonzero.rs @@ -1,36 +1,35 @@ use { + alloy::primitives::U256, anyhow::Context, - primitive_types::U256 as ZeroU256, serde::{Deserialize, Deserializer, Serialize, Serializer}, std::fmt::{self, Display, Formatter}, }; #[derive(Copy, Clone, Debug, Hash, Eq, PartialEq, Ord, PartialOrd)] -pub struct U256(ZeroU256); +pub struct NonZeroU256(U256); -impl U256 { - pub fn new(value: ZeroU256) -> Option { - (!value.is_zero()).then_some(Self(value)) - } +impl NonZeroU256 { + pub const MAX: Self = NonZeroU256(U256::MAX); + pub const ONE: Self = NonZeroU256(U256::ONE); - pub fn one() -> Self { - Self(ZeroU256::one()) + pub fn new(value: U256) -> Option { + (!value.is_zero()).then_some(Self(value)) } - pub fn get(&self) -> ZeroU256 { + pub fn get(self) -> U256 { self.0 } } -impl TryFrom for U256 { +impl TryFrom for NonZeroU256 { type Error = anyhow::Error; - fn try_from(value: ZeroU256) -> Result { + fn try_from(value: U256) -> Result { Self::new(value).context("Value cannot be zero!") } } -impl Serialize for U256 { +impl Serialize for NonZeroU256 { fn serialize(&self, serializer: S) -> Result where S: Serializer, @@ -39,38 +38,37 @@ impl Serialize for U256 { } } -impl<'de> Deserialize<'de> for U256 { +impl<'de> Deserialize<'de> for NonZeroU256 { fn deserialize(deserializer: D) -> Result where D: Deserializer<'de>, { - let s = String::deserialize(deserializer)?; - let u256_val = ZeroU256::from_dec_str(&s).map_err(serde::de::Error::custom)?; - U256::try_from(u256_val).map_err(serde::de::Error::custom) + let u256 = U256::deserialize(deserializer)?; + NonZeroU256::try_from(u256).map_err(serde::de::Error::custom) } } -impl TryFrom for U256 { +impl TryFrom for NonZeroU256 { type Error = anyhow::Error; fn try_from(value: u128) -> Result { - U256::try_from(ZeroU256::from(value)) + NonZeroU256::try_from(U256::from(value)) } } -impl Default for U256 { +impl Default for NonZeroU256 { fn default() -> Self { - Self(ZeroU256::one()) + Self::ONE } } -impl From for ZeroU256 { - fn from(val: U256) -> Self { +impl From for U256 { + fn from(val: NonZeroU256) -> Self { val.0 } } -impl Display for U256 { +impl Display for NonZeroU256 { fn fmt(&self, f: &mut Formatter) -> fmt::Result { Display::fmt(&self.0, f) } diff --git a/crates/orderbook/src/api/post_quote.rs b/crates/orderbook/src/api/post_quote.rs index ce8d9d2b75..a2dbfbf2e9 100644 --- a/crates/orderbook/src/api/post_quote.rs +++ b/crates/orderbook/src/api/post_quote.rs @@ -104,7 +104,7 @@ mod tests { Validity, }, }, - number::nonzero::U256 as NonZeroU256, + number::nonzero::NonZeroU256, reqwest::StatusCode, serde_json::json, shared::order_quoting::CalculateQuoteError, diff --git a/crates/orderbook/src/quoter.rs b/crates/orderbook/src/quoter.rs index 7b274d4d60..7487ccc100 100644 --- a/crates/orderbook/src/quoter.rs +++ b/crates/orderbook/src/quoter.rs @@ -254,14 +254,13 @@ mod tests { use { super::*, crate::arguments::FeeFactor, - alloy::primitives::U256, - ethrpc::alloy::conversions::IntoLegacy, + alloy::primitives::{U256, utils::Unit}, model::quote::OrderQuoteSide, shared::order_quoting::{Quote, QuoteData}, }; - fn to_wei(base: u32) -> U256 { - U256::from(base) * U256::from(10).pow(U256::from(18)) + fn eth(base: u32) -> U256 { + U256::from(base) * Unit::ETHER.wei() } fn create_test_quote(sell_amount: U256, buy_amount: U256) -> Quote { @@ -295,10 +294,10 @@ mod tests { }; // Selling 100 tokens, expecting to buy 100 tokens - let quote = create_test_quote(to_wei(100), to_wei(100)); + let quote = create_test_quote(eth(100), eth(100)); let side = OrderQuoteSide::Sell { sell_amount: model::quote::SellAmount::BeforeFee { - value: number::nonzero::U256::try_from(to_wei(100).into_legacy()).unwrap(), + value: number::nonzero::NonZeroU256::try_from(eth(100)).unwrap(), }, }; @@ -308,12 +307,12 @@ mod tests { // - sell_amount stays the same // - buy_amount is reduced by 0.02% of original buy_amount // - protocol_fee_bps = "2" - assert_eq!(result.sell_amount, to_wei(100)); + assert_eq!(result.sell_amount, eth(100)); assert_eq!(result.protocol_fee_bps, Some("2".to_string())); // buy_amount should be reduced by 0.02% // Expected: 100 - (100 * 0.0002) = 100 - 0.02 = 99.98 - let expected_buy = to_wei(100) - (to_wei(100) / U256::from(5000)); // 0.02% = 1/5000 + let expected_buy = eth(100) - (eth(100) / U256::from(5000)); // 0.02% = 1/5000 assert_eq!(result.buy_amount, expected_buy); } @@ -328,10 +327,9 @@ mod tests { }; // Buying 100 tokens, expecting to sell 100 tokens, with no network fee - let quote = create_test_quote(to_wei(100), to_wei(100)); + let quote = create_test_quote(eth(100), eth(100)); let side = OrderQuoteSide::Buy { - buy_amount_after_fee: number::nonzero::U256::try_from(to_wei(100).into_legacy()) - .unwrap(), + buy_amount_after_fee: number::nonzero::NonZeroU256::try_from(eth(100)).unwrap(), }; let result = get_adjusted_quote_data("e, Some(&volume_fee_config), &side).unwrap(); @@ -340,12 +338,12 @@ mod tests { // - buy_amount stays the same // - sell_amount is increased by 0.02% of original sell_amount // - protocol_fee_bps = "2" - assert_eq!(result.buy_amount, to_wei(100)); + assert_eq!(result.buy_amount, eth(100)); assert_eq!(result.protocol_fee_bps, Some("2".to_string())); // sell_amount should be increased by 0.02% of sell_amount (no network fee) // Expected: 100 + (100 * 0.0002) = 100 + 0.02 = 100.02 - let expected_sell = to_wei(100) + (to_wei(100) / U256::from(5000)); // 0.02% = 1/5000 + let expected_sell = eth(100) + (eth(100) / U256::from(5000)); // 0.02% = 1/5000 assert_eq!(result.sell_amount, expected_sell); } @@ -358,11 +356,10 @@ mod tests { }; // Buying 100 tokens, expecting to sell 100 tokens, with 5 token network fee - let mut quote = create_test_quote(to_wei(100), to_wei(100)); - quote.fee_amount = to_wei(5); // Network fee in sell token + let mut quote = create_test_quote(eth(100), eth(100)); + quote.fee_amount = eth(5); // Network fee in sell token let side = OrderQuoteSide::Buy { - buy_amount_after_fee: number::nonzero::U256::try_from(to_wei(100).into_legacy()) - .unwrap(), + buy_amount_after_fee: number::nonzero::NonZeroU256::try_from(eth(100)).unwrap(), }; let result = get_adjusted_quote_data("e, Some(&volume_fee_config), &side).unwrap(); @@ -371,16 +368,16 @@ mod tests { // - buy_amount stays the same // - protocol fee is calculated on (sell_amount + network_fee) // - sell_amount is increased by protocol fee - assert_eq!(result.buy_amount, to_wei(100)); + assert_eq!(result.buy_amount, eth(100)); assert_eq!(result.protocol_fee_bps, Some("2".to_string())); // Total volume = sell_amount + network_fee = 100 + 5 = 105 // Protocol fee = 105 * 0.0002 = 0.021 // sell_amount should be increased by protocol fee // Expected: 100 + 0.021 = 100.021 - let total_volume = to_wei(100) + to_wei(5); // 105 + let total_volume = eth(100) + eth(5); // 105 let expected_protocol_fee = total_volume / U256::from(5000); // 0.021 - let expected_sell = to_wei(100) + expected_protocol_fee; // 100.021 + let expected_sell = eth(100) + expected_protocol_fee; // 100.021 assert_eq!(result.sell_amount, expected_sell); } @@ -393,20 +390,20 @@ mod tests { }; // Selling 100 tokens, expecting to buy 200 tokens (2:1 price ratio) - let quote = create_test_quote(to_wei(100), to_wei(200)); + let quote = create_test_quote(eth(100), eth(200)); let side = OrderQuoteSide::Sell { sell_amount: model::quote::SellAmount::BeforeFee { - value: number::nonzero::U256::try_from(to_wei(100).into_legacy()).unwrap(), + value: number::nonzero::NonZeroU256::try_from(eth(100)).unwrap(), }, }; let result = get_adjusted_quote_data("e, Some(&volume_fee_config), &side).unwrap(); assert_eq!(result.protocol_fee_bps, Some("10".to_string())); - assert_eq!(result.sell_amount, to_wei(100)); + assert_eq!(result.sell_amount, eth(100)); // buy_amount reduced by 0.1% of 200 = 0.2 tokens - let expected_buy = to_wei(200) - (to_wei(200) / U256::from(1000)); + let expected_buy = eth(200) - (eth(200) / U256::from(1000)); assert_eq!(result.buy_amount, expected_buy); } @@ -427,10 +424,10 @@ mod tests { effective_from_timestamp: None, }; - let quote = create_test_quote(to_wei(100), to_wei(100)); + let quote = create_test_quote(eth(100), eth(100)); let side = OrderQuoteSide::Sell { sell_amount: model::quote::SellAmount::BeforeFee { - value: number::nonzero::U256::try_from(to_wei(100).into_legacy()).unwrap(), + value: number::nonzero::NonZeroU256::try_from(eth(100)).unwrap(), }, }; @@ -450,18 +447,18 @@ mod tests { }; // Selling 100 tokens, expecting to buy 100 tokens - let quote = create_test_quote(to_wei(100), to_wei(100)); + let quote = create_test_quote(eth(100), eth(100)); let side = OrderQuoteSide::Sell { sell_amount: model::quote::SellAmount::BeforeFee { - value: number::nonzero::U256::try_from(to_wei(100).into_legacy()).unwrap(), + value: number::nonzero::NonZeroU256::try_from(eth(100)).unwrap(), }, }; let result = get_adjusted_quote_data("e, Some(&volume_fee_config), &side).unwrap(); // Since the effective date is in the future, no volume fee should be applied - assert_eq!(result.sell_amount, to_wei(100)); - assert_eq!(result.buy_amount, to_wei(100)); + assert_eq!(result.sell_amount, eth(100)); + assert_eq!(result.buy_amount, eth(100)); assert_eq!(result.protocol_fee_bps, None); } } diff --git a/crates/shared/src/encoded_settlement.rs b/crates/shared/src/encoded_settlement.rs index 5d41fa7563..bfb64135f8 100644 --- a/crates/shared/src/encoded_settlement.rs +++ b/crates/shared/src/encoded_settlement.rs @@ -31,7 +31,7 @@ pub fn encode_trade( owner: H160, sell_token_index: usize, buy_token_index: usize, - executed_amount: &U256, + executed_amount: U256, ) -> EncodedTrade { ( sell_token_index.into(), @@ -43,7 +43,7 @@ pub fn encode_trade( Bytes(order.app_data.0), order.fee_amount.into_legacy(), order_flags(order, signature), - *executed_amount, + executed_amount, Bytes(signature.encode_for_settlement(owner).to_vec()), ) } @@ -210,7 +210,7 @@ mod tests { owner, Default::default(), Default::default(), - &Default::default(), + Default::default(), ); assert_eq!(encoded_signature.0, bytes); } diff --git a/crates/shared/src/order_quoting.rs b/crates/shared/src/order_quoting.rs index 2f63570e5f..e133985f2d 100644 --- a/crates/shared/src/order_quoting.rs +++ b/crates/shared/src/order_quoting.rs @@ -492,10 +492,10 @@ impl OrderQuoter { } | OrderQuoteSide::Sell { sell_amount: SellAmount::AfterFee { value: sell_amount }, - } => (sell_amount.get().into_alloy(), trade_estimate.out_amount), + } => (sell_amount.get(), trade_estimate.out_amount), OrderQuoteSide::Buy { buy_amount_after_fee: buy_amount, - } => (trade_estimate.out_amount, buy_amount.get().into_alloy()), + } => (trade_estimate.out_amount, buy_amount.get()), }; let fee_parameters = FeeParameters { gas_amount: trade_estimate.gas as _, @@ -617,7 +617,6 @@ impl OrderQuoting for OrderQuoter { { let sell_amount = sell_amount_before_fee .get() - .into_alloy() .saturating_sub(quote.fee_amount); if sell_amount.is_zero() { // We want a sell_amount of at least 1! @@ -807,7 +806,7 @@ mod tests { gas_estimation::GasPrice1559, mockall::{Sequence, predicate::eq}, model::time, - number::nonzero::U256 as NonZeroU256, + number::nonzero::NonZeroU256, }; fn mock_balance_fetcher() -> Arc { diff --git a/crates/shared/src/order_validation.rs b/crates/shared/src/order_validation.rs index efc7845d25..e5c51ad7d7 100644 --- a/crates/shared/src/order_validation.rs +++ b/crates/shared/src/order_validation.rs @@ -904,7 +904,6 @@ async fn get_or_create_quote( OrderKind::Buy => OrderQuoteSide::Buy { buy_amount_after_fee: quote_search_parameters .buy_amount - .into_legacy() .try_into() .map_err(|_| ValidationError::ZeroAmount)?, }, @@ -912,7 +911,6 @@ async fn get_or_create_quote( sell_amount: SellAmount::AfterFee { value: quote_search_parameters .sell_amount - .into_legacy() .try_into() .map_err(|_| ValidationError::ZeroAmount)?, }, @@ -1034,7 +1032,7 @@ mod tests { quote::default_verification_gas_limit, signature::{EcdsaSignature, EcdsaSigningScheme}, }, - number::nonzero::U256 as NonZeroU256, + number::nonzero::NonZeroU256, serde_json::json, std::str::FromStr, }; @@ -2320,10 +2318,7 @@ mod tests { buy_token: quote_search_parameters.buy_token, side: OrderQuoteSide::Sell { sell_amount: SellAmount::AfterFee { - value: NonZeroU256::try_from( - quote_search_parameters.sell_amount.into_legacy(), - ) - .unwrap(), + value: NonZeroU256::new(quote_search_parameters.sell_amount).unwrap(), }, }, verification, diff --git a/crates/shared/src/price_estimation/competition/mod.rs b/crates/shared/src/price_estimation/competition/mod.rs index 41722a2f05..8a692bff13 100644 --- a/crates/shared/src/price_estimation/competition/mod.rs +++ b/crates/shared/src/price_estimation/competition/mod.rs @@ -252,7 +252,7 @@ mod tests { anyhow::anyhow, futures::channel::oneshot::channel, model::order::OrderKind, - number::nonzero::U256 as NonZeroU256, + number::nonzero::NonZeroU256, std::time::Duration, tokio::time::sleep, }; diff --git a/crates/shared/src/price_estimation/factory.rs b/crates/shared/src/price_estimation/factory.rs index 3e99ae703b..708cdef357 100644 --- a/crates/shared/src/price_estimation/factory.rs +++ b/crates/shared/src/price_estimation/factory.rs @@ -30,9 +30,9 @@ use { alloy::primitives::Address, anyhow::{Context as _, Result}, contracts::alloy::WETH9, - ethrpc::{alloy::conversions::IntoLegacy, block_stream::CurrentBlockWatcher}, + ethrpc::block_stream::CurrentBlockWatcher, gas_estimation::GasPriceEstimating, - number::nonzero::U256 as NonZeroU256, + number::nonzero::NonZeroU256, rate_limit::RateLimiter, reqwest::Url, std::{collections::HashMap, num::NonZeroUsize, sync::Arc}, @@ -125,16 +125,11 @@ impl<'a> PriceEstimatorFactory<'a> { } fn native_token_price_estimation_amount(&self) -> Result { - NonZeroU256::try_from( - self.args - .amount_to_estimate_prices_with - .unwrap_or_else(|| { - self.network - .chain - .default_amount_to_estimate_native_prices_with() - }) - .into_legacy(), - ) + NonZeroU256::try_from(self.args.amount_to_estimate_prices_with.unwrap_or_else(|| { + self.network + .chain + .default_amount_to_estimate_native_prices_with() + })) } fn rate_limiter(&self, name: &str) -> Arc { diff --git a/crates/shared/src/price_estimation/instrumented.rs b/crates/shared/src/price_estimation/instrumented.rs index 91ab34223c..ec95ab11d8 100644 --- a/crates/shared/src/price_estimation/instrumented.rs +++ b/crates/shared/src/price_estimation/instrumented.rs @@ -132,7 +132,7 @@ mod tests { alloy::primitives::Address, anyhow::anyhow, model::order::OrderKind, - number::nonzero::U256 as NonZeroU256, + number::nonzero::NonZeroU256, }; #[tokio::test] diff --git a/crates/shared/src/price_estimation/mod.rs b/crates/shared/src/price_estimation/mod.rs index f9c37e4dd0..065780f7fb 100644 --- a/crates/shared/src/price_estimation/mod.rs +++ b/crates/shared/src/price_estimation/mod.rs @@ -8,11 +8,10 @@ use { anyhow::{Result, ensure}, bigdecimal::BigDecimal, ethcontract::H160, - ethrpc::alloy::conversions::IntoAlloy, futures::future::BoxFuture, itertools::Itertools, model::order::{BuyTokenDestination, OrderKind, SellTokenSource}, - number::nonzero::U256 as NonZeroU256, + number::nonzero::NonZeroU256, rate_limit::{RateLimiter, Strategy}, reqwest::Url, serde::{Deserialize, Serialize}, @@ -543,8 +542,8 @@ impl Estimate { /// Returns (sell_amount, buy_amount). pub fn amounts(&self, query: &Query) -> (U256, U256) { match query.kind { - OrderKind::Buy => (self.out_amount, query.in_amount.get().into_alloy()), - OrderKind::Sell => (query.in_amount.get().into_alloy(), self.out_amount), + OrderKind::Buy => (self.out_amount, query.in_amount.get()), + OrderKind::Sell => (query.in_amount.get(), self.out_amount), } } diff --git a/crates/shared/src/price_estimation/native/mod.rs b/crates/shared/src/price_estimation/native/mod.rs index 0b18d6fefd..23702c8ac5 100644 --- a/crates/shared/src/price_estimation/native/mod.rs +++ b/crates/shared/src/price_estimation/native/mod.rs @@ -4,7 +4,7 @@ use { bigdecimal::{BigDecimal, ToPrimitive}, futures::FutureExt, model::order::OrderKind, - number::nonzero::U256 as NonZeroU256, + number::nonzero::NonZeroU256, std::{ sync::{Arc, LazyLock}, time::Duration, @@ -123,7 +123,6 @@ mod tests { super::*, crate::price_estimation::{Estimate, HEALTHY_PRICE_ESTIMATION_TIME, MockPriceEstimating}, alloy::primitives::{Address, U256}, - ethrpc::alloy::conversions::IntoLegacy, primitive_types::H160, std::str::FromStr, }; @@ -149,10 +148,8 @@ mod tests { let native_price_estimator = NativePriceEstimator { inner: Arc::new(inner), native_token: Address::with_last_byte(7), - price_estimation_amount: NonZeroU256::try_from( - U256::from(10).pow(U256::from(18)).into_legacy(), - ) - .unwrap(), + price_estimation_amount: NonZeroU256::try_from(U256::from(10).pow(U256::from(18))) + .unwrap(), }; let result = native_price_estimator @@ -173,10 +170,8 @@ mod tests { let native_price_estimator = NativePriceEstimator { inner: Arc::new(inner), native_token: Address::with_last_byte(7), - price_estimation_amount: NonZeroU256::try_from( - U256::from(10).pow(U256::from(18)).into_legacy(), - ) - .unwrap(), + price_estimation_amount: NonZeroU256::try_from(U256::from(10).pow(U256::from(18))) + .unwrap(), }; let result = native_price_estimator diff --git a/crates/shared/src/price_estimation/sanitized.rs b/crates/shared/src/price_estimation/sanitized.rs index 6144340bb9..0980ef305c 100644 --- a/crates/shared/src/price_estimation/sanitized.rs +++ b/crates/shared/src/price_estimation/sanitized.rs @@ -11,7 +11,6 @@ use { }, alloy::primitives::Address, anyhow::anyhow, - ethrpc::alloy::conversions::IntoAlloy, futures::FutureExt, model::order::BUY_ETH_ADDRESS, std::sync::Arc, @@ -66,7 +65,7 @@ impl PriceEstimating for SanitizedPriceEstimator { // buy_token == sell_token => 1 to 1 conversion if query.buy_token == query.sell_token { let estimation = Estimate { - out_amount: query.in_amount.get().into_alloy(), + out_amount: query.in_amount.get(), gas: 0, solver: Default::default(), verified: true, @@ -79,7 +78,7 @@ impl PriceEstimating for SanitizedPriceEstimator { // sell WETH for ETH => 1 to 1 conversion with cost for unwrapping if query.sell_token == self.native_token && query.buy_token == BUY_ETH_ADDRESS { let estimation = Estimate { - out_amount: query.in_amount.get().into_alloy(), + out_amount: query.in_amount.get(), gas: GAS_PER_WETH_UNWRAP, solver: Default::default(), verified: true, @@ -92,7 +91,7 @@ impl PriceEstimating for SanitizedPriceEstimator { // sell ETH for WETH => 1 to 1 conversion with cost for wrapping if query.sell_token == BUY_ETH_ADDRESS && query.buy_token == self.native_token { let estimation = Estimate { - out_amount: query.in_amount.get().into_alloy(), + out_amount: query.in_amount.get(), gas: GAS_PER_WETH_WRAP, solver: Default::default(), verified: true, @@ -153,19 +152,17 @@ mod tests { price_estimation::{HEALTHY_PRICE_ESTIMATION_TIME, MockPriceEstimating}, }, alloy::primitives::{Address, U256 as AlloyU256}, - ethrpc::alloy::conversions::IntoAlloy, model::order::OrderKind, - number::nonzero::U256 as NonZeroU256, - primitive_types::{H160, U256}, + number::nonzero::NonZeroU256, }; - const BAD_TOKEN: H160 = H160([0x12; 20]); + const BAD_TOKEN: Address = Address::repeat_byte(0x12); #[tokio::test] async fn handles_trivial_estimates_on_its_own() { let mut bad_token_detector = MockBadTokenDetecting::new(); bad_token_detector.expect_detect().returning(|token| { - if token == BAD_TOKEN.into_alloy() { + if token == BAD_TOKEN { Ok(TokenQuality::Bad { reason: "Token not supported".into(), }) @@ -226,7 +223,7 @@ mod tests { verification: Default::default(), sell_token: Address::with_last_byte(1), buy_token: BUY_ETH_ADDRESS, - in_amount: NonZeroU256::try_from(U256::MAX).unwrap(), + in_amount: NonZeroU256::MAX, kind: OrderKind::Buy, block_dependent: false, timeout: HEALTHY_PRICE_ESTIMATION_TIME, @@ -341,7 +338,7 @@ mod tests { ( Query { verification: Default::default(), - sell_token: BAD_TOKEN.into_alloy(), + sell_token: BAD_TOKEN, buy_token: Address::with_last_byte(1), in_amount: NonZeroU256::try_from(1).unwrap(), kind: OrderKind::Buy, @@ -349,7 +346,7 @@ mod tests { timeout: HEALTHY_PRICE_ESTIMATION_TIME, }, Err(PriceEstimationError::UnsupportedToken { - token: BAD_TOKEN.into_alloy(), + token: BAD_TOKEN, reason: "".to_string(), }), ), @@ -358,14 +355,14 @@ mod tests { Query { verification: Default::default(), sell_token: Address::with_last_byte(1), - buy_token: BAD_TOKEN.into_alloy(), + buy_token: BAD_TOKEN, in_amount: NonZeroU256::try_from(1).unwrap(), kind: OrderKind::Buy, block_dependent: false, timeout: HEALTHY_PRICE_ESTIMATION_TIME, }, Err(PriceEstimationError::UnsupportedToken { - token: BAD_TOKEN.into_alloy(), + token: BAD_TOKEN, reason: "".to_string(), }), ), diff --git a/crates/shared/src/price_estimation/trade_verifier/mod.rs b/crates/shared/src/price_estimation/trade_verifier/mod.rs index f3582b97e5..47c89577a2 100644 --- a/crates/shared/src/price_estimation/trade_verifier/mod.rs +++ b/crates/shared/src/price_estimation/trade_verifier/mod.rs @@ -39,7 +39,7 @@ use { num::BigRational, number::{ conversions::{big_decimal_to_big_rational, u256_to_big_rational}, - nonzero::U256 as NonZeroU256, + nonzero::NonZeroU256, }, std::{ collections::{HashMap, HashSet}, @@ -137,10 +137,10 @@ impl TradeVerifier { let tokens = vec![query.sell_token, query.buy_token]; let prices = match query.kind { OrderKind::Sell => { - vec![*out_amount, query.in_amount.get().into_alloy()] + vec![*out_amount, query.in_amount.get()] } OrderKind::Buy => { - vec![query.in_amount.get().into_alloy(), *out_amount] + vec![query.in_amount.get(), *out_amount] } }; (tokens, prices) @@ -240,8 +240,8 @@ impl TradeVerifier { // settlement buffers to make the quote happen. When the settlement contract // itself is the trader or receiver these values need to be adjusted slightly. let (sell_amount, buy_amount) = match query.kind { - OrderKind::Sell => (query.in_amount.get().into_alloy(), summary.out_amount), - OrderKind::Buy => (summary.out_amount, query.in_amount.get().into_alloy()), + OrderKind::Sell => (query.in_amount.get(), summary.out_amount), + OrderKind::Buy => (summary.out_amount, query.in_amount.get()), }; // It looks like the contract lost a lot of sell tokens but only because it was @@ -309,12 +309,12 @@ impl TradeVerifier { token: query.sell_token.into_legacy(), holder: Self::SPARDOSE.into_legacy(), amount: match query.kind { - OrderKind::Sell => query.in_amount.get(), + OrderKind::Sell => query.in_amount.get().into_legacy(), OrderKind::Buy => trade .out_amount( &query.buy_token, &query.sell_token, - &query.in_amount.get().into_alloy(), + &query.in_amount.get(), &query.kind, )? .into_legacy(), @@ -467,7 +467,7 @@ impl TradeVerifying for TradeVerifier { .out_amount( &query.buy_token, &query.sell_token, - &query.in_amount.get().into_alloy(), + &query.in_amount.get(), &query.kind, ) .context("failed to compute trade out amount")?; @@ -536,7 +536,7 @@ fn encode_settlement( // ourselves here. let buy_amount = match query.kind { OrderKind::Sell => *out_amount, - OrderKind::Buy => query.in_amount.get().into_alloy(), + OrderKind::Buy => query.in_amount.get(), }; trade_interactions.push(( native_token, @@ -565,7 +565,7 @@ fn encode_settlement( // with helpful error messages. let trade_setup_interaction = { let sell_amount = match query.kind { - OrderKind::Sell => query.in_amount.get().into_alloy(), + OrderKind::Sell => query.in_amount.get(), OrderKind::Buy => *out_amount, }; let solver_address = trade.solver(); @@ -614,13 +614,10 @@ fn encode_fake_trade( // the [`Trade`] the simulation will still work and we can compute the actual // [`Trade::out_amount`] afterwards. let (sell_amount, buy_amount) = match query.kind { - OrderKind::Sell => ( - query.in_amount.get().into_alloy(), - alloy::primitives::U256::ZERO, - ), + OrderKind::Sell => (query.in_amount.get(), alloy::primitives::U256::ZERO), OrderKind::Buy => ( (*out_amount).max(alloy::primitives::U256::from(u128::MAX)), - query.in_amount.get().into_alloy(), + query.in_amount.get(), ), }; let fake_order = OrderData { @@ -652,7 +649,7 @@ fn encode_fake_trade( .iter() .position(|token| token == &query.buy_token) .context("missing buy token index")?, - &query.in_amount.get(), + query.in_amount.get().into_legacy(), ); Ok(encoded_trade) @@ -699,7 +696,7 @@ fn encode_jit_orders( .iter() .position(|token| token.into_legacy() == jit_order.buy_token) .context("missing jit order buy token index")?, - &jit_order.executed_amount, + jit_order.executed_amount, )) }) .collect::, Error>>() @@ -850,8 +847,8 @@ fn ensure_quote_accuracy( ) -> std::result::Result { // amounts verified by the simulation let (sell_amount, buy_amount) = match query.kind { - OrderKind::Buy => (summary.out_amount, query.in_amount.get().into_alloy()), - OrderKind::Sell => (query.in_amount.get().into_alloy(), summary.out_amount), + OrderKind::Buy => (summary.out_amount, query.in_amount.get()), + OrderKind::Sell => (query.in_amount.get(), summary.out_amount), }; let (sell_amount, buy_amount) = ( number::conversions::alloy::u256_to_big_rational(&sell_amount), diff --git a/crates/shared/src/trade_finding/external.rs b/crates/shared/src/trade_finding/external.rs index 00da7f7771..5d5962dc49 100644 --- a/crates/shared/src/trade_finding/external.rs +++ b/crates/shared/src/trade_finding/external.rs @@ -61,7 +61,7 @@ impl ExternalTradeFinder { let order = dto::Order { sell_token: query.sell_token.into_legacy(), buy_token: query.buy_token.into_legacy(), - amount: query.in_amount.get(), + amount: query.in_amount.get().into_legacy(), kind: query.kind, deadline: chrono::Utc::now() + query.timeout, }; @@ -219,7 +219,7 @@ impl TradeFinding for ExternalTradeFinder { .out_amount( &query.buy_token, &query.sell_token, - &query.in_amount.get().into_alloy(), + &query.in_amount.get(), &query.kind, ) .map_err(TradeError::Other)?, diff --git a/crates/solver/src/settlement/mod.rs b/crates/solver/src/settlement/mod.rs index b46798ee55..50870bc999 100644 --- a/crates/solver/src/settlement/mod.rs +++ b/crates/solver/src/settlement/mod.rs @@ -94,7 +94,7 @@ impl Trade { self.order.metadata.owner.into_legacy(), sell_token_index, buy_token_index, - &self.executed_amount.into_legacy(), + self.executed_amount.into_legacy(), ) } }