System Architecture
Kuest is built on a modern, serverless architecture that combines Next.js App Router, Polygon blockchain, and Supabase for a scalable, production-ready prediction market platform.Architecture Overview
Tech Stack
Frontend Framework
Next.js 16
App Router with Server Components, Server Actions, and Parallel Routes for optimal performance
React 19
Latest React features with Suspense, Transitions, and Server Components
TypeScript
Full type safety across the entire application
Tailwind CSS 4
Utility-first CSS with custom theme configuration
Blockchain Layer (Polygon)
Kuest currently runs on Polygon Amoy testnet with mainnet deployment coming soon. All contracts and infrastructure are production-ready.
Smart Contracts
| Contract | Address | Purpose |
|---|---|---|
| Conditional Tokens | 0x4682...A9C7 | ERC-1155 tokens representing YES/NO outcomes |
| CTF Exchange | 0xB559...61cb | Standard binary markets order matching |
| Neg Risk Exchange | 0xef02...24F5 | Negative risk markets (e.g., “Who will NOT win?”) |
| UMA CTF Adapter | 0x2008...bf8 | Oracle adapter for outcome resolution |
| UMA Neg Risk Adapter | 0x7242...d76 | Oracle adapter for negative risk markets |
| USDC Token | 0x41E9...7582 (testnet) | Collateral token for trading |
Blockchain Integration
- Reown AppKit: WalletConnect v2 integration for MetaMask, Rainbow, Coinbase Wallet, etc.
- Safe Wallet Support: Gnosis Safe integration for multi-sig wallets
- EIP-712 Signatures: Gasless order signing with typed data
- Contract Reads: Real-time fee rates and referral data from chain
Database Layer (Supabase)
PostgreSQL database with Drizzle ORM for type-safe queries:Database Schema
- Events
- Orders
- Users
- Affiliates
events table stores prediction markets:
- Stores market metadata, condition IDs for blockchain
- UMA oracle tracking for resolution
- Category tags and visibility settings
Storage
- Supabase Storage: Market images, logos, and user avatars
- S3-Compatible: Alternative to Supabase Storage for self-hosting
External APIs
Kuest CLOB (Central Limit Order Book)
- All forks connect to the same order book
- Shared liquidity across all deployments
- Real-time market data and price updates
- Order matching and execution
- Historical trades and volume
POST /orders- Place limit/market ordersDELETE /orders/:id- Cancel ordersGET /orderbook- Real-time order bookGET /markets- Market data and pricesGET /trades- Trade history
Component Architecture
Application Structure
Key Components
Trading System
Trading System
Order Flow:
- User creates order in UI (market/limit)
- Order parameters validated client-side
- EIP-712 signature generated (gasless)
- Order submitted to Kuest CLOB
- CLOB matches order against orderbook
- Settlement executed on-chain (CTF Exchange)
- Database updated with order status
src/lib/orders/signing.ts- EIP-712 order signingsrc/lib/orders/validation.ts- Order validation rulessrc/lib/exchange.ts- Exchange contract interactions
Market Data
Market Data
Data Pipeline:
- Sync Jobs (
/api/sync/*) run every 5 minutes - Fetch market data from Kuest CLOB
- Update database with latest prices/volumes
- Generate chart data and statistics
- Cache results with Next.js Data Cache
- Binary markets (YES/NO outcomes)
- Negative risk markets (exclusion logic)
- Recurring markets (crypto prices, Nasdaq, social metrics)
- Sports markets (live events)
src/app/api/sync/- Cron job endpointssrc/lib/db/queries/event.ts- Market queries
Authentication
Authentication
Auth Flow:Files:
- User connects wallet (Reown AppKit)
- Sign-in-with-Ethereum (SIWE) challenge
- User signs message with wallet
- Better Auth creates session
- Session stored in database + cookie
src/lib/auth.ts- Better Auth configurationsrc/lib/trading-auth/- CLOB authentication
UMA Oracle Resolution
UMA Oracle Resolution
Resolution Process:Files:
- Market reaches end date
- Admin/bot proposes outcome to UMA oracle
- UMA initiates challenge period (2 hours default)
- Anyone can dispute with bond
- If no dispute, outcome settles
- If disputed, UMA governance votes
- Winning outcome pushed on-chain
- Users redeem winning shares
src/lib/uma.ts- UMA URL builderssrc/lib/contracts.ts- UMA adapter addresses
Data Flow
Trading Flow
Market Sync Flow
Infrastructure Options
Option 1: Vercel + Supabase (Recommended)
Best for: Quick deployment, zero maintenancePros
- One-click deployment
- Automatic scaling
- Built-in CDN
- Integrated database
- Free tier available
Cons
- Vendor lock-in
- Usage-based pricing
- Limited customization
- Vercel: Next.js hosting, serverless functions, cron jobs
- Supabase: PostgreSQL, Storage, Auth (optional)
- Revalidation: ISR with 60s cache
Option 2: Docker Self-Hosted
Best for: Full control, cost optimizationPros
- Complete control
- Fixed costs
- Custom infrastructure
- No vendor lock-in
Cons
- Manual maintenance
- Requires DevOps knowledge
- Scaling complexity
- PostgreSQL database (self-hosted or managed)
- S3-compatible storage (MinIO, AWS S3, Backblaze B2)
- External cron scheduler
- Reverse proxy (Nginx, Traefik)
Option 3: Kubernetes
Best for: Enterprise deployments, high availabilityPros
- High availability
- Auto-scaling
- Multi-region support
- Production-grade
Cons
- Complex setup
- Higher costs
- K8s expertise required
- Deployment with replicas
- Service and Ingress
- ConfigMaps and Secrets
- CronJob for sync tasks
See Deployment Options for detailed guides on each infrastructure option.
Performance Optimizations
Server-Side Rendering (SSR)
- Market pages rendered on-demand
- User-specific data fetched server-side
- Parallel data loading with React Suspense
Incremental Static Regeneration (ISR)
Client-Side Caching
- React Query for API data
- Zustand for global state
- LocalStorage for user preferences
Database Optimization
- Indexed queries on high-traffic tables
- Materialized views for complex queries
- Connection pooling with Supabase
Security Considerations
Authentication
- Wallet-based auth (SIWE)
- Encrypted trading credentials
- Session management with Better Auth
- CSRF protection on mutations
API Security
- Rate limiting on public endpoints
- CRON_SECRET for scheduled jobs
- Input validation with Zod
- SQL injection prevention (Drizzle ORM)
Smart Contracts
- Audited UMA oracle contracts
- EIP-712 typed signatures
- On-chain fee enforcement
- Immutable condition IDs
Infrastructure
- HTTPS only (enforced)
- Environment variable encryption
- Sentry error monitoring
- Automated dependency updates
Scalability
Current Limits
- Vercel Free Tier: 100GB bandwidth, 100 serverless function hours
- Supabase Free Tier: 500MB database, 1GB storage, 2GB bandwidth
- Order Rate: Limited by CLOB API rate limits
Scaling Strategies
Monitoring & Observability
Built-in Monitoring
- Vercel Analytics: Traffic, performance, errors
- Sentry: Error tracking and alerting
- Supabase Dashboard: Database performance, query stats
Custom Metrics
Next Steps
Now that you understand the architecture:- Deployment: Choose your infrastructure
- Configuration: Configure advanced settings
- Features: Explore platform features
- API Reference: Build integrations