From 016bdf613884e7883a1da788a0f33dc6ef8568ef Mon Sep 17 00:00:00 2001 From: ilya Date: Thu, 4 Apr 2024 15:43:02 +0100 Subject: [PATCH 1/8] Use services/solver-dto --- Cargo.lock | 62 +++- Cargo.toml | 1 + src/api/routes/solve/dto/auction.rs | 452 ++++++++------------------- src/api/routes/solve/dto/mod.rs | 6 +- src/api/routes/solve/dto/solution.rs | 438 +++++++------------------- src/api/routes/solve/mod.rs | 6 +- 6 files changed, 293 insertions(+), 672 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 3049b1f..6fd27c4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1260,7 +1260,7 @@ dependencies = [ "ethcontract", "hex", "mockall", - "predicates 3.0.4", + "predicates 3.1.0", "rlp", ] @@ -1588,7 +1588,7 @@ dependencies = [ "futures-sink", "futures-util", "http", - "indexmap 2.1.0", + "indexmap 2.2.6", "slab", "tokio", "tokio-util 0.7.10", @@ -1942,9 +1942,9 @@ dependencies = [ [[package]] name = "indexmap" -version = "2.1.0" +version = "2.2.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d530e1a18b1cb4c484e6e34556a0d948706958449fca0cab753d649f2bce3d1f" +checksum = "168fb715dda47215e360912c096649d23d58bf392ac62f73919e831745e40f26" dependencies = [ "equivalent", "hashbrown 0.14.3", @@ -2213,7 +2213,7 @@ dependencies = [ "lazy_static", "maplit", "num", - "number", + "number 0.1.0 (git+https://github.com/cowprotocol/services.git?tag=v2.237.0)", "primitive-types", "secp256k1", "serde", @@ -2394,6 +2394,19 @@ dependencies = [ "serde_with", ] +[[package]] +name = "number" +version = "0.1.0" +source = "git+https://github.com/cowprotocol/services.git?tag=v2.252.0#5430414e90bc3cd121e0f307093ac4adccc675b6" +dependencies = [ + "anyhow", + "bigdecimal", + "num", + "primitive-types", + "serde", + "serde_with", +] + [[package]] name = "object" version = "0.32.1" @@ -2645,14 +2658,13 @@ dependencies = [ [[package]] name = "predicates" -version = "3.0.4" +version = "3.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6dfc28575c2e3f19cb3c73b93af36460ae898d426eba6fc15b9bd2a5220758a0" +checksum = "68b87bfd4605926cdfefc1c3b5f8fe560e3feca9d5552cf68c466d3d8236c7e8" dependencies = [ "anstyle", "difflib", "float-cmp", - "itertools 0.11.0", "normalize-line-endings", "predicates-core", "regex", @@ -3184,16 +3196,17 @@ dependencies = [ [[package]] name = "serde_with" -version = "3.4.0" +version = "3.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "64cd236ccc1b7a29e7e2739f27c0b2dd199804abc4290e32f59f3b68d6405c23" +checksum = "ee80b0e361bbf88fd2f6e242ccd19cfda072cb0faa6ae694ecee08199938569a" dependencies = [ "base64 0.21.5", "chrono", "hex", "indexmap 1.9.3", - "indexmap 2.1.0", + "indexmap 2.2.6", "serde", + "serde_derive", "serde_json", "serde_with_macros", "time", @@ -3201,9 +3214,9 @@ dependencies = [ [[package]] name = "serde_with_macros" -version = "3.4.0" +version = "3.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "93634eb5f75a2323b16de4748022ac4297f9e76b6dced2be287a099f41b5e788" +checksum = "6561dc161a9224638a31d876ccdfefbc1df91d3f3a8342eddb35f055d48c7655" dependencies = [ "darling", "proc-macro2", @@ -3296,7 +3309,7 @@ dependencies = [ "mockall", "model", "num", - "number", + "number 0.1.0 (git+https://github.com/cowprotocol/services.git?tag=v2.237.0)", "observe", "primitive-types", "prometheus", @@ -3415,6 +3428,7 @@ dependencies = [ "serde_json", "serde_with", "shared", + "solvers-dto", "tempfile", "thiserror", "tokio", @@ -3425,6 +3439,20 @@ dependencies = [ "web3", ] +[[package]] +name = "solvers-dto" +version = "0.1.0" +source = "git+https://github.com/cowprotocol/services.git?tag=v2.252.0#5430414e90bc3cd121e0f307093ac4adccc675b6" +dependencies = [ + "bigdecimal", + "chrono", + "hex", + "number 0.1.0 (git+https://github.com/cowprotocol/services.git?tag=v2.252.0)", + "serde", + "serde_with", + "web3", +] + [[package]] name = "spin" version = "0.5.2" @@ -3498,7 +3526,7 @@ dependencies = [ "futures-util", "hashlink", "hex", - "indexmap 2.1.0", + "indexmap 2.2.6", "log", "memchr", "native-tls", @@ -3995,7 +4023,7 @@ version = "0.19.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1b5bb770da30e5cbfde35a2d7b9b8a2c4b8ef89548a7a6aeab5c9a576e3e7421" dependencies = [ - "indexmap 2.1.0", + "indexmap 2.2.6", "serde", "serde_spanned", "toml_datetime", @@ -4008,7 +4036,7 @@ version = "0.20.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "70f427fce4d84c72b5b732388bf4a9f4531b53f74e2887e3ecb2481f68f66d81" dependencies = [ - "indexmap 2.1.0", + "indexmap 2.2.6", "toml_datetime", "winnow", ] diff --git a/Cargo.toml b/Cargo.toml index 30e039a..c22c57f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -44,6 +44,7 @@ contracts = { git = "https://github.com/cowprotocol/services.git", tag = "v2.237 ethrpc = { git = "https://github.com/cowprotocol/services.git", tag = "v2.237.0", package = "ethrpc" } observe = { git = "https://github.com/cowprotocol/services.git", tag = "v2.237.0", package = "observe" } shared = { git = "https://github.com/cowprotocol/services.git", tag = "v2.237.0", package = "shared" } +dto = { git = "https://github.com/cowprotocol/services.git", tag = "v2.252.0", package = "solvers-dto" } [dev-dependencies] glob = "0.3" diff --git a/src/api/routes/solve/dto/auction.rs b/src/api/routes/solve/dto/auction.rs index e761b87..8f4bbf9 100644 --- a/src/api/routes/solve/dto/auction.rs +++ b/src/api/routes/solve/dto/auction.rs @@ -2,213 +2,94 @@ use { crate::{ api::routes::Error, domain::{auction, eth, liquidity, order}, - util::{conv, serialize}, + util::conv, }, - bigdecimal::BigDecimal, - ethereum_types::{H160, H256, U256}, - itertools::Itertools as _, - serde::Deserialize, - serde_with::{serde_as, DisplayFromStr}, - std::collections::HashMap, + dto::auction::*, + itertools::Itertools, }; -impl Auction { - /// Converts a data transfer object into its domain object representation. - pub fn to_domain(&self) -> Result { - Ok(auction::Auction { - id: match self.id { - Some(id) => auction::Id::Solve(id), - None => auction::Id::Quote, - }, - tokens: auction::Tokens( - self.tokens - .iter() - .map(|(address, token)| { - ( - eth::TokenAddress(*address), - auction::Token { - decimals: token.decimals, - symbol: token.symbol.clone(), - reference_price: token - .reference_price - .map(eth::Ether) - .map(auction::Price), - available_balance: token.available_balance, - trusted: token.trusted, - }, - ) - }) - .collect(), - ), - orders: self - .orders +/// Converts a data transfer object into its domain object representation. +pub fn to_domain(auction: &Auction) -> Result { + Ok(auction::Auction { + id: match auction.id { + Some(id) => auction::Id::Solve(id), + None => auction::Id::Quote, + }, + tokens: auction::Tokens( + auction + .tokens .iter() - .map(|order| order::Order { - uid: order::Uid(order.uid), - sell: eth::Asset { - token: eth::TokenAddress(order.sell_token), - amount: order.sell_amount, - }, - buy: eth::Asset { - token: eth::TokenAddress(order.buy_token), - amount: order.buy_amount, - }, - side: match order.kind { - Kind::Buy => order::Side::Buy, - Kind::Sell => order::Side::Sell, - }, - class: match order.class { - Class::Market => order::Class::Market, - Class::Limit => order::Class::Limit, - Class::Liquidity => order::Class::Liquidity, - }, - fee: order::Fee(order.fee_amount), - partially_fillable: order.partially_fillable, + .map(|(address, token)| { + ( + eth::TokenAddress(*address), + auction::Token { + decimals: token.decimals, + symbol: token.symbol.clone(), + reference_price: token + .reference_price + .map(eth::Ether) + .map(auction::Price), + available_balance: token.available_balance, + trusted: token.trusted, + }, + ) }) .collect(), - liquidity: self - .liquidity - .iter() - .map(|liquidity| match liquidity { - Liquidity::ConstantProduct(liquidity) => liquidity.to_domain(), - Liquidity::WeightedProduct(liquidity) => liquidity.to_domain(), - Liquidity::Stable(liquidity) => liquidity.to_domain(), - Liquidity::ConcentratedLiquidity(liquidity) => liquidity.to_domain(), - Liquidity::LimitOrder(liquidity) => Ok(liquidity.to_domain()), - }) - .try_collect()?, - gas_price: auction::GasPrice(eth::Ether(self.effective_gas_price)), - deadline: auction::Deadline(self.deadline), - }) - } -} - -#[serde_as] -#[derive(Debug, Deserialize)] -#[serde(rename_all = "camelCase", deny_unknown_fields)] -pub struct Auction { - #[serde_as(as = "Option")] - id: Option, - tokens: HashMap, - orders: Vec, - liquidity: Vec, - #[serde_as(as = "serialize::U256")] - effective_gas_price: U256, - deadline: chrono::DateTime, -} - -#[serde_as] -#[derive(Debug, Deserialize)] -#[serde(rename_all = "camelCase", deny_unknown_fields)] -struct Order { - #[serde_as(as = "serialize::Hex")] - uid: [u8; 56], - sell_token: H160, - buy_token: H160, - #[serde_as(as = "serialize::U256")] - sell_amount: U256, - #[serde_as(as = "serialize::U256")] - buy_amount: U256, - #[serde_as(as = "serialize::U256")] - fee_amount: U256, - kind: Kind, - partially_fillable: bool, - class: Class, - fee_policies: Option>, -} - -#[serde_as] -#[derive(Clone, Debug, Deserialize)] -#[serde(rename_all = "camelCase")] -pub enum FeePolicy { - #[serde(rename_all = "camelCase")] - Surplus { factor: f64, max_volume_factor: f64 }, - #[serde(rename_all = "camelCase")] - PriceImprovement { - factor: f64, - max_volume_factor: f64, - quote: Quote, - }, - #[serde(rename_all = "camelCase")] - Volume { factor: f64 }, -} - -#[serde_as] -#[derive(Clone, Debug, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct Quote { - #[serde_as(as = "serialize::U256")] - pub sell_amount: eth::U256, - #[serde_as(as = "serialize::U256")] - pub buy_amount: eth::U256, - #[serde_as(as = "serialize::U256")] - pub fee: eth::U256, -} - -#[derive(Debug, Deserialize)] -#[serde(rename_all = "camelCase")] -enum Kind { - Sell, - Buy, -} - -#[derive(Debug, Deserialize)] -#[serde(rename_all = "camelCase")] -enum Class { - Market, - Limit, - Liquidity, -} - -#[serde_as] -#[derive(Debug, Deserialize)] -#[serde(rename_all = "camelCase", deny_unknown_fields)] -struct Token { - decimals: Option, - symbol: Option, - #[serde_as(as = "Option")] - reference_price: Option, - #[serde_as(as = "serialize::U256")] - available_balance: U256, - trusted: bool, -} - -#[allow(clippy::enum_variant_names)] -#[derive(Debug, Deserialize)] -#[serde(tag = "kind", rename_all = "camelCase", deny_unknown_fields)] -enum Liquidity { - ConstantProduct(ConstantProductPool), - WeightedProduct(WeightedProductPool), - Stable(StablePool), - ConcentratedLiquidity(ConcentratedLiquidityPool), - LimitOrder(ForeignLimitOrder), -} - -#[serde_as] -#[derive(Debug, Deserialize)] -#[serde(rename_all = "camelCase", deny_unknown_fields)] -struct ConstantProductPool { - id: String, - address: H160, - router: H160, - #[serde_as(as = "serialize::U256")] - gas_estimate: U256, - tokens: HashMap, - fee: BigDecimal, + ), + orders: auction + .orders + .iter() + .map(|order| order::Order { + uid: order::Uid(order.uid), + sell: eth::Asset { + token: eth::TokenAddress(order.sell_token), + amount: order.sell_amount, + }, + buy: eth::Asset { + token: eth::TokenAddress(order.buy_token), + amount: order.buy_amount, + }, + side: match order.kind { + Kind::Buy => order::Side::Buy, + Kind::Sell => order::Side::Sell, + }, + class: match order.class { + Class::Market => order::Class::Market, + Class::Limit => order::Class::Limit, + Class::Liquidity => order::Class::Liquidity, + }, + fee: order::Fee(order.fee_amount), + partially_fillable: order.partially_fillable, + }) + .collect(), + liquidity: auction + .liquidity + .iter() + .map(|liquidity| match liquidity { + Liquidity::ConstantProduct(liquidity) => { + constant_product_pool::to_domain(liquidity) + } + Liquidity::WeightedProduct(liquidity) => { + weighted_product_pool::to_domain(liquidity) + } + Liquidity::Stable(liquidity) => stable_pool::to_domain(liquidity), + Liquidity::ConcentratedLiquidity(liquidity) => { + concentrated_liquidity_pool::to_domain(liquidity) + } + Liquidity::LimitOrder(liquidity) => Ok(foreign_limit_order::to_domain(liquidity)), + }) + .try_collect()?, + gas_price: auction::GasPrice(eth::Ether(auction.effective_gas_price)), + deadline: auction::Deadline(auction.deadline), + }) } -#[serde_as] -#[derive(Debug, Deserialize)] -#[serde(rename_all = "camelCase", deny_unknown_fields)] -struct ConstantProductReserve { - #[serde_as(as = "serialize::U256")] - balance: U256, -} +mod constant_product_pool { + use {super::*, itertools::Itertools}; -impl ConstantProductPool { - fn to_domain(&self) -> Result { + pub fn to_domain(pool: &ConstantProductPool) -> Result { let reserves = { - let (a, b) = self + let (a, b) = pool .tokens .iter() .map(|(token, reserve)| eth::Asset { @@ -222,52 +103,22 @@ impl ConstantProductPool { }; Ok(liquidity::Liquidity { - id: liquidity::Id(self.id.clone()), - address: self.address, - gas: eth::Gas(self.gas_estimate), + id: liquidity::Id(pool.id.clone()), + address: pool.address, + gas: eth::Gas(pool.gas_estimate), state: liquidity::State::ConstantProduct(liquidity::constant_product::Pool { reserves, - fee: conv::decimal_to_rational(&self.fee).ok_or("invalid constant product fee")?, + fee: conv::decimal_to_rational(&pool.fee).ok_or("invalid constant product fee")?, }), }) } } -#[serde_as] -#[derive(Debug, Deserialize)] -#[serde(rename_all = "camelCase", deny_unknown_fields)] -struct WeightedProductPool { - id: String, - address: H160, - balancer_pool_id: H256, - #[serde_as(as = "serialize::U256")] - gas_estimate: U256, - tokens: HashMap, - fee: BigDecimal, - version: WeightedProductVersion, -} - -#[serde_as] -#[derive(Debug, Deserialize)] -#[serde(rename_all = "camelCase", deny_unknown_fields)] -struct WeightedProductReserve { - #[serde_as(as = "serialize::U256")] - balance: U256, - scaling_factor: BigDecimal, - weight: BigDecimal, -} - -#[derive(Debug, Deserialize)] -#[serde(rename_all = "camelCase")] -enum WeightedProductVersion { - V0, - V3Plus, -} - -impl WeightedProductPool { - fn to_domain(&self) -> Result { +mod weighted_product_pool { + use super::*; + pub fn to_domain(pool: &WeightedProductPool) -> Result { let reserves = { - let entries = self + let entries = pool .tokens .iter() .map(|(address, token)| { @@ -289,13 +140,13 @@ impl WeightedProductPool { }; Ok(liquidity::Liquidity { - id: liquidity::Id(self.id.clone()), - address: self.address, - gas: eth::Gas(self.gas_estimate), + id: liquidity::Id(pool.id.clone()), + address: pool.address, + gas: eth::Gas(pool.gas_estimate), state: liquidity::State::WeightedProduct(liquidity::weighted_product::Pool { reserves, - fee: conv::decimal_to_rational(&self.fee).ok_or("invalid weighted product fee")?, - version: match self.version { + fee: conv::decimal_to_rational(&pool.fee).ok_or("invalid weighted product fee")?, + version: match pool.version { WeightedProductVersion::V0 => liquidity::weighted_product::Version::V0, WeightedProductVersion::V3Plus => liquidity::weighted_product::Version::V3Plus, }, @@ -304,33 +155,12 @@ impl WeightedProductPool { } } -#[serde_as] -#[derive(Debug, Deserialize)] -#[serde(rename_all = "camelCase", deny_unknown_fields)] -struct StablePool { - id: String, - address: H160, - balancer_pool_id: H256, - #[serde_as(as = "serialize::U256")] - gas_estimate: U256, - tokens: HashMap, - amplification_parameter: BigDecimal, - fee: BigDecimal, -} - -#[serde_as] -#[derive(Debug, Deserialize)] -#[serde(rename_all = "camelCase", deny_unknown_fields)] -struct StableReserve { - #[serde_as(as = "serialize::U256")] - balance: U256, - scaling_factor: BigDecimal, -} +mod stable_pool { + use super::*; -impl StablePool { - fn to_domain(&self) -> Result { + pub fn to_domain(pool: &StablePool) -> Result { let reserves = { - let entries = self + let entries = pool .tokens .iter() .map(|(address, token)| { @@ -349,43 +179,25 @@ impl StablePool { }; Ok(liquidity::Liquidity { - id: liquidity::Id(self.id.clone()), - address: self.address, - gas: eth::Gas(self.gas_estimate), + id: liquidity::Id(pool.id.clone()), + address: pool.address, + gas: eth::Gas(pool.gas_estimate), state: liquidity::State::Stable(liquidity::stable::Pool { reserves, - amplification_parameter: conv::decimal_to_rational(&self.amplification_parameter) + amplification_parameter: conv::decimal_to_rational(&pool.amplification_parameter) .ok_or("invalid amplification parameter")?, - fee: conv::decimal_to_rational(&self.fee).ok_or("invalid stable pool fee")?, + fee: conv::decimal_to_rational(&pool.fee).ok_or("invalid stable pool fee")?, }), }) } } -#[serde_as] -#[derive(Debug, Deserialize)] -#[serde(rename_all = "camelCase", deny_unknown_fields)] -struct ConcentratedLiquidityPool { - id: String, - address: H160, - router: H160, - #[serde_as(as = "serialize::U256")] - gas_estimate: U256, - tokens: Vec, - #[serde_as(as = "serialize::U256")] - sqrt_price: U256, - #[serde_as(as = "DisplayFromStr")] - liquidity: u128, - tick: i32, - #[serde_as(as = "HashMap")] - liquidity_net: HashMap, - fee: BigDecimal, -} +mod concentrated_liquidity_pool { + use {super::*, itertools::Itertools}; -impl ConcentratedLiquidityPool { - fn to_domain(&self) -> Result { + pub fn to_domain(pool: &ConcentratedLiquidityPool) -> Result { let tokens = { - let (a, b) = self + let (a, b) = pool .tokens .iter() .copied() @@ -397,15 +209,15 @@ impl ConcentratedLiquidityPool { }; Ok(liquidity::Liquidity { - id: liquidity::Id(self.id.clone()), - address: self.address, - gas: eth::Gas(self.gas_estimate), + id: liquidity::Id(pool.id.clone()), + address: pool.address, + gas: eth::Gas(pool.gas_estimate), state: liquidity::State::Concentrated(liquidity::concentrated::Pool { tokens, - sqrt_price: liquidity::concentrated::SqrtPrice(self.sqrt_price), - liquidity: liquidity::concentrated::Amount(self.liquidity), - tick: liquidity::concentrated::Tick(self.tick), - liquidity_net: self + sqrt_price: liquidity::concentrated::SqrtPrice(pool.sqrt_price), + liquidity: liquidity::concentrated::Amount(pool.liquidity), + tick: liquidity::concentrated::Tick(pool.tick), + liquidity_net: pool .liquidity_net .iter() .map(|(tick, liquidity)| { @@ -416,7 +228,7 @@ impl ConcentratedLiquidityPool { }) .collect(), fee: liquidity::concentrated::Fee( - conv::decimal_to_rational(&self.fee) + conv::decimal_to_rational(&pool.fee) .ok_or("invalid concentrated liquidity pool fee")?, ), }), @@ -424,42 +236,24 @@ impl ConcentratedLiquidityPool { } } -#[serde_as] -#[derive(Debug, Deserialize)] -#[serde(rename_all = "camelCase", deny_unknown_fields)] -struct ForeignLimitOrder { - id: String, - address: H160, - #[serde_as(as = "serialize::U256")] - gas_estimate: U256, - #[serde_as(as = "serialize::Hex")] - hash: [u8; 32], - maker_token: H160, - taker_token: H160, - #[serde_as(as = "serialize::U256")] - maker_amount: U256, - #[serde_as(as = "serialize::U256")] - taker_amount: U256, - #[serde_as(as = "serialize::U256")] - taker_token_fee_amount: U256, -} +mod foreign_limit_order { + use super::*; -impl ForeignLimitOrder { - fn to_domain(&self) -> liquidity::Liquidity { + pub fn to_domain(order: &ForeignLimitOrder) -> liquidity::Liquidity { liquidity::Liquidity { - id: liquidity::Id(self.id.clone()), - address: self.address, - gas: eth::Gas(self.gas_estimate), + id: liquidity::Id(order.id.clone()), + address: order.address, + gas: eth::Gas(order.gas_estimate), state: liquidity::State::LimitOrder(liquidity::limit_order::LimitOrder { maker: eth::Asset { - token: eth::TokenAddress(self.maker_token), - amount: self.maker_amount, + token: eth::TokenAddress(order.maker_token), + amount: order.maker_amount, }, taker: eth::Asset { - token: eth::TokenAddress(self.taker_token), - amount: self.taker_amount, + token: eth::TokenAddress(order.taker_token), + amount: order.taker_amount, }, - fee: liquidity::limit_order::TakerAmount(self.taker_token_fee_amount), + fee: liquidity::limit_order::TakerAmount(order.taker_token_fee_amount), }), } } diff --git a/src/api/routes/solve/dto/mod.rs b/src/api/routes/solve/dto/mod.rs index 68e2866..67e611b 100644 --- a/src/api/routes/solve/dto/mod.rs +++ b/src/api/routes/solve/dto/mod.rs @@ -1,4 +1,4 @@ -mod auction; -mod solution; +pub mod auction; +pub mod solution; -pub use self::{auction::Auction, solution::Solutions}; +pub use dto::{auction::Auction, solution::Solutions}; diff --git a/src/api/routes/solve/dto/solution.rs b/src/api/routes/solve/dto/solution.rs index 99a237d..3923dfd 100644 --- a/src/api/routes/solve/dto/solution.rs +++ b/src/api/routes/solve/dto/solution.rs @@ -1,326 +1,126 @@ use { - crate::{ - domain::{order, solution}, - util::serialize, - }, - ethereum_types::{H160, U256}, - serde::Serialize, - serde_with::serde_as, - std::collections::HashMap, + crate::domain::{order, solution}, + dto::solution::*, }; -impl Solutions { - /// Creates a new solution DTO from its domain object. - pub fn from_domain(solutions: &[solution::Solution]) -> Self { - Self { - solutions: solutions - .iter() - .map(|solution| Solution { - id: solution.id.0, - prices: solution - .prices - .0 - .iter() - .map(|(token, price)| (token.0, *price)) - .collect(), - trades: solution - .trades - .iter() - .map(|trade| match trade { - solution::Trade::Fulfillment(trade) => { - Trade::Fulfillment(Fulfillment { - order: trade.order().uid.0, - executed_amount: trade.executed().amount, - fee: trade.surplus_fee().map(|fee| fee.amount), - }) - } - solution::Trade::Jit(trade) => { - let (signing_scheme, signature) = match &trade.order.signature { - order::Signature::Eip712(signature) => { - (SigningScheme::Eip712, signature.to_bytes().to_vec()) - } - order::Signature::EthSign(signature) => { - (SigningScheme::EthSign, signature.to_bytes().to_vec()) - } - order::Signature::Eip1271(bytes) => { - (SigningScheme::Eip1271, bytes.clone()) - } - order::Signature::PreSign => (SigningScheme::PreSign, vec![]), - }; - - Trade::Jit(JitTrade { - order: JitOrder { - sell_token: trade.order.sell.token.0, - sell_amount: trade.order.sell.amount, - buy_token: trade.order.buy.token.0, - buy_amount: trade.order.buy.amount, - receiver: trade.order.receiver, - valid_to: trade.order.valid_to, - app_data: trade.order.app_data.0, - fee_amount: trade.order.fee.0, - kind: match trade.order.side { - crate::domain::order::Side::Buy => Kind::Buy, - crate::domain::order::Side::Sell => Kind::Sell, - }, - partially_fillable: trade.order.partially_fillable, - sell_token_balance: SellTokenBalance::Erc20, - buy_token_balance: BuyTokenBalance::Erc20, - signing_scheme, - signature, +/// Creates a new solution DTO from its domain object. +pub fn from_domain(solutions: &[solution::Solution]) -> super::Solutions { + super::Solutions { + solutions: solutions + .iter() + .map(|solution| Solution { + id: solution.id.0, + prices: solution + .prices + .0 + .iter() + .map(|(token, price)| (token.0, *price)) + .collect(), + trades: solution + .trades + .iter() + .map(|trade| match trade { + solution::Trade::Fulfillment(trade) => Trade::Fulfillment(Fulfillment { + order: trade.order().uid.0, + executed_amount: trade.executed().amount, + fee: trade.surplus_fee().map(|fee| fee.amount), + }), + solution::Trade::Jit(trade) => { + let (signing_scheme, signature) = match &trade.order.signature { + order::Signature::Eip712(signature) => { + (SigningScheme::Eip712, signature.to_bytes().to_vec()) + } + order::Signature::EthSign(signature) => { + (SigningScheme::EthSign, signature.to_bytes().to_vec()) + } + order::Signature::Eip1271(bytes) => { + (SigningScheme::Eip1271, bytes.clone()) + } + order::Signature::PreSign => (SigningScheme::PreSign, vec![]), + }; + + Trade::Jit(JitTrade { + order: JitOrder { + sell_token: trade.order.sell.token.0, + sell_amount: trade.order.sell.amount, + buy_token: trade.order.buy.token.0, + buy_amount: trade.order.buy.amount, + receiver: trade.order.receiver, + valid_to: trade.order.valid_to, + app_data: trade.order.app_data.0, + fee_amount: trade.order.fee.0, + kind: match trade.order.side { + crate::domain::order::Side::Buy => Kind::Buy, + crate::domain::order::Side::Sell => Kind::Sell, }, - executed_amount: trade.executed, - }) - } - }) - .collect(), - interactions: solution - .interactions - .iter() - .map(|interaction| match interaction { - solution::Interaction::Liquidity(interaction) => { - Interaction::Liquidity(LiquidityInteraction { - id: interaction.liquidity.id.0.clone(), - input_token: interaction.input.token.0, - input_amount: interaction.input.amount, - output_token: interaction.output.token.0, - output_amount: interaction.output.amount, - internalize: interaction.internalize, - }) - } - solution::Interaction::Custom(interaction) => { - Interaction::Custom(CustomInteraction { - target: interaction.target, - value: interaction.value.0, - calldata: interaction.calldata.clone(), - internalize: interaction.internalize, - allowances: interaction - .allowances - .iter() - .map(|allowance| Allowance { - token: allowance.asset.token.0, - amount: allowance.asset.amount, - spender: allowance.spender, - }) - .collect(), - inputs: interaction - .inputs - .iter() - .map(|i| Asset { - token: i.token.0, - amount: i.amount, - }) - .collect(), - outputs: interaction - .outputs - .iter() - .map(|o| Asset { - token: o.token.0, - amount: o.amount, - }) - .collect(), - }) - } - }) - .collect(), - score: match solution.score.clone() { - solution::Score::Solver(score) => Score::Solver { score }, - solution::Score::RiskAdjusted(score) => Score::RiskAdjusted { - success_probability: score.0, - }, + partially_fillable: trade.order.partially_fillable, + sell_token_balance: SellTokenBalance::Erc20, + buy_token_balance: BuyTokenBalance::Erc20, + signing_scheme, + signature, + }, + executed_amount: trade.executed, + }) + } + }) + .collect(), + interactions: solution + .interactions + .iter() + .map(|interaction| match interaction { + solution::Interaction::Liquidity(interaction) => { + Interaction::Liquidity(LiquidityInteraction { + id: interaction.liquidity.id.0.clone(), + input_token: interaction.input.token.0, + input_amount: interaction.input.amount, + output_token: interaction.output.token.0, + output_amount: interaction.output.amount, + internalize: interaction.internalize, + }) + } + solution::Interaction::Custom(interaction) => { + Interaction::Custom(CustomInteraction { + target: interaction.target, + value: interaction.value.0, + calldata: interaction.calldata.clone(), + internalize: interaction.internalize, + allowances: interaction + .allowances + .iter() + .map(|allowance| Allowance { + token: allowance.asset.token.0, + amount: allowance.asset.amount, + spender: allowance.spender, + }) + .collect(), + inputs: interaction + .inputs + .iter() + .map(|i| Asset { + token: i.token.0, + amount: i.amount, + }) + .collect(), + outputs: interaction + .outputs + .iter() + .map(|o| Asset { + token: o.token.0, + amount: o.amount, + }) + .collect(), + }) + } + }) + .collect(), + score: match solution.score.clone() { + solution::Score::Solver(score) => Score::Solver { score }, + solution::Score::RiskAdjusted(score) => Score::RiskAdjusted { + success_probability: score.0, }, - gas: solution.gas.map(|gas| gas.0.as_u64()), - }) - .collect(), - } + }, + gas: solution.gas.map(|gas| gas.0.as_u64()), + }) + .collect(), } } - -#[derive(Debug, Serialize, Default)] -#[serde(rename_all = "camelCase")] -pub struct Solutions { - solutions: Vec, -} - -#[serde_as] -#[derive(Debug, Serialize)] -#[serde(rename_all = "camelCase")] -struct Solution { - id: u64, - #[serde_as(as = "HashMap<_, serialize::U256>")] - prices: HashMap, - trades: Vec, - interactions: Vec, - score: Score, - #[serde(skip_serializing_if = "Option::is_none")] - gas: Option, -} - -#[derive(Debug, Serialize)] -#[serde(tag = "kind", rename_all = "camelCase")] -enum Trade { - Fulfillment(Fulfillment), - Jit(JitTrade), -} - -#[serde_as] -#[derive(Debug, Serialize)] -#[serde(rename_all = "camelCase")] -struct Fulfillment { - #[serde_as(as = "serialize::Hex")] - order: [u8; 56], - #[serde_as(as = "serialize::U256")] - executed_amount: U256, - #[serde(skip_serializing_if = "Option::is_none")] - #[serde_as(as = "Option")] - fee: Option, -} - -#[serde_as] -#[derive(Debug, Serialize)] -#[serde(rename_all = "camelCase")] -struct JitTrade { - order: JitOrder, - #[serde_as(as = "serialize::U256")] - executed_amount: U256, -} - -#[serde_as] -#[derive(Debug, Serialize)] -#[serde(rename_all = "camelCase")] -struct JitOrder { - sell_token: H160, - buy_token: H160, - receiver: H160, - #[serde_as(as = "serialize::U256")] - sell_amount: U256, - #[serde_as(as = "serialize::U256")] - buy_amount: U256, - valid_to: u32, - #[serde_as(as = "serialize::Hex")] - app_data: [u8; 32], - #[serde_as(as = "serialize::U256")] - fee_amount: U256, - kind: Kind, - partially_fillable: bool, - sell_token_balance: SellTokenBalance, - buy_token_balance: BuyTokenBalance, - signing_scheme: SigningScheme, - #[serde_as(as = "serialize::Hex")] - signature: Vec, -} - -#[derive(Debug, Serialize)] -#[serde(rename_all = "camelCase")] -enum Kind { - Sell, - Buy, -} - -#[derive(Debug, Serialize)] -#[serde(tag = "kind", rename_all = "camelCase")] -enum Interaction { - Liquidity(LiquidityInteraction), - Custom(CustomInteraction), -} - -#[serde_as] -#[derive(Debug, Serialize)] -#[serde(rename_all = "camelCase")] -struct LiquidityInteraction { - internalize: bool, - id: String, - input_token: H160, - output_token: H160, - #[serde_as(as = "serialize::U256")] - input_amount: U256, - #[serde_as(as = "serialize::U256")] - output_amount: U256, -} - -#[serde_as] -#[derive(Debug, Serialize)] -#[serde(rename_all = "camelCase")] -struct CustomInteraction { - internalize: bool, - target: H160, - #[serde_as(as = "serialize::U256")] - value: U256, - #[serde(rename = "callData")] - #[serde_as(as = "serialize::Hex")] - calldata: Vec, - allowances: Vec, - inputs: Vec, - outputs: Vec, -} - -/// An interaction that can be executed as part of an order's pre- or -/// post-interactions. -#[serde_as] -#[derive(Debug, Serialize)] -#[serde(rename_all = "camelCase")] -struct OrderInteraction { - target: H160, - #[serde_as(as = "serialize::U256")] - value: U256, - #[serde(rename = "callData")] - #[serde_as(as = "serialize::Hex")] - calldata: Vec, -} - -#[serde_as] -#[derive(Debug, Serialize)] -#[serde(rename_all = "camelCase")] -struct Asset { - token: H160, - #[serde_as(as = "serialize::U256")] - amount: U256, -} - -#[serde_as] -#[derive(Debug, Serialize)] -#[serde(rename_all = "camelCase")] -struct Allowance { - token: H160, - spender: H160, - #[serde_as(as = "serialize::U256")] - amount: U256, -} - -#[derive(Debug, Default, Serialize)] -#[serde(rename_all = "camelCase")] -enum SellTokenBalance { - #[default] - Erc20, - Internal, - External, -} - -#[derive(Debug, Default, Serialize)] -#[serde(rename_all = "camelCase")] -enum BuyTokenBalance { - #[default] - Erc20, - Internal, -} - -#[derive(Debug, Serialize)] -#[serde(rename_all = "camelCase")] -enum SigningScheme { - Eip712, - EthSign, - PreSign, - Eip1271, -} - -/// A score for a solution. The score is used to rank solutions. -#[serde_as] -#[derive(Debug, Serialize)] -#[serde(rename_all = "camelCase", tag = "kind")] -pub enum Score { - Solver { - #[serde_as(as = "serialize::U256")] - score: U256, - }, - #[serde(rename_all = "camelCase")] - RiskAdjusted { success_probability: f64 }, -} diff --git a/src/api/routes/solve/mod.rs b/src/api/routes/solve/mod.rs index 786800e..3fd9d88 100644 --- a/src/api/routes/solve/mod.rs +++ b/src/api/routes/solve/mod.rs @@ -12,7 +12,7 @@ pub async fn solve( axum::response::Json>, ) { let handle_request = async { - let auction = match auction.to_domain() { + let auction = match dto::auction::to_domain(&auction) { Ok(value) => value, Err(err) => { tracing::warn!(?err, "invalid auction"); @@ -23,8 +23,6 @@ pub async fn solve( } }; - tracing::trace!(?auction); - let auction_id = auction.id; let solutions = state .solve(auction) @@ -33,7 +31,7 @@ pub async fn solve( tracing::trace!(?auction_id, ?solutions); - let solutions = dto::Solutions::from_domain(&solutions); + let solutions = dto::solution::from_domain(&solutions); ( axum::http::StatusCode::OK, axum::response::Json(Response::Ok(solutions)), From e2677276fa62c1836996e932d8e84e2453e7a7d8 Mon Sep 17 00:00:00 2001 From: ilya Date: Thu, 4 Apr 2024 15:51:02 +0100 Subject: [PATCH 2/8] Update services version --- Cargo.lock | 168 ++++++++++++++++------------------- Cargo.toml | 9 +- src/boundary/mod.rs | 6 -- src/boundary/rate_limiter.rs | 54 ----------- src/domain/solver/dex/mod.rs | 10 ++- src/infra/config/dex/file.rs | 3 +- src/infra/config/dex/mod.rs | 7 +- src/lib.rs | 1 - 8 files changed, 90 insertions(+), 168 deletions(-) delete mode 100644 src/boundary/mod.rs delete mode 100644 src/boundary/rate_limiter.rs diff --git a/Cargo.lock b/Cargo.lock index 6fd27c4..47b7193 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -124,10 +124,25 @@ version = "1.0.75" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a4668cab20f66d8d020e1fbc0ebe47217433c1b6c8f2040faf858554e394ace6" +[[package]] +name = "app-data" +version = "0.1.0" +source = "git+https://github.com/cowprotocol/services.git?tag=v2.252.0#5430414e90bc3cd121e0f307093ac4adccc675b6" +dependencies = [ + "anyhow", + "app-data-hash", + "bytes-hex", + "hex", + "primitive-types", + "serde", + "serde_json", + "serde_with", +] + [[package]] name = "app-data-hash" version = "0.1.0" -source = "git+https://github.com/cowprotocol/services.git?tag=v2.237.0#12d1af497c0f53cbb0cd842feafcd7687b872a0c" +source = "git+https://github.com/cowprotocol/services.git?tag=v2.252.0#5430414e90bc3cd121e0f307093ac4adccc675b6" dependencies = [ "hex-literal", "tiny-keccak", @@ -152,28 +167,6 @@ dependencies = [ "tokio", ] -[[package]] -name = "async-stream" -version = "0.3.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cd56dd203fef61ac097dd65721a419ddccb106b2d2b70ba60a6b529f03961a51" -dependencies = [ - "async-stream-impl", - "futures-core", - "pin-project-lite", -] - -[[package]] -name = "async-stream-impl" -version = "0.3.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "16e62a023e7c117e27523144c5d2459f4397fcc3cab0085af8e2224f643a0193" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.41", -] - [[package]] name = "async-trait" version = "0.1.74" @@ -711,6 +704,17 @@ version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a2bd12c1caf447e69cd4528f47f94d203fd2582878ecb9e9465484c4148a8223" +[[package]] +name = "bytes-hex" +version = "0.1.0" +source = "git+https://github.com/cowprotocol/services.git?tag=v2.252.0#5430414e90bc3cd121e0f307093ac4adccc675b6" +dependencies = [ + "hex", + "serde", + "serde_json", + "serde_with", +] + [[package]] name = "bytes-utils" version = "0.1.4" @@ -836,11 +840,10 @@ dependencies = [ [[package]] name = "contracts" version = "0.1.0" -source = "git+https://github.com/cowprotocol/services.git?tag=v2.237.0#12d1af497c0f53cbb0cd842feafcd7687b872a0c" +source = "git+https://github.com/cowprotocol/services.git?tag=v2.252.0#5430414e90bc3cd121e0f307093ac4adccc675b6" dependencies = [ "ethcontract", "ethcontract-generate", - "maplit", "serde", ] @@ -1000,7 +1003,7 @@ dependencies = [ [[package]] name = "database" version = "0.1.0" -source = "git+https://github.com/cowprotocol/services.git?tag=v2.237.0#12d1af497c0f53cbb0cd842feafcd7687b872a0c" +source = "git+https://github.com/cowprotocol/services.git?tag=v2.252.0#5430414e90bc3cd121e0f307093ac4adccc675b6" dependencies = [ "bigdecimal", "chrono", @@ -1008,6 +1011,7 @@ dependencies = [ "futures", "hex", "sqlx", + "strum", ] [[package]] @@ -1189,7 +1193,6 @@ dependencies = [ "aws-config", "aws-sdk-kms", "ethcontract-common", - "ethcontract-derive", "futures", "futures-timer", "hex", @@ -1222,20 +1225,6 @@ dependencies = [ "web3", ] -[[package]] -name = "ethcontract-derive" -version = "0.25.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2e68257cfdf589ae3f9d2edd348072e2bf105fa87288fc0a7f5e090e20a2acd4" -dependencies = [ - "anyhow", - "ethcontract-common", - "ethcontract-generate", - "proc-macro2", - "quote", - "syn 2.0.41", -] - [[package]] name = "ethcontract-generate" version = "0.25.4" @@ -1251,19 +1240,6 @@ dependencies = [ "url", ] -[[package]] -name = "ethcontract-mock" -version = "0.25.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7c017cc834bf73743adb5956f4033e4e1053f3651ab52ff1e5be0a09c3fc7e13" -dependencies = [ - "ethcontract", - "hex", - "mockall", - "predicates 3.1.0", - "rlp", -] - [[package]] name = "ethereum-types" version = "0.14.1" @@ -1281,7 +1257,7 @@ dependencies = [ [[package]] name = "ethrpc" version = "0.1.0" -source = "git+https://github.com/cowprotocol/services.git?tag=v2.237.0#12d1af497c0f53cbb0cd842feafcd7687b872a0c" +source = "git+https://github.com/cowprotocol/services.git?tag=v2.252.0#5430414e90bc3cd121e0f307093ac4adccc675b6" dependencies = [ "anyhow", "async-trait", @@ -2182,7 +2158,7 @@ dependencies = [ "fragile", "lazy_static", "mockall_derive", - "predicates 2.1.5", + "predicates", "predicates-tree", ] @@ -2201,19 +2177,20 @@ dependencies = [ [[package]] name = "model" version = "0.1.0" -source = "git+https://github.com/cowprotocol/services.git?tag=v2.237.0#12d1af497c0f53cbb0cd842feafcd7687b872a0c" +source = "git+https://github.com/cowprotocol/services.git?tag=v2.252.0#5430414e90bc3cd121e0f307093ac4adccc675b6" dependencies = [ "anyhow", + "app-data", "app-data-hash", "bigdecimal", + "bytes-hex", "chrono", "derivative", "hex", "hex-literal", "lazy_static", - "maplit", "num", - "number 0.1.0 (git+https://github.com/cowprotocol/services.git?tag=v2.237.0)", + "number", "primitive-types", "secp256k1", "serde", @@ -2381,19 +2358,6 @@ dependencies = [ "libc", ] -[[package]] -name = "number" -version = "0.1.0" -source = "git+https://github.com/cowprotocol/services.git?tag=v2.237.0#12d1af497c0f53cbb0cd842feafcd7687b872a0c" -dependencies = [ - "anyhow", - "bigdecimal", - "num", - "primitive-types", - "serde", - "serde_with", -] - [[package]] name = "number" version = "0.1.0" @@ -2419,7 +2383,7 @@ dependencies = [ [[package]] name = "observe" version = "0.1.0" -source = "git+https://github.com/cowprotocol/services.git?tag=v2.237.0#12d1af497c0f53cbb0cd842feafcd7687b872a0c" +source = "git+https://github.com/cowprotocol/services.git?tag=v2.252.0#5430414e90bc3cd121e0f307093ac4adccc675b6" dependencies = [ "atty", "futures", @@ -2489,6 +2453,18 @@ dependencies = [ "vcpkg", ] +[[package]] +name = "order-validation" +version = "0.1.0" +source = "git+https://github.com/cowprotocol/services.git?tag=v2.252.0#5430414e90bc3cd121e0f307093ac4adccc675b6" +dependencies = [ + "cached", + "contracts", + "ethcontract", + "thiserror", + "tracing", +] + [[package]] name = "outref" version = "0.5.1" @@ -2656,20 +2632,6 @@ dependencies = [ "regex", ] -[[package]] -name = "predicates" -version = "3.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "68b87bfd4605926cdfefc1c3b5f8fe560e3feca9d5552cf68c466d3d8236c7e8" -dependencies = [ - "anstyle", - "difflib", - "float-cmp", - "normalize-line-endings", - "predicates-core", - "regex", -] - [[package]] name = "predicates-core" version = "1.0.6" @@ -2821,6 +2783,23 @@ dependencies = [ "getrandom", ] +[[package]] +name = "rate-limit" +version = "0.1.0" +source = "git+https://github.com/cowprotocol/services.git?tag=v2.252.0#5430414e90bc3cd121e0f307093ac4adccc675b6" +dependencies = [ + "anyhow", + "futures", + "humantime", + "observe", + "prometheus", + "prometheus-metric-storage", + "reqwest", + "thiserror", + "tokio", + "tracing", +] + [[package]] name = "redox_syscall" version = "0.4.1" @@ -3281,13 +3260,14 @@ dependencies = [ [[package]] name = "shared" version = "0.1.0" -source = "git+https://github.com/cowprotocol/services.git?tag=v2.237.0#12d1af497c0f53cbb0cd842feafcd7687b872a0c" +source = "git+https://github.com/cowprotocol/services.git?tag=v2.252.0#5430414e90bc3cd121e0f307093ac4adccc675b6" dependencies = [ "anyhow", + "app-data", "app-data-hash", - "async-stream", "async-trait", "bigdecimal", + "bytes-hex", "cached", "chrono", "clap", @@ -3296,24 +3276,27 @@ dependencies = [ "delay_map", "derivative", "ethcontract", - "ethcontract-mock", "ethrpc", "flate2", "futures", "gas-estimation", "hex", "hex-literal", + "humantime", + "indexmap 2.2.6", "itertools 0.11.0", "lazy_static", "maplit", "mockall", "model", "num", - "number 0.1.0 (git+https://github.com/cowprotocol/services.git?tag=v2.237.0)", + "number", "observe", + "order-validation", "primitive-types", "prometheus", "prometheus-metric-storage", + "rate-limit", "reqwest", "secp256k1", "serde", @@ -3423,6 +3406,7 @@ dependencies = [ "observe", "prometheus", "prometheus-metric-storage", + "rate-limit", "reqwest", "serde", "serde_json", @@ -3447,7 +3431,7 @@ dependencies = [ "bigdecimal", "chrono", "hex", - "number 0.1.0 (git+https://github.com/cowprotocol/services.git?tag=v2.252.0)", + "number", "serde", "serde_with", "web3", diff --git a/Cargo.toml b/Cargo.toml index c22c57f..4b34d2e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -40,11 +40,12 @@ tower-http = { version = "0.4", features = ["trace"] } tracing = "0.1" web3 = "0.19" -contracts = { git = "https://github.com/cowprotocol/services.git", tag = "v2.237.0", package = "contracts" } -ethrpc = { git = "https://github.com/cowprotocol/services.git", tag = "v2.237.0", package = "ethrpc" } -observe = { git = "https://github.com/cowprotocol/services.git", tag = "v2.237.0", package = "observe" } -shared = { git = "https://github.com/cowprotocol/services.git", tag = "v2.237.0", package = "shared" } +contracts = { git = "https://github.com/cowprotocol/services.git", tag = "v2.252.0", package = "contracts" } +ethrpc = { git = "https://github.com/cowprotocol/services.git", tag = "v2.252.0", package = "ethrpc" } +observe = { git = "https://github.com/cowprotocol/services.git", tag = "v2.252.0", package = "observe" } +shared = { git = "https://github.com/cowprotocol/services.git", tag = "v2.252.0", package = "shared" } dto = { git = "https://github.com/cowprotocol/services.git", tag = "v2.252.0", package = "solvers-dto" } +rate-limit = { git = "https://github.com/cowprotocol/services.git", tag = "v2.252.0", package = "rate-limit" } [dev-dependencies] glob = "0.3" diff --git a/src/boundary/mod.rs b/src/boundary/mod.rs deleted file mode 100644 index 0d160cc..0000000 --- a/src/boundary/mod.rs +++ /dev/null @@ -1,6 +0,0 @@ -//! This is a abstraction layer between the solver engine and the existing -//! "legacy" logic in `shared` and `model`. - -pub mod rate_limiter; - -pub type Result = anyhow::Result; diff --git a/src/boundary/rate_limiter.rs b/src/boundary/rate_limiter.rs deleted file mode 100644 index 04e4d4d..0000000 --- a/src/boundary/rate_limiter.rs +++ /dev/null @@ -1,54 +0,0 @@ -use { - anyhow::Result, - std::{future::Future, time::Duration}, - thiserror::Error, -}; - -// todo: remove on the next services release -pub struct RateLimiter { - inner: shared::RateLimiter, -} - -#[derive(Debug, Clone)] -pub struct RateLimitingStrategy { - inner: shared::RateLimitingStrategy, -} - -impl RateLimitingStrategy { - pub fn try_new( - back_off_growth_factor: f64, - min_back_off: Duration, - max_back_off: Duration, - ) -> Result { - shared::RateLimitingStrategy::try_new(back_off_growth_factor, min_back_off, max_back_off) - .map(|shared| Self { inner: shared }) - } -} - -#[derive(Error, Debug, Clone, Default)] -pub enum RateLimiterError { - #[default] - #[error("rate limited")] - RateLimited, -} - -impl RateLimiter { - pub fn new(strategy: RateLimitingStrategy, name: String) -> Self { - Self { - inner: shared::RateLimiter::from_strategy(strategy.inner, name), - } - } - - pub async fn execute_with_back_off( - &self, - task: impl Future, - requires_back_off: impl Fn(&T) -> bool, - ) -> Result { - self.inner - .execute_with_back_off(task, requires_back_off) - .await - .map_err(|err| match err { - shared::RateLimiterError::RateLimited => RateLimiterError::RateLimited, - }) - } -} diff --git a/src/domain/solver/dex/mod.rs b/src/domain/solver/dex/mod.rs index 3b222a8..5fac582 100644 --- a/src/domain/solver/dex/mod.rs +++ b/src/domain/solver/dex/mod.rs @@ -3,7 +3,6 @@ use { crate::{ - boundary::rate_limiter::{RateLimiter, RateLimiterError}, domain::{ self, auction, @@ -42,7 +41,7 @@ pub struct Dex { risk: domain::Risk, /// Handles 429 Too Many Requests error with a retry mechanism - rate_limiter: RateLimiter, + rate_limiter: rate_limit::RateLimiter, } /// The amount of time we aim the solver to finish before the final deadline is @@ -51,7 +50,10 @@ const DEADLINE_SLACK: chrono::Duration = chrono::Duration::milliseconds(500); impl Dex { pub fn new(dex: infra::dex::Dex, config: infra::config::dex::Config) -> Self { - let rate_limiter = RateLimiter::new(config.rate_limiting_strategy, "dex_api".to_string()); + let rate_limiter = rate_limit::RateLimiter::from_strategy( + config.rate_limiting_strategy, + "dex_api".to_string(), + ); Self { dex, simulator: infra::dex::Simulator::new( @@ -154,7 +156,7 @@ impl Dex { }) .await .map_err(|err| match err { - RateLimiterError::RateLimited => infra::dex::Error::RateLimited, + rate_limit::Error::RateLimited => infra::dex::Error::RateLimited, }) .and_then(|result| result) .ok() diff --git a/src/infra/config/dex/file.rs b/src/infra/config/dex/file.rs index bd3f716..6c99916 100644 --- a/src/infra/config/dex/file.rs +++ b/src/infra/config/dex/file.rs @@ -2,7 +2,6 @@ use { crate::{ - boundary::rate_limiter::RateLimitingStrategy, domain::{dex::slippage, eth, Risk}, infra::{blockchain, config::unwrap_or_log, contracts}, util::serialize, @@ -147,7 +146,7 @@ pub async fn load(path: &Path) -> (super::Config, T) { nmb_orders_factor: config.risk_parameters.2, intercept: config.risk_parameters.3, }, - rate_limiting_strategy: RateLimitingStrategy::try_new( + rate_limiting_strategy: rate_limit::Strategy::try_new( config.back_off_growth_factor, config.min_back_off, config.max_back_off, diff --git a/src/infra/config/dex/mod.rs b/src/infra/config/dex/mod.rs index 921d797..c7ef905 100644 --- a/src/infra/config/dex/mod.rs +++ b/src/infra/config/dex/mod.rs @@ -5,10 +5,7 @@ pub mod paraswap; pub mod zeroex; use { - crate::{ - boundary::rate_limiter::RateLimitingStrategy, - domain::{dex::slippage, eth, Risk}, - }, + crate::domain::{dex::slippage, eth, Risk}, std::num::NonZeroUsize, }; @@ -26,6 +23,6 @@ pub struct Config { pub concurrent_requests: NonZeroUsize, pub smallest_partial_fill: eth::Ether, pub risk: Risk, - pub rate_limiting_strategy: RateLimitingStrategy, + pub rate_limiting_strategy: rate_limit::Strategy, pub solution_gas_offset: eth::SignedGas, } diff --git a/src/lib.rs b/src/lib.rs index 23c05bf..43f21e5 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -3,7 +3,6 @@ #![recursion_limit = "256"] mod api; -mod boundary; mod domain; mod infra; mod run; From 92f11098804bfe02bfd3f5b29a11b96bc6c349f5 Mon Sep 17 00:00:00 2001 From: ilya Date: Mon, 8 Apr 2024 09:12:40 +0100 Subject: [PATCH 3/8] Risk clean-up --- Cargo.lock | 6 +-- Cargo.toml | 2 +- openapi.yml | 28 ------------ src/api/routes/solve/dto/solution.rs | 6 --- src/domain/dex/mod.rs | 6 +-- src/domain/mod.rs | 3 -- src/domain/notification.rs | 43 +++++-------------- src/domain/risk.rs | 26 ----------- src/domain/solution.rs | 64 +++++----------------------- src/domain/solver/dex/mod.rs | 7 +-- src/infra/config/dex/file.rs | 8 +--- src/infra/config/dex/mod.rs | 3 +- src/tests/balancer/market_order.rs | 8 ---- src/tests/dex/partial_fill.rs | 12 ------ src/tests/oneinch/market_order.rs | 4 -- src/tests/paraswap/market_order.rs | 8 ---- src/tests/zeroex/market_order.rs | 8 ---- src/tests/zeroex/options.rs | 4 -- 18 files changed, 29 insertions(+), 217 deletions(-) delete mode 100644 src/domain/risk.rs diff --git a/Cargo.lock b/Cargo.lock index 6fd27c4..711b49b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2397,7 +2397,7 @@ dependencies = [ [[package]] name = "number" version = "0.1.0" -source = "git+https://github.com/cowprotocol/services.git?tag=v2.252.0#5430414e90bc3cd121e0f307093ac4adccc675b6" +source = "git+https://github.com/cowprotocol/services.git?tag=v2.253.0#2e6fbac515927e88dc40b720f1bb135cf8425075" dependencies = [ "anyhow", "bigdecimal", @@ -3442,12 +3442,12 @@ dependencies = [ [[package]] name = "solvers-dto" version = "0.1.0" -source = "git+https://github.com/cowprotocol/services.git?tag=v2.252.0#5430414e90bc3cd121e0f307093ac4adccc675b6" +source = "git+https://github.com/cowprotocol/services.git?tag=v2.253.0#2e6fbac515927e88dc40b720f1bb135cf8425075" dependencies = [ "bigdecimal", "chrono", "hex", - "number 0.1.0 (git+https://github.com/cowprotocol/services.git?tag=v2.252.0)", + "number 0.1.0 (git+https://github.com/cowprotocol/services.git?tag=v2.253.0)", "serde", "serde_with", "web3", diff --git a/Cargo.toml b/Cargo.toml index c22c57f..4debb8d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -44,7 +44,7 @@ contracts = { git = "https://github.com/cowprotocol/services.git", tag = "v2.237 ethrpc = { git = "https://github.com/cowprotocol/services.git", tag = "v2.237.0", package = "ethrpc" } observe = { git = "https://github.com/cowprotocol/services.git", tag = "v2.237.0", package = "observe" } shared = { git = "https://github.com/cowprotocol/services.git", tag = "v2.237.0", package = "shared" } -dto = { git = "https://github.com/cowprotocol/services.git", tag = "v2.252.0", package = "solvers-dto" } +dto = { git = "https://github.com/cowprotocol/services.git", tag = "v2.253.0", package = "solvers-dto" } [dev-dependencies] glob = "0.3" diff --git a/openapi.yml b/openapi.yml index 83c788c..dabb714 100644 --- a/openapi.yml +++ b/openapi.yml @@ -757,7 +757,6 @@ components: - prices - trades - interactions - - score properties: id: description: An opaque identifier for the solution. @@ -781,30 +780,3 @@ components: type: array items: $ref: "#/components/schemas/Interaction" - score: - description: | - Information required by the driver to score the solution. - - Can either be a raw score or a success probability. - oneOf: - - type: object - properties: - kind: - type: string - enum: [solver] - score: - description: | - The raw score of the solution. This is the score that is - used by the driver to rank solutions. - allOf: - - $ref: "#/components/schemas/Decimal" - - type: object - properties: - kind: - type: string - enum: [riskAdjusted] - successProbability: - description: | - The revert probability of the solution. Used by the driver to compute a risk-adjusted score. - type: number - example: 0.9 diff --git a/src/api/routes/solve/dto/solution.rs b/src/api/routes/solve/dto/solution.rs index 3923dfd..7c1bf2f 100644 --- a/src/api/routes/solve/dto/solution.rs +++ b/src/api/routes/solve/dto/solution.rs @@ -113,12 +113,6 @@ pub fn from_domain(solutions: &[solution::Solution]) -> super::Solutions { } }) .collect(), - score: match solution.score.clone() { - solution::Score::Solver(score) => Score::Solver { score }, - solution::Score::RiskAdjusted(score) => Score::RiskAdjusted { - success_probability: score.0, - }, - }, gas: solution.gas.map(|gas| gas.0.as_u64()), }) .collect(), diff --git a/src/domain/dex/mod.rs b/src/domain/dex/mod.rs index 5289c26..3f56c26 100644 --- a/src/domain/dex/mod.rs +++ b/src/domain/dex/mod.rs @@ -107,7 +107,6 @@ impl Swap { order: order::Order, gas_price: auction::GasPrice, sell_token: Option, - risk: &domain::Risk, simulator: &infra::dex::Simulator, ) -> Option { let gas = match simulator.gas(order.owner(), &self).await { @@ -117,9 +116,6 @@ impl Swap { return None; } }; - let score = solution::Score::RiskAdjusted(solution::SuccessProbability( - risk.success_probability(gas, gas_price, 1), - )); let allowance = self.allowance(); let interactions = vec![solution::Interaction::Custom(solution::CustomInteraction { @@ -139,7 +135,7 @@ impl Swap { interactions, gas, } - .into_solution(gas_price, sell_token, score) + .into_solution(gas_price, sell_token) } pub fn satisfies(&self, order: &domain::order::Order) -> bool { diff --git a/src/domain/mod.rs b/src/domain/mod.rs index 6a0434b..414298a 100644 --- a/src/domain/mod.rs +++ b/src/domain/mod.rs @@ -6,8 +6,5 @@ pub mod eth; pub mod liquidity; pub mod notification; pub mod order; -pub mod risk; pub mod solution; pub mod solver; - -pub use risk::Risk; diff --git a/src/domain/notification.rs b/src/domain/notification.rs index bdb52da..a04c554 100644 --- a/src/domain/notification.rs +++ b/src/domain/notification.rs @@ -2,7 +2,7 @@ use { super::{ auction, eth::{self, Ether, TokenAddress}, - solution::{self, SuccessProbability}, + solution::{self}, }, std::collections::BTreeSet, }; @@ -19,10 +19,16 @@ pub type SimulationSucceededAtLeastOnce = bool; #[derive(Debug)] pub struct Notification { pub auction_id: auction::Id, - pub solution_id: Option, + pub solution_id: Option, pub kind: Kind, } +#[derive(Debug, Clone)] +pub enum Id { + Single(solution::Id), + Merged(Vec), +} + /// All types of notifications solvers can be informed about. #[derive(Debug)] pub enum Kind { @@ -34,6 +40,7 @@ pub enum Kind { NonBufferableTokensUsed(TokensUsed), SolverAccountInsufficientBalance(RequiredEther), Settled(Settlement), + DriverError(String), PostprocessingTimedOut, } @@ -48,35 +55,5 @@ pub enum Settlement { #[derive(Debug)] pub enum ScoreKind { - ZeroScore, - ScoreHigherThanQuality(Score, Quality), - SuccessProbabilityOutOfRange(SuccessProbability), - ObjectiveValueNonPositive(Quality, GasCost), -} - -#[derive(Debug, Copy, Clone)] -pub struct Score(pub eth::U256); - -impl From for Score { - fn from(value: eth::U256) -> Self { - Self(value) - } -} - -#[derive(Debug, Copy, Clone)] -pub struct Quality(pub eth::U256); - -impl From for Quality { - fn from(value: eth::U256) -> Self { - Self(value) - } -} - -#[derive(Debug, Copy, Clone)] -pub struct GasCost(pub eth::U256); - -impl From for GasCost { - fn from(value: eth::U256) -> Self { - Self(value) - } + InvalidClearingPrices, } diff --git a/src/domain/risk.rs b/src/domain/risk.rs deleted file mode 100644 index d74c6e3..0000000 --- a/src/domain/risk.rs +++ /dev/null @@ -1,26 +0,0 @@ -use super::{auction::GasPrice, eth::Gas}; - -/// Parameters that define the possibility of a revert when executing a -/// solution. -#[derive(Debug, Default, Clone)] -pub struct Risk { - pub gas_amount_factor: f64, - pub gas_price_factor: f64, - pub nmb_orders_factor: f64, - pub intercept: f64, -} - -impl Risk { - pub fn success_probability( - &self, - gas_amount: Gas, - gas_price: GasPrice, - nmb_orders: usize, - ) -> f64 { - let exponent = -self.intercept - - self.gas_amount_factor * gas_amount.0.to_f64_lossy() / 1_000_000. - - self.gas_price_factor * gas_price.0 .0.to_f64_lossy() / 10_000_000_000. - - self.nmb_orders_factor * nmb_orders as f64; - 1. / (1. + exponent.exp()) - } -} diff --git a/src/domain/solution.rs b/src/domain/solution.rs index 46534da..bac4128 100644 --- a/src/domain/solution.rs +++ b/src/domain/solution.rs @@ -1,6 +1,6 @@ use { crate::{ - domain::{auction, eth, liquidity, order, solution, Risk}, + domain::{auction, eth, liquidity, order}, util, }, ethereum_types::{Address, U256}, @@ -23,7 +23,6 @@ pub struct Solution { pub prices: ClearingPrices, pub trades: Vec, pub interactions: Vec, - pub score: Score, pub gas: Option, } @@ -33,21 +32,12 @@ impl Solution { Self { id, ..self } } - /// Returns `self` with a new score. - pub fn with_score(self, score: Score) -> Self { - Self { score, ..self } - } - - pub fn with_risk_adjusted_score( - self, - risk: &Risk, - gas: eth::Gas, - gas_price: auction::GasPrice, - ) -> Self { - let nmb_orders = self.trades.len(); - self.with_score(Score::RiskAdjusted(SuccessProbability( - risk.success_probability(gas, gas_price, nmb_orders), - ))) + /// Sets the provided gas. + pub fn with_gas(self, gas: eth::Gas) -> Self { + Self { + gas: Some(gas), + ..self + } } /// Returns `self` with eligible interactions internalized using the @@ -129,9 +119,7 @@ pub struct Single { pub output: eth::Asset, /// The swap interactions for the single order settlement. pub interactions: Vec, - /// The estimated gas needed for swapping the sell amount to buy amount - /// already including the additional overhead of calling the settlement - /// contract. + /// The estimated gas needed for the solution settling this single order. pub gas: eth::Gas, } @@ -142,14 +130,13 @@ impl Single { self, gas_price: auction::GasPrice, sell_token: Option, - score: solution::Score, ) -> Option { let Self { order, input, output, interactions, - gas: swap, + gas, } = self; if (order.sell.token, order.buy.token) != (input.token, output.token) { @@ -162,7 +149,7 @@ impl Single { // full order fee as well as a solver computed fee. Note that this // is fine for now, since there is no way to create limit orders // with non-zero fees. - Fee::Surplus(sell_token?.ether_value(eth::Ether(swap.0.checked_mul(gas_price.0 .0)?))?) + Fee::Surplus(sell_token?.ether_value(eth::Ether(gas.0.checked_mul(gas_price.0 .0)?))?) } else { Fee::Protocol }; @@ -210,8 +197,7 @@ impl Single { ]), trades: vec![Trade::Fulfillment(Fulfillment::new(order, executed, fee)?)], interactions, - score, - gas: Some(self.gas), + gas: Some(gas), }) } } @@ -387,34 +373,6 @@ pub struct Allowance { pub asset: eth::Asset, } -/// Represents the probability that a solution will be successfully settled. -#[derive(Debug, Copy, Clone)] -pub struct SuccessProbability(pub f64); - -impl From for SuccessProbability { - fn from(value: f64) -> Self { - Self(value) - } -} - -/// A score for a solution. The score is used to rank solutions. -#[derive(Debug, Clone)] -pub enum Score { - /// The score value is provided as is from solver. - /// Success probability is not incorporated into this value. - Solver(U256), - /// This option is used to indicate that the solver did not provide a score. - /// Instead, the score should be computed by the protocol given the success - /// probability. - RiskAdjusted(SuccessProbability), -} - -impl Default for Score { - fn default() -> Self { - Self::RiskAdjusted(SuccessProbability(1.0)) - } -} - // initial tx gas used to call the settle function from the settlement contract pub const INITIALIZATION_COST: u64 = 32_000; /// minimum gas every settlement takes (isSolver) diff --git a/src/domain/solver/dex/mod.rs b/src/domain/solver/dex/mod.rs index 3b222a8..756e33c 100644 --- a/src/domain/solver/dex/mod.rs +++ b/src/domain/solver/dex/mod.rs @@ -5,7 +5,6 @@ use { crate::{ boundary::rate_limiter::{RateLimiter, RateLimiterError}, domain::{ - self, auction, dex::{self, slippage}, order::{self, Order}, @@ -38,9 +37,6 @@ pub struct Dex { /// fillable orders). fills: Fills, - /// Parameters used to calculate the revert risk of a solution. - risk: domain::Risk, - /// Handles 429 Too Many Requests error with a retry mechanism rate_limiter: RateLimiter, } @@ -63,7 +59,6 @@ impl Dex { slippage: config.slippage, concurrent_requests: config.concurrent_requests, fills: Fills::new(config.smallest_partial_fill), - risk: config.risk, rate_limiter, } } @@ -181,7 +176,7 @@ impl Dex { let swap = self.try_solve(order, &dex_order, tokens, gas_price).await?; let sell = tokens.reference_price(&order.sell.token); let Some(solution) = swap - .into_solution(order.clone(), gas_price, sell, &self.risk, &self.simulator) + .into_solution(order.clone(), gas_price, sell, &self.simulator) .await else { tracing::debug!("no solution for swap"); diff --git a/src/infra/config/dex/file.rs b/src/infra/config/dex/file.rs index bd3f716..c4714d7 100644 --- a/src/infra/config/dex/file.rs +++ b/src/infra/config/dex/file.rs @@ -3,7 +3,7 @@ use { crate::{ boundary::rate_limiter::RateLimitingStrategy, - domain::{dex::slippage, eth, Risk}, + domain::{dex::slippage, eth}, infra::{blockchain, config::unwrap_or_log, contracts}, util::serialize, }, @@ -141,12 +141,6 @@ pub async fn load(path: &Path) -> (super::Config, T) { .expect("invalid slippage limits"), concurrent_requests: config.concurrent_requests, smallest_partial_fill: eth::Ether(config.smallest_partial_fill), - risk: Risk { - gas_amount_factor: config.risk_parameters.0, - gas_price_factor: config.risk_parameters.1, - nmb_orders_factor: config.risk_parameters.2, - intercept: config.risk_parameters.3, - }, rate_limiting_strategy: RateLimitingStrategy::try_new( config.back_off_growth_factor, config.min_back_off, diff --git a/src/infra/config/dex/mod.rs b/src/infra/config/dex/mod.rs index 921d797..1e8f770 100644 --- a/src/infra/config/dex/mod.rs +++ b/src/infra/config/dex/mod.rs @@ -7,7 +7,7 @@ pub mod zeroex; use { crate::{ boundary::rate_limiter::RateLimitingStrategy, - domain::{dex::slippage, eth, Risk}, + domain::{dex::slippage, eth}, }, std::num::NonZeroUsize, }; @@ -25,7 +25,6 @@ pub struct Config { pub slippage: slippage::Limits, pub concurrent_requests: NonZeroUsize, pub smallest_partial_fill: eth::Ether, - pub risk: Risk, pub rate_limiting_strategy: RateLimitingStrategy, pub solution_gas_offset: eth::SignedGas, } diff --git a/src/tests/balancer/market_order.rs b/src/tests/balancer/market_order.rs index 0a5c58f..bff56fd 100644 --- a/src/tests/balancer/market_order.rs +++ b/src/tests/balancer/market_order.rs @@ -160,10 +160,6 @@ async fn sell() { ], } ], - "score": { - "kind": "riskAdjusted", - "successProbability": 0.5, - }, "gas": 195283, }] }), @@ -324,10 +320,6 @@ async fn buy() { ], } ], - "score": { - "kind": "riskAdjusted", - "successProbability": 0.5, - }, "gas": 195283, }] }), diff --git a/src/tests/dex/partial_fill.rs b/src/tests/dex/partial_fill.rs index 8b8fa99..9c934f1 100644 --- a/src/tests/dex/partial_fill.rs +++ b/src/tests/dex/partial_fill.rs @@ -262,10 +262,6 @@ endpoint = 'http://{}/sor' "order": "0x2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a" } ], - "score": { - "kind": "riskAdjusted", - "successProbability": 0.5, - }, "gas": 195283, }] }) @@ -596,10 +592,6 @@ endpoint = 'http://{}/sor' "order": "0x2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a" } ], - "score": { - "kind": "riskAdjusted", - "successProbability": 0.5, - }, "gas": 195283, }] }) @@ -870,10 +862,6 @@ async fn market() { "order": "0x2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a" } ], - "score": { - "kind": "riskAdjusted", - "successProbability": 0.5, - }, "gas": 195283, }] }) diff --git a/src/tests/oneinch/market_order.rs b/src/tests/oneinch/market_order.rs index 0a1b211..4e3c851 100644 --- a/src/tests/oneinch/market_order.rs +++ b/src/tests/oneinch/market_order.rs @@ -211,10 +211,6 @@ async fn sell() { "order": "0x2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a" } ], - "score": { - "kind": "riskAdjusted", - "successProbability": 0.5, - }, "gas": 206391, } ] diff --git a/src/tests/paraswap/market_order.rs b/src/tests/paraswap/market_order.rs index befe5e8..55a09d0 100644 --- a/src/tests/paraswap/market_order.rs +++ b/src/tests/paraswap/market_order.rs @@ -240,10 +240,6 @@ async fn sell() { "order": "0x2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a" } ], - "score": { - "kind": "riskAdjusted", - "successProbability": 0.5, - }, "gas": 348691, } ] @@ -501,10 +497,6 @@ async fn buy() { "order": "0x2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a" } ], - "score": { - "kind": "riskAdjusted", - "successProbability": 0.5, - }, "gas": 213326, } ] diff --git a/src/tests/zeroex/market_order.rs b/src/tests/zeroex/market_order.rs index 043c7db..1815d11 100644 --- a/src/tests/zeroex/market_order.rs +++ b/src/tests/zeroex/market_order.rs @@ -191,10 +191,6 @@ async fn sell() { ], }, ], - "score": { - "kind": "riskAdjusted", - "successProbability": 0.5, - }, "gas": 234277, }] }), @@ -379,10 +375,6 @@ async fn buy() { ], }, ], - "score": { - "kind": "riskAdjusted", - "successProbability": 0.5, - }, "gas": 217391, }] }), diff --git a/src/tests/zeroex/options.rs b/src/tests/zeroex/options.rs index 1e637f5..568dd31 100644 --- a/src/tests/zeroex/options.rs +++ b/src/tests/zeroex/options.rs @@ -294,10 +294,6 @@ enable-slippage-protection = true ], }, ], - "score": { - "kind": "riskAdjusted", - "successProbability": 0.5, - }, "gas": 234277, }] }), From 50a5dc44246a785e2b29940ddfbcec2a29a63881 Mon Sep 17 00:00:00 2001 From: ilya Date: Mon, 8 Apr 2024 09:22:36 +0100 Subject: [PATCH 4/8] Fix after merge --- src/domain/notification.rs | 19 +------------------ 1 file changed, 1 insertion(+), 18 deletions(-) diff --git a/src/domain/notification.rs b/src/domain/notification.rs index 55f482c..a04c554 100644 --- a/src/domain/notification.rs +++ b/src/domain/notification.rs @@ -36,6 +36,7 @@ pub enum Kind { EmptySolution, DuplicatedSolutionId, SimulationFailed(BlockNo, Transaction, SimulationSucceededAtLeastOnce), + ScoringFailed(ScoreKind), NonBufferableTokensUsed(TokensUsed), SolverAccountInsufficientBalance(RequiredEther), Settled(Settlement), @@ -56,21 +57,3 @@ pub enum Settlement { pub enum ScoreKind { InvalidClearingPrices, } - -#[derive(Debug, Copy, Clone)] -pub struct Quality(pub eth::U256); - -impl From for Quality { - fn from(value: eth::U256) -> Self { - Self(value) - } -} - -#[derive(Debug, Copy, Clone)] -pub struct GasCost(pub eth::U256); - -impl From for GasCost { - fn from(value: eth::U256) -> Self { - Self(value) - } -} From 0e0ccaab3fd13ee9e34daacd3f8121003351da48 Mon Sep 17 00:00:00 2001 From: ilya Date: Mon, 8 Apr 2024 09:48:28 +0100 Subject: [PATCH 5/8] Fix after merge --- Cargo.lock | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 4e5aff5..89c86f7 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2190,7 +2190,7 @@ dependencies = [ "hex-literal", "lazy_static", "num", - "number", + "number 0.1.0 (git+https://github.com/cowprotocol/services.git?tag=v2.252.0)", "primitive-types", "secp256k1", "serde", @@ -2358,6 +2358,19 @@ dependencies = [ "libc", ] +[[package]] +name = "number" +version = "0.1.0" +source = "git+https://github.com/cowprotocol/services.git?tag=v2.252.0#5430414e90bc3cd121e0f307093ac4adccc675b6" +dependencies = [ + "anyhow", + "bigdecimal", + "num", + "primitive-types", + "serde", + "serde_with", +] + [[package]] name = "number" version = "0.1.0" @@ -3290,7 +3303,7 @@ dependencies = [ "mockall", "model", "num", - "number", + "number 0.1.0 (git+https://github.com/cowprotocol/services.git?tag=v2.252.0)", "observe", "order-validation", "primitive-types", From 7e088ad38d6977a7cba989e0f0863fa6982187e7 Mon Sep 17 00:00:00 2001 From: ilya Date: Mon, 8 Apr 2024 09:49:18 +0100 Subject: [PATCH 6/8] v2.253.0 --- Cargo.lock | 41 ++++++++++++++--------------------------- Cargo.toml | 10 +++++----- 2 files changed, 19 insertions(+), 32 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 89c86f7..c0eae53 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -127,7 +127,7 @@ checksum = "a4668cab20f66d8d020e1fbc0ebe47217433c1b6c8f2040faf858554e394ace6" [[package]] name = "app-data" version = "0.1.0" -source = "git+https://github.com/cowprotocol/services.git?tag=v2.252.0#5430414e90bc3cd121e0f307093ac4adccc675b6" +source = "git+https://github.com/cowprotocol/services.git?tag=v2.253.0#2e6fbac515927e88dc40b720f1bb135cf8425075" dependencies = [ "anyhow", "app-data-hash", @@ -142,7 +142,7 @@ dependencies = [ [[package]] name = "app-data-hash" version = "0.1.0" -source = "git+https://github.com/cowprotocol/services.git?tag=v2.252.0#5430414e90bc3cd121e0f307093ac4adccc675b6" +source = "git+https://github.com/cowprotocol/services.git?tag=v2.253.0#2e6fbac515927e88dc40b720f1bb135cf8425075" dependencies = [ "hex-literal", "tiny-keccak", @@ -707,7 +707,7 @@ checksum = "a2bd12c1caf447e69cd4528f47f94d203fd2582878ecb9e9465484c4148a8223" [[package]] name = "bytes-hex" version = "0.1.0" -source = "git+https://github.com/cowprotocol/services.git?tag=v2.252.0#5430414e90bc3cd121e0f307093ac4adccc675b6" +source = "git+https://github.com/cowprotocol/services.git?tag=v2.253.0#2e6fbac515927e88dc40b720f1bb135cf8425075" dependencies = [ "hex", "serde", @@ -840,7 +840,7 @@ dependencies = [ [[package]] name = "contracts" version = "0.1.0" -source = "git+https://github.com/cowprotocol/services.git?tag=v2.252.0#5430414e90bc3cd121e0f307093ac4adccc675b6" +source = "git+https://github.com/cowprotocol/services.git?tag=v2.253.0#2e6fbac515927e88dc40b720f1bb135cf8425075" dependencies = [ "ethcontract", "ethcontract-generate", @@ -1003,7 +1003,7 @@ dependencies = [ [[package]] name = "database" version = "0.1.0" -source = "git+https://github.com/cowprotocol/services.git?tag=v2.252.0#5430414e90bc3cd121e0f307093ac4adccc675b6" +source = "git+https://github.com/cowprotocol/services.git?tag=v2.253.0#2e6fbac515927e88dc40b720f1bb135cf8425075" dependencies = [ "bigdecimal", "chrono", @@ -1257,7 +1257,7 @@ dependencies = [ [[package]] name = "ethrpc" version = "0.1.0" -source = "git+https://github.com/cowprotocol/services.git?tag=v2.252.0#5430414e90bc3cd121e0f307093ac4adccc675b6" +source = "git+https://github.com/cowprotocol/services.git?tag=v2.253.0#2e6fbac515927e88dc40b720f1bb135cf8425075" dependencies = [ "anyhow", "async-trait", @@ -2177,7 +2177,7 @@ dependencies = [ [[package]] name = "model" version = "0.1.0" -source = "git+https://github.com/cowprotocol/services.git?tag=v2.252.0#5430414e90bc3cd121e0f307093ac4adccc675b6" +source = "git+https://github.com/cowprotocol/services.git?tag=v2.253.0#2e6fbac515927e88dc40b720f1bb135cf8425075" dependencies = [ "anyhow", "app-data", @@ -2190,7 +2190,7 @@ dependencies = [ "hex-literal", "lazy_static", "num", - "number 0.1.0 (git+https://github.com/cowprotocol/services.git?tag=v2.252.0)", + "number", "primitive-types", "secp256k1", "serde", @@ -2358,19 +2358,6 @@ dependencies = [ "libc", ] -[[package]] -name = "number" -version = "0.1.0" -source = "git+https://github.com/cowprotocol/services.git?tag=v2.252.0#5430414e90bc3cd121e0f307093ac4adccc675b6" -dependencies = [ - "anyhow", - "bigdecimal", - "num", - "primitive-types", - "serde", - "serde_with", -] - [[package]] name = "number" version = "0.1.0" @@ -2396,7 +2383,7 @@ dependencies = [ [[package]] name = "observe" version = "0.1.0" -source = "git+https://github.com/cowprotocol/services.git?tag=v2.252.0#5430414e90bc3cd121e0f307093ac4adccc675b6" +source = "git+https://github.com/cowprotocol/services.git?tag=v2.253.0#2e6fbac515927e88dc40b720f1bb135cf8425075" dependencies = [ "atty", "futures", @@ -2469,7 +2456,7 @@ dependencies = [ [[package]] name = "order-validation" version = "0.1.0" -source = "git+https://github.com/cowprotocol/services.git?tag=v2.252.0#5430414e90bc3cd121e0f307093ac4adccc675b6" +source = "git+https://github.com/cowprotocol/services.git?tag=v2.253.0#2e6fbac515927e88dc40b720f1bb135cf8425075" dependencies = [ "cached", "contracts", @@ -2799,7 +2786,7 @@ dependencies = [ [[package]] name = "rate-limit" version = "0.1.0" -source = "git+https://github.com/cowprotocol/services.git?tag=v2.252.0#5430414e90bc3cd121e0f307093ac4adccc675b6" +source = "git+https://github.com/cowprotocol/services.git?tag=v2.253.0#2e6fbac515927e88dc40b720f1bb135cf8425075" dependencies = [ "anyhow", "futures", @@ -3273,7 +3260,7 @@ dependencies = [ [[package]] name = "shared" version = "0.1.0" -source = "git+https://github.com/cowprotocol/services.git?tag=v2.252.0#5430414e90bc3cd121e0f307093ac4adccc675b6" +source = "git+https://github.com/cowprotocol/services.git?tag=v2.253.0#2e6fbac515927e88dc40b720f1bb135cf8425075" dependencies = [ "anyhow", "app-data", @@ -3303,7 +3290,7 @@ dependencies = [ "mockall", "model", "num", - "number 0.1.0 (git+https://github.com/cowprotocol/services.git?tag=v2.252.0)", + "number", "observe", "order-validation", "primitive-types", @@ -3444,7 +3431,7 @@ dependencies = [ "bigdecimal", "chrono", "hex", - "number 0.1.0 (git+https://github.com/cowprotocol/services.git?tag=v2.253.0)", + "number", "serde", "serde_with", "web3", diff --git a/Cargo.toml b/Cargo.toml index 3889908..0a3ba4b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -40,12 +40,12 @@ tower-http = { version = "0.4", features = ["trace"] } tracing = "0.1" web3 = "0.19" -contracts = { git = "https://github.com/cowprotocol/services.git", tag = "v2.252.0", package = "contracts" } -ethrpc = { git = "https://github.com/cowprotocol/services.git", tag = "v2.252.0", package = "ethrpc" } -observe = { git = "https://github.com/cowprotocol/services.git", tag = "v2.252.0", package = "observe" } -shared = { git = "https://github.com/cowprotocol/services.git", tag = "v2.252.0", package = "shared" } +contracts = { git = "https://github.com/cowprotocol/services.git", tag = "v2.253.0", package = "contracts" } +ethrpc = { git = "https://github.com/cowprotocol/services.git", tag = "v2.253.0", package = "ethrpc" } +observe = { git = "https://github.com/cowprotocol/services.git", tag = "v2.253.0", package = "observe" } +shared = { git = "https://github.com/cowprotocol/services.git", tag = "v2.253.0", package = "shared" } dto = { git = "https://github.com/cowprotocol/services.git", tag = "v2.253.0", package = "solvers-dto" } -rate-limit = { git = "https://github.com/cowprotocol/services.git", tag = "v2.252.0", package = "rate-limit" } +rate-limit = { git = "https://github.com/cowprotocol/services.git", tag = "v2.253.0", package = "rate-limit" } [dev-dependencies] glob = "0.3" From a80fad17925e33da0e2ddb54cef18a39201ee312 Mon Sep 17 00:00:00 2001 From: ilya Date: Mon, 8 Apr 2024 09:55:30 +0100 Subject: [PATCH 7/8] Fix after merge --- src/domain/solution.rs | 10 +--------- 1 file changed, 1 insertion(+), 9 deletions(-) diff --git a/src/domain/solution.rs b/src/domain/solution.rs index 483c263..07fb86e 100644 --- a/src/domain/solution.rs +++ b/src/domain/solution.rs @@ -32,14 +32,6 @@ impl Solution { Self { id, ..self } } - /// Sets the provided gas. - pub fn with_gas(self, gas: eth::Gas) -> Self { - Self { - gas: Some(gas), - ..self - } - } - /// Returns `self` with eligible interactions internalized using the /// Settlement contract buffers. /// @@ -139,7 +131,7 @@ impl Single { input, output, interactions, - gas, + gas: swap, } = self; if (order.sell.token, order.buy.token) != (input.token, output.token) { From a07776d5e77a8d3341b819e1536c67b829076f31 Mon Sep 17 00:00:00 2001 From: ilya Date: Tue, 9 Apr 2024 11:52:45 +0100 Subject: [PATCH 8/8] Fix after merge --- Cargo.lock | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index ba84ea6..91a0a38 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2190,7 +2190,7 @@ dependencies = [ "hex-literal", "lazy_static", "num", - "number 0.1.0 (git+https://github.com/cowprotocol/services.git?tag=v2.237.0)", + "number 0.1.0 (git+https://github.com/cowprotocol/services.git?tag=v2.253.0)", "primitive-types", "secp256k1", "serde", @@ -3303,7 +3303,7 @@ dependencies = [ "mockall", "model", "num", - "number 0.1.0 (git+https://github.com/cowprotocol/services.git?tag=v2.237.0)", + "number 0.1.0 (git+https://github.com/cowprotocol/services.git?tag=v2.253.0)", "observe", "order-validation", "primitive-types", @@ -3439,12 +3439,12 @@ dependencies = [ [[package]] name = "solvers-dto" version = "0.1.0" -source = "git+https://github.com/cowprotocol/services.git?tag=v2.253.0#2e6fbac515927e88dc40b720f1bb135cf8425075" +source = "git+https://github.com/cowprotocol/services.git?tag=v2.253.1#a940bc1d0421a66abdcfa2db7fc72b4b8068ff42" dependencies = [ "bigdecimal", "chrono", "hex", - "number", + "number 0.1.0 (git+https://github.com/cowprotocol/services.git?tag=v2.253.1)", "serde", "serde_with", "web3",