/** * Shared application bootstrap (migrations, background jobs, game registration). */ import { config } from '../config'; import { runMigrations } from '../db/connection'; import { registerBuiltinGames } from '../games/bootstrap'; import { startRegisteredGameEngines } from '../games/engineRunner'; import { processAllDeposits } from '../services/depositMonitorService'; import { runLedgerIntegrityCheck, getIntegrityCheckIntervalMs } from '../services/securityService'; import { runFileIntegrityCheck } from '../services/fileIntegrityService'; import { processDbTamperEvents, getTamperCheckIntervalMs } from '../services/dbTamperService'; import { createSweepBatchApprovalRequests, SWEEP_BATCH_INTERVAL_MS, } from '../services/sweepBatchService'; import { processAutoEligibleSweeps, getSweepPollIntervalMs } from '../services/sweepService'; import { ensureCountriesSeeded } from '../services/countryService'; import { scheduleAdminStatsBackfill } from '../services/userAdminStatsService'; import { startAdminExportWorker } from '../services/adminUserExportService'; import { processPendingReferralCommissions, getReferralCommissionPollIntervalMs, } from '../services/referralService'; import { scheduleAnalyticsMaterializedViewRefresh } from '../utils/analyticsMaterializedViews'; import { scheduleEncryptionKeyRotationReminder } from '../services/encryptionRotationReminderService'; import { validateProductionMainnetOrThrow, validateTestnetSafetyOrThrow, } from '../safety/networkGuard'; import { validateProductionSecretsOrThrow } from '../safety/productionSecretsGuard'; import { connectRedis } from '../realtime/redis/client'; const DEPOSIT_POLL_INTERVAL_MS = 60 * 1000; const WITHDRAWAL_MONITOR_INTERVAL_MS = 20 * 1000; /** Confirms broadcast payouts on-chain (completed only after required confirmations). */ function startWithdrawalMonitor(): void { const run = async () => { try { const { runWithdrawalMonitorCycle } = await import('../services/withdrawalService'); const r = await runWithdrawalMonitorCycle(); if (r.completed > 0) console.log(`[withdrawal] ${r.completed} payout(s) confirmed`); } catch (e) { console.error('Withdrawal monitor error:', e); } setTimeout(run, WITHDRAWAL_MONITOR_INTERVAL_MS); }; setTimeout(run, 20 * 1000); } async function startDepositMonitor(): Promise { const run = async () => { try { await processAllDeposits(); } catch (e) { console.error('Deposit monitor error:', e); } setTimeout(run, DEPOSIT_POLL_INTERVAL_MS); }; setTimeout(run, 10 * 1000); } function startLedgerIntegrityMonitor(): void { const intervalMs = getIntegrityCheckIntervalMs(); const run = async () => { try { const issues = await runLedgerIntegrityCheck(); if (issues.length > 0) { console.warn(`[security] Ledger integrity check found ${issues.length} issue(s)`); } } catch (e) { console.error('Ledger integrity check error:', e); } setTimeout(run, intervalMs); }; setTimeout(run, 30_000); } function startFileIntegrityMonitor(): void { const intervalMs = getIntegrityCheckIntervalMs(); const run = async () => { try { const issues = await runFileIntegrityCheck(); if (issues.length > 0) { console.warn(`[security] File integrity check found ${issues.length} issue(s)`); } } catch (e) { console.error('File integrity check error:', e); } setTimeout(run, intervalMs); }; setTimeout(run, 45_000); } function startDbTamperMonitor(): void { const intervalMs = getTamperCheckIntervalMs(); const run = async () => { try { const n = await processDbTamperEvents(); if (n > 0) { console.warn(`[security] Processed ${n} unauthorized DB change event(s)`); } } catch (e) { console.error('DB tamper monitor error:', e); } setTimeout(run, intervalMs); }; setTimeout(run, 15_000); } function startSweepBatchMonitor(): void { const auto = config.treasury.sweepEnabled && config.treasury.sweepAutoExecute; console.log( `[sweep] monitor start: SWEEP_ENABLED=${config.treasury.sweepEnabled} ` + `SWEEP_AUTO_EXECUTE=${config.treasury.sweepAutoExecute} ` + `allowlist=${config.treasury.sweepColdAllowlist.length} addr(s) ` + `maxRaw=${config.treasury.sweepAutoMaxAmountRaw || '(none)'}` ); const run = async () => { try { if (config.treasury.sweepEnabled && config.treasury.sweepAutoExecute) { const nAuto = await processAutoEligibleSweeps(); if (nAuto > 0) { console.log(`[sweep] auto-executed ${nAuto} sweep(s)`); } } // Creates Approvals only when needed; also cancels orphan batches already auto-swept. const n = await createSweepBatchApprovalRequests(); if (n > 0) { console.log(`[sweep-batch] Enqueued ${n} batch approval request(s)`); } } catch (e) { console.error('Sweep batch job error:', e); } const nextMs = auto ? Math.min(SWEEP_BATCH_INTERVAL_MS, getSweepPollIntervalMs()) : SWEEP_BATCH_INTERVAL_MS; setTimeout(run, nextMs); }; // First pass quickly so a pending sweep after deploy does not wait a full minute setTimeout(run, auto ? 10_000 : 60_000); } function startReferralCommissionMonitor(): void { const intervalMs = getReferralCommissionPollIntervalMs(); const run = async () => { try { const n = await processPendingReferralCommissions(); if (n > 0 && process.env.NODE_ENV !== 'production') { console.log(`[referral] Settled ${n} pending commission(s)`); } } catch (e) { console.error('Referral commission monitor error:', e); } setTimeout(run, intervalMs); }; setTimeout(run, 60_000); } export type BootstrapOptions = { /** Start Candle Predict / other game engines (disable on API-only process). */ startEngines?: boolean; /** Start deposit, sweep, referral background monitors (disable on engine-only process). */ startPlatformMonitors?: boolean; /** Run dev migrations on boot. */ runDevMigrations?: boolean; }; /** Core bootstrap shared by API and engine processes. */ export async function bootstrapCore(opts: BootstrapOptions = {}): Promise { const { startEngines = config.engineEnabled, startPlatformMonitors = true, runDevMigrations = config.env === 'development', } = opts; validateTestnetSafetyOrThrow(); validateProductionMainnetOrThrow(); validateProductionSecretsOrThrow(); if (runDevMigrations) { try { await runMigrations(); console.log('Migrations OK'); } catch (e) { console.warn('Migrations warning:', e); } } await ensureCountriesSeeded(); if (config.redis.enabled) { try { await connectRedis(); console.log('[redis] Connected'); } catch (e) { console.warn('[redis] Connection failed (continuing without cache):', e); } } registerBuiltinGames(); if (startPlatformMonitors) { scheduleAdminStatsBackfill(); startAdminExportWorker(); scheduleAnalyticsMaterializedViewRefresh(); startDepositMonitor(); startWithdrawalMonitor(); startLedgerIntegrityMonitor(); startFileIntegrityMonitor(); startDbTamperMonitor(); startSweepBatchMonitor(); startReferralCommissionMonitor(); scheduleEncryptionKeyRotationReminder(); } if (startEngines) { startRegisteredGameEngines(); } }