Skip to content
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: 38 additions & 1 deletion internal/migrations/032-order-book-actions.sql
Original file line number Diff line number Diff line change
Expand Up @@ -541,6 +541,10 @@ CREATE OR REPLACE ACTION match_direct(
-- Transfer payment from vault to seller
ob_unlock_collateral($bridge, $seller_wallet_address, $seller_payment);

-- Record fill events (execution price = sell_price for direct matches)
ob_record_order_event($query_id, $buy_participant_id, 'direct_buy_fill', $outcome, $sell_price, $match_amount, $sell_participant_id);
ob_record_order_event($query_id, $sell_participant_id, 'direct_sell_fill', $outcome, $sell_price, $match_amount, $buy_participant_id);

-- Record sell impact for P&L
ob_record_tx_impact($sell_participant_id, $outcome, -$match_amount, $seller_payment, FALSE);

Expand Down Expand Up @@ -715,6 +719,10 @@ CREATE OR REPLACE ACTION match_mint(
$mint_amount := $no_amount;
}

-- Record mint fill events
ob_record_order_event($query_id, $yes_participant_id, 'mint_fill', TRUE, $yes_price, $mint_amount, $no_participant_id);
ob_record_order_event($query_id, $no_participant_id, 'mint_fill', FALSE, $no_price, $mint_amount, $yes_participant_id);

-- Delete fully matched buy orders FIRST
DELETE FROM ob_positions
WHERE query_id = $query_id
Expand Down Expand Up @@ -887,6 +895,10 @@ CREATE OR REPLACE ACTION match_burn(
$burn_amount := $no_amount;
}

-- Record burn fill events
ob_record_order_event($query_id, $yes_participant_id, 'burn_fill', TRUE, $yes_price, $burn_amount, $no_participant_id);
ob_record_order_event($query_id, $no_participant_id, 'burn_fill', FALSE, $no_price, $burn_amount, $yes_participant_id);

-- Calculate payouts
$yes_payout NUMERIC(78, 0) := ($burn_amount::NUMERIC(78, 0) *
$yes_price::NUMERIC(78, 0) *
Expand Down Expand Up @@ -1218,6 +1230,9 @@ CREATE OR REPLACE ACTION place_buy_order(
SET amount = ob_positions.amount + EXCLUDED.amount,
last_updated = EXCLUDED.last_updated;

-- Record order event
ob_record_order_event($query_id, $participant_id, 'buy_placed', $outcome, $price, $amount, NULL);

-- ==========================================================================
-- SECTION 7: TRIGGER MATCHING ENGINE
-- ==========================================================================
Expand All @@ -1228,7 +1243,7 @@ CREATE OR REPLACE ACTION place_buy_order(
-- ==========================================================================
-- SECTION 8: CLEANUP & MATERIALIZE IMPACTS
-- ==========================================================================

ob_cleanup_tx_payouts($query_id);

-- Success: Order placed (may be partially or fully matched by future matching engine)
Expand Down Expand Up @@ -1406,6 +1421,9 @@ CREATE OR REPLACE ACTION place_sell_order(
SET amount = ob_positions.amount + EXCLUDED.amount,
last_updated = EXCLUDED.last_updated;

-- Record order event
ob_record_order_event($query_id, $participant_id, 'sell_placed', $outcome, $price, $amount, NULL);

-- ==========================================================================
-- SECTION 5: TRIGGER MATCHING ENGINE
-- ==========================================================================
Expand Down Expand Up @@ -1662,6 +1680,10 @@ CREATE OR REPLACE ACTION place_split_limit_order(
SET amount = ob_positions.amount + EXCLUDED.amount,
last_updated = EXCLUDED.last_updated;

-- Record order events: YES holding + NO sell
ob_record_order_event($query_id, $participant_id, 'split_placed', TRUE, $true_price, $amount, NULL);
ob_record_order_event($query_id, $participant_id, 'split_placed', FALSE, $false_price, $amount, NULL);

-- ==========================================================================
-- SECTION 8: TRIGGER MATCHING ENGINE
-- ==========================================================================
Expand Down Expand Up @@ -1859,6 +1881,15 @@ CREATE OR REPLACE ACTION cancel_order(
last_updated = EXCLUDED.last_updated;
}

-- Record cancel event (use absolute price for display)
$abs_cancel_price INT;
if $price < 0 {
$abs_cancel_price := -$price;
} else {
$abs_cancel_price := $price;
}
ob_record_order_event($query_id, $participant_id, 'cancelled', $outcome, $abs_cancel_price, $order_amount, NULL);

-- ==========================================================================
-- SECTION 7: DELETE CANCELLED ORDER
-- ==========================================================================
Expand Down Expand Up @@ -2119,6 +2150,9 @@ CREATE OR REPLACE ACTION change_bid(
ELSE EXCLUDED.last_updated -- Keep earlier timestamp (moved order was first)
END;

-- Record bid change event (positive price for display)
ob_record_order_event($query_id, $participant_id, 'bid_changed', $outcome, $new_abs_price, $new_amount, NULL);

-- ==========================================================================
-- SECTION 9: TRIGGER MATCHING ENGINE
-- ==========================================================================
Expand Down Expand Up @@ -2383,6 +2417,9 @@ CREATE OR REPLACE ACTION change_ask(
ELSE EXCLUDED.last_updated -- Keep earlier timestamp (moved order was first)
END;

-- Record ask change event
ob_record_order_event($query_id, $participant_id, 'ask_changed', $outcome, $new_price, $new_amount, NULL);

-- ==========================================================================
-- SECTION 8: TRIGGER MATCHING ENGINE
-- ==========================================================================
Expand Down
34 changes: 32 additions & 2 deletions internal/migrations/033-order-book-settlement.sql
Original file line number Diff line number Diff line change
Expand Up @@ -280,18 +280,48 @@ CREATE OR REPLACE ACTION process_settlement(
$outcomes BOOL[];
$total_fees NUMERIC(78, 0) := '0'::NUMERIC(78, 0);

-- First: record settlement events for ALL positions (winners + losers + open buys)
-- This uses a broader query than the payout calculation to include losing positions.
for $evt_row in
SELECT pos.participant_id, pos.price, pos.amount, pos.outcome
FROM ob_positions pos
WHERE pos.query_id = $query_id
ORDER BY pos.participant_id, pos.outcome, pos.price, pos.amount
{
$evt_pid INT := $evt_row.participant_id;
$evt_out BOOL := $evt_row.outcome;
$evt_amount INT8 := $evt_row.amount;
$evt_raw_price INT := $evt_row.price;

-- Determine settlement price for the event:
-- - Winning holdings (price=0, winning outcome): 98 (redemption at $0.98)
-- - Winning sell orders (price>0, winning outcome): 98 (redeemed, not sold)
-- - Losing positions (wrong outcome, price>=0): 0 (worthless)
-- - Open buy orders (price<0): abs(price) (collateral refund at buy price)
$evt_settle_price INT;
if $evt_raw_price < 0 {
$evt_settle_price := -$evt_raw_price;
} else if $evt_out = $winning_outcome {
$evt_settle_price := 98;
} else {
$evt_settle_price := 0;
}
ob_record_order_event($query_id, $evt_pid, 'settled', $evt_out, $evt_settle_price, $evt_amount, NULL);
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.

-- Second: calculate payouts (original logic, only winners + open buys)
for $res in
WITH target_positions AS (
SELECT pos.participant_id, p.wallet_address, pos.price, pos.amount, pos.outcome
FROM ob_positions pos JOIN ob_participants p ON pos.participant_id = p.id
WHERE pos.query_id = $query_id AND ((pos.price >= 0 AND pos.outcome = $winning_outcome) OR (pos.price < 0))
),
payout_calculation AS (
SELECT
SELECT
participant_id,
wallet_address,
'0x' || encode(wallet_address, 'hex') as wallet_hex,
CASE
CASE
WHEN price >= 0 THEN ((amount::NUMERIC(78, 0) * '1000000000000000000'::NUMERIC(78, 0) * 98::NUMERIC(78, 0)) / 100::NUMERIC(78, 0))
ELSE (amount::NUMERIC(78, 0) * (CASE WHEN price < 0 THEN -price ELSE price END)::NUMERIC(78, 0) * '10000000000000000'::NUMERIC(78, 0))
END as pay,
Expand Down
122 changes: 122 additions & 0 deletions internal/migrations/044-order-book-events.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
/*
* ORDER BOOK EVENT HISTORY
*
* Creates the ob_order_events table to record individual order events
* (placement, cancellation, fill, settlement) for wallet history queries.
*
* This table is EPHEMERAL on-chain — the indexer syncs events to permanent
* storage, then trim_order_events() deletes old rows to bound node storage.
* This follows the same pattern as tn_digest (write → index → trim).
*/

-- =============================================================================
-- ob_order_events: Individual order event log
-- =============================================================================
CREATE TABLE IF NOT EXISTS ob_order_events (
id INT8 PRIMARY KEY,
tx_hash BYTEA NOT NULL,
query_id INT NOT NULL,
participant_id INT NOT NULL,
event_type TEXT NOT NULL,
outcome BOOLEAN NOT NULL,
price INT NOT NULL,
amount INT8 NOT NULL,
counterparty_id INT,
block_height INT8 NOT NULL,
block_timestamp INT8 NOT NULL,

FOREIGN KEY (query_id) REFERENCES ob_queries(id),
FOREIGN KEY (participant_id) REFERENCES ob_participants(id)
);
Comment thread
coderabbitai[bot] marked this conversation as resolved.

-- Index for indexer sequential sync (same pattern as ob_net_impacts)
CREATE INDEX IF NOT EXISTS idx_ob_order_events_id ON ob_order_events(id);

-- Index for trim operations (delete by block_height)
CREATE INDEX IF NOT EXISTS idx_ob_order_events_height ON ob_order_events(block_height);

-- =============================================================================
-- ob_record_order_event: Helper to insert a single order event
-- =============================================================================
CREATE OR REPLACE ACTION ob_record_order_event(
$query_id INT,
$participant_id INT,
$event_type TEXT,
$outcome BOOLEAN,
$price INT,
$amount INT8,
$counterparty_id INT
) PRIVATE {
$next_id INT8;
for $row in SELECT COALESCE(MAX(id), 0::INT8) + 1 as val FROM ob_order_events {
$next_id := $row.val;
}

INSERT INTO ob_order_events (
id, tx_hash, query_id, participant_id, event_type,
outcome, price, amount, counterparty_id,
block_height, block_timestamp
) VALUES (
$next_id, decode(@txid, 'hex'), $query_id, $participant_id, $event_type,
$outcome, $price, $amount, $counterparty_id,
@height, @block_timestamp
);
};

-- =============================================================================
-- trim_order_events: Delete old events after indexer has synced them
-- =============================================================================
/**
* Called by the tn_digest scheduler (leader-only) to trim old order events.
* Uses block_height cutoff with a configurable buffer to ensure the indexer
* has had time to sync before deletion.
*
* Parameters:
* - $preserve_blocks: Number of recent blocks to keep (e.g., 172800 = ~2 days)
* - $delete_cap: Maximum rows to delete per invocation (prevents large txs)
*
* Returns via NOTICE: deleted count, remaining count, has_more flag
*/
CREATE OR REPLACE ACTION trim_order_events(
$preserve_blocks INT8,
$delete_cap INT
) PUBLIC owner {
$cutoff INT8 := @height - $preserve_blocks;

-- Don't trim if cutoff is negative (chain is younger than preserve window)
if $cutoff <= 0 {
NOTICE('trim_order_events: cutoff<=0, nothing to trim');
RETURN;
}

$count INT;
for $row in SELECT count(*)::INT as cnt FROM ob_order_events WHERE block_height < $cutoff {
$count := $row.cnt;
}

if $count = 0 {
NOTICE('trim_order_events: deleted=0 remaining=0 has_more=false');
RETURN;
}

$to_delete INT;
if $count > $delete_cap {
$to_delete := $delete_cap;
} else {
$to_delete := $count;
}

DELETE FROM ob_order_events
WHERE id IN (
SELECT id FROM ob_order_events
WHERE block_height < $cutoff
ORDER BY id ASC
LIMIT $to_delete
);

$remaining INT := $count - $to_delete;
$has_more BOOL := $count > $delete_cap;
NOTICE('trim_order_events: deleted=' || $to_delete::TEXT
|| ' remaining=' || $remaining::TEXT
|| ' has_more=' || $has_more::TEXT);
};
Loading
Loading