Files
eventbook-exchange/crates/exchange/src/schema.sql
T

330 lines
17 KiB
SQL

CREATE TABLE IF NOT EXISTS accounts (
id TEXT PRIMARY KEY, cash INTEGER NOT NULL CHECK(cash >= 0)
);
CREATE INDEX IF NOT EXISTS accounts_by_wallet ON accounts(id COLLATE NOCASE);
CREATE TABLE IF NOT EXISTS markets (
id TEXT PRIMARY KEY, rules TEXT NOT NULL, phase TEXT NOT NULL,
collateral INTEGER NOT NULL DEFAULT 0 CHECK(collateral >= 0), winner TEXT
);
CREATE TABLE IF NOT EXISTS market_visibility (
market TEXT PRIMARY KEY REFERENCES markets(id),
active INTEGER NOT NULL CHECK(active IN (0,1)), archived INTEGER NOT NULL CHECK(archived IN (0,1))
);
CREATE INDEX IF NOT EXISTS market_condition_case ON markets(id COLLATE NOCASE);
CREATE TABLE IF NOT EXISTS market_clarifications (
id INTEGER PRIMARY KEY, market TEXT NOT NULL REFERENCES markets(id),
content TEXT NOT NULL CHECK(length(trim(content))>0),
clear_book INTEGER NOT NULL CHECK(clear_book IN (0,1)),
created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now'))
);
CREATE INDEX IF NOT EXISTS clarifications_by_market ON market_clarifications(market,id);
CREATE TABLE IF NOT EXISTS positions (
account TEXT REFERENCES accounts, market TEXT REFERENCES markets, outcome TEXT,
quantity INTEGER NOT NULL CHECK(quantity >= 0), PRIMARY KEY(account,market,outcome)
);
CREATE INDEX IF NOT EXISTS positions_by_market ON positions(market,account,outcome);
CREATE TABLE IF NOT EXISTS orders (
seq INTEGER PRIMARY KEY, account TEXT REFERENCES accounts, market TEXT REFERENCES markets,
outcome TEXT NOT NULL, side TEXT NOT NULL, price INTEGER NOT NULL, quantity INTEGER NOT NULL,
remaining INTEGER NOT NULL CHECK(remaining >= 0), status TEXT NOT NULL
);
CREATE INDEX IF NOT EXISTS active_book ON orders(market,outcome,seq) WHERE status='live';
CREATE INDEX IF NOT EXISTS account_open_orders ON orders(account,seq) WHERE status='live';
CREATE TABLE IF NOT EXISTS fills (
seq INTEGER PRIMARY KEY, bid INTEGER REFERENCES orders, ask INTEGER REFERENCES orders,
price INTEGER NOT NULL, quantity INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS requests (
id TEXT PRIMARY KEY, payload TEXT NOT NULL, response TEXT NOT NULL
);
-- Keep only the last change per order. Other connections can catch up by revision.
CREATE TABLE IF NOT EXISTS book_changes (
seq INTEGER PRIMARY KEY REFERENCES orders, revision INTEGER NOT NULL UNIQUE
);
CREATE TRIGGER IF NOT EXISTS book_insert AFTER INSERT ON orders BEGIN
INSERT INTO book_changes(seq, revision)
SELECT NEW.seq, COALESCE(MAX(revision), 0) + 1 FROM book_changes;
END;
CREATE TRIGGER IF NOT EXISTS book_update AFTER UPDATE OF remaining,status ON orders BEGIN
INSERT OR REPLACE INTO book_changes(seq, revision)
SELECT NEW.seq, COALESCE(MAX(revision), 0) + 1 FROM book_changes;
END;
CREATE TABLE IF NOT EXISTS events (
id TEXT PRIMARY KEY, title TEXT NOT NULL, sport TEXT NOT NULL, competition TEXT NOT NULL,
home TEXT NOT NULL, away TEXT NOT NULL, scheduled_at_ms INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS sports_markets (
market TEXT PRIMARY KEY REFERENCES markets, event TEXT NOT NULL REFERENCES events,
question TEXT NOT NULL, yes_label TEXT NOT NULL, no_label TEXT NOT NULL,
terms TEXT NOT NULL, source TEXT NOT NULL, resolver TEXT NOT NULL, rules_version INTEGER NOT NULL
);
CREATE INDEX IF NOT EXISTS event_markets ON sports_markets(event,market);
-- A sports event's existing ID is also its discovery slug. Keep both lookup
-- keys unique across sports and topics, including writes from older clients.
CREATE TABLE IF NOT EXISTS topics (
id TEXT PRIMARY KEY, slug TEXT NOT NULL UNIQUE, title TEXT NOT NULL, category TEXT NOT NULL
);
CREATE TRIGGER IF NOT EXISTS topic_keys BEFORE INSERT ON topics
WHEN EXISTS (SELECT 1 FROM events WHERE id IN (NEW.id, NEW.slug)) BEGIN
SELECT RAISE(ABORT,'event ID or slug already exists');
END;
CREATE TRIGGER IF NOT EXISTS sports_event_keys BEFORE INSERT ON events
WHEN EXISTS (SELECT 1 FROM topics WHERE id=NEW.id OR slug=NEW.id) BEGIN
SELECT RAISE(ABORT,'event ID or slug already exists');
END;
CREATE TABLE IF NOT EXISTS topic_markets (
market TEXT PRIMARY KEY REFERENCES markets, event TEXT NOT NULL REFERENCES topics,
question TEXT NOT NULL, yes_label TEXT NOT NULL, no_label TEXT NOT NULL,
source TEXT NOT NULL, resolver TEXT NOT NULL, rules_version INTEGER NOT NULL,
group_title TEXT, group_order INTEGER NOT NULL
);
CREATE INDEX IF NOT EXISTS topic_children ON topic_markets(event,group_order,market);
CREATE VIEW IF NOT EXISTS event_directory AS
SELECT id,id AS slug,title,'sports' AS category,sport,competition,home,away,scheduled_at_ms FROM events
UNION ALL SELECT id,slug,title,category,NULL,NULL,NULL,NULL,NULL FROM topics;
CREATE VIEW IF NOT EXISTS listed_markets AS
SELECT market,event,question,yes_label,no_label,terms,source,resolver,rules_version,
NULL AS group_title,0 AS group_order FROM sports_markets
UNION ALL SELECT market,event,question,yes_label,no_label,NULL,source,resolver,rules_version,
group_title,group_order FROM topic_markets;
CREATE TABLE IF NOT EXISTS trade_prices (
fill INTEGER PRIMARY KEY REFERENCES fills, market TEXT NOT NULL REFERENCES markets,
outcome TEXT NOT NULL, at_ms INTEGER NOT NULL, price_micros INTEGER NOT NULL, quantity INTEGER NOT NULL
);
CREATE INDEX IF NOT EXISTS trade_series ON trade_prices(market,outcome,at_ms,fill);
CREATE TABLE IF NOT EXISTS paired_fills (
seq INTEGER PRIMARY KEY, market TEXT NOT NULL REFERENCES markets,
kind TEXT NOT NULL CHECK(kind IN ('mint','merge')),
yes_order INTEGER NOT NULL REFERENCES orders, no_order INTEGER NOT NULL REFERENCES orders,
yes_price INTEGER NOT NULL CHECK(yes_price BETWEEN 0 AND 100),
quantity INTEGER NOT NULL CHECK(quantity>0),
at_ms INTEGER NOT NULL DEFAULT (CAST(unixepoch('subsec')*1000 AS INTEGER))
);
CREATE INDEX IF NOT EXISTS public_direct_time ON trade_prices(at_ms,fill);
CREATE VIEW IF NOT EXISTS next_execution AS
SELECT 1+MAX(COALESCE((SELECT MAX(seq) FROM fills),0),
COALESCE((SELECT MAX(seq) FROM paired_fills),0)) AS id;
CREATE TABLE IF NOT EXISTS order_deadlines (
seq INTEGER PRIMARY KEY REFERENCES orders,
expiration INTEGER NOT NULL,
pending INTEGER NOT NULL DEFAULT 1 CHECK(pending IN (0,1))
);
CREATE INDEX IF NOT EXISTS pending_deadlines ON order_deadlines(expiration) WHERE pending=1;
CREATE TRIGGER IF NOT EXISTS finish_deadline AFTER UPDATE OF status ON orders
WHEN OLD.status='live' AND NEW.status<>'live' BEGIN
UPDATE order_deadlines SET pending=0 WHERE seq=NEW.seq;
END;
-- A present row with no taker records an opening auction. Older executions
-- have no row and retain an unknown role.
CREATE TABLE IF NOT EXISTS execution_context (
execution INTEGER PRIMARY KEY, taker_order INTEGER REFERENCES orders(seq)
);
CREATE INDEX IF NOT EXISTS account_orders_history ON orders(account,seq);
CREATE INDEX IF NOT EXISTS market_buy_orders ON orders(market,seq) WHERE side='buy';
CREATE INDEX IF NOT EXISTS fills_by_bid ON fills(bid,seq);
CREATE INDEX IF NOT EXISTS fills_by_ask ON fills(ask,seq);
CREATE TABLE IF NOT EXISTS optimistic_markets (
market TEXT PRIMARY KEY REFERENCES markets(id), eligible_at INTEGER NOT NULL CHECK(eligible_at>=0)
);
CREATE TABLE IF NOT EXISTS resolution_questions (
market TEXT PRIMARY KEY REFERENCES optimistic_markets(market), question_id TEXT NOT NULL UNIQUE
);
CREATE TABLE IF NOT EXISTS resolution_proposals (
id INTEGER PRIMARY KEY, market TEXT NOT NULL REFERENCES optimistic_markets(market),
round INTEGER NOT NULL CHECK(round IN (1,2)),
result TEXT NOT NULL CHECK(result IN ('YES','NO','VOID')), proposer TEXT NOT NULL, evidence TEXT NOT NULL,
proposed_at INTEGER NOT NULL, challenger TEXT, challenged_at INTEGER, challenge_evidence TEXT,
verdict TEXT CHECK(verdict IN ('YES','NO','VOID','TOO_EARLY')), verdict_evidence TEXT, decided_at INTEGER
);
CREATE INDEX IF NOT EXISTS proposal_history ON resolution_proposals(market,id);
CREATE VIEW IF NOT EXISTS market_resolution AS
SELECT m.id AS market,m.winner,m.phase,p.eligible_at,r.id AS proposal,r.result,r.verdict,
CASE WHEN m.phase='resolved' THEN 'resolved'
WHEN m.phase<>'closed' THEN 'trading'
WHEN p.market IS NULL THEN 'awaiting_manual_result'
WHEN unixepoch()<p.eligible_at THEN 'waiting_for_end'
WHEN r.id IS NULL OR r.verdict='TOO_EARLY' THEN 'awaiting_proposal'
WHEN r.verdict IS NOT NULL THEN 'arbitrated'
WHEN r.challenged_at IS NOT NULL AND r.round=1 THEN 'awaiting_second_proposal'
WHEN r.challenged_at IS NOT NULL THEN 'awaiting_arbitration'
WHEN unixepoch()>=r.proposed_at+7200 THEN 'ready_to_finalize'
ELSE 'challenge_window' END AS status
FROM markets m LEFT JOIN optimistic_markets p ON p.market=m.id
LEFT JOIN resolution_proposals r ON r.id=(
SELECT id FROM resolution_proposals WHERE market=m.id ORDER BY id DESC LIMIT 1);
CREATE TABLE IF NOT EXISTS twap_markets (
market TEXT PRIMARY KEY REFERENCES markets, stream TEXT NOT NULL,
start_at INTEGER NOT NULL CHECK(start_at>=0), end_at INTEGER NOT NULL CHECK(end_at>start_at),
pending_close INTEGER NOT NULL DEFAULT 1
);
CREATE INDEX IF NOT EXISTS twap_close_time ON twap_markets(end_at) WHERE pending_close=1;
CREATE TRIGGER IF NOT EXISTS finish_twap_window AFTER UPDATE OF phase ON markets
WHEN NEW.phase='closed' BEGIN
UPDATE twap_markets SET pending_close=0 WHERE market=NEW.id;
END;
CREATE TABLE IF NOT EXISTS twap_reports (
stream TEXT NOT NULL, observed_at INTEGER NOT NULL, price TEXT NOT NULL,
evidence TEXT NOT NULL, PRIMARY KEY(stream,observed_at)
);
CREATE VIEW IF NOT EXISTS twap_result AS
SELECT t.market,t.stream,t.start_at,t.end_at,a.price AS opening,b.price AS closing,
a.evidence AS opening_source,b.evidence AS closing_source,
CASE WHEN unixepoch()>=t.end_at AND a.price IS NOT NULL AND b.price IS NOT NULL THEN
CASE WHEN (instr(b.price||'.','.'),b.price)>=(instr(a.price||'.','.'),a.price)
THEN 'YES' ELSE 'NO' END END AS result
FROM twap_markets t
LEFT JOIN twap_reports a ON a.stream=t.stream AND a.observed_at=t.start_at
LEFT JOIN twap_reports b ON b.stream=t.stream AND b.observed_at=t.end_at;
CREATE TABLE IF NOT EXISTS budget_buys (
order_seq INTEGER PRIMARY KEY REFERENCES orders,
amount_cents INTEGER NOT NULL CHECK(amount_cents>0),
spent_cents INTEGER NOT NULL CHECK(spent_cents BETWEEN 0 AND amount_cents)
);
-- Each conversion adds an equal YES-minus-NO supply to every member.
-- This reserve covers that excess at the single winning member.
CREATE TABLE IF NOT EXISTS neg_risk_groups (
id TEXT PRIMARY KEY, reserve_cents INTEGER NOT NULL DEFAULT 0 CHECK(reserve_cents>=0),
winner TEXT REFERENCES markets
);
CREATE TABLE IF NOT EXISTS neg_risk_conversion_fees (
group_id TEXT PRIMARY KEY REFERENCES neg_risk_groups(id),
bps INTEGER NOT NULL CHECK(bps BETWEEN 0 AND 10000),
vault TEXT NOT NULL REFERENCES accounts(id)
);
CREATE TABLE IF NOT EXISTS neg_risk_reserve_remainders (
group_id TEXT PRIMARY KEY REFERENCES neg_risk_groups(id), micros INTEGER NOT NULL CHECK(micros BETWEEN 0 AND 9999)
);
CREATE VIEW IF NOT EXISTS neg_risk_reserves AS
SELECT g.id,g.winner,g.reserve_cents*10000+COALESCE(r.micros,0) AS micros
FROM neg_risk_groups g LEFT JOIN neg_risk_reserve_remainders r ON r.group_id=g.id;
CREATE TABLE IF NOT EXISTS neg_risk_members (
market TEXT PRIMARY KEY REFERENCES markets, group_id TEXT NOT NULL REFERENCES neg_risk_groups,
ordinal INTEGER NOT NULL, UNIQUE(group_id,ordinal)
);
CREATE TABLE IF NOT EXISTS augmented_outcomes (
market TEXT PRIMARY KEY REFERENCES neg_risk_members(market),
group_id TEXT NOT NULL REFERENCES neg_risk_groups(id),
role TEXT NOT NULL CHECK(role IN ('named','placeholder','other')),
name TEXT, question TEXT, clarification TEXT, named_at INTEGER,
CHECK ((role='placeholder')=(name IS NULL)),
UNIQUE(group_id,name)
);
CREATE UNIQUE INDEX IF NOT EXISTS augmented_other ON augmented_outcomes(group_id) WHERE role='other';
CREATE TABLE IF NOT EXISTS augmented_results (
group_id TEXT PRIMARY KEY REFERENCES neg_risk_groups(id),
observed_name TEXT NOT NULL, winner TEXT NOT NULL REFERENCES augmented_outcomes(market),
evidence TEXT NOT NULL
);
CREATE TRIGGER IF NOT EXISTS reject_placeholder_orders BEFORE INSERT ON orders
WHEN EXISTS(SELECT 1 FROM augmented_outcomes WHERE market=NEW.market AND role='placeholder')
BEGIN SELECT RAISE(ABORT,'outcome has not been named'); END;
-- Existing resolved rows have no trustworthy settlement timestamp to backfill.
CREATE TABLE IF NOT EXISTS price_settlements (
id INTEGER PRIMARY KEY, market TEXT NOT NULL UNIQUE REFERENCES markets,
winner TEXT NOT NULL, at_ms INTEGER NOT NULL
);
CREATE TRIGGER IF NOT EXISTS record_price_settlement AFTER UPDATE OF phase ON markets
WHEN NEW.phase='resolved' AND OLD.phase<>'resolved' BEGIN
INSERT INTO price_settlements(market,winner,at_ms)
VALUES(NEW.id,NEW.winner,CAST(unixepoch('subsec')*1000 AS INTEGER));
END;
CREATE TABLE IF NOT EXISTS market_fee_rates (
market TEXT PRIMARY KEY REFERENCES markets(id), rate_ppm INTEGER NOT NULL CHECK(rate_ppm BETWEEN 0 AND 1000000)
);
CREATE TABLE IF NOT EXISTS market_base_fees (
market TEXT PRIMARY KEY REFERENCES markets(id), maker_bps INTEGER NOT NULL CHECK(maker_bps>=0),
taker_bps INTEGER NOT NULL CHECK(taker_bps>=0)
);
-- Older editions stored only the execution curve. Publish its coefficient as an
-- integer basis-point default only when that conversion is exact.
CREATE VIEW IF NOT EXISTS market_fee_terms AS
SELECT m.id AS market, COALESCE(f.rate_ppm,0) AS rate_ppm, COALESCE(b.maker_bps,0) AS maker_bps,
COALESCE(b.taker_bps,CASE WHEN COALESCE(f.rate_ppm,0)%100=0 THEN COALESCE(f.rate_ppm,0)/100 END) AS taker_bps
FROM markets m LEFT JOIN market_fee_rates f ON f.market=m.id LEFT JOIN market_base_fees b ON b.market=m.id;
CREATE TABLE IF NOT EXISTS cash_remainders (
account TEXT PRIMARY KEY REFERENCES accounts(id), micros INTEGER NOT NULL CHECK(micros BETWEEN 0 AND 9999)
);
CREATE TABLE IF NOT EXISTS execution_fees (
execution INTEGER PRIMARY KEY REFERENCES execution_context(execution),
taker_order INTEGER NOT NULL REFERENCES orders(seq), fee_micros INTEGER NOT NULL CHECK(fee_micros>0)
);
CREATE INDEX IF NOT EXISTS fees_by_order ON execution_fees(taker_order);
CREATE TABLE IF NOT EXISTS order_keys (
order_seq INTEGER PRIMARY KEY REFERENCES orders(seq), key_id TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS order_heartbeats (
account TEXT NOT NULL REFERENCES accounts(id), key_id TEXT NOT NULL,
heartbeat_id TEXT NOT NULL, deadline_ms INTEGER NOT NULL,
PRIMARY KEY(account,key_id)
);
CREATE INDEX IF NOT EXISTS heartbeat_deadlines ON order_heartbeats(deadline_ms);
CREATE TABLE IF NOT EXISTS market_minimum_sizes (
market TEXT PRIMARY KEY REFERENCES markets(id),
microshares INTEGER NOT NULL CHECK(microshares BETWEEN 1 AND 1000000000000000)
);
CREATE TABLE IF NOT EXISTS market_tick_sizes (
market TEXT PRIMARY KEY REFERENCES markets(id),
step_micros INTEGER NOT NULL CHECK(step_micros IN (100000,10000,5000,2500,1000,100))
);
CREATE TABLE IF NOT EXISTS tick_changes (
seq INTEGER PRIMARY KEY, market TEXT NOT NULL REFERENCES market_tick_sizes(market),
at_ms INTEGER NOT NULL CHECK(at_ms>=0), old_micros INTEGER, new_micros INTEGER NOT NULL,
request_id TEXT NOT NULL REFERENCES requests(id) DEFERRABLE INITIALLY DEFERRED,
UNIQUE(market,at_ms)
);
CREATE INDEX IF NOT EXISTS tick_changes_by_seq ON tick_changes(market,seq);
CREATE TABLE IF NOT EXISTS position_remainders (
account TEXT NOT NULL, market TEXT NOT NULL, outcome TEXT NOT NULL,
micros INTEGER NOT NULL CHECK(micros BETWEEN 0 AND 999999),
PRIMARY KEY(account,market,outcome),
FOREIGN KEY(account,market,outcome) REFERENCES positions(account,market,outcome)
);
CREATE TABLE IF NOT EXISTS collateral_remainders (
market TEXT PRIMARY KEY REFERENCES markets(id), micros INTEGER NOT NULL CHECK(micros BETWEEN 0 AND 9999)
);
CREATE TABLE IF NOT EXISTS settlement_dust (
market TEXT PRIMARY KEY REFERENCES markets(id), micros INTEGER NOT NULL CHECK(micros>0)
);
CREATE TABLE IF NOT EXISTS precise_movements (
request_id TEXT NOT NULL, account TEXT NOT NULL, shares_micros INTEGER NOT NULL, cash_micros INTEGER NOT NULL,
PRIMARY KEY(request_id,account),
FOREIGN KEY(request_id,account) REFERENCES wallet_movements(request_id,account) DEFERRABLE INITIALLY DEFERRED
);
CREATE VIEW IF NOT EXISTS position_units AS
SELECT p.account,p.market,p.outcome,p.available*1000000+COALESCE(r.micros,0) AS available,
p.reserved*10000 AS reserved,p.phase,p.payout_per_share
FROM position_sizes p LEFT JOIN position_remainders r USING(account,market,outcome);
CREATE VIEW IF NOT EXISTS market_backing AS
SELECT m.id AS market,m.collateral*10000+COALESCE(r.micros,0) AS micros
FROM markets m LEFT JOIN collateral_remainders r ON r.market=m.id;
CREATE TABLE IF NOT EXISTS budget_spend_micros (
order_seq INTEGER PRIMARY KEY REFERENCES budget_buys(order_seq),
micros INTEGER NOT NULL CHECK(micros>=0)
);
-- Keep issued public trade cursors valid after a restart, scoped to this database.
CREATE TABLE IF NOT EXISTS trade_cursor_key (
singleton INTEGER PRIMARY KEY CHECK(singleton=1), secret BLOB NOT NULL CHECK(length(secret)=32)
);
INSERT INTO trade_cursor_key(singleton,secret)
SELECT 1,randomblob(32) WHERE NOT EXISTS(SELECT 1 FROM trade_cursor_key);