2594 lines
88 KiB
TypeScript
2594 lines
88 KiB
TypeScript
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 { startEngineAuditRetentionJob } from '../../services/engineAuditRetentionService';
|
|
import { startCandleRetentionJob } from '../../services/candleRetentionService';
|
|
import { processPredictionReferralCommissions } from '../../services/referralService';
|
|
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 * as testWalletService from '../../services/testWalletService';
|
|
import * as soloEncouragementService from '../../services/soloEncouragementService';
|
|
import {
|
|
pickRandomDirectionalOutcome,
|
|
projectMajorityWinSettlement,
|
|
resolveDailyRevenueOutcome,
|
|
usdtDisplayToRaw,
|
|
usdtRawToDisplay,
|
|
utcRevenueDate,
|
|
type DailyRevenueOverflowStrategy,
|
|
} from '../../services/dailyRevenueOutcomeService';
|
|
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 {
|
|
bumpConfigVersionSafe,
|
|
bumpUserAutoVersionSafe,
|
|
bumpUserBetVersionSafe,
|
|
} from '../../realtime/redis/stateVersions';
|
|
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<void> {
|
|
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<string, unknown>, 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 {
|
|
if (value === 'majority') return 'majority';
|
|
if (value === 'daily_revenue') return 'daily_revenue';
|
|
return 'minority';
|
|
}
|
|
|
|
function parseDailyRevenueOverflowStrategy(
|
|
value: string | null | undefined
|
|
): DailyRevenueOverflowStrategy {
|
|
return value === 'minority' ? 'minority' : 'neutral';
|
|
}
|
|
|
|
function isRealMoneyStakeKind(kind: string | null | undefined): boolean {
|
|
return kind === 'main' || kind === 'bonus' || kind == null;
|
|
}
|
|
|
|
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 resolveNeutralityEnabled(
|
|
globalEnabled: boolean | null | undefined,
|
|
intervalOverride: boolean | null | undefined
|
|
): boolean {
|
|
// 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: 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: resolveNeutralityEnabled(
|
|
global.tie_tolerance_min_enabled,
|
|
interval?.tieToleranceMinEnabled
|
|
),
|
|
maxToleranceEnabled: resolveNeutralityEnabled(
|
|
global.tie_tolerance_max_enabled,
|
|
interval?.tieToleranceMaxEnabled
|
|
),
|
|
};
|
|
}
|
|
|
|
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),
|
|
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(),
|
|
};
|
|
}
|
|
|
|
type PlayerConfigDto = Omit<
|
|
ReturnType<typeof mapConfig>,
|
|
| 'poolWinnerRule'
|
|
| 'poolMultiplier'
|
|
| 'tieTolerancePercent'
|
|
| 'tieToleranceMaxPercent'
|
|
| 'tieToleranceMinEnabled'
|
|
| 'tieToleranceMaxEnabled'
|
|
| 'dailyRevenueTarget'
|
|
| 'dailyRevenueOverflowStrategy'
|
|
>;
|
|
|
|
function mapConfigForPlayer(row: repo.CandlePredictConfigRow): PlayerConfigDto {
|
|
const {
|
|
poolWinnerRule: _poolWinnerRule,
|
|
poolMultiplier: _poolMultiplier,
|
|
tieTolerancePercent: _min,
|
|
tieToleranceMaxPercent: _max,
|
|
tieToleranceMinEnabled: _minEn,
|
|
tieToleranceMaxEnabled: _maxEn,
|
|
dailyRevenueTarget: _drt,
|
|
dailyRevenueOverflowStrategy: _dros,
|
|
...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: 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: 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<typeof mapIntervalDto>,
|
|
| '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<ResolvedInterval[]> {
|
|
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?: repo.CandlePredictConfigRow): Promise<void> {
|
|
if (!config.redis.enabled) return;
|
|
const configVersion = await bumpConfigVersionSafe();
|
|
const sourceCfg = cfg ?? (await repo.getConfig());
|
|
const activeIntervals = await loadResolvedIntervals(sourceCfg, true);
|
|
await Promise.all(
|
|
activeIntervals
|
|
.filter((i) => i.isActive)
|
|
.map((i) =>
|
|
publishRoundEvent(i.intervalMinutes, {
|
|
type: 'config.updated',
|
|
intervalMinutes: i.intervalMinutes,
|
|
payload: {
|
|
...(configVersion != null ? { versions: { config: configVersion } } : {}),
|
|
},
|
|
})
|
|
)
|
|
);
|
|
}
|
|
|
|
async function resolveSelectedInterval(
|
|
cfg: repo.CandlePredictConfigRow,
|
|
intervalMinutes?: number
|
|
): Promise<ResolvedInterval> {
|
|
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<typeof getActiveRoundTiming>,
|
|
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<typeof mapRound>) {
|
|
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();
|
|
const mapped = mapConfig(cfg);
|
|
const netRaw = await repo.getDailyRevenueNetRaw(utcRevenueDate());
|
|
return {
|
|
...mapped,
|
|
dailyRevenueNetToday: usdtRawToDisplay(netRaw),
|
|
};
|
|
}
|
|
|
|
export async function updateAdminConfig(body: Record<string, unknown>) {
|
|
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' &&
|
|
body.poolWinnerRule !== 'daily_revenue'
|
|
) {
|
|
throw new Error('poolWinnerRule must be minority, majority, or daily_revenue');
|
|
}
|
|
poolWinnerRule = body.poolWinnerRule;
|
|
}
|
|
|
|
let dailyRevenueTarget: number | undefined;
|
|
if (typeof body.dailyRevenueTarget === 'number') {
|
|
if (body.dailyRevenueTarget < 0) {
|
|
throw new Error('dailyRevenueTarget must be >= 0');
|
|
}
|
|
dailyRevenueTarget = body.dailyRevenueTarget;
|
|
}
|
|
|
|
let dailyRevenueOverflowStrategy: repo.DailyRevenueOverflowStrategy | undefined;
|
|
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 as Record<string, unknown>)
|
|
: 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 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,
|
|
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.redis.enabled) {
|
|
await publishConfigUpdated(updated);
|
|
}
|
|
|
|
const mapped = mapConfig(updated);
|
|
const netRaw = await repo.getDailyRevenueNetRaw(utcRevenueDate());
|
|
return {
|
|
...mapped,
|
|
dailyRevenueNetToday: usdtRawToDisplay(netRaw),
|
|
};
|
|
}
|
|
|
|
export 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),
|
|
};
|
|
});
|
|
}
|
|
|
|
export async function createAdminInterval(body: Record<string, unknown>) {
|
|
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));
|
|
}
|
|
|
|
export async function updateAdminInterval(id: number, body: Record<string, unknown>) {
|
|
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));
|
|
}
|
|
|
|
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);
|
|
await publishConfigUpdated();
|
|
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),
|
|
dailyRevenueNetToday: usdtRawToDisplay(
|
|
await repo.getDailyRevenueNetRaw(utcRevenueDate())
|
|
),
|
|
}
|
|
: 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<repo.CandlePredictRoundRow> {
|
|
return repo.createRound({
|
|
candleOpenMs: openMs,
|
|
intervalMinutes: interval.intervalMinutes,
|
|
status,
|
|
});
|
|
}
|
|
|
|
export async function tickGameEngine(): Promise<void> {
|
|
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<number>();
|
|
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: 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<ReturnType<typeof settingsRepository.getSettings>>
|
|
): Promise<void> {
|
|
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<void> {
|
|
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<void> {
|
|
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 },
|
|
});
|
|
}
|
|
|
|
const _settlingInProgress = new Set<number>();
|
|
|
|
async function settleMaturityAtOpenMs(
|
|
candleOpenMs: number,
|
|
cfg: repo.CandlePredictConfigRow
|
|
): Promise<void> {
|
|
if (_settlingInProgress.has(candleOpenMs)) return;
|
|
_settlingInProgress.add(candleOpenMs);
|
|
try {
|
|
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<number, RoundOutcome>();
|
|
|
|
const runPoolSettlement = async () => {
|
|
const rule = parsePoolWinnerRule(cfg.pool_winner_rule);
|
|
let shared: RoundOutcome;
|
|
|
|
if (rule === 'daily_revenue') {
|
|
const neutralityRules = buildPoolNeutralityRules(cfg, primary);
|
|
shared = await resolveDailyRevenueSharedOutcome(
|
|
cfg,
|
|
shortPool,
|
|
longPool,
|
|
candleOpenMs,
|
|
neutralityRules
|
|
);
|
|
} else {
|
|
const neutralityRules = buildPoolNeutralityRules(cfg, primary);
|
|
shared = resolvePoolOutcome(shortPool, longPool, neutralityRules, rule);
|
|
}
|
|
|
|
for (const interval of aligning) {
|
|
outcomesByIntervalMinutes.set(interval.intervalMinutes, shared);
|
|
}
|
|
|
|
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');
|
|
}
|
|
}
|
|
|
|
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(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,
|
|
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
|
|
);
|
|
}
|
|
|
|
// 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: repo.CandlePredictConfigRow,
|
|
shortPool: number,
|
|
longPool: number,
|
|
candleOpenMs: number,
|
|
neutralityRules: PoolNeutralityRules
|
|
): Promise<RoundOutcome> {
|
|
const revenueDate = utcRevenueDate();
|
|
const dailyNetRaw = await repo.getOrCreateDailyRevenueNetRaw(revenueDate);
|
|
const random = pickRandomDirectionalOutcome();
|
|
const randomWinner = random.winner ?? 'long';
|
|
|
|
const majority: 'short' | 'long' | null =
|
|
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 = 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 resolveDailyRevenueOutcome({
|
|
shortPool,
|
|
longPool,
|
|
randomWinner,
|
|
projectedMajorityRoundPnlRaw,
|
|
dailyNetRaw,
|
|
targetRaw: usdtDisplayToRaw(Number(cfg.daily_revenue_target ?? 0)),
|
|
overflowStrategy: parseDailyRevenueOverflowStrategy(cfg.daily_revenue_overflow_strategy),
|
|
neutralityRules,
|
|
});
|
|
}
|
|
|
|
async function finalizeIntervalCandleAtMaturity(
|
|
round: repo.CandlePredictRoundRow,
|
|
interval: ResolvedInterval,
|
|
outcome: RoundOutcome,
|
|
shortPool: number,
|
|
longPool: number
|
|
): Promise<void> {
|
|
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;
|
|
// Publish real time-to-next-betting so clients do not stick at 0s until refresh.
|
|
const timingNext = 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' as const,
|
|
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 = <T>(p: Promise<T>): Promise<T | void> =>
|
|
Promise.race([p, new Promise<void>((r) => setTimeout(r, PUBLISH_TIMEOUT_MS))]);
|
|
|
|
await withTimeout(
|
|
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(
|
|
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: number,
|
|
outcomeForInterval: (intervalMinutes: number) => RoundOutcome,
|
|
cfg: repo.CandlePredictConfigRow
|
|
): Promise<bigint> {
|
|
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),
|
|
} as ResolvedInterval);
|
|
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');
|
|
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');
|
|
}
|
|
queueUserAdminStatsRefresh(bet.user_id);
|
|
}
|
|
|
|
if (config.redis.enabled && bets.length > 0) {
|
|
const seen = new Set<string>();
|
|
await Promise.all(
|
|
bets.map(async (bet) => {
|
|
const key = `${bet.user_id}:${bet.interval_minutes}`;
|
|
if (seen.has(key)) return;
|
|
seen.add(key);
|
|
await bumpUserBetVersionSafe(bet.user_id, bet.interval_minutes);
|
|
})
|
|
);
|
|
}
|
|
|
|
return housePnlRaw;
|
|
}
|
|
|
|
async function processAutoBets(
|
|
round: repo.CandlePredictRoundRow,
|
|
interval: ResolvedInterval,
|
|
cfg: repo.CandlePredictConfigRow
|
|
): Promise<void> {
|
|
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 bumpUserAutoVersionSafe(auto.user_id);
|
|
if (config.redis.enabled) {
|
|
await 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}`);
|
|
}
|
|
}
|
|
}
|
|
|
|
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);
|
|
const autoVersion = await bumpUserAutoVersionSafe(userId);
|
|
if (config.redis.enabled) {
|
|
await 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: unknown): AccountKind {
|
|
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: {
|
|
id: string;
|
|
user_id: string;
|
|
stake_raw: string | number | bigint;
|
|
stake_account_kind?: string | null;
|
|
wallet_type_id: number;
|
|
},
|
|
betOutcome: 'won' | 'lost'
|
|
): void {
|
|
void 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: 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<void> {
|
|
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);
|
|
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),
|
|
},
|
|
});
|
|
|
|
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.redis.enabled) {
|
|
try {
|
|
const betVersion = await bumpUserBetVersionSafe(userId, interval.intervalMinutes);
|
|
await publishUserEvent(userId, {
|
|
type: 'bet.accepted',
|
|
payload: {
|
|
bet: mapped as unknown as Record<string, unknown>,
|
|
...(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;
|
|
}
|
|
|
|
export type PlaceBetOptions = {
|
|
idempotencyKey?: string;
|
|
source?: 'http' | 'ws';
|
|
};
|
|
|
|
export type PlaceBetResult =
|
|
| { status: 'accepted'; bet: Awaited<ReturnType<typeof executePlaceBetInternal>> }
|
|
| { status: 'queued'; idempotencyKey: string };
|
|
|
|
export async function placeBet(
|
|
userId: string,
|
|
direction: string,
|
|
stakeDisplay: number,
|
|
intervalMinutes?: number,
|
|
stakeAccountKind?: AccountKind,
|
|
opts?: PlaceBetOptions
|
|
): Promise<PlaceBetResult> {
|
|
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<ReturnType<typeof executePlaceBetInternal>> };
|
|
}
|
|
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<ReturnType<typeof executePlaceBetInternal>> };
|
|
}
|
|
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) {
|
|
try {
|
|
const timingAfter = 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 };
|
|
}
|
|
|
|
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<string, unknown>) {
|
|
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();
|
|
}
|
|
}
|
|
|
|
const autoVersion = await bumpUserAutoVersionSafe(userId);
|
|
if (config.redis.enabled) {
|
|
await publishUserEvent(userId, {
|
|
type: 'auto.updated',
|
|
payload: {
|
|
autoSettings: result as unknown as Record<string, unknown>,
|
|
...(autoVersion != null ? { versions: { auto: autoVersion } } : {}),
|
|
},
|
|
});
|
|
}
|
|
|
|
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<string, unknown>) {
|
|
if (!Array.isArray(body.levels)) {
|
|
throw new Error('levels array is required');
|
|
}
|
|
const results = [];
|
|
for (const item of body.levels as Record<string, unknown>[]) {
|
|
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;
|
|
}
|
|
|
|
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);
|
|
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,
|
|
},
|
|
});
|
|
|
|
queueUserAdminStatsRefresh(userId);
|
|
|
|
if (config.redis.enabled) {
|
|
const betVersion = await bumpUserBetVersionSafe(userId, interval.intervalMinutes);
|
|
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<string, unknown>,
|
|
...(betVersion != null ? { versions: { bet: betVersion } } : {}),
|
|
},
|
|
});
|
|
}
|
|
|
|
return multiService.mapMultiBet(bet);
|
|
}
|
|
|
|
export function startCandlePredictEngine(): void {
|
|
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);
|
|
startEngineAuditRetentionJob();
|
|
startCandleRetentionJob();
|
|
}
|