import * as repo from '../../repositories/candlePredictRepository'; import * as ledgerRepository from '../../repositories/ledgerRepository'; import type { AccountKind } from '../../repositories/ledgerRepository'; import * as walletRepository from '../../repositories/walletRepository'; import * as transactionRepository from '../../repositories/transactionRepository'; import * as auditLogRepository from '../../repositories/auditLogRepository'; import * as settingsRepository from '../../repositories/settingsRepository'; import { assertPositiveStakeAmount, parseStakeAmountFromBody } from '../../utils/stakeAmountValidation'; import { queueUserAdminStatsRefresh } from '../../services/userAdminStatsService'; import * as predictionAuditService from '../../services/predictionAuditService'; import { generateSyntheticCandle, defaultSeedCandle, resolvePoolOutcome, resolveAutoNoBetOutcome, type RoundOutcome, type PoolNeutralityRules, } from '../../services/candleGenerationService'; import { getActiveRoundTiming, resolveDisplayStatus, currentCandleOpenMs, maxPredictionWindowSeconds, isMaturityBoundaryForInterval, } from '../../services/gameTimingService'; import * as multiService from '../../services/candlePredictMultiService'; import { publishRoundState, publishCandleAppend } from './realtime/publishRoundState'; import { publishRoundEvent } from '../../realtime/redis/pubsub'; import { loadCachedRound } from './read/roundCache'; import { config } from '../../config'; import { isRedisEnabled } from '../../realtime/redis/client'; import { publishUserEvent } from '../../realtime/redis/pubsub'; import { claimBetIdempotencyProcessing, enqueueBet, getBetIdempotency, } from '../../realtime/streams/betQueue'; import { v4 as uuidv4 } from 'uuid'; const DECIMALS = 6n; async function creditGameOutcome( bet: { user_id: string; wallet_type_id: number; id: string; stake_account_kind?: string }, amount: bigint, entryType: 'game_refund' | 'game_payout' ): Promise { const stakeKind = parseStakeAccountKind(bet.stake_account_kind); let creditKind: AccountKind = stakeKind; if (entryType === 'game_payout' && stakeKind === 'bonus') { creditKind = 'main'; } const account = await ledgerRepository.getOrCreateAccount(bet.user_id, bet.wallet_type_id, creditKind); await ledgerRepository.credit(account.id, amount, entryType, 'candle_predict_bet', bet.id); } let lastBackfillRunMs = 0; function stakeToRaw(stakeDisplay: number): bigint { return BigInt(Math.round(stakeDisplay * 10 ** Number(DECIMALS))); } function rawToStake(raw: bigint): number { return Number(raw) / 10 ** Number(DECIMALS); } const STAKE_AMOUNT_EPS = 1e-9; const MIN_STAKE_FLOOR = 0.01; const MAX_STAKE_CEILING = 1_000_000; function getStakeBounds(cfg: repo.CandlePredictConfigRow): { min: number; max: number } { const minFromDb = Number(cfg.min_stake_amount); const maxFromDb = Number(cfg.max_stake_amount); const min = Number.isFinite(minFromDb) && minFromDb > 0 ? minFromDb : MIN_STAKE_FLOOR; if (Number.isFinite(maxFromDb) && maxFromDb > min) { return { min, max: maxFromDb }; } const amounts = cfg.stake_amounts.map(Number).filter((n) => Number.isFinite(n) && n > 0); if (!amounts.length) return { min, max: 1000 }; return { min: Math.min(...amounts), max: Math.max(...amounts) }; } /** Live stake pools for the target candle maturity (betting) or settled round row. */ async function resolveLivePoolTotals( openMs: number, phase: string, row: repo.CandlePredictRoundRow ): Promise<{ shortPool: number; longPool: number }> { if (phase === 'betting') { return repo.getGlobalPoolTotalsForMaturity(openMs); } return { shortPool: Number(row.short_pool_display), longPool: Number(row.long_pool_display), }; } function assertStakeInRange(cfg: repo.CandlePredictConfigRow, stake: number): void { assertPositiveStakeAmount(stake); const { min, max } = getStakeBounds(cfg); const n = Number(stake); if (n < min - STAKE_AMOUNT_EPS || n > max + STAKE_AMOUNT_EPS) { throw new Error(`Stake must be between ${min} and ${max}`); } } function isStakeInRange(cfg: repo.CandlePredictConfigRow, stake: number): boolean { try { assertStakeInRange(cfg, stake); return true; } catch { return false; } } function assertStakePresetsInRange(cfg: repo.CandlePredictConfigRow, stakeAmounts: number[]): void { const { min, max } = getStakeBounds(cfg); for (const amount of stakeAmounts) { if (amount < min - STAKE_AMOUNT_EPS || amount > max + STAKE_AMOUNT_EPS) { throw new Error(`Preset stake ${amount} must be between ${min} and ${max}`); } } } function validateStakeLimits(minStakeAmount: number, maxStakeAmount: number): void { if (!Number.isFinite(minStakeAmount) || minStakeAmount < MIN_STAKE_FLOOR) { throw new Error(`minStakeAmount must be at least ${MIN_STAKE_FLOOR}`); } if (!Number.isFinite(maxStakeAmount) || maxStakeAmount > MAX_STAKE_CEILING) { throw new Error(`maxStakeAmount must be at most ${MAX_STAKE_CEILING}`); } if (maxStakeAmount <= minStakeAmount) { throw new Error('maxStakeAmount must be greater than minStakeAmount'); } } function parseStakeDisplay(body: Record, fallback: number): number { const raw = body.stakeDisplay ?? body.stakeAmount ?? body.stake_amount; if (raw !== undefined) { return parseStakeAmountFromBody(raw); } return fallback; } function parsePoolWinnerRule(value: string | null | undefined): repo.PoolWinnerRule { return value === 'majority' ? 'majority' : 'minority'; } function validateNeutralityRules(input: { minPercent?: number; maxPercent?: number; }): void { if (input.minPercent !== undefined && (input.minPercent < 0 || input.minPercent > 50)) { throw new Error('tieTolerancePercent must be between 0 and 50'); } if (input.maxPercent !== undefined && (input.maxPercent < 51 || input.maxPercent > 100)) { throw new Error('tieToleranceMaxPercent must be between 51 and 100'); } } function buildPoolNeutralityRules( global: repo.CandlePredictConfigRow, interval?: ResolvedInterval | null ): PoolNeutralityRules { return { minTolerancePercent: interval?.tieTolerancePercent ?? Number(global.tie_tolerance_percent), maxTolerancePercent: interval?.tieToleranceMaxPercent ?? Number(global.tie_tolerance_max_percent), minToleranceEnabled: interval?.tieToleranceMinEnabled ?? global.tie_tolerance_min_enabled ?? true, maxToleranceEnabled: interval?.tieToleranceMaxEnabled ?? global.tie_tolerance_max_enabled ?? true, }; } function mapConfig(row: repo.CandlePredictConfigRow) { const { min, max } = getStakeBounds(row); return { stakeAmounts: row.stake_amounts, minStakeAmount: min, maxStakeAmount: max, poolWinnerRule: parsePoolWinnerRule(row.pool_winner_rule), predictionWindowSeconds: row.prediction_window_seconds, tieTolerancePercent: Number(row.tie_tolerance_percent), tieToleranceMaxPercent: Number(row.tie_tolerance_max_percent), tieToleranceMinEnabled: row.tie_tolerance_min_enabled, tieToleranceMaxEnabled: row.tie_tolerance_max_enabled, basePrice: Number(row.base_price), payoutMultiplier: Number(row.payout_multiplier), poolMultiplier: Number(row.pool_multiplier), walletTypeCode: row.wallet_type_code, autoModes: row.auto_modes, isActive: row.is_active, predictionTypes: { single: row.prediction_single_enabled ?? true, auto: row.prediction_auto_enabled ?? true, multiCandle: row.prediction_multi_enabled ?? true, }, updatedAt: row.updated_at.toISOString(), }; } type PlayerConfigDto = Omit< ReturnType, | 'poolWinnerRule' | 'poolMultiplier' | 'tieTolerancePercent' | 'tieToleranceMaxPercent' | 'tieToleranceMinEnabled' | 'tieToleranceMaxEnabled' >; function mapConfigForPlayer(row: repo.CandlePredictConfigRow): PlayerConfigDto { const { poolWinnerRule: _poolWinnerRule, poolMultiplier: _poolMultiplier, tieTolerancePercent: _min, tieToleranceMaxPercent: _max, tieToleranceMinEnabled: _minEn, tieToleranceMaxEnabled: _maxEn, ...player } = mapConfig(row); return player; } export type ResolvedInterval = { id: number; intervalMinutes: number; label: string; sortOrder: number; isDefault: boolean; isActive: boolean; predictionWindowSeconds: number; tieTolerancePercent: number; tieToleranceMaxPercent: number; tieToleranceMinEnabled: boolean; tieToleranceMaxEnabled: boolean; basePrice: number; payoutMultiplier: number; poolMultiplier: number; chartCandleLimit: number; }; function resolveInterval( global: repo.CandlePredictConfigRow, row: repo.CandlePredictIntervalRow ): ResolvedInterval { return { id: row.id, intervalMinutes: row.interval_minutes, label: row.label, sortOrder: row.sort_order, isDefault: row.is_default, isActive: row.is_active, predictionWindowSeconds: row.prediction_window_seconds ?? global.prediction_window_seconds, tieTolerancePercent: Number(row.tie_tolerance_percent ?? global.tie_tolerance_percent), tieToleranceMaxPercent: Number( row.tie_tolerance_max_percent ?? global.tie_tolerance_max_percent ), tieToleranceMinEnabled: row.tie_tolerance_min_enabled ?? global.tie_tolerance_min_enabled ?? true, tieToleranceMaxEnabled: row.tie_tolerance_max_enabled ?? global.tie_tolerance_max_enabled ?? true, basePrice: Number(row.base_price ?? global.base_price), payoutMultiplier: Number(row.payout_multiplier ?? global.payout_multiplier), poolMultiplier: Number(row.pool_multiplier ?? global.pool_multiplier), chartCandleLimit: row.chart_candle_limit ?? 120, }; } function mapIntervalDto(interval: ResolvedInterval) { return { id: interval.id, intervalMinutes: interval.intervalMinutes, label: interval.label, sortOrder: interval.sortOrder, isDefault: interval.isDefault, isActive: interval.isActive, predictionWindowSeconds: interval.predictionWindowSeconds, maxPredictionWindowSeconds: maxPredictionWindowSeconds(interval.intervalMinutes), tieTolerancePercent: interval.tieTolerancePercent, tieToleranceMaxPercent: interval.tieToleranceMaxPercent, tieToleranceMinEnabled: interval.tieToleranceMinEnabled, tieToleranceMaxEnabled: interval.tieToleranceMaxEnabled, basePrice: interval.basePrice, payoutMultiplier: interval.payoutMultiplier, poolMultiplier: interval.poolMultiplier, chartCandleLimit: interval.chartCandleLimit, }; } type PlayerIntervalDto = Omit< ReturnType, | 'tieTolerancePercent' | 'tieToleranceMaxPercent' | 'tieToleranceMinEnabled' | 'tieToleranceMaxEnabled' | 'poolMultiplier' >; function mapIntervalDtoForPlayer(interval: ResolvedInterval): PlayerIntervalDto { const { tieTolerancePercent: _min, tieToleranceMaxPercent: _max, tieToleranceMinEnabled: _minEn, tieToleranceMaxEnabled: _maxEn, poolMultiplier: _poolMultiplier, ...player } = mapIntervalDto(interval); return player; } function assertPredictionWindowAllowed( intervalMinutes: number, predictionWindowSeconds: number | null | undefined ): void { if (predictionWindowSeconds == null) return; if (!Number.isFinite(predictionWindowSeconds) || predictionWindowSeconds < 5) { throw new Error('predictionWindowSeconds must be at least 5'); } const max = maxPredictionWindowSeconds(intervalMinutes); if (predictionWindowSeconds > max) { throw new Error( `predictionWindowSeconds cannot exceed ${max} for a ${intervalMinutes}-minute interval (duration minus 5 seconds)` ); } } const CANDLE_API_BATCH_MAX = 200; function mapCandleRow(c: repo.GeneratedCandleRow) { return { time: Math.floor(Number(c.candle_open_ms) / 1000), open: Number(c.open_price), high: Number(c.high_price), low: Number(c.low_price), close: Number(c.close_price), colorHint: c.color_hint, outcome: c.outcome, intervalMinutes: c.interval_minutes, candleOpenMs: Number(c.candle_open_ms), }; } function mapCandleRowForPlayer(c: repo.GeneratedCandleRow) { const { colorHint: _colorHint, ...player } = mapCandleRow(c); return player; } async function loadResolvedIntervals( cfg: repo.CandlePredictConfigRow, activeOnly = true ): Promise { const rows = activeOnly ? await repo.listActiveIntervals() : await repo.listAllIntervals(); return rows.map((r) => resolveInterval(cfg, r)); } async function resolveSelectedInterval( cfg: repo.CandlePredictConfigRow, intervalMinutes?: number ): Promise { const intervals = await loadResolvedIntervals(cfg, true); if (!intervals.length) { throw new Error('No active prediction intervals configured'); } if (intervalMinutes != null) { const match = intervals.find((i) => i.intervalMinutes === intervalMinutes); if (!match) throw new Error('Invalid or inactive interval'); return match; } return intervals.find((i) => i.isDefault) ?? intervals[0]; } function mapRound( row: repo.CandlePredictRoundRow, nowMs: number, windowSec: number, timing: ReturnType, pools?: { shortPool: number; longPool: number } ) { const openMs = Number(row.candle_open_ms); const intervalMs = row.interval_minutes * 60 * 1000; const bettingStartMs = openMs - windowSec * 1000; const closeMs = openMs + intervalMs; const shortPool = pools?.shortPool ?? Number(row.short_pool_display); const longPool = pools?.longPool ?? Number(row.long_pool_display); const total = shortPool + longPool; const displayStatus = resolveDisplayStatus( row.status, timing.phase, openMs, row.interval_minutes, nowMs ); const bettingTargetOpenMs = timing.phase === 'betting' ? timing.openMs : timing.nextOpenMs; const secondsToBettingEnd = timing.phase === 'betting' ? Math.max(0, Math.ceil((bettingTargetOpenMs - nowMs) / 1000)) : 0; const secondsToBettingStart = timing.phase === 'betting' ? 0 : Math.max(0, Math.ceil((timing.nextBettingStartMs - nowMs) / 1000)); return { id: row.id, candleOpenMs: openMs, candleCloseMs: closeMs, intervalMinutes: row.interval_minutes, status: displayStatus, bettingStartMs, bettingEndMs: openMs, outcome: row.outcome, neutralColor: row.neutral_color, shortPool, longPool, shortPoolPercent: total > 0 ? Math.round((shortPool / total) * 1000) / 10 : 0, longPoolPercent: total > 0 ? Math.round((longPool / total) * 1000) / 10 : 0, openPrice: row.open_price ? Number(row.open_price) : null, highPrice: row.high_price ? Number(row.high_price) : null, lowPrice: row.low_price ? Number(row.low_price) : null, closePrice: row.close_price ? Number(row.close_price) : null, totalBets: row.total_bets, settledAt: row.settled_at?.toISOString() ?? null, serverNowMs: nowMs, secondsToBettingEnd, secondsToBettingStart, secondsToClose: Math.max(0, Math.ceil((closeMs - nowMs) / 1000)), }; } function mapRoundForPlayer(round: ReturnType) { const { shortPool: _shortPool, longPool: _longPool, neutralColor: _neutralColor, totalBets: _totalBets, ...player } = round; return player; } function mapBet(row: repo.CandlePredictBetRow & { candle_open_ms?: string }) { const candleOpenMs = row.candle_open_ms != null && row.candle_open_ms !== '' ? Number(row.candle_open_ms) : null; const candleCloseMs = candleOpenMs != null ? candleOpenMs + row.interval_minutes * 60 * 1000 : null; const base = { id: row.id, roundId: row.round_id, direction: row.direction, stakeDisplay: Number(row.stake_display), status: row.status, payoutDisplay: rawToStake(BigInt(row.payout_raw)), isAuto: row.is_auto, intervalMinutes: row.interval_minutes, createdAt: row.created_at.toISOString(), candleOpenMs, candleCloseMs, predictionMode: (row.prediction_mode ?? 'single') as repo.PredictionMode, stakeAccountKind: parseStakeAccountKind(row.stake_account_kind), }; if (row.prediction_mode === 'multi_candle') { return { ...base, ...multiService.mapMultiBet(row), }; } return base; } export async function getPublicConfig() { const cfg = await repo.getConfig(); return mapConfig(cfg); } export async function updateAdminConfig(body: Record) { const cfg = await repo.getConfig(); const stakeAmounts = Array.isArray(body.stakeAmounts) ? (body.stakeAmounts as unknown[]).map(Number).filter((n) => n > 0) : undefined; const minStakeAmount = typeof body.minStakeAmount === 'number' ? body.minStakeAmount : Number(cfg.min_stake_amount); const maxStakeAmount = typeof body.maxStakeAmount === 'number' ? body.maxStakeAmount : Number(cfg.max_stake_amount); validateStakeLimits(minStakeAmount, maxStakeAmount); const draftCfg: repo.CandlePredictConfigRow = { ...cfg, min_stake_amount: String(minStakeAmount), max_stake_amount: String(maxStakeAmount), stake_amounts: stakeAmounts ?? cfg.stake_amounts, }; if (stakeAmounts?.length) { assertStakePresetsInRange(draftCfg, stakeAmounts); } else { assertStakePresetsInRange(draftCfg, cfg.stake_amounts); } const tieTolerancePercent = typeof body.tieTolerancePercent === 'number' ? body.tieTolerancePercent : undefined; const tieToleranceMaxPercent = typeof body.tieToleranceMaxPercent === 'number' ? body.tieToleranceMaxPercent : undefined; validateNeutralityRules({ minPercent: tieTolerancePercent, maxPercent: tieToleranceMaxPercent, }); let poolWinnerRule: repo.PoolWinnerRule | undefined; if (typeof body.poolWinnerRule === 'string') { if (body.poolWinnerRule !== 'minority' && body.poolWinnerRule !== 'majority') { throw new Error('poolWinnerRule must be minority or majority'); } poolWinnerRule = body.poolWinnerRule; } const updated = await repo.updateConfig({ stakeAmounts, minStakeAmount, maxStakeAmount, poolWinnerRule, predictionWindowSeconds: typeof body.predictionWindowSeconds === 'number' ? body.predictionWindowSeconds : undefined, tieTolerancePercent, tieToleranceMaxPercent, tieToleranceMinEnabled: typeof body.tieToleranceMinEnabled === 'boolean' ? body.tieToleranceMinEnabled : undefined, tieToleranceMaxEnabled: typeof body.tieToleranceMaxEnabled === 'boolean' ? body.tieToleranceMaxEnabled : undefined, basePrice: typeof body.basePrice === 'number' ? body.basePrice : undefined, payoutMultiplier: typeof body.payoutMultiplier === 'number' ? body.payoutMultiplier : undefined, poolMultiplier: typeof body.poolMultiplier === 'number' ? body.poolMultiplier : undefined, walletTypeCode: typeof body.walletTypeCode === 'string' ? body.walletTypeCode : undefined, autoModes: Array.isArray(body.autoModes) ? (body.autoModes as string[]) : undefined, isActive: typeof body.isActive === 'boolean' ? body.isActive : undefined, predictionSingleEnabled: typeof body.predictionSingleEnabled === 'boolean' ? body.predictionSingleEnabled : typeof body.predictionTypes === 'object' && body.predictionTypes !== null && typeof (body.predictionTypes as { single?: boolean }).single === 'boolean' ? (body.predictionTypes as { single: boolean }).single : undefined, predictionAutoEnabled: typeof body.predictionAutoEnabled === 'boolean' ? body.predictionAutoEnabled : typeof body.predictionTypes === 'object' && body.predictionTypes !== null && typeof (body.predictionTypes as { auto?: boolean }).auto === 'boolean' ? (body.predictionTypes as { auto: boolean }).auto : undefined, predictionMultiEnabled: typeof body.predictionMultiEnabled === 'boolean' ? body.predictionMultiEnabled : typeof body.predictionTypes === 'object' && body.predictionTypes !== null && typeof (body.predictionTypes as { multiCandle?: boolean }).multiCandle === 'boolean' ? (body.predictionTypes as { multiCandle: boolean }).multiCandle : undefined, }); if (config.redis.enabled) { const activeIntervals = await loadResolvedIntervals(updated, true); await Promise.all( activeIntervals .filter((i) => i.isActive) .map((i) => publishRoundEvent(i.intervalMinutes, { type: 'config.updated', intervalMinutes: i.intervalMinutes, payload: {}, }) ) ); } return mapConfig(updated); } export async function listAdminIntervals() { const cfg = await repo.getConfig(); const intervals = await loadResolvedIntervals(cfg, false); return intervals.map(mapIntervalDto); } export async function createAdminInterval(body: Record) { const intervalMinutes = typeof body.intervalMinutes === 'number' ? body.intervalMinutes : Number(body.intervalMinutes); if (!Number.isFinite(intervalMinutes) || intervalMinutes < 1 || intervalMinutes > 1440) { throw new Error('intervalMinutes must be between 1 and 1440'); } const label = typeof body.label === 'string' && body.label.trim() ? body.label.trim() : `${intervalMinutes} min`; const existing = await repo.getIntervalByMinutes(intervalMinutes); if (existing) throw new Error('An interval with these minutes already exists'); const predictionWindowSeconds = typeof body.predictionWindowSeconds === 'number' ? body.predictionWindowSeconds : null; assertPredictionWindowAllowed(intervalMinutes, predictionWindowSeconds); const tieTolerancePercent = typeof body.tieTolerancePercent === 'number' ? body.tieTolerancePercent : null; const tieToleranceMaxPercent = typeof body.tieToleranceMaxPercent === 'number' ? body.tieToleranceMaxPercent : null; validateNeutralityRules({ minPercent: tieTolerancePercent ?? undefined, maxPercent: tieToleranceMaxPercent ?? undefined, }); const row = await repo.createInterval({ intervalMinutes, label, sortOrder: typeof body.sortOrder === 'number' ? body.sortOrder : intervalMinutes, isActive: body.isActive !== false, isDefault: body.isDefault === true, predictionWindowSeconds, tieTolerancePercent: typeof body.tieTolerancePercent === 'number' ? body.tieTolerancePercent : null, tieToleranceMaxPercent: typeof body.tieToleranceMaxPercent === 'number' ? body.tieToleranceMaxPercent : null, tieToleranceMinEnabled: typeof body.tieToleranceMinEnabled === 'boolean' ? body.tieToleranceMinEnabled : null, tieToleranceMaxEnabled: typeof body.tieToleranceMaxEnabled === 'boolean' ? body.tieToleranceMaxEnabled : null, payoutMultiplier: typeof body.payoutMultiplier === 'number' ? body.payoutMultiplier : null, poolMultiplier: typeof body.poolMultiplier === 'number' ? body.poolMultiplier : null, basePrice: typeof body.basePrice === 'number' ? body.basePrice : null, chartCandleLimit: typeof body.chartCandleLimit === 'number' ? body.chartCandleLimit : 120, }); if (row.is_default) { await repo.clearDefaultIntervalExcept(row.id); } const cfg = await repo.getConfig(); return mapIntervalDto(resolveInterval(cfg, row)); } export async function updateAdminInterval(id: number, body: Record) { const cfg = await repo.getConfig(); const current = (await repo.listAllIntervals()).find((r) => r.id === id); if (!current) throw new Error('Interval not found'); const nextIntervalMinutes = typeof body.intervalMinutes === 'number' ? body.intervalMinutes : current.interval_minutes; if (body.intervalMinutes != null) { const mins = Number(body.intervalMinutes); if (!Number.isFinite(mins) || mins < 1 || mins > 1440) { throw new Error('intervalMinutes must be between 1 and 1440'); } const clash = await repo.getIntervalByMinutes(mins); if (clash && clash.id !== id) throw new Error('An interval with these minutes already exists'); } const nextWindow = body.predictionWindowSeconds === null ? null : typeof body.predictionWindowSeconds === 'number' ? body.predictionWindowSeconds : current.prediction_window_seconds; assertPredictionWindowAllowed(nextIntervalMinutes, nextWindow); const nextMinTie = body.tieTolerancePercent === null ? null : typeof body.tieTolerancePercent === 'number' ? body.tieTolerancePercent : current.tie_tolerance_percent != null ? Number(current.tie_tolerance_percent) : undefined; const nextMaxTie = body.tieToleranceMaxPercent === null ? null : typeof body.tieToleranceMaxPercent === 'number' ? body.tieToleranceMaxPercent : current.tie_tolerance_max_percent != null ? Number(current.tie_tolerance_max_percent) : undefined; validateNeutralityRules({ minPercent: typeof nextMinTie === 'number' ? nextMinTie : undefined, maxPercent: typeof nextMaxTie === 'number' ? nextMaxTie : undefined, }); const updated = await repo.updateInterval(id, { intervalMinutes: typeof body.intervalMinutes === 'number' ? body.intervalMinutes : undefined, label: typeof body.label === 'string' ? body.label.trim() : undefined, sortOrder: typeof body.sortOrder === 'number' ? body.sortOrder : undefined, isActive: typeof body.isActive === 'boolean' ? body.isActive : undefined, isDefault: typeof body.isDefault === 'boolean' ? body.isDefault : undefined, predictionWindowSeconds: body.predictionWindowSeconds === null ? null : typeof body.predictionWindowSeconds === 'number' ? body.predictionWindowSeconds : undefined, tieTolerancePercent: body.tieTolerancePercent === null ? null : typeof body.tieTolerancePercent === 'number' ? body.tieTolerancePercent : undefined, tieToleranceMaxPercent: body.tieToleranceMaxPercent === null ? null : typeof body.tieToleranceMaxPercent === 'number' ? body.tieToleranceMaxPercent : undefined, tieToleranceMinEnabled: body.tieToleranceMinEnabled === null ? null : typeof body.tieToleranceMinEnabled === 'boolean' ? body.tieToleranceMinEnabled : undefined, tieToleranceMaxEnabled: body.tieToleranceMaxEnabled === null ? null : typeof body.tieToleranceMaxEnabled === 'boolean' ? body.tieToleranceMaxEnabled : undefined, payoutMultiplier: body.payoutMultiplier === null ? null : typeof body.payoutMultiplier === 'number' ? body.payoutMultiplier : undefined, poolMultiplier: body.poolMultiplier === null ? null : typeof body.poolMultiplier === 'number' ? body.poolMultiplier : undefined, basePrice: body.basePrice === null ? null : typeof body.basePrice === 'number' ? body.basePrice : undefined, chartCandleLimit: typeof body.chartCandleLimit === 'number' ? body.chartCandleLimit : undefined, }); if (!updated) throw new Error('Interval not found'); if (updated.is_default) await repo.clearDefaultIntervalExcept(updated.id); return mapIntervalDto(resolveInterval(cfg, updated)); } export async function deleteAdminInterval(id: number) { const row = (await repo.listAllIntervals()).find((r) => r.id === id); if (!row) throw new Error('Interval not found'); if (row.is_default) throw new Error('Cannot delete the default interval'); const roundCount = await repo.countRoundsForInterval(row.interval_minutes); if (roundCount > 0) { throw new Error('Cannot delete an interval that has game rounds — disable it instead'); } await repo.deleteInterval(id); return { ok: true }; } export async function getGameState( userId?: string, intervalMinutes?: number, opts?: { includeInternal?: boolean } ) { const includeInternal = opts?.includeInternal === true; const cfg = await repo.getConfig(); const intervals = await loadResolvedIntervals(cfg, true); const selected = await resolveSelectedInterval(cfg, intervalMinutes); const nowMs = Date.now(); const timing = getActiveRoundTiming( nowMs, selected.intervalMinutes, selected.predictionWindowSeconds ); let round = await repo.getRoundByOpenMs(timing.openMs, selected.intervalMinutes); if (!round) { round = await syncRound(selected, timing.openMs, timing.phase); } else if (round.status !== timing.phase && round.status !== 'settled') { await repo.updateRoundStatus(round.id, timing.phase); round = { ...round, status: timing.phase }; } let pools: { shortPool: number; longPool: number } | undefined; if (round && timing.phase === 'betting') { pools = await resolveLivePoolTotals(timing.openMs, timing.phase, round); } else if (includeInternal && round) { pools = { shortPool: Number(round.short_pool_display), longPool: Number(round.long_pool_display), }; } const roundDto = round ? mapRound(round, nowMs, selected.predictionWindowSeconds, timing, pools) : null; let playerRoundDto = roundDto ? (includeInternal ? roundDto : mapRoundForPlayer(roundDto)) : null; if (!includeInternal && playerRoundDto && timing.openMs) { const cached = await loadCachedRound(selected.intervalMinutes, timing.openMs); if (cached) { // Timing fields come from mapRound (authoritative). Cache only enriches pools/OHLC. playerRoundDto = { ...playerRoundDto, outcome: cached.outcome as typeof playerRoundDto.outcome, openPrice: cached.openPrice, highPrice: cached.highPrice, lowPrice: cached.lowPrice, closePrice: cached.closePrice, settledAt: cached.settledAt, shortPoolPercent: cached.shortPoolPercent, longPoolPercent: cached.longPoolPercent, secondsToClose: cached.secondsToClose, }; } } let userBet = null; let userMultiBet = null; if (userId) { if (round) { const bet = await repo.getUserBetForRound(round.id, userId); if (bet) userBet = mapBet(bet); } const activeMulti = await repo.getUserActiveMultiBet(userId, selected.intervalMinutes); if (activeMulti) userMultiBet = multiService.mapMultiBet(activeMulti); } const allMultiLevels = await repo.listMultiLevels(); const multiLevels = cfg.prediction_multi_enabled ? allMultiLevels .filter((l) => l.enabled) .map(includeInternal ? multiService.mapMultiLevel : multiService.mapMultiLevelForPlayer) : []; let autoSettings = null; if (userId && (cfg.prediction_auto_enabled ?? true)) { autoSettings = await getAutoSettings(userId); } return { config: includeInternal ? mapConfig(cfg) : mapConfigForPlayer(cfg), intervals: intervals.map(includeInternal ? mapIntervalDto : mapIntervalDtoForPlayer), selectedIntervalMinutes: selected.intervalMinutes, interval: includeInternal ? mapIntervalDto(selected) : mapIntervalDtoForPlayer(selected), round: playerRoundDto, userBet, userMultiBet, multiLevels, autoSettings, }; } export async function getCandlesPage(input: { limit?: number; intervalMinutes?: number; beforeOpenMs?: number; includeInternal?: boolean; }) { const includeInternal = input.includeInternal === true; const cfg = await repo.getConfig(); const selected = await resolveSelectedInterval(cfg, input.intervalMinutes); const defaultLimit = Math.min(selected.chartCandleLimit, CANDLE_API_BATCH_MAX); const pageSize = Math.min( Math.max(1, input.limit ?? defaultLimit), CANDLE_API_BATCH_MAX ); const rows = await repo.listGeneratedCandlesPage({ intervalMinutes: selected.intervalMinutes, limit: pageSize, beforeOpenMs: input.beforeOpenMs, }); const items = rows .reverse() .map((c) => (includeInternal ? mapCandleRow(c) : mapCandleRowForPlayer(c))); const oldestOpenMs = items[0]?.candleOpenMs ?? null; const newestOpenMs = items[items.length - 1]?.candleOpenMs ?? null; const hasMore = oldestOpenMs != null ? await repo.hasOlderCandles(selected.intervalMinutes, oldestOpenMs) : false; return { items, hasMore, oldestOpenMs, newestOpenMs, pageSize, intervalMinutes: selected.intervalMinutes, }; } /** @deprecated use getCandlesPage */ export async function getCandles(limit = 100, intervalMinutes?: number) { const page = await getCandlesPage({ limit, intervalMinutes }); return page.items; } async function syncRound( interval: ResolvedInterval, openMs: number, status: repo.CandlePredictRoundRow['status'] ): Promise { return repo.createRound({ candleOpenMs: openMs, intervalMinutes: interval.intervalMinutes, status, }); } export async function tickGameEngine(): Promise { const cfg = await repo.getConfig(); if (!cfg.is_active) return; const intervals = await loadResolvedIntervals(cfg, true); const nowMs = Date.now(); const overdue = await repo.listOverdueUnsettledRounds(nowMs); const settledMaturities = new Set(); for (const due of overdue) { const openMs = Number(due.candle_open_ms); if (settledMaturities.has(openMs)) continue; settledMaturities.add(openMs); await settleMaturityAtOpenMs(openMs, cfg); } const multiDueOpenMs = await repo.listDueMultiValidationCandleOpenMs(nowMs); for (const openMs of multiDueOpenMs) { if (settledMaturities.has(openMs)) continue; settledMaturities.add(openMs); await settleMaturityAtOpenMs(openMs, cfg); } for (const interval of intervals) { await tickIntervalEngine(cfg, interval, nowMs); } const settings = await settingsRepository.getSettings(); if (nowMs - lastBackfillRunMs >= settings.candle_predict_backfill_interval_ms) { for (const interval of intervals) { await backfillMissedAutoCandles(interval, nowMs, cfg, settings); } lastBackfillRunMs = nowMs; } } function lastCompletedCandleOpenMs(nowMs: number, intervalMinutes: number): number { const intervalMs = intervalMinutes * 60 * 1000; let openMs = currentCandleOpenMs(nowMs, intervalMinutes); if (nowMs < openMs + intervalMs) { openMs -= intervalMs; } return openMs; } /** * Fills missing candles for inactive intervals so charts stay alive without player bets. */ async function backfillMissedAutoCandles( interval: ResolvedInterval, nowMs: number, cfg: repo.CandlePredictConfigRow, settings: Awaited> ): Promise { const intervalMs = interval.intervalMinutes * 60 * 1000; const lastCompletedOpen = lastCompletedCandleOpenMs(nowMs, interval.intervalMinutes); const lastCandleOpen = await repo.getLastCandleOpenMs(interval.intervalMinutes); let nextOpen: number; if (lastCandleOpen != null) { nextOpen = lastCandleOpen + intervalMs; } else { const seedCount = Math.min(interval.chartCandleLimit, settings.candle_predict_backfill_seed_max); nextOpen = lastCompletedOpen - (seedCount - 1) * intervalMs; } if (nextOpen > lastCompletedOpen) return; let processed = 0; for ( let openMs = nextOpen; openMs <= lastCompletedOpen && processed < settings.candle_predict_backfill_max_per_tick; openMs += intervalMs ) { if (!isMaturityBoundaryForInterval(openMs, interval.intervalMinutes)) continue; if (await repo.hasCandle(openMs, interval.intervalMinutes)) continue; // Per-interval 5-streak rule is applied inside settleMaturityAtOpenMs (auto mode). await settleMaturityAtOpenMs(openMs, cfg); processed += 1; } } async function tickIntervalEngine( cfg: repo.CandlePredictConfigRow, interval: ResolvedInterval, nowMs: number ): Promise { const timing = getActiveRoundTiming( nowMs, interval.intervalMinutes, interval.predictionWindowSeconds ); let round = await repo.getRoundByOpenMs(timing.openMs, interval.intervalMinutes); if (!round) { round = await syncRound(interval, timing.openMs, timing.phase); } if (round.status === 'betting' && timing.phase === 'locked') { await repo.updateRoundStatus(round.id, 'locked'); await settleMaturityAtOpenMs(Number(round.candle_open_ms), cfg); const lockedRound = await repo.getRoundByOpenMs(timing.openMs, interval.intervalMinutes); if (lockedRound) { const timingNow = getActiveRoundTiming( nowMs, interval.intervalMinutes, interval.predictionWindowSeconds ); const livePools = await resolveLivePoolTotals( timing.openMs, timingNow.phase, lockedRound ); const dto = mapRoundForPlayer( mapRound(lockedRound, nowMs, interval.predictionWindowSeconds, timingNow, livePools) ); await publishRoundState({ intervalMinutes: interval.intervalMinutes, openMs: timing.openMs, round: dto, pools: { short: livePools.shortPool, long: livePools.longPool }, }); } return; } if (round.status !== timing.phase && round.status !== 'settled') { await repo.updateRoundStatus(round.id, timing.phase); round = { ...round, status: timing.phase }; } if (timing.phase === 'betting') { await processAutoBets(round, interval, cfg); } const refreshed = await repo.getRoundByOpenMs(timing.openMs, interval.intervalMinutes); if (refreshed) { const timingNow = getActiveRoundTiming( nowMs, interval.intervalMinutes, interval.predictionWindowSeconds ); const livePools = await resolveLivePoolTotals( timing.openMs, timingNow.phase, refreshed ); const dto = mapRoundForPlayer( mapRound(refreshed, nowMs, interval.predictionWindowSeconds, timingNow, livePools) ); await publishRoundState({ intervalMinutes: interval.intervalMinutes, openMs: timing.openMs, round: dto, pools: { short: livePools.shortPool, long: livePools.longPool }, }); } } /** Republish round + pool snapshot after a bet or external mutation. */ export async function publishRoundSnapshot( intervalMinutes: number, openMs: number ): Promise { if (!config.redis.enabled) return; const cfg = await repo.getConfig(); const interval = await resolveSelectedInterval(cfg, intervalMinutes); const nowMs = Date.now(); const timing = getActiveRoundTiming( nowMs, interval.intervalMinutes, interval.predictionWindowSeconds ); const refreshed = await repo.getRoundByOpenMs(openMs, intervalMinutes); if (!refreshed) return; const livePools = await resolveLivePoolTotals(openMs, timing.phase, refreshed); const dto = mapRoundForPlayer( mapRound(refreshed, nowMs, interval.predictionWindowSeconds, timing, livePools) ); await publishRoundState({ intervalMinutes, openMs, round: dto, pools: { short: livePools.shortPool, long: livePools.longPool }, }); } async function settleMaturityAtOpenMs( candleOpenMs: number, cfg: repo.CandlePredictConfigRow ): Promise { const intervals = await loadResolvedIntervals(cfg, true); const aligning = intervals.filter((i) => isMaturityBoundaryForInterval(candleOpenMs, i.intervalMinutes) ); if (!aligning.length) return; const pendingCount = await repo.countPendingBetsForMaturity(candleOpenMs); const multiValidationCount = await repo.countMultiBetsForValidationAtOpenMs(candleOpenMs); const realMoneyPendingCount = await repo.countPendingRealMoneyBetsForMaturity(candleOpenMs); const allCandlesExist = await Promise.all( aligning.map((i) => repo.hasCandle(candleOpenMs, i.intervalMinutes)) ); if (allCandlesExist.every(Boolean) && pendingCount === 0 && multiValidationCount === 0) return; const multiContributions = await repo.getMultiCandlePoolContributions(candleOpenMs); const outcomeMode = multiService.resolveMaturityOutcomeMode({ realMoneySinglePending: realMoneyPendingCount > 0, multiFinalPoolShort: multiContributions.shortPool, multiFinalPoolLong: multiContributions.longPool, }); const { shortPool, longPool } = await multiService.buildMaturityPools(candleOpenMs); const primary = aligning.find((i) => i.intervalMinutes === 1) ?? aligning.sort((a, b) => a.intervalMinutes - b.intervalMinutes)[0]; /** Shared pool outcome, or per-interval auto outcomes (5-streak rule per chart). */ const outcomesByIntervalMinutes = new Map(); if (outcomeMode === 'pool') { const neutralityRules = buildPoolNeutralityRules(cfg, primary); const shared = resolvePoolOutcome( shortPool, longPool, neutralityRules, parsePoolWinnerRule(cfg.pool_winner_rule) ); for (const interval of aligning) { outcomesByIntervalMinutes.set(interval.intervalMinutes, shared); } } else { // No real-money stake: each interval uses its own history so the // max-5 consecutive same-direction rule applies on every chart. for (const interval of aligning) { const recentOutcomes = await repo.listRecentCandleOutcomes(interval.intervalMinutes, 10); outcomesByIntervalMinutes.set( interval.intervalMinutes, resolveAutoNoBetOutcome(recentOutcomes) ); } } const outcomeForInterval = (intervalMinutes: number): RoundOutcome => outcomesByIntervalMinutes.get(intervalMinutes) ?? outcomesByIntervalMinutes.get(primary.intervalMinutes)!; for (const interval of aligning) { let round = await repo.getRoundByOpenMs(candleOpenMs, interval.intervalMinutes); if (!round) { round = await syncRound(interval, candleOpenMs, 'locked'); } else if (!round.settled_at && round.status !== 'settled') { await repo.updateRoundStatus(round.id, 'locked'); } } if (pendingCount > 0) { await payOutBetsAtMaturity(candleOpenMs, outcomeForInterval, cfg); } if (multiValidationCount > 0) { const levelRows = await repo.listMultiLevels(); const payoutMultiplierMap = new Map( levelRows.map((l) => [l.level, Number(l.payout_multiplier)]) ); await multiService.processMultiBetsAtMaturity( candleOpenMs, outcomeForInterval, payoutMultiplierMap ); } for (const interval of aligning) { let round = await repo.getRoundByOpenMs(candleOpenMs, interval.intervalMinutes); if (!round) { round = await syncRound(interval, candleOpenMs, 'locked'); } if (round.settled_at) continue; await finalizeIntervalCandleAtMaturity( round, interval, outcomeForInterval(interval.intervalMinutes), shortPool, longPool ); } } async function finalizeIntervalCandleAtMaturity( round: repo.CandlePredictRoundRow, interval: ResolvedInterval, outcome: RoundOutcome, shortPool: number, longPool: number ): Promise { if (round.settled_at) return; const openMs = Number(round.candle_open_ms); const prev = (await repo.getPreviousCandleOhlc(openMs, interval.intervalMinutes)) ?? defaultSeedCandle(interval.basePrice); const candle = generateSyntheticCandle(prev, outcome); await repo.insertGeneratedCandle({ candleOpenMs: openMs, intervalMinutes: interval.intervalMinutes, open: candle.open, high: candle.high, low: candle.low, close: candle.close, colorHint: candle.colorHint, outcome: outcome.type, }); await repo.settleRound(round.id, { open: candle.open, high: candle.high, low: candle.low, close: candle.close, outcome: outcome.type, neutralColor: outcome.type === 'neutral' ? outcome.neutralColor : null, shortPool, longPool, }); void predictionAuditService.logPredictionRoundSettled({ roundId: round.id, candleOpenMs: openMs, intervalMinutes: interval.intervalMinutes, outcomeType: outcome.type, winner: outcome.type === 'neutral' ? null : outcome.winner ?? null, shortPool, longPool, }); const nowMs = Date.now(); const closeMs = openMs + interval.intervalMinutes * 60 * 1000; const settledDto = { id: round.id, candleOpenMs: openMs, candleCloseMs: closeMs, intervalMinutes: interval.intervalMinutes, status: 'settled' as const, outcome: outcome.type, openPrice: candle.open, highPrice: candle.high, lowPrice: candle.low, closePrice: candle.close, settledAt: new Date().toISOString(), serverNowMs: nowMs, secondsToBettingEnd: 0, secondsToBettingStart: 0, secondsToClose: 0, }; await publishRoundState({ intervalMinutes: interval.intervalMinutes, openMs, round: settledDto, pools: { short: shortPool, long: longPool }, eventType: 'round.settled', }); await publishCandleAppend(interval.intervalMinutes, { time: Math.floor(openMs / 1000), open: candle.open, high: candle.high, low: candle.low, close: candle.close, outcome: outcome.type, intervalMinutes: interval.intervalMinutes, candleOpenMs: openMs, }); } async function payOutBetsAtMaturity( candleOpenMs: number, outcomeForInterval: (intervalMinutes: number) => RoundOutcome, cfg: repo.CandlePredictConfigRow ): Promise { const bets = await repo.listPendingBetsForMaturity(candleOpenMs); const allIntervals = await loadResolvedIntervals(cfg, true); const intervalMap = new Map(allIntervals.map((i) => [i.intervalMinutes, i])); for (const bet of bets) { const outcome = outcomeForInterval(bet.interval_minutes); const interval = intervalMap.get(bet.interval_minutes) ?? ({ intervalMinutes: bet.interval_minutes, payoutMultiplier: Number(cfg.payout_multiplier), } as ResolvedInterval); const multiplier = interval.payoutMultiplier; const stakeRaw = BigInt(bet.stake_raw); if (outcome.type === 'neutral') { await creditGameOutcome(bet, stakeRaw, 'game_refund'); await repo.updateBetOutcome(bet.id, 'refunded', stakeRaw); void predictionAuditService.logPredictionBetSettled({ userId: bet.user_id, betId: bet.id, candleOpenMs, status: 'refunded', direction: bet.direction, outcomeType: outcome.type, stakeRaw: bet.stake_raw, payoutRaw: bet.stake_raw, predictionMode: bet.prediction_mode ?? 'single', intervalMinutes: bet.interval_minutes, }); await transactionRepository.create({ userId: bet.user_id, walletTypeId: bet.wallet_type_id, type: 'game_refund', amount: stakeRaw, status: 'completed', metadata: { bet_id: bet.id, round_id: bet.round_id, candle_open_ms: candleOpenMs, outcome: 'neutral', stake_account_kind: parseStakeAccountKind(bet.stake_account_kind), }, }); queueUserAdminStatsRefresh(bet.user_id); continue; } if (bet.direction === outcome.winner) { const payoutRaw = BigInt(Math.round(Number(stakeRaw) * multiplier)); await creditGameOutcome(bet, payoutRaw, 'game_payout'); await repo.updateBetOutcome(bet.id, 'won', payoutRaw); void predictionAuditService.logPredictionBetSettled({ userId: bet.user_id, betId: bet.id, candleOpenMs, status: 'won', direction: bet.direction, outcomeType: outcome.type, stakeRaw: bet.stake_raw, payoutRaw: payoutRaw.toString(), predictionMode: bet.prediction_mode ?? 'single', intervalMinutes: bet.interval_minutes, }); await transactionRepository.create({ userId: bet.user_id, walletTypeId: bet.wallet_type_id, type: 'game_payout', amount: payoutRaw, status: 'completed', metadata: { bet_id: bet.id, round_id: bet.round_id, candle_open_ms: candleOpenMs, outcome: outcome.type, stake_account_kind: parseStakeAccountKind(bet.stake_account_kind), }, }); } else { await repo.updateBetOutcome(bet.id, 'lost', 0n); void predictionAuditService.logPredictionBetSettled({ userId: bet.user_id, betId: bet.id, candleOpenMs, status: 'lost', direction: bet.direction, outcomeType: outcome.type, stakeRaw: bet.stake_raw, payoutRaw: '0', predictionMode: bet.prediction_mode ?? 'single', intervalMinutes: bet.interval_minutes, }); } queueUserAdminStatsRefresh(bet.user_id); } } async function processAutoBets( round: repo.CandlePredictRoundRow, interval: ResolvedInterval, cfg: repo.CandlePredictConfigRow ): Promise { if (!cfg.prediction_auto_enabled) return; const autos = await repo.listEnabledAutoSettings(); for (const auto of autos) { if (auto.period_minutes !== interval.intervalMinutes) continue; if (!auto.direction) continue; if (!isStakeInRange(cfg, Number(auto.stake_display))) continue; const existing = await repo.getUserBetForRound(round.id, auto.user_id); if (existing) continue; if (auto.mode === 'interval') { const intervalSec = auto.interval_seconds ?? 60; const last = auto.last_auto_bet_at?.getTime() ?? 0; if (Date.now() - last < intervalSec * 1000) continue; } try { await executePlaceBetInternal(auto.user_id, { direction: auto.direction, stakeDisplay: Number(auto.stake_display), intervalMinutes: interval.intervalMinutes, isAuto: true, stakeAccountKind: parseStakeAccountKind(auto.stake_account_kind), }); await repo.touchAutoBet(auto.user_id); } catch (e) { const msg = e instanceof Error ? e.message : String(e); console.warn(`[candle-predict] auto bet skipped for ${auto.user_id}: ${msg}`); } } } export async function processAutoBetForUser( userId: string, intervalMinutes?: number ): Promise<{ placed: boolean; error?: string }> { const cfg = await repo.getConfig(); if (!cfg.is_active) return { placed: false, error: 'Game is currently disabled' }; if (!cfg.prediction_auto_enabled) { return { placed: false, error: 'Auto predictions are currently disabled' }; } const interval = await resolveSelectedInterval(cfg, intervalMinutes); const auto = await repo.getAutoSettings(userId); if (!auto?.enabled || !auto.direction) { return { placed: false, error: 'Auto prediction is not enabled' }; } if (auto.period_minutes !== interval.intervalMinutes) { return { placed: false, error: 'Auto prediction is configured for a different interval' }; } if (!isStakeInRange(cfg, Number(auto.stake_display))) { return { placed: false, error: 'Invalid stake amount' }; } const nowMs = Date.now(); const timing = getActiveRoundTiming( nowMs, interval.intervalMinutes, interval.predictionWindowSeconds ); if (timing.phase !== 'betting') { return { placed: false, error: 'Prediction window is closed' }; } const round = await repo.getRoundByOpenMs(timing.openMs, interval.intervalMinutes); if (!round) return { placed: false, error: 'No active round' }; const existing = await repo.getUserBetForRound(round.id, userId); if (existing) return { placed: false, error: 'Already predicted this round' }; if (auto.mode === 'interval') { const intervalSec = auto.interval_seconds ?? 60; const last = auto.last_auto_bet_at?.getTime() ?? 0; if (Date.now() - last < intervalSec * 1000) { return { placed: false, error: 'Interval not elapsed' }; } } try { await executePlaceBetInternal(userId, { direction: auto.direction, stakeDisplay: Number(auto.stake_display), intervalMinutes: interval.intervalMinutes, isAuto: true, stakeAccountKind: parseStakeAccountKind(auto.stake_account_kind), }); await repo.touchAutoBet(userId); return { placed: true }; } catch (e) { const msg = e instanceof Error ? e.message : 'Auto prediction failed'; return { placed: false, error: msg }; } } function parseStakeAccountKind(value: unknown): AccountKind { if (value === 'bonus') return 'bonus'; if (value === 'test') return 'test'; return 'main'; } async function resolveDebitAccount( userId: string, walletTypeId: number, stakeRaw: bigint, requestedKind: AccountKind = 'main' ): Promise<{ stakeAccountKind: AccountKind; debitAccountId: string }> { const mainAccount = await ledgerRepository.getOrCreateAccount(userId, walletTypeId, 'main'); const bonusAccount = await ledgerRepository.getOrCreateBonusAccount(userId, walletTypeId); const testAccount = await ledgerRepository.getOrCreateTestAccount(userId, walletTypeId); const mainBal = BigInt(mainAccount.available_balance ?? '0'); const bonusBal = BigInt(bonusAccount.available_balance ?? '0'); const testBal = BigInt(testAccount.available_balance ?? '0'); const account = requestedKind === 'bonus' ? bonusAccount : requestedKind === 'test' ? testAccount : mainAccount; const balance = requestedKind === 'bonus' ? bonusBal : requestedKind === 'test' ? testBal : mainBal; if (balance < stakeRaw) { const label = requestedKind === 'bonus' ? 'bonus' : requestedKind === 'test' ? 'test' : 'main'; throw new Error(`Insufficient ${label} wallet balance for this stake.`); } return { stakeAccountKind: requestedKind, debitAccountId: account.id }; } async function assertStakeWalletBalance( userId: string, walletTypeCode: string, stakeDisplay: number, stakeAccountKind: AccountKind ): Promise { const walletType = await walletRepository.getWalletTypeByCode(walletTypeCode); if (!walletType) throw new Error('Wallet type not configured'); const stakeRaw = stakeToRaw(stakeDisplay); await resolveDebitAccount(userId, walletType.id, stakeRaw, stakeAccountKind); } export async function executePlaceBetInternal( userId: string, input: { direction: 'short' | 'long'; stakeDisplay: number; intervalMinutes: number; isAuto?: boolean; stakeAccountKind?: AccountKind; } ) { const cfg = await repo.getConfig(); if (!cfg.is_active) throw new Error('Game is currently disabled'); if (!cfg.prediction_single_enabled) { throw new Error('Single-candle predictions are currently disabled'); } const interval = await resolveSelectedInterval(cfg, input.intervalMinutes); assertStakeInRange(cfg, input.stakeDisplay); const nowMs = Date.now(); const timing = getActiveRoundTiming( nowMs, interval.intervalMinutes, interval.predictionWindowSeconds ); if (timing.phase !== 'betting') { throw new Error('Prediction window is closed'); } let round = await repo.getRoundByOpenMs(timing.openMs, interval.intervalMinutes); if (!round) { round = await syncRound(interval, timing.openMs, 'betting'); } else if (round.status !== 'betting' && round.status !== 'settled') { await repo.updateRoundStatus(round.id, 'betting'); round = { ...round, status: 'betting' }; } if (round.status === 'settled') { throw new Error('Predictions are not open for this round'); } const existing = await repo.getUserBetForRound(round.id, userId); if (existing) throw new Error('You already placed a prediction for this round'); const activeMulti = await repo.getUserActiveMultiBet(userId, interval.intervalMinutes); if (activeMulti) { throw new Error('Finish or wait for your multi-candle prediction before placing a single bet'); } const walletType = await walletRepository.getWalletTypeByCode(cfg.wallet_type_code); if (!walletType) throw new Error('Wallet type not configured'); const stakeRaw = stakeToRaw(input.stakeDisplay); const stakeAccountKind = parseStakeAccountKind(input.stakeAccountKind); const { debitAccountId } = await resolveDebitAccount( userId, walletType.id, stakeRaw, stakeAccountKind ); await ledgerRepository.debit(debitAccountId, stakeRaw, 'game_stake', 'candle_predict_bet', round.id); const bet = await repo.createBet({ roundId: round.id, userId, direction: input.direction, stakeRaw, stakeDisplay: input.stakeDisplay, walletTypeId: walletType.id, intervalMinutes: interval.intervalMinutes, isAuto: input.isAuto, stakeAccountKind, }); await repo.incrementRoundBetCount(round.id); await transactionRepository.create({ userId, walletTypeId: walletType.id, type: 'game_stake', amount: stakeRaw, status: 'completed', metadata: { bet_id: bet.id, round_id: round.id, direction: input.direction, interval_minutes: interval.intervalMinutes, stake_account_kind: stakeAccountKind, }, }); await auditLogRepository.create({ userId, action: 'prediction_placed', resourceType: 'candle_predict_bet', resourceId: bet.id, metadata: { direction: input.direction, stake_display: input.stakeDisplay, interval_minutes: interval.intervalMinutes, is_auto: Boolean(input.isAuto), }, }); queueUserAdminStatsRefresh(userId); const mapped = mapBet(bet); if (config.redis.enabled) { await publishUserEvent(userId, { type: 'bet.accepted', payload: { bet: mapped as unknown as Record, }, }); } return mapped; } export type PlaceBetOptions = { idempotencyKey?: string; source?: 'http' | 'ws'; }; export type PlaceBetResult = | { status: 'accepted'; bet: Awaited> } | { status: 'queued'; idempotencyKey: string }; export async function placeBet( userId: string, direction: string, stakeDisplay: number, intervalMinutes?: number, stakeAccountKind?: AccountKind, opts?: PlaceBetOptions ): Promise { assertPositiveStakeAmount(stakeDisplay); if (direction !== 'short' && direction !== 'long') { throw new Error('direction must be short or long'); } const cfg = await repo.getConfig(); const interval = await resolveSelectedInterval(cfg, intervalMinutes); const idempotencyKey = opts?.idempotencyKey?.trim() || uuidv4(); const source = opts?.source ?? 'http'; // Manual bets from HTTP must be synchronous (same as multi-candle). Async queue + WS // confirmation only applies to WebSocket place_bet messages. const useBetQueue = source === 'ws' && config.redis.betAsyncEnabled && isRedisEnabled(); if (useBetQueue) { const existing = await getBetIdempotency(idempotencyKey); if (existing?.status === 'accepted') { return { status: 'accepted', bet: existing.bet as Awaited> }; } if (existing?.status === 'rejected') { throw new Error(existing.error); } if (existing?.status === 'processing') { return { status: 'queued', idempotencyKey }; } const nowMs = Date.now(); const timing = getActiveRoundTiming( nowMs, interval.intervalMinutes, interval.predictionWindowSeconds ); if (timing.phase !== 'betting') { throw new Error('Prediction window is closed'); } const { streamId } = await enqueueBet({ userId, direction, stakeDisplay, intervalMinutes: interval.intervalMinutes, stakeAccountKind: parseStakeAccountKind(stakeAccountKind), idempotencyKey, source, requestedAt: nowMs, }); const claimed = await claimBetIdempotencyProcessing(idempotencyKey, streamId); if (!claimed) { const replay = await getBetIdempotency(idempotencyKey); if (replay?.status === 'accepted') { return { status: 'accepted', bet: replay.bet as Awaited> }; } if (replay?.status === 'rejected') throw new Error(replay.error); return { status: 'queued', idempotencyKey }; } return { status: 'queued', idempotencyKey }; } const bet = await executePlaceBetInternal(userId, { direction, stakeDisplay, intervalMinutes: interval.intervalMinutes, stakeAccountKind: parseStakeAccountKind(stakeAccountKind), }); if (config.redis.enabled) { const timingAfter = getActiveRoundTiming( Date.now(), interval.intervalMinutes, interval.predictionWindowSeconds ); if (timingAfter.phase === 'betting') { await publishRoundSnapshot(interval.intervalMinutes, timingAfter.openMs); } } return { status: 'accepted', bet }; } export async function getRecentPredictions( userId: string, page = 1, pageSize = 10, intervalMinutes?: number, filters?: { stakeAccountKind?: string; status?: string } ) { const safePage = Math.max(1, page); const safeSize = Math.min(50, Math.max(1, pageSize)); const offset = (safePage - 1) * safeSize; const stakeAccountKind = filters?.stakeAccountKind; const status = filters?.status; const [rows, total] = await Promise.all([ repo.listRecentBets(userId, safeSize, offset, intervalMinutes, stakeAccountKind, status), repo.countUserPredictions(userId, intervalMinutes, stakeAccountKind, status), ]); return { items: rows.map(mapBet), total, page: safePage, pageSize: safeSize, totalPages: Math.max(1, Math.ceil(total / safeSize)), }; } export async function getRecentBets(userId: string) { const result = await getRecentPredictions(userId, 1, 20); return result.items; } export async function saveAutoSettings(userId: string, body: Record) { const cfg = await repo.getConfig(); if (!cfg.prediction_auto_enabled) { throw new Error('Auto predictions are currently disabled'); } const enabled = Boolean(body.enabled); const direction = body.direction === 'short' || body.direction === 'long' ? (body.direction as 'short' | 'long') : null; const stakeDisplay = parseStakeDisplay(body, cfg.stake_amounts[0] ?? 1); const mode = body.mode === 'interval' || body.mode === 'each_round' ? (body.mode as 'each_round' | 'interval') : 'each_round'; const periodMinutes = typeof body.periodMinutes === 'number' ? body.periodMinutes : typeof body.intervalMinutes === 'number' ? body.intervalMinutes : 1; await resolveSelectedInterval(cfg, periodMinutes); assertStakeInRange(cfg, stakeDisplay); if (enabled && !direction) { throw new Error('direction is required when auto prediction is enabled'); } if (!cfg.auto_modes.includes(mode)) { throw new Error('Invalid auto prediction mode'); } const stakeAccountKind = parseStakeAccountKind(body.stakeAccountKind ?? body.stake_account_kind); const validateWalletBalance = body.validateWalletBalance === true; const attemptImmediateBet = body.attemptImmediateBet === true; if (enabled && validateWalletBalance) { await assertStakeWalletBalance(userId, cfg.wallet_type_code, stakeDisplay, stakeAccountKind); } const row = await repo.upsertAutoSettings(userId, { enabled, direction, stakeDisplay, mode, periodMinutes, stakeAccountKind, intervalSeconds: typeof body.intervalSeconds === 'number' ? body.intervalSeconds : typeof body.intervalSeconds === 'string' ? Number(body.intervalSeconds) || (mode === 'interval' ? 60 : null) : mode === 'interval' ? 60 : null, }); const result = { enabled: row.enabled, direction: row.direction, stakeDisplay: Number(row.stake_display), mode: row.mode, intervalSeconds: row.interval_seconds, periodMinutes: row.period_minutes, stakeAccountKind: parseStakeAccountKind(row.stake_account_kind), lastAutoBetAt: row.last_auto_bet_at?.toISOString() ?? null, autoBetPlaced: false, autoBetError: null as string | null, }; if (enabled && direction && attemptImmediateBet) { const attempt = await processAutoBetForUser(userId, row.period_minutes); result.autoBetPlaced = attempt.placed; result.autoBetError = attempt.error ?? null; if (attempt.placed) { result.lastAutoBetAt = new Date().toISOString(); } } return result; } export async function getAutoSettings(userId: string) { const row = await repo.getAutoSettings(userId); if (!row) { return { enabled: false, direction: null, stakeDisplay: 1, mode: 'each_round' as const, intervalSeconds: 60, periodMinutes: 1, stakeAccountKind: 'main' as const, lastAutoBetAt: null, }; } return { enabled: row.enabled, direction: row.direction, stakeDisplay: Number(row.stake_display), mode: row.mode, intervalSeconds: row.interval_seconds, periodMinutes: row.period_minutes, stakeAccountKind: parseStakeAccountKind(row.stake_account_kind), lastAutoBetAt: row.last_auto_bet_at?.toISOString() ?? null, }; } export async function listAdminMultiLevels() { const rows = await repo.listMultiLevels(); return rows.map(multiService.mapMultiLevel); } export async function updateAdminMultiLevels(body: Record) { if (!Array.isArray(body.levels)) { throw new Error('levels array is required'); } const results = []; for (const item of body.levels as Record[]) { const level = typeof item.level === 'number' ? item.level : Number(item.level); if (!Number.isFinite(level) || level < 2 || level > 20) { throw new Error('Each level must be between 2 and 20'); } const payoutMultiplier = typeof item.payoutMultiplier === 'number' ? item.payoutMultiplier : undefined; if (payoutMultiplier != null && payoutMultiplier <= 0) { throw new Error('payoutMultiplier must be positive'); } const poolMultiplier = typeof item.poolMultiplier === 'number' ? item.poolMultiplier : undefined; if (poolMultiplier != null && poolMultiplier <= 0) { throw new Error('poolMultiplier must be positive'); } const updated = await repo.upsertMultiLevel({ level, enabled: typeof item.enabled === 'boolean' ? item.enabled : undefined, payoutMultiplier, poolMultiplier, sortOrder: typeof item.sortOrder === 'number' ? item.sortOrder : undefined, }); results.push(multiService.mapMultiLevel(updated)); } return results; } export async function placeMultiCandleBet( userId: string, input: { level: number; sequence: ('short' | 'long')[]; stakeDisplay: number; intervalMinutes?: number; stakeAccountKind?: AccountKind; } ) { assertPositiveStakeAmount(input.stakeDisplay); const cfg = await repo.getConfig(); if (!cfg.is_active) throw new Error('Game is currently disabled'); if (!cfg.prediction_multi_enabled) { throw new Error('Multi-candle predictions are currently disabled'); } const levelConfig = await repo.getMultiLevel(input.level); if (!levelConfig || !levelConfig.enabled) { throw new Error('This multi-candle level is not available'); } if (!Array.isArray(input.sequence) || input.sequence.length !== input.level) { throw new Error(`Sequence must contain exactly ${input.level} directions`); } for (const d of input.sequence) { if (d !== 'short' && d !== 'long') { throw new Error('Each direction must be short or long'); } } if (input.level < 2) { throw new Error('Multi-candle level must be at least 2 — use single prediction for one candle'); } const interval = await resolveSelectedInterval(cfg, input.intervalMinutes); assertStakeInRange(cfg, input.stakeDisplay); const nowMs = Date.now(); const timing = getActiveRoundTiming( nowMs, interval.intervalMinutes, interval.predictionWindowSeconds ); if (timing.phase !== 'betting') { throw new Error('Prediction window is closed'); } let round = await repo.getRoundByOpenMs(timing.openMs, interval.intervalMinutes); if (!round) { round = await syncRound(interval, timing.openMs, 'betting'); } else if (round.status !== 'betting' && round.status !== 'settled') { await repo.updateRoundStatus(round.id, 'betting'); round = { ...round, status: 'betting' }; } if (round.status === 'settled') { throw new Error('Predictions are not open for this round'); } const activeMulti = await repo.getUserActiveMultiBet(userId, interval.intervalMinutes); if (activeMulti) { throw new Error('You already have an active multi-candle prediction'); } const existingSingle = await repo.getUserBetForRound(round.id, userId); if (existingSingle) { throw new Error('You already placed a single prediction for this round'); } const walletType = await walletRepository.getWalletTypeByCode(cfg.wallet_type_code); if (!walletType) throw new Error('Wallet type not configured'); const stakeRaw = stakeToRaw(input.stakeDisplay); const stakeAccountKind = parseStakeAccountKind(input.stakeAccountKind); const { debitAccountId } = await resolveDebitAccount( userId, walletType.id, stakeRaw, stakeAccountKind ); await ledgerRepository.debit(debitAccountId, stakeRaw, 'game_stake', 'candle_predict_bet', round.id); const bet = await repo.createMultiCandleBet({ roundId: round.id, userId, stakeRaw, stakeDisplay: input.stakeDisplay, walletTypeId: walletType.id, intervalMinutes: interval.intervalMinutes, stakeAccountKind, level: input.level, sequenceDirections: input.sequence, anchorCandleOpenMs: timing.openMs, }); await repo.incrementRoundBetCount(round.id); await transactionRepository.create({ userId, walletTypeId: walletType.id, type: 'game_stake', amount: stakeRaw, status: 'completed', metadata: { bet_id: bet.id, round_id: round.id, prediction_mode: 'multi_candle', multi_level: input.level, sequence: input.sequence, interval_minutes: interval.intervalMinutes, stake_account_kind: stakeAccountKind, }, }); queueUserAdminStatsRefresh(userId); if (config.redis.enabled) { await publishRoundSnapshot(interval.intervalMinutes, timing.openMs); const mapped = multiService.mapMultiBet(bet); await publishUserEvent(userId, { type: 'multi.updated', payload: { intervalMinutes: interval.intervalMinutes, userMultiBet: mapped as unknown as Record, }, }); } return multiService.mapMultiBet(bet); } export function startCandlePredictEngine(): void { const run = async () => { try { await tickGameEngine(); } catch (e) { console.error('Candle Predict engine error:', e); } const settings = await settingsRepository.getSettings(); setTimeout(run, settings.candle_predict_engine_tick_ms); }; setTimeout(run, 5000); }