From 8273cd80cec095fcd8313a9f0aa48e357c25a15c Mon Sep 17 00:00:00 2001 From: Dusan Stanivukovic Date: Tue, 5 Nov 2024 11:19:14 +0100 Subject: [PATCH] Adjust the sql query for total surplus (#3090) # Description Fixes https://github.com/cowprotocol/services/issues/3089 # Changes Includes orders from "jit_orders" to calculate the total surplus. - [ ] Updated sql query. ## How to test Executed manually the new query against prod db. Two things are verified: 1. https://explorer.cow.fi/address/0xbf8868b754a77e90ea68ffc0b5b10a7c729457e1 now returns non-zero surplus. 2. Regular owners surplus remains the same, so this change did not break existing functionality. Performance should be good since "jit_orders" table also has index on owners. --- .../orderbook/src/database/total_surplus.rs | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/crates/orderbook/src/database/total_surplus.rs b/crates/orderbook/src/database/total_surplus.rs index d835031fd5..d0627de038 100644 --- a/crates/orderbook/src/database/total_surplus.rs +++ b/crates/orderbook/src/database/total_surplus.rs @@ -39,6 +39,32 @@ trade_components AS ( JOIN order_execution oe ON o.uid = oe.order_uid -- use this weird construction instead of `where owner=address or sender=address` to help postgres make efficient use of indices WHERE uid = ANY(ARRAY_CAT((SELECT ids FROM regular_orders), (SELECT ids FROM onchain_orders))) + + UNION ALL + + -- Additional query for jit_orders + SELECT + CASE j.kind + WHEN 'sell' THEN t.buy_amount + WHEN 'buy' THEN t.sell_amount - t.fee_amount + END AS trade_amount, + CASE j.kind + WHEN 'sell' THEN (t.sell_amount - t.fee_amount) * j.buy_amount / j.sell_amount + WHEN 'buy' THEN t.buy_amount * j.sell_amount / j.buy_amount + END AS limit_amount, + j.kind, + CASE j.kind + WHEN 'sell' THEN (SELECT price FROM auction_prices ap WHERE ap.token = j.buy_token AND ap.auction_id = oe.auction_id) + WHEN 'buy' THEN (SELECT price FROM auction_prices ap WHERE ap.token = j.sell_token AND ap.auction_id = oe.auction_id) + END AS surplus_token_native_price + FROM jit_orders j + JOIN trades t ON j.uid = t.order_uid + JOIN order_execution oe ON j.uid = oe.order_uid + WHERE j.owner = $1 AND NOT EXISTS ( + SELECT 1 + FROM orders o + WHERE o.uid = j.uid + ) ), trade_surplus AS ( SELECT