games_app/backend/dist/domain/candle-predict/index.js
2026-10-26 14:18:55 +02:00

2023 lines
91 KiB
JavaScript

"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.getPublicConfig = getPublicConfig;
exports.updateAdminConfig = updateAdminConfig;
exports.listAdminIntervals = listAdminIntervals;
exports.createAdminInterval = createAdminInterval;
exports.updateAdminInterval = updateAdminInterval;
exports.deleteAdminInterval = deleteAdminInterval;
exports.getGameState = getGameState;
exports.getCandlesPage = getCandlesPage;
exports.getCandles = getCandles;
exports.tickGameEngine = tickGameEngine;
exports.publishRoundSnapshot = publishRoundSnapshot;
exports.processAutoBetForUser = processAutoBetForUser;
exports.executePlaceBetInternal = executePlaceBetInternal;
exports.placeBet = placeBet;
exports.getRecentPredictions = getRecentPredictions;
exports.getRecentBets = getRecentBets;
exports.saveAutoSettings = saveAutoSettings;
exports.getAutoSettings = getAutoSettings;
exports.listAdminMultiLevels = listAdminMultiLevels;
exports.updateAdminMultiLevels = updateAdminMultiLevels;
exports.placeMultiCandleBet = placeMultiCandleBet;
exports.startCandlePredictEngine = startCandlePredictEngine;
const repo = __importStar(require("../../repositories/candlePredictRepository"));
const ledgerRepository = __importStar(require("../../repositories/ledgerRepository"));
const walletRepository = __importStar(require("../../repositories/walletRepository"));
const transactionRepository = __importStar(require("../../repositories/transactionRepository"));
const auditLogRepository = __importStar(require("../../repositories/auditLogRepository"));
const settingsRepository = __importStar(require("../../repositories/settingsRepository"));
const stakeAmountValidation_1 = require("../../utils/stakeAmountValidation");
const userAdminStatsService_1 = require("../../services/userAdminStatsService");
const predictionAuditService = __importStar(require("../../services/predictionAuditService"));
const engineAuditRetentionService_1 = require("../../services/engineAuditRetentionService");
const referralService_1 = require("../../services/referralService");
const candleGenerationService_1 = require("../../services/candleGenerationService");
const gameTimingService_1 = require("../../services/gameTimingService");
const multiService = __importStar(require("../../services/candlePredictMultiService"));
const testWalletService = __importStar(require("../../services/testWalletService"));
const soloEncouragementService = __importStar(require("../../services/soloEncouragementService"));
const dailyRevenueOutcomeService_1 = require("../../services/dailyRevenueOutcomeService");
const publishRoundState_1 = require("./realtime/publishRoundState");
const pubsub_1 = require("../../realtime/redis/pubsub");
const roundCache_1 = require("./read/roundCache");
const config_1 = require("../../config");
const client_1 = require("../../realtime/redis/client");
const pubsub_2 = require("../../realtime/redis/pubsub");
const stateVersions_1 = require("../../realtime/redis/stateVersions");
const betQueue_1 = require("../../realtime/streams/betQueue");
const uuid_1 = require("uuid");
const DECIMALS = 6n;
async function creditGameOutcome(bet, amount, entryType) {
const stakeKind = parseStakeAccountKind(bet.stake_account_kind);
let creditKind = 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) {
return BigInt(Math.round(stakeDisplay * 10 ** Number(DECIMALS)));
}
function rawToStake(raw) {
return Number(raw) / 10 ** Number(DECIMALS);
}
const STAKE_AMOUNT_EPS = 1e-9;
const MIN_STAKE_FLOOR = 0.01;
const MAX_STAKE_CEILING = 1000000;
function getStakeBounds(cfg) {
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, phase, row) {
if (phase === 'betting') {
return repo.getGlobalPoolTotalsForMaturity(openMs);
}
return {
shortPool: Number(row.short_pool_display),
longPool: Number(row.long_pool_display),
};
}
function assertStakeInRange(cfg, stake) {
(0, stakeAmountValidation_1.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, stake) {
try {
assertStakeInRange(cfg, stake);
return true;
}
catch {
return false;
}
}
function assertStakePresetsInRange(cfg, stakeAmounts) {
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, maxStakeAmount) {
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, fallback) {
const raw = body.stakeDisplay ?? body.stakeAmount ?? body.stake_amount;
if (raw !== undefined) {
return (0, stakeAmountValidation_1.parseStakeAmountFromBody)(raw);
}
return fallback;
}
function parsePoolWinnerRule(value) {
if (value === 'majority')
return 'majority';
if (value === 'daily_revenue')
return 'daily_revenue';
return 'minority';
}
function parseDailyRevenueOverflowStrategy(value) {
return value === 'minority' ? 'minority' : 'neutral';
}
function isRealMoneyStakeKind(kind) {
return kind === 'main' || kind === 'bonus' || kind == null;
}
function validateNeutralityRules(input) {
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 resolveNeutralityEnabled(globalEnabled, intervalOverride) {
// Global catalog toggle is the master switch: OFF disables every interval.
if (globalEnabled === false)
return false;
// Interval may only further disable; null/undefined inherits global (on by default).
if (intervalOverride === false)
return false;
return true;
}
function buildPoolNeutralityRules(global, interval) {
return {
minTolerancePercent: interval?.tieTolerancePercent ?? Number(global.tie_tolerance_percent),
maxTolerancePercent: interval?.tieToleranceMaxPercent ?? Number(global.tie_tolerance_max_percent),
minToleranceEnabled: resolveNeutralityEnabled(global.tie_tolerance_min_enabled, interval?.tieToleranceMinEnabled),
maxToleranceEnabled: resolveNeutralityEnabled(global.tie_tolerance_max_enabled, interval?.tieToleranceMaxEnabled),
};
}
function mapConfig(row) {
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),
dailyRevenueTarget: Number(row.daily_revenue_target ?? 0),
dailyRevenueOverflowStrategy: parseDailyRevenueOverflowStrategy(row.daily_revenue_overflow_strategy),
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,
},
/** Display-only chart identity (synthetic; not an external market symbol). */
instrument: {
symbol: row.instrument_symbol ?? 'FO',
displayName: row.instrument_display_name ?? 'Full Option',
quoteCurrency: row.instrument_quote_currency ?? 'USDT',
priceDigits: Number(row.instrument_price_digits ?? 2),
},
updatedAt: row.updated_at.toISOString(),
};
}
function mapConfigForPlayer(row) {
const { poolWinnerRule: _poolWinnerRule, poolMultiplier: _poolMultiplier, tieTolerancePercent: _min, tieToleranceMaxPercent: _max, tieToleranceMinEnabled: _minEn, tieToleranceMaxEnabled: _maxEn, dailyRevenueTarget: _drt, dailyRevenueOverflowStrategy: _dros, ...player } = mapConfig(row);
return player;
}
function resolveInterval(global, row) {
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: resolveNeutralityEnabled(global.tie_tolerance_min_enabled, row.tie_tolerance_min_enabled),
tieToleranceMaxEnabled: resolveNeutralityEnabled(global.tie_tolerance_max_enabled, row.tie_tolerance_max_enabled),
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) {
return {
id: interval.id,
intervalMinutes: interval.intervalMinutes,
label: interval.label,
sortOrder: interval.sortOrder,
isDefault: interval.isDefault,
isActive: interval.isActive,
predictionWindowSeconds: interval.predictionWindowSeconds,
maxPredictionWindowSeconds: (0, gameTimingService_1.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,
};
}
function mapIntervalDtoForPlayer(interval) {
const { tieTolerancePercent: _min, tieToleranceMaxPercent: _max, tieToleranceMinEnabled: _minEn, tieToleranceMaxEnabled: _maxEn, poolMultiplier: _poolMultiplier, ...player } = mapIntervalDto(interval);
return player;
}
function assertPredictionWindowAllowed(intervalMinutes, predictionWindowSeconds) {
if (predictionWindowSeconds == null)
return;
if (!Number.isFinite(predictionWindowSeconds) || predictionWindowSeconds < 5) {
throw new Error('predictionWindowSeconds must be at least 5');
}
const max = (0, gameTimingService_1.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) {
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) {
const { colorHint: _colorHint, ...player } = mapCandleRow(c);
return player;
}
async function loadResolvedIntervals(cfg, activeOnly = true) {
const rows = activeOnly ? await repo.listActiveIntervals() : await repo.listAllIntervals();
return rows.map((r) => resolveInterval(cfg, r));
}
/**
* Bump the shared config version and notify every active interval channel.
* Used by admin config / interval / multi-level mutations so clients invalidate
* `/state` consistently (version ETag + live `config.updated`).
*/
async function publishConfigUpdated(cfg) {
if (!config_1.config.redis.enabled)
return;
const configVersion = await (0, stateVersions_1.bumpConfigVersionSafe)();
const sourceCfg = cfg ?? (await repo.getConfig());
const activeIntervals = await loadResolvedIntervals(sourceCfg, true);
await Promise.all(activeIntervals
.filter((i) => i.isActive)
.map((i) => (0, pubsub_1.publishRoundEvent)(i.intervalMinutes, {
type: 'config.updated',
intervalMinutes: i.intervalMinutes,
payload: {
...(configVersion != null ? { versions: { config: configVersion } } : {}),
},
})));
}
async function resolveSelectedInterval(cfg, intervalMinutes) {
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, nowMs, windowSec, timing, pools) {
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 = (0, gameTimingService_1.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) {
const { shortPool: _shortPool, longPool: _longPool, neutralColor: _neutralColor, totalBets: _totalBets, ...player } = round;
return player;
}
function mapBet(row) {
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'),
stakeAccountKind: parseStakeAccountKind(row.stake_account_kind),
};
if (row.prediction_mode === 'multi_candle') {
return {
...base,
...multiService.mapMultiBet(row),
};
}
return base;
}
async function getPublicConfig() {
const cfg = await repo.getConfig();
const mapped = mapConfig(cfg);
const netRaw = await repo.getDailyRevenueNetRaw((0, dailyRevenueOutcomeService_1.utcRevenueDate)());
return {
...mapped,
dailyRevenueNetToday: (0, dailyRevenueOutcomeService_1.usdtRawToDisplay)(netRaw),
};
}
async function updateAdminConfig(body) {
const cfg = await repo.getConfig();
const stakeAmounts = Array.isArray(body.stakeAmounts)
? body.stakeAmounts.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 = {
...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;
if (typeof body.poolWinnerRule === 'string') {
if (body.poolWinnerRule !== 'minority' &&
body.poolWinnerRule !== 'majority' &&
body.poolWinnerRule !== 'daily_revenue') {
throw new Error('poolWinnerRule must be minority, majority, or daily_revenue');
}
poolWinnerRule = body.poolWinnerRule;
}
let dailyRevenueTarget;
if (typeof body.dailyRevenueTarget === 'number') {
if (body.dailyRevenueTarget < 0) {
throw new Error('dailyRevenueTarget must be >= 0');
}
dailyRevenueTarget = body.dailyRevenueTarget;
}
let dailyRevenueOverflowStrategy;
if (typeof body.dailyRevenueOverflowStrategy === 'string') {
if (body.dailyRevenueOverflowStrategy !== 'minority' &&
body.dailyRevenueOverflowStrategy !== 'neutral') {
throw new Error('dailyRevenueOverflowStrategy must be minority or neutral');
}
dailyRevenueOverflowStrategy = body.dailyRevenueOverflowStrategy;
}
const instrumentBody = typeof body.instrument === 'object' && body.instrument !== null
? body.instrument
: null;
const instrumentSymbol = typeof instrumentBody?.symbol === 'string'
? instrumentBody.symbol.trim()
: typeof body.instrumentSymbol === 'string'
? body.instrumentSymbol.trim()
: undefined;
const instrumentDisplayName = typeof instrumentBody?.displayName === 'string'
? instrumentBody.displayName.trim()
: typeof body.instrumentDisplayName === 'string'
? body.instrumentDisplayName.trim()
: undefined;
const instrumentQuoteCurrency = typeof instrumentBody?.quoteCurrency === 'string'
? instrumentBody.quoteCurrency.trim()
: typeof body.instrumentQuoteCurrency === 'string'
? body.instrumentQuoteCurrency.trim()
: undefined;
const instrumentPriceDigits = typeof instrumentBody?.priceDigits === 'number'
? instrumentBody.priceDigits
: typeof body.instrumentPriceDigits === 'number'
? body.instrumentPriceDigits
: undefined;
if (instrumentSymbol !== undefined && !instrumentSymbol) {
throw new Error('instrument.symbol must not be empty');
}
if (instrumentDisplayName !== undefined && !instrumentDisplayName) {
throw new Error('instrument.displayName must not be empty');
}
if (instrumentQuoteCurrency !== undefined && !instrumentQuoteCurrency) {
throw new Error('instrument.quoteCurrency must not be empty');
}
if (instrumentPriceDigits !== undefined &&
(!Number.isInteger(instrumentPriceDigits) ||
instrumentPriceDigits < 0 ||
instrumentPriceDigits > 8)) {
throw new Error('instrument.priceDigits must be an integer between 0 and 8');
}
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,
dailyRevenueTarget,
dailyRevenueOverflowStrategy,
walletTypeCode: typeof body.walletTypeCode === 'string' ? body.walletTypeCode : undefined,
autoModes: Array.isArray(body.autoModes) ? body.autoModes : 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.single === 'boolean'
? body.predictionTypes.single
: undefined,
predictionAutoEnabled: typeof body.predictionAutoEnabled === 'boolean'
? body.predictionAutoEnabled
: typeof body.predictionTypes === 'object' &&
body.predictionTypes !== null &&
typeof body.predictionTypes.auto === 'boolean'
? body.predictionTypes.auto
: undefined,
predictionMultiEnabled: typeof body.predictionMultiEnabled === 'boolean'
? body.predictionMultiEnabled
: typeof body.predictionTypes === 'object' &&
body.predictionTypes !== null &&
typeof body.predictionTypes.multiCandle === 'boolean'
? body.predictionTypes.multiCandle
: undefined,
instrumentSymbol,
instrumentDisplayName,
instrumentQuoteCurrency,
instrumentPriceDigits,
});
// Global enable toggles should win over stale per-interval "on/off" overrides.
if (typeof body.tieToleranceMinEnabled === 'boolean' ||
typeof body.tieToleranceMaxEnabled === 'boolean') {
await repo.clearIntervalNeutralityEnabledOverrides();
}
if (config_1.config.redis.enabled) {
await publishConfigUpdated(updated);
}
const mapped = mapConfig(updated);
const netRaw = await repo.getDailyRevenueNetRaw((0, dailyRevenueOutcomeService_1.utcRevenueDate)());
return {
...mapped,
dailyRevenueNetToday: (0, dailyRevenueOutcomeService_1.usdtRawToDisplay)(netRaw),
};
}
async function listAdminIntervals() {
const cfg = await repo.getConfig();
const rows = await repo.listAllIntervals();
// Return raw override fields (null = inherit) so the admin form can show Inherit/On/Off.
// Settlement still uses resolveInterval() which applies the global master switch.
return rows.map((row) => {
const resolved = resolveInterval(cfg, row);
return {
...mapIntervalDto(resolved),
tieTolerancePercent: row.tie_tolerance_percent == null ? null : Number(row.tie_tolerance_percent),
tieToleranceMaxPercent: row.tie_tolerance_max_percent == null ? null : Number(row.tie_tolerance_max_percent),
tieToleranceMinEnabled: row.tie_tolerance_min_enabled,
tieToleranceMaxEnabled: row.tie_tolerance_max_enabled,
predictionWindowSeconds: row.prediction_window_seconds,
payoutMultiplier: row.payout_multiplier == null ? null : Number(row.payout_multiplier),
poolMultiplier: row.pool_multiplier == null ? null : Number(row.pool_multiplier),
basePrice: row.base_price == null ? null : Number(row.base_price),
};
});
}
async function createAdminInterval(body) {
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();
await publishConfigUpdated(cfg);
return mapIntervalDto(resolveInterval(cfg, row));
}
async function updateAdminInterval(id, body) {
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);
await publishConfigUpdated(cfg);
return mapIntervalDto(resolveInterval(cfg, updated));
}
async function deleteAdminInterval(id) {
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);
await publishConfigUpdated();
return { ok: true };
}
async function getGameState(userId, intervalMinutes, opts) {
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 = (0, gameTimingService_1.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;
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 (0, roundCache_1.loadCachedRound)(selected.intervalMinutes, timing.openMs);
if (cached) {
// Timing fields come from mapRound (authoritative). Cache only enriches pools/OHLC.
playerRoundDto = {
...playerRoundDto,
outcome: cached.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),
dailyRevenueNetToday: (0, dailyRevenueOutcomeService_1.usdtRawToDisplay)(await repo.getDailyRevenueNetRaw((0, dailyRevenueOutcomeService_1.utcRevenueDate)())),
}
: mapConfigForPlayer(cfg),
intervals: intervals.map(includeInternal ? mapIntervalDto : mapIntervalDtoForPlayer),
selectedIntervalMinutes: selected.intervalMinutes,
interval: includeInternal ? mapIntervalDto(selected) : mapIntervalDtoForPlayer(selected),
round: playerRoundDto,
userBet,
userMultiBet,
multiLevels,
autoSettings,
};
}
async function getCandlesPage(input) {
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 */
async function getCandles(limit = 100, intervalMinutes) {
const page = await getCandlesPage({ limit, intervalMinutes });
return page.items;
}
async function syncRound(interval, openMs, status) {
return repo.createRound({
candleOpenMs: openMs,
intervalMinutes: interval.intervalMinutes,
status,
});
}
async function tickGameEngine() {
const cfg = await repo.getConfig();
if (!cfg.is_active)
return;
const intervals = await loadResolvedIntervals(cfg, true);
const nowMs = Date.now();
// Settle overdue rounds — isolate each so a single failure doesn't block the rest.
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);
try {
await settleMaturityAtOpenMs(openMs, cfg);
}
catch (e) {
console.error(`[engine] settleMaturity failed for openMs=${openMs}:`, e);
}
}
const multiDueOpenMs = await repo.listDueMultiValidationCandleOpenMs(nowMs);
for (const openMs of multiDueOpenMs) {
if (settledMaturities.has(openMs))
continue;
settledMaturities.add(openMs);
try {
await settleMaturityAtOpenMs(openMs, cfg);
}
catch (e) {
console.error(`[engine] settleMaturity (multi) failed for openMs=${openMs}:`, e);
}
}
for (const interval of intervals) {
try {
await tickIntervalEngine(cfg, interval, nowMs);
}
catch (e) {
console.error(`[engine] tickInterval failed for ${interval.intervalMinutes}m:`, e);
}
}
try {
const settings = await settingsRepository.getSettings();
if (nowMs - lastBackfillRunMs >= settings.candle_predict_backfill_interval_ms) {
for (const interval of intervals) {
try {
await backfillMissedAutoCandles(interval, nowMs, cfg, settings);
}
catch (e) {
console.error(`[engine] backfill failed for ${interval.intervalMinutes}m:`, e);
}
}
lastBackfillRunMs = nowMs;
}
}
catch (e) {
console.error('[engine] backfill settings read failed:', e);
}
}
function lastCompletedCandleOpenMs(nowMs, intervalMinutes) {
const intervalMs = intervalMinutes * 60 * 1000;
let openMs = (0, gameTimingService_1.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, nowMs, cfg, settings) {
const intervalMs = interval.intervalMinutes * 60 * 1000;
const lastCompletedOpen = lastCompletedCandleOpenMs(nowMs, interval.intervalMinutes);
const lastCandleOpen = await repo.getLastCandleOpenMs(interval.intervalMinutes);
let nextOpen;
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 (!(0, gameTimingService_1.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, interval, nowMs) {
const timing = (0, gameTimingService_1.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 = (0, gameTimingService_1.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 (0, publishRoundState_1.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 = (0, gameTimingService_1.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 (0, publishRoundState_1.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. */
async function publishRoundSnapshot(intervalMinutes, openMs) {
if (!config_1.config.redis.enabled)
return;
const cfg = await repo.getConfig();
const interval = await resolveSelectedInterval(cfg, intervalMinutes);
const nowMs = Date.now();
const timing = (0, gameTimingService_1.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 (0, publishRoundState_1.publishRoundState)({
intervalMinutes,
openMs,
round: dto,
pools: { short: livePools.shortPool, long: livePools.longPool },
});
}
const _settlingInProgress = new Set();
async function settleMaturityAtOpenMs(candleOpenMs, cfg) {
if (_settlingInProgress.has(candleOpenMs))
return;
_settlingInProgress.add(candleOpenMs);
try {
const intervals = await loadResolvedIntervals(cfg, true);
const aligning = intervals.filter((i) => (0, gameTimingService_1.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();
const runPoolSettlement = async () => {
const rule = parsePoolWinnerRule(cfg.pool_winner_rule);
let shared;
if (rule === 'daily_revenue') {
const neutralityRules = buildPoolNeutralityRules(cfg, primary);
shared = await resolveDailyRevenueSharedOutcome(cfg, shortPool, longPool, candleOpenMs, neutralityRules);
}
else {
const neutralityRules = buildPoolNeutralityRules(cfg, primary);
shared = (0, candleGenerationService_1.resolvePoolOutcome)(shortPool, longPool, neutralityRules, rule);
}
for (const interval of aligning) {
outcomesByIntervalMinutes.set(interval.intervalMinutes, shared);
}
const outcomeForInterval = (intervalMinutes) => 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');
}
}
let housePnlDeltaRaw = 0n;
if (pendingCount > 0) {
housePnlDeltaRaw += 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)]));
housePnlDeltaRaw += await multiService.processMultiBetsAtMaturity(candleOpenMs, outcomeForInterval, payoutMultiplierMap);
}
if (housePnlDeltaRaw !== 0n) {
await repo.addDailyRevenuePnl((0, dailyRevenueOutcomeService_1.utcRevenueDate)(), housePnlDeltaRaw);
}
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);
}
void soloEncouragementService.onMaturitySettled(candleOpenMs).catch((e) => console.error('[solo-encouragement] onMaturitySettled failed:', e));
};
if (outcomeMode === 'pool') {
// Serialize daily-revenue reads + settlement PnL updates across concurrent maturities.
await repo.withDailyRevenueLock(runPoolSettlement);
}
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, (0, candleGenerationService_1.resolveAutoNoBetOutcome)(recentOutcomes));
}
const outcomeForInterval = (intervalMinutes) => 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);
}
// Keep hook even on auto path (e.g. test-only / multi-only maturities) for consistency.
void soloEncouragementService.onMaturitySettled(candleOpenMs).catch((e) => console.error('[solo-encouragement] onMaturitySettled failed:', e));
}
}
finally {
_settlingInProgress.delete(candleOpenMs);
}
}
async function resolveDailyRevenueSharedOutcome(cfg, shortPool, longPool, candleOpenMs, neutralityRules) {
const revenueDate = (0, dailyRevenueOutcomeService_1.utcRevenueDate)();
const dailyNetRaw = await repo.getOrCreateDailyRevenueNetRaw(revenueDate);
const random = (0, dailyRevenueOutcomeService_1.pickRandomDirectionalOutcome)();
const randomWinner = random.winner ?? 'long';
const majority = shortPool === longPool ? null : shortPool > longPool ? 'short' : 'long';
let projectedMajorityRoundPnlRaw = 0n;
if (majority != null) {
const allIntervals = await loadResolvedIntervals(cfg, true);
const intervalMap = new Map(allIntervals.map((i) => [i.intervalMinutes, i]));
const levelRows = await repo.listMultiLevels();
const multiMult = new Map(levelRows.map((l) => [l.level, Number(l.payout_multiplier)]));
const singles = await repo.listPendingBetsForMaturity(candleOpenMs);
const multis = await repo.listMultiBetsForValidationAtOpenMs(candleOpenMs);
const projected = (0, dailyRevenueOutcomeService_1.projectMajorityWinSettlement)({
majority,
singles,
multis: multis.map((b) => ({
sequence_directions: b.sequence_directions,
multi_level: b.multi_level,
sequence_step: b.sequence_step,
stake_raw: b.stake_raw,
stake_display: b.stake_display,
stake_account_kind: b.stake_account_kind,
})),
singlePayoutMultiplier: (intervalMinutes) => intervalMap.get(intervalMinutes)?.payoutMultiplier ?? Number(cfg.payout_multiplier),
multiPayoutMultiplier: (level) => multiMult.get(level) ?? 1,
});
projectedMajorityRoundPnlRaw = projected.roundPnlRaw;
}
return (0, dailyRevenueOutcomeService_1.resolveDailyRevenueOutcome)({
shortPool,
longPool,
randomWinner,
projectedMajorityRoundPnlRaw,
dailyNetRaw,
targetRaw: (0, dailyRevenueOutcomeService_1.usdtDisplayToRaw)(Number(cfg.daily_revenue_target ?? 0)),
overflowStrategy: parseDailyRevenueOverflowStrategy(cfg.daily_revenue_overflow_strategy),
neutralityRules,
});
}
async function finalizeIntervalCandleAtMaturity(round, interval, outcome, shortPool, longPool) {
if (round.settled_at)
return;
const openMs = Number(round.candle_open_ms);
const prev = (await repo.getPreviousCandleOhlc(openMs, interval.intervalMinutes)) ??
(0, candleGenerationService_1.defaultSeedCandle)(interval.basePrice);
const candle = (0, candleGenerationService_1.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;
// Publish real time-to-next-betting so clients do not stick at 0s until refresh.
const timingNext = (0, gameTimingService_1.getActiveRoundTiming)(nowMs, interval.intervalMinutes, interval.predictionWindowSeconds);
const secondsToBettingEnd = timingNext.phase === 'betting'
? Math.max(0, Math.ceil((timingNext.openMs - nowMs) / 1000))
: 0;
const secondsToBettingStart = timingNext.phase === 'betting'
? 0
: Math.max(0, Math.ceil((timingNext.nextBettingStartMs - nowMs) / 1000));
const settledDto = {
id: round.id,
candleOpenMs: openMs,
candleCloseMs: closeMs,
intervalMinutes: interval.intervalMinutes,
status: 'settled',
outcome: outcome.type,
openPrice: candle.open,
highPrice: candle.high,
lowPrice: candle.low,
closePrice: candle.close,
settledAt: new Date().toISOString(),
serverNowMs: nowMs,
secondsToBettingEnd,
secondsToBettingStart,
secondsToClose: Math.max(0, Math.ceil((closeMs - nowMs) / 1000)),
};
// Fire-and-forget Redis publish — must never block or kill the engine loop.
const PUBLISH_TIMEOUT_MS = 5000;
const withTimeout = (p) => Promise.race([p, new Promise((r) => setTimeout(r, PUBLISH_TIMEOUT_MS))]);
await withTimeout((0, publishRoundState_1.publishRoundState)({
intervalMinutes: interval.intervalMinutes,
openMs,
round: settledDto,
pools: { short: shortPool, long: longPool },
eventType: 'round.settled',
})).catch((e) => console.error(`[engine] publishRoundState failed for ${interval.intervalMinutes}m openMs=${openMs}:`, e));
await withTimeout((0, publishRoundState_1.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,
})).catch((e) => console.error(`[engine] publishCandleAppend failed for ${interval.intervalMinutes}m:`, e));
}
async function payOutBetsAtMaturity(candleOpenMs, outcomeForInterval, cfg) {
const bets = await repo.listPendingBetsForMaturity(candleOpenMs);
const allIntervals = await loadResolvedIntervals(cfg, true);
const intervalMap = new Map(allIntervals.map((i) => [i.intervalMinutes, i]));
let housePnlRaw = 0n;
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),
};
const multiplier = interval.payoutMultiplier;
const stakeRaw = BigInt(bet.stake_raw);
const countInDaily = isRealMoneyStakeKind(bet.stake_account_kind);
if (outcome.type === 'neutral') {
await creditGameOutcome(bet, stakeRaw, 'game_refund');
await repo.updateBetOutcome(bet.id, 'refunded', stakeRaw);
if (countInDaily)
housePnlRaw += 0n;
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),
},
});
await transactionRepository.mergeGameStakeBetStatus(bet.id, 'refunded');
(0, userAdminStatsService_1.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);
if (countInDaily)
housePnlRaw += stakeRaw - 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),
},
});
await transactionRepository.mergeGameStakeBetStatus(bet.id, 'won');
queuePredictionReferralCommission(bet, 'won');
}
else {
await repo.updateBetOutcome(bet.id, 'lost', 0n);
await transactionRepository.mergeGameStakeBetStatus(bet.id, 'lost');
if (countInDaily)
housePnlRaw += stakeRaw;
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,
});
queuePredictionReferralCommission(bet, 'lost');
}
(0, userAdminStatsService_1.queueUserAdminStatsRefresh)(bet.user_id);
}
if (config_1.config.redis.enabled && bets.length > 0) {
const seen = new Set();
await Promise.all(bets.map(async (bet) => {
const key = `${bet.user_id}:${bet.interval_minutes}`;
if (seen.has(key))
return;
seen.add(key);
await (0, stateVersions_1.bumpUserBetVersionSafe)(bet.user_id, bet.interval_minutes);
}));
}
return housePnlRaw;
}
async function processAutoBets(round, interval, cfg) {
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);
const autoVersion = await (0, stateVersions_1.bumpUserAutoVersionSafe)(auto.user_id);
if (config_1.config.redis.enabled) {
await (0, pubsub_2.publishUserEvent)(auto.user_id, {
type: 'auto.updated',
payload: {
autoSettings: {
lastAutoBetAt: new Date().toISOString(),
autoBetPlaced: false,
autoBetError: null,
},
...(autoVersion != null ? { versions: { auto: autoVersion } } : {}),
},
});
}
}
catch (e) {
const msg = e instanceof Error ? e.message : String(e);
console.warn(`[candle-predict] auto bet skipped for ${auto.user_id}: ${msg}`);
}
}
}
async function processAutoBetForUser(userId, intervalMinutes) {
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 = (0, gameTimingService_1.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);
const autoVersion = await (0, stateVersions_1.bumpUserAutoVersionSafe)(userId);
if (config_1.config.redis.enabled) {
await (0, pubsub_2.publishUserEvent)(userId, {
type: 'auto.updated',
payload: {
autoSettings: {
lastAutoBetAt: new Date().toISOString(),
autoBetPlaced: false,
autoBetError: null,
},
...(autoVersion != null ? { versions: { auto: autoVersion } } : {}),
},
});
}
return { placed: true };
}
catch (e) {
const msg = e instanceof Error ? e.message : 'Auto prediction failed';
return { placed: false, error: msg };
}
}
function parseStakeAccountKind(value) {
if (value === 'bonus')
return 'bonus';
if (value === 'test')
return 'test';
return 'main';
}
/** Referral prediction commissions only on terminal win/loss — never on neutral refund. */
function queuePredictionReferralCommission(bet, betOutcome) {
void (0, referralService_1.processPredictionReferralCommissions)({
betId: bet.id,
referredUserId: bet.user_id,
stakeRaw: BigInt(bet.stake_raw),
stakeAccountKind: parseStakeAccountKind(bet.stake_account_kind),
walletTypeId: bet.wallet_type_id,
betOutcome,
}).catch((e) => console.error('[referral] prediction commission failed:', e));
}
async function resolveDebitAccount(userId, walletTypeId, stakeRaw, requestedKind = 'main') {
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, walletTypeCode, stakeDisplay, stakeAccountKind) {
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);
}
async function executePlaceBetInternal(userId, input) {
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 = (0, gameTimingService_1.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);
if (stakeAccountKind === 'test') {
await testWalletService.assertTestPredictionAllowed(userId);
}
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),
},
});
(0, userAdminStatsService_1.queueUserAdminStatsRefresh)(userId);
const mapped = mapBet(bet);
// Redis fan-out must not fail the HTTP bet after ledger/DB commit succeeded.
// A Redis replica READONLY error previously surfaced as a false "DB" failure.
if (config_1.config.redis.enabled) {
try {
const betVersion = await (0, stateVersions_1.bumpUserBetVersionSafe)(userId, interval.intervalMinutes);
await (0, pubsub_2.publishUserEvent)(userId, {
type: 'bet.accepted',
payload: {
bet: mapped,
...(betVersion != null ? { versions: { bet: betVersion } } : {}),
},
});
}
catch (e) {
console.error('[candle-predict] post-bet Redis publish failed (bet already committed):', e instanceof Error ? e.message : e);
}
}
return mapped;
}
async function placeBet(userId, direction, stakeDisplay, intervalMinutes, stakeAccountKind, opts) {
(0, stakeAmountValidation_1.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() || (0, uuid_1.v4)();
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_1.config.redis.betAsyncEnabled && (0, client_1.isRedisEnabled)();
if (useBetQueue) {
const existing = await (0, betQueue_1.getBetIdempotency)(idempotencyKey);
if (existing?.status === 'accepted') {
return { status: 'accepted', bet: existing.bet };
}
if (existing?.status === 'rejected') {
throw new Error(existing.error);
}
if (existing?.status === 'processing') {
return { status: 'queued', idempotencyKey };
}
const nowMs = Date.now();
const timing = (0, gameTimingService_1.getActiveRoundTiming)(nowMs, interval.intervalMinutes, interval.predictionWindowSeconds);
if (timing.phase !== 'betting') {
throw new Error('Prediction window is closed');
}
const { streamId } = await (0, betQueue_1.enqueueBet)({
userId,
direction,
stakeDisplay,
intervalMinutes: interval.intervalMinutes,
stakeAccountKind: parseStakeAccountKind(stakeAccountKind),
idempotencyKey,
source,
requestedAt: nowMs,
});
const claimed = await (0, betQueue_1.claimBetIdempotencyProcessing)(idempotencyKey, streamId);
if (!claimed) {
const replay = await (0, betQueue_1.getBetIdempotency)(idempotencyKey);
if (replay?.status === 'accepted') {
return { status: 'accepted', bet: replay.bet };
}
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_1.config.redis.enabled) {
try {
const timingAfter = (0, gameTimingService_1.getActiveRoundTiming)(Date.now(), interval.intervalMinutes, interval.predictionWindowSeconds);
if (timingAfter.phase === 'betting') {
await publishRoundSnapshot(interval.intervalMinutes, timingAfter.openMs);
}
}
catch (e) {
console.error('[candle-predict] post-bet round snapshot failed (bet already committed):', e instanceof Error ? e.message : e);
}
}
return { status: 'accepted', bet };
}
async function getRecentPredictions(userId, page = 1, pageSize = 10, intervalMinutes, filters) {
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)),
};
}
async function getRecentBets(userId) {
const result = await getRecentPredictions(userId, 1, 20);
return result.items;
}
async function saveAutoSettings(userId, body) {
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
: null;
const stakeDisplay = parseStakeDisplay(body, cfg.stake_amounts[0] ?? 1);
const mode = body.mode === 'interval' || body.mode === 'each_round'
? body.mode
: '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,
};
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();
}
}
const autoVersion = await (0, stateVersions_1.bumpUserAutoVersionSafe)(userId);
if (config_1.config.redis.enabled) {
await (0, pubsub_2.publishUserEvent)(userId, {
type: 'auto.updated',
payload: {
autoSettings: result,
...(autoVersion != null ? { versions: { auto: autoVersion } } : {}),
},
});
}
return result;
}
async function getAutoSettings(userId) {
const row = await repo.getAutoSettings(userId);
if (!row) {
return {
enabled: false,
direction: null,
stakeDisplay: 1,
mode: 'each_round',
intervalSeconds: 60,
periodMinutes: 1,
stakeAccountKind: 'main',
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,
};
}
async function listAdminMultiLevels() {
const rows = await repo.listMultiLevels();
return rows.map(multiService.mapMultiLevel);
}
async function updateAdminMultiLevels(body) {
if (!Array.isArray(body.levels)) {
throw new Error('levels array is required');
}
const results = [];
for (const item of body.levels) {
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));
}
await publishConfigUpdated();
return results;
}
async function placeMultiCandleBet(userId, input) {
(0, stakeAmountValidation_1.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 = (0, gameTimingService_1.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);
if (stakeAccountKind === 'test') {
await testWalletService.assertTestPredictionAllowed(userId);
}
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,
},
});
(0, userAdminStatsService_1.queueUserAdminStatsRefresh)(userId);
if (config_1.config.redis.enabled) {
const betVersion = await (0, stateVersions_1.bumpUserBetVersionSafe)(userId, interval.intervalMinutes);
await publishRoundSnapshot(interval.intervalMinutes, timing.openMs);
const mapped = multiService.mapMultiBet(bet);
await (0, pubsub_2.publishUserEvent)(userId, {
type: 'multi.updated',
payload: {
intervalMinutes: interval.intervalMinutes,
userMultiBet: mapped,
...(betVersion != null ? { versions: { bet: betVersion } } : {}),
},
});
}
return multiService.mapMultiBet(bet);
}
function startCandlePredictEngine() {
const DEFAULT_TICK_MS = 3000;
const run = async () => {
let tickMs = DEFAULT_TICK_MS;
try {
await tickGameEngine();
}
catch (e) {
console.error('Candle Predict engine error:', e);
}
try {
const settings = await settingsRepository.getSettings();
tickMs = settings.candle_predict_engine_tick_ms || DEFAULT_TICK_MS;
}
catch (e) {
console.error('Candle Predict engine: failed to read settings, retrying in', tickMs, 'ms —', e);
}
setTimeout(run, tickMs);
};
setTimeout(run, 5000);
(0, engineAuditRetentionService_1.startEngineAuditRetentionJob)();
}
//# sourceMappingURL=index.js.map