Skip to content

skypank-coder/parity-exchange

Repository files navigation

⟁ PARITY

A real-time, globally-consistent event exchange — built on Amazon Aurora DSQL + Vercel.

Binary YES/NO prediction markets · a central limit order book per market · matching, ledger, and settlement in one strongly-consistent transaction.

🎥 Demo video · ▶ Live app · Consistency proof (live JSON) · Markets · Writeup (dev.to)

Aurora DSQL · Next.js (App Router) · TypeScript · Vercel · H0 Hackathon · Track 1 (Monetizable B2C)


The one sentence

Building an exchange normally needs a clearinghouse, a distributed ledger, and an infra team to keep balances consistent across regions. Aurora DSQL collapses all of that into one serverless primitive — so one developer built a globally-fair exchange where orders match and money settles in the same transaction, instantly, with zero ops.

No signup to try it: open the app and click "Enter as guest" for a funded account.


Why Aurora DSQL — the design is the point

DSQL uses optimistic concurrency control (OCC) with snapshot isolation: excellent when transactions touch distinct rows, bad under hot-row contention. Parity is architected with that grain, which is exactly what makes it a showcase rather than a naïve port:

  • Matching is scoped per-market — each market is its own contention domain; unrelated markets never conflict.
  • Every fill is a balanced double-entry across distinct rows — debit the buyer, credit the seller, update both positions, append two ledger rows, insert the fill. Counterparties are distinct rows → the OCC sweet spot.
  • Conflicts retry, lock-free — on SQLSTATE 40001 the whole transaction retries with exponential backoff + jitter (src/lib/tx.ts).
  • No negative balance, no double-spend — atomically — the debit is conditional (UPDATE … WHERE balance >= cost); if it can't fund, the fill simply doesn't happen.
  • Instant settlement — resolving a market pays every winning contract 100¢ and losers 0¢ in one consistent transaction set (src/lib/settle.ts).

DSQL-aware schema & connection

  • UUID primary keys (no sequences / SERIAL)
  • No foreign keys — relationships enforced in app logic
  • CREATE INDEX ASYNC — applied and verified on the live cluster
  • IAM-token auth, no hardcoded secrets — the Postgres password is a short-lived token minted on demand by @aws-sdk/dsql-signer (src/lib/db.ts)

Live consistency proof

Every fill is a balanced double-entry, so the ledger must net to zero — and you can verify it against the real cluster on demand:

GET https://parity-exchange.vercel.app/api/proof
{
  "backend": "Aurora DSQL",
  "trades": 23,
  "ledgerImbalance": 0,        // SUM of all trade ledger deltas — must be 0
  "negativeBalances": 0,       // no account can ever go below 0
  "cashConserved": true,       // total cash == total deposits
  "consistent": true
}

And the stress test fires 200+ concurrent, conflicting trades across markets, then asserts the invariants — exercising real DSQL OCC and 40001 retries:

npx tsx scripts/stress.ts
# PASS — ledger nets to 0, no double-spend, strong consistency.

Strong consistency under contention — not eventual.


Screenshots

Architecture — solid = shipped, dashed = roadmap:

Architecture

Aurora DSQL cluster (AWS console) Live trading page
DSQL cluster Trading
Live consistency proof (/api/proof) Vercel deployment
Proof Vercel

Architecture

 Client (Vercel / Next.js)
        │  REST, polled book (~1s)
        ▼
 /api match handler  ──────────►  Aurora DSQL  (per-market matching)
   • read resting book                ledger: distinct account rows
   • match (price-time priority)       OCC snapshot isolation
   • one short transaction             retry on 40001 (backoff + jitter)
   • debit/credit · positions · fills · ledger
        ▲
        └── single-region today (Tokyo); active-active multi-region by design

The data layer is dual-mode (src/lib/db.ts): set DATABASE_URL for standard Postgres (local Docker, managed PG) or DSQL_ENDPOINT + DSQL_REGION for Aurora DSQL. Identical app code — DSQL is Postgres-compatible.


Features

  • Markets — create + browse binary YES/NO markets; live last-price
  • Live trading page — polled order book, depth bars, order ticket, recent-trades tape
  • Matching engine — price-time priority CLOB, partial fills, cancels
  • Portfolio — balance, positions (long/short), open orders with cancel
  • Settlement — one-click resolve → instant payout to every position
  • Auth — one-click funded guest session + Continue with Google (OAuth)
  • Landing — cinematic scroll, R3F globe, scroll-driven architecture diagram, live consistency proof

Tech stack

Next.js 16 (App Router) · TypeScript · Tailwind v4 · Geist · Framer Motion · React Three Fiber · node-postgres · @aws-sdk/dsql-signer · Aurora DSQL · Vercel.


API

POST   /api/session              mint a funded guest account
DELETE /api/session              sign out
GET    /api/auth/google          Google OAuth start
GET    /api/auth/google/callback Google OAuth callback
GET    /api/markets              list markets (+ last price)
POST   /api/markets              create a market
GET    /api/markets/[id]/book    order book + recent trades (poll ~1s)
POST   /api/markets/[id]/settle  resolve a market { outcome: yes|no }
POST   /api/orders               place a limit order (matches + settles fills)
DELETE /api/orders/[id]          cancel an open order
GET    /api/portfolio            balance, positions, open orders
GET    /api/proof                live ledger invariants (consistency proof)

Core modules (hand-written, unit-tested)

File Role
src/lib/match.ts Pure price-time matcher + the atomic match/ledger transaction
src/lib/tx.ts OCC retry wrapper (40001 → backoff + jitter)
src/lib/settle.ts Instant settlement (winners → 100¢, losers → 0¢)
src/lib/db.ts Dual-mode pool (DSQL IAM token / Postgres URL)
src/lib/accounts.ts Guest + Google sessions

Run it

cp .env.example .env.local        # set DSQL_ENDPOINT + DSQL_REGION (+ AWS creds), or DATABASE_URL
npm install
npm run db:migrate                # apply db/schema.sql (DSQL keeps ASYNC indexes)
npm run db:seed                   # demo markets + house liquidity
npm run dev                       # http://localhost:3000

npm test                          # pure matcher unit tests
npx tsx scripts/stress.ts         # consistency proof: ~200 concurrent trades → ledger nets to 0

Local Postgres in one line (no AWS needed for dev):

docker run -d --name parity-pg -e POSTGRES_PASSWORD=parity -e POSTGRES_USER=parity -e POSTGRES_DB=parity -p 5433:5432 postgres:16
# then DATABASE_URL=postgresql://parity:parity@localhost:5433/parity

Hackathon submission alignment

Requirement Status
Primary backend is an AWS DB → Aurora DSQL ✅ live & verified
Frontend on Vercel ✅ deployed
Full-stack app, fits a track → Track 1
New project
Judges use it free, frictionless ✅ "Enter as guest"
Virtual credits, no real money
English throughout

Built for the H0 Hackathon. Aurora DSQL is the primary backend and the settlement ledger; the schema and transaction design are a deliberate, OCC-aware choice. #H0Hackathon

About

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

No releases published

Packages

 
 
 

Contributors