Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Do not count "in-market" orders for the order limit #2433 #2456

Merged
merged 4 commits into from
Mar 5, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 39 additions & 0 deletions crates/database/src/orders.rs
Original file line number Diff line number Diff line change
Expand Up @@ -716,6 +716,45 @@ pub async fn count_limit_orders_by_owner(
.await
}

#[derive(Debug, sqlx::FromRow)]
pub struct OrderWithQuote {
pub order_buy_amount: BigDecimal,
pub order_sell_amount: BigDecimal,
pub order_fee_amount: BigDecimal,
pub quote_buy_amount: BigDecimal,
pub quote_sell_amount: BigDecimal,
pub quote_gas_amount: f64,
pub quote_gas_price: f64,
pub quote_sell_token_price: f64,
}

pub async fn user_orders_with_quote(
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There is already a SQL query that counts limit orders. Instead of fetching all this data and counting in the rust code you could have the in-market check already in SQL to only return a single number.

Copy link
Contributor Author

@m-lord-renkse m-lord-renkse Mar 4, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@MartinquaXD how could we do that? we need to precisely operate the f64 so we can consider the limit order as "out of market" 🤔 do you mean by doing the operation directly in SQL?

see https://github.com/cowprotocol/services/pull/2456/files#diff-d22c8612ee861d55e838fdc5487a1c139da73b795295670acdcccea91f805011R386

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Basically reimplement the logic of is_order_outside_market_price() inside count_limit_orders_by_owner(). Hopefully there is a way in PSQL to convert the types appropriately for the computation.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@MartinquaXD In my opinion, doing arithmetical operations in PSQL query involving U256 and f64 is really not a good idea (unless it is plain sum, and even so), we are going to lose precision, and we are going to push CPU overhead to the database. What's more, I don't think we will save time, since database CPU is less powerful than the backend CPU, and the rust code will be definitely faster.

I understand your concern of potential long queries in case the user placed many orders, for that please, consider adding the internal class (as I proposed here #2456 (comment)), which will tackle down all the issues. We could also do the queries by pagination in case of long queries.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

not a good idea (unless it is plain sum

Interesting. Why do you think so?

we are going to lose precision

This is also the case in the rust code since.fee()calls U256::from_f64_lossy().

I don't think we will save time, since database CPU is less powerful than the backend CPU, and the rust code will be definitely faster.

Computations might be faster in rust but I very much doubt that returning all that data, parsing it, allocating the structs (1 Vec per BigDecimal) and doing the computation in rust will be faster than doing a computation inside the db and returning a single number.

This is not a hill I'm willing to die on (although I disagree) if you feel strongly about keeping the computation out of the DB I'd at least consider fetching the data using a stream instead of call .fetch_all() to limit the memory consumption when a user has lots of orders.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I guess we would need to benchmark this in order to get a definitive answer. It's true that for accounts with a lot of orders this may become a bottleneck. In theory we could also decide the "in-marketness" of an order when it's inserted into the db (and then simply count based on a flag)?

I'd be curious how PSQL math is less accurate than rust math?

ex: &mut PgConnection,
min_valid_to: i64,
owner: &Address,
) -> Result<Vec<OrderWithQuote>, sqlx::Error> {
#[rustfmt::skip]
const QUERY: &str = const_format::concatcp!(
"SELECT o_quotes.sell_amount as quote_sell_amount, o.sell_amount as order_sell_amount,",
" o_quotes.buy_amount as quote_buy_amount, o.buy_amount as order_buy_amount,",
" o.fee_amount as order_fee_amount, o_quotes.gas_amount as quote_gas_amount,",
" o_quotes.gas_price as quote_gas_price, o_quotes.sell_token_price as quote_sell_token_price",
" FROM order_quotes o_quotes",
" LEFT JOIN (",
" SELECT *",
" FROM (", OPEN_ORDERS,
" AND owner = $2",
" AND class = 'limit'",
" ) AS subquery",
" ) AS o ON o_quotes.order_uid = o.uid"
);
sqlx::query_as::<_, OrderWithQuote>(QUERY)
.bind(min_valid_to)
.bind(owner)
.fetch_all(ex)
.await
}

#[cfg(test)]
mod tests {
use {
Expand Down
130 changes: 130 additions & 0 deletions crates/e2e/tests/e2e/limit_orders.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use {
contracts::ERC20,
driver::domain::eth::NonZeroU256,
e2e::{nodes::forked_node::ForkedNodeApi, setup::*, tx},
ethcontract::{prelude::U256, H160},
model::{
Expand Down Expand Up @@ -30,6 +31,12 @@ async fn local_node_too_many_limit_orders() {
run_test(too_many_limit_orders_test).await;
}

#[tokio::test]
#[ignore]
async fn local_node_limit_does_not_apply_to_in_market_orders_test() {
run_test(limit_does_not_apply_to_in_market_orders_test).await;
}

#[tokio::test]
#[ignore]
async fn local_node_mixed_limit_and_market_orders() {
Expand Down Expand Up @@ -483,6 +490,129 @@ async fn too_many_limit_orders_test(web3: Web3) {
&onchain.contracts().domain_separator,
SecretKeyRef::from(&SecretKey::from_slice(trader.private_key()).unwrap()),
);

let (status, body) = services.create_order(&order).await.unwrap_err();
assert_eq!(status, 400);
assert!(body.contains("TooManyLimitOrders"));
}

async fn limit_does_not_apply_to_in_market_orders_test(web3: Web3) {
let mut onchain = OnchainComponents::deploy(web3.clone()).await;

let [solver] = onchain.make_solvers(to_wei(1)).await;
let [trader] = onchain.make_accounts(to_wei(1)).await;
let [token] = onchain
.deploy_tokens_with_weth_uni_v2_pools(to_wei(1_000), to_wei(1_000))
.await;
token.mint(trader.address(), to_wei(100)).await;

// Approve GPv2 for trading
tx!(
trader.account(),
token.approve(onchain.contracts().allowance, to_wei(101))
);

// Place Orders
let services = Services::new(onchain.contracts()).await;
let solver_endpoint =
colocation::start_baseline_solver(onchain.contracts().weth.address()).await;
colocation::start_driver(
onchain.contracts(),
vec![colocation::SolverEngine {
name: "test_solver".into(),
account: solver,
endpoint: solver_endpoint,
}],
);
services
.start_api(vec![
"--max-limit-orders-per-user=1".into(),
"--price-estimation-drivers=test_quoter|http://localhost:11088/test_solver".to_string(),
])
.await;

let quote_request = OrderQuoteRequest {
from: trader.address(),
sell_token: token.address(),
buy_token: onchain.contracts().weth.address(),
side: OrderQuoteSide::Sell {
sell_amount: SellAmount::BeforeFee {
value: NonZeroU256::try_from(to_wei(5)).unwrap(),
},
},
..Default::default()
};
let quote = services.submit_quote(&quote_request).await.unwrap();

// Place "in-market" order
let order = OrderCreation {
sell_token: token.address(),
sell_amount: quote.quote.sell_amount,
buy_token: onchain.contracts().weth.address(),
buy_amount: quote.quote.buy_amount.saturating_sub(to_wei(4)),
valid_to: model::time::now_in_epoch_seconds() + 300,
kind: OrderKind::Sell,
..Default::default()
}
.sign(
EcdsaSigningScheme::Eip712,
&onchain.contracts().domain_separator,
SecretKeyRef::from(&SecretKey::from_slice(trader.private_key()).unwrap()),
);
assert!(services.create_order(&order).await.is_ok());

// Place a "limit" order
let order = OrderCreation {
sell_token: token.address(),
sell_amount: to_wei(1),
buy_token: onchain.contracts().weth.address(),
buy_amount: to_wei(3),
valid_to: model::time::now_in_epoch_seconds() + 300,
kind: OrderKind::Sell,
..Default::default()
}
.sign(
EcdsaSigningScheme::Eip712,
&onchain.contracts().domain_separator,
SecretKeyRef::from(&SecretKey::from_slice(trader.private_key()).unwrap()),
);
let order_id = services.create_order(&order).await.unwrap();
let limit_order = services.get_order(&order_id).await.unwrap();
assert!(limit_order.metadata.class.is_limit());

// Place another "in-market" order in order to check it is not limited
let order = OrderCreation {
sell_token: token.address(),
sell_amount: quote.quote.sell_amount,
buy_token: onchain.contracts().weth.address(),
buy_amount: quote.quote.buy_amount.saturating_sub(to_wei(2)),
valid_to: model::time::now_in_epoch_seconds() + 300,
kind: OrderKind::Sell,
..Default::default()
}
.sign(
EcdsaSigningScheme::Eip712,
&onchain.contracts().domain_separator,
SecretKeyRef::from(&SecretKey::from_slice(trader.private_key()).unwrap()),
);
assert!(services.create_order(&order).await.is_ok());

// Place a "limit" order in order to see if fails
let order = OrderCreation {
sell_token: token.address(),
sell_amount: to_wei(1),
buy_token: onchain.contracts().weth.address(),
buy_amount: to_wei(2),
valid_to: model::time::now_in_epoch_seconds() + 300,
kind: OrderKind::Sell,
..Default::default()
}
.sign(
EcdsaSigningScheme::Eip712,
&onchain.contracts().domain_separator,
SecretKeyRef::from(&SecretKey::from_slice(trader.private_key()).unwrap()),
);

let (status, body) = services.create_order(&order).await.unwrap_err();
assert_eq!(status, 400);
assert!(body.contains("TooManyLimitOrders"));
Expand Down
26 changes: 24 additions & 2 deletions crates/orderbook/src/database/orders.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,9 @@ use {
signing_scheme_from,
signing_scheme_into,
},
fee::FeeParameters,
order_quoting::Quote,
order_validation::LimitOrderCounting,
order_validation::{is_order_outside_market_price, Amounts, LimitOrderCounting},
},
sqlx::{types::BigDecimal, Connection, PgConnection},
std::convert::TryInto,
Expand Down Expand Up @@ -374,12 +375,33 @@ impl LimitOrderCounting for Postgres {
.start_timer();

let mut ex = self.pool.acquire().await?;
Ok(database::orders::count_limit_orders_by_owner(
Ok(database::orders::user_orders_with_quote(
&mut ex,
now_in_epoch_seconds().into(),
&ByteArray(owner.0),
)
.await?
.into_iter()
.filter(|order_with_quote| {
is_order_outside_market_price(
&Amounts {
sell: big_decimal_to_u256(&order_with_quote.order_sell_amount).unwrap(),
buy: big_decimal_to_u256(&order_with_quote.order_buy_amount).unwrap(),
fee: big_decimal_to_u256(&order_with_quote.order_fee_amount).unwrap(),
},
&Amounts {
sell: big_decimal_to_u256(&order_with_quote.quote_sell_amount).unwrap(),
buy: big_decimal_to_u256(&order_with_quote.quote_buy_amount).unwrap(),
fee: FeeParameters {
gas_amount: order_with_quote.quote_gas_amount,
gas_price: order_with_quote.quote_gas_price,
sell_token_price: order_with_quote.quote_sell_token_price,
}
.fee(),
},
)
})
.count()
.try_into()
.unwrap())
}
Expand Down
Loading
Loading