Architecture
Data Model Prisma schema with 90+ models across ~12 domains
The backend uses Prisma ORM with PostgreSQL. The schema contains 90+ models organized across roughly a dozen domain groups (auth, trading/portfolio, social, signals/AI, agent chat, combo trades, sports/contests, rewards, notifications, and platform). All financial values use Prisma Decimal types with explicit precision -- never JavaScript floats. The tables below cover the core models; agent-chat, combo, contest, and sports models are described on their respective architecture pages.
Financial field precisions: @db.Decimal(18, 2) for USD amounts and volumes, @db.Decimal(10, 6) for prices and probabilities, @db.Decimal(18, 6) for fees and share quantities, @db.Decimal(5, 4) for rates and tolerances.
Model Key Fields Purpose UserwalletAddress, walletChain, tier, accountTier, totalVolume, totalPointsPrimary user record, linked to all trading and social data RefreshTokentokenHash, family, used, revoked, expiresAtJWT refresh token with rotation and family-based revocation SubWalletchain, address, signerCiphertext, clobApiKeyExchange sub-wallets with encrypted private keys and CLOB credentials AccessKeykey, creatorId, usedById, status, source, maxUses, usedCount, expiresAtInvite-based access keys (KeyStatus: ACTIVE, USED, REVOKED, EXPIRED) ReferralreferrerId, refereeId, layerMulti-layer referral chain ReferralEarningfeeAmount, commission, ratePer-order referral commission tracking UserPreferencesTrading defaults, display settings, notification toggles User-configurable settings ApiKeykeyPrefix, keyHash, permissionsAPI key management with permission scoping KycVerificationstatus, level, documentType, withdrawal limitsIdentity verification workflow (NOT_STARTED through APPROVED/REJECTED) RewardEscrowtype, amount, status, releaseAtReward escrow with delayed release and clawback
Model Key Fields Purpose Marketslug, source, yesPrice, noPrice, volume24h, change24h, closesAtUnified market record from Polymarket or Kalshi EventGroupslug, title, category, totalVolumeGroups related markets into a single event Orderside, type, action, status, price, quantity, filledQuantity, exchangeTrade orders with state machine (CREATED through FILLED/CANCELLED/FAILED) Positionside, shares, entryPrice, currentPrice, unrealizedPnl, takeProfitPrice, stopLossPriceOpen and closed positions with TP/SL Transactiontype, status, amount, currency, txHashDeposit/withdrawal transaction records PnlSnapshottotalValue, realizedPnl, unrealizedPnl, snapshotDateDaily portfolio value snapshots for PnL charts MarketPriceSnapshotmarketId, yesPrice, createdAtPrice history data points for sparklines and charts ExchangeTradesource, side, outcome, price, size, makerAddress, tradedAtSynced trades from Polymarket/Kalshi for the trade feed SniperOrdertriggerPrice, amount, slippage, statusPrice-triggered orders (WATCHING, EXECUTING, FILLED, EXPIRED) CounterTradeConfigtargetWalletAddress, strategy, sizeMultiplier, dailyStopLossAutomated inverse trading configuration
Model Key Fields Purpose WatchlistuserId, marketIdUser's watched markets TrackedWalletaddress, displayName, category, alertOnWallet addresses the user is monitoring CopyTradeSubscriptiontargetWalletAddress, sizingStrategy, fixedAmount, maxPositionUsdCopy trade configuration with sizing, exit, and filter rules CommentmarketId, content, parentId, likesCountMarket discussion threads with nested replies CommentLikecommentId, userIdPer-user comment likes TopTraderaddress, pnl, roi, winRate, volume, period, category, rankCached leaderboard data from Polymarket LoginStreakuserId, loginDateDaily login tracking for streak rewards ActivityLogtype, address, side, amount, metadataAll platform activity for the global feed Challengetitle, type, target, metric, rewardPointsTime-limited trading challenges ChallengeParticipantchallengeId, userId, progress, completedUser progress in active challenges
Model Key Fields Purpose AiPredictionmarketId, aiPrediction, confidence, alpha, signal, accuracy7dLLM-backed predictions per market (via OpenRouter) AiModelStatsmodelVersion, overallAccuracy, winRate, totalPredictionsAggregate model performance metrics MonitorSignaltype, severity, headline, source, category, lat, lng, address, marketIdNews + whale signals with geo-coordinates NewsArticletitle, source, url, sentiment, publishedAtIngested news articles linked to markets and event groups
Model Key Fields Purpose InsiderAlertwalletAddress, marketId, tier, score, coordinatedIdFanout target -- one row per published alert WalletLabelwalletAddress, filterClass, fundingClass, expiresAt11-layer filter classification + funding-trace class, 30d TTL MarketClusterclusterId, marketIds[], eventIdDCS metric input (rule-based: same Polymarket event_id OR title-token Jaccard ≥0.5 + ±7d resolution date) InsiderAlertFeedbackalertId, userId, voteFalse-positive / real votes for tuning TelegramBindingtelegramId, userId, chatId, walletTypeUser → Telegram chat link (bot linking)
Model Key Fields Purpose PointsLedgeramount, source, sourceIdPoint credit/debit records Missiontitle, reward, target, type, metric, activeMission definitions (daily, weekly, one-time) MissionProgressuserId, missionId, progress, target, completed, claimedPer-user mission completion tracking
Model Key Fields Purpose Notificationtype, title, message, read, marketIdIn-app notification records PriceAlertmarketId, condition, targetPrice, channels, triggeredUser-configured price alerts with multi-channel delivery
Model Key Fields Purpose WaitlistEntryemail, position, status, tweetUrl, accessKeyIdEarly access waitlist (PENDING_TWEET, TWEET_VERIFIED, KEY_ACTIVATED) DeviceTokentoken, platform, deviceId, activeMobile push notification tokens (iOS/Android) PaperBalancebalance, initialBalancePaper trading virtual balance PaperTransactiontype, amount, balanceBefore, balanceAfterPaper trading transaction history CryptoPriceTicksymbol, price, source, createdAtPer-tick crypto spot prices from Chainlink via Polymarket RTDS (source=CHAINLINK). Written inline by PolymarketRtdsConnector on the worker-rtds container. Used by the short-duration crypto chart and target-price service. Cleaned up after 24h.
Newer subsystems add their own model families (see the Agent Chat page for the agent models in depth):
Model(s) Domain Purpose AgentConversation, AgentMessage, AgentToolCall, AgentTradeMemory, AgentUserPreferenceAgent chat Conversation threads, messages, per-tool invocation records, remembered trade context, and per-user agent preferences ResearchReportResearch Structured AI market-research reports (shared + private) ComboOrder, ComboLeg, ComboEligibleMarketCombo Multi-leg combo orders, their legs, and the per-game eligibility catalog LeagueStandings, MatchStats, SportsMeta, WorldCupSnapshotSports ESPN standings, live match stats, sport metadata, World Cup snapshots Contest, ContestEntry, ContestStandingContests World Cup oracle contest entries and standings MarketMatch, MarketEmbedding, MarketTraderAggregateMatching Cross-platform market matching and semantic embeddings CommissionRule, MakerRebateSnapshot, LpRewardSnapshotRewards/rebates Commission tiers, maker rebates, and LP reward snapshots TelegramBinding, TelegramSignalPost, DailySignalStatTelegram Account linking, published signal posts, daily signal stats
Enum Values Used By MarketStatusACTIVE, SUSPENDED, RESOLVED, CANCELLED Market OrderStatusCREATED, SUBMITTING, OPEN, PARTIALLY_FILLED, FILLED, CANCELLING, CANCELLED, REJECTED, FAILED Order UserTierBRONZE, SILVER, GOLD, DIAMOND User SniperStatusWATCHING, EXECUTING, FILLED, EXPIRED, CANCELLED, INSUFFICIENT_BALANCE, FAILED SniperOrder KycStatusNOT_STARTED, INITIATED, DOCUMENTS_UPLOADED, PENDING_REVIEW, APPROVED, REJECTED KycVerification WaitlistStatusPENDING_TWEET, TWEET_VERIFIED, KEY_ACTIVATED, UNSUBSCRIBED WaitlistEntry EscrowStatusPENDING, AVAILABLE, CREDITED, CLAWED_BACK RewardEscrow