Skip to content

Commit

Permalink
Adjust the sql query for total surplus (#3090)
Browse files Browse the repository at this point in the history
# Description
Fixes #3089

# Changes
<!-- List of detailed changes (how the change is accomplished) -->

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.
  • Loading branch information
sunce86 authored Nov 5, 2024
1 parent ce91316 commit 8273cd8
Showing 1 changed file with 26 additions and 0 deletions.
26 changes: 26 additions & 0 deletions crates/orderbook/src/database/total_surplus.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit 8273cd8

Please sign in to comment.