809 lines
18 KiB
TypeScript
809 lines
18 KiB
TypeScript
import { createHash } from 'crypto';
|
|
import { Response } from 'express';
|
|
|
|
import { AuthRequest } from '../middleware/auth';
|
|
import { hasAdminAccess } from '../utils/roleAccess';
|
|
|
|
import * as candlePredictService from '../services/candlePredictService';
|
|
import { TestWalletError } from '../services/testWalletService';
|
|
import { parseStakeAmountFromBody } from '../utils/stakeAmountValidation';
|
|
import { readIdempotencyKey, sendPlaceBetResult } from '../utils/placeBetResponse';
|
|
import {
|
|
buildVersionEtag,
|
|
getStateVersions,
|
|
} from '../realtime/redis/stateVersions';
|
|
|
|
function placeBetErrorBody(e: unknown, fallback: string): { error: string; code?: string; wait?: string } {
|
|
if (e instanceof TestWalletError) {
|
|
return {
|
|
error: e.message,
|
|
...(e.code ? { code: e.code } : {}),
|
|
...(e.waitLabel ? { wait: e.waitLabel } : {}),
|
|
};
|
|
}
|
|
return { error: e instanceof Error ? e.message : fallback };
|
|
}
|
|
const STATE_CACHE_TTL_MS = 1200;
|
|
const STATE_CACHE_MAX_ENTRIES = 500;
|
|
|
|
type CachedStateEntry = {
|
|
expiresAt: number;
|
|
etag: string;
|
|
body: unknown;
|
|
};
|
|
|
|
const stateResponseCache = new Map<string, CachedStateEntry>();
|
|
|
|
function compactPart(value: unknown): string {
|
|
if (value == null) return '';
|
|
if (Array.isArray(value)) return value.map(compactPart).join(',');
|
|
if (typeof value === 'object') return JSON.stringify(value);
|
|
return String(value);
|
|
}
|
|
|
|
function businessFingerprint(state: any): string {
|
|
const config = state?.config ?? {};
|
|
const interval = state?.interval ?? {};
|
|
const round = state?.round ?? {};
|
|
const userBet = state?.userBet ?? {};
|
|
const userMultiBet = state?.userMultiBet ?? {};
|
|
const autoSettings = state?.autoSettings ?? {};
|
|
const intervals = Array.isArray(state?.intervals) ? state.intervals : [];
|
|
const multiLevels = Array.isArray(state?.multiLevels) ? state.multiLevels : [];
|
|
|
|
const intervalFingerprint = intervals
|
|
.map((item: any) =>
|
|
[
|
|
item?.id,
|
|
item?.intervalMinutes,
|
|
item?.isActive,
|
|
item?.isDefault,
|
|
item?.predictionWindowSeconds,
|
|
item?.chartCandleLimit,
|
|
].map(compactPart).join(':')
|
|
)
|
|
.join('|');
|
|
|
|
const multiLevelFingerprint = multiLevels
|
|
.map((item: any) =>
|
|
[
|
|
item?.level,
|
|
item?.candleCount,
|
|
item?.enabled,
|
|
item?.payoutMultiplier,
|
|
item?.poolMultiplier,
|
|
item?.sortOrder,
|
|
].map(compactPart).join(':')
|
|
)
|
|
.join('|');
|
|
|
|
return [
|
|
config?.updatedAt,
|
|
config?.isActive,
|
|
config?.walletTypeCode,
|
|
config?.predictionTypes ? JSON.stringify(config.predictionTypes) : '',
|
|
config?.dailyRevenueNetToday,
|
|
interval?.id,
|
|
interval?.intervalMinutes,
|
|
interval?.predictionWindowSeconds,
|
|
interval?.chartCandleLimit,
|
|
state?.selectedIntervalMinutes,
|
|
intervalFingerprint,
|
|
round?.id,
|
|
round?.status,
|
|
round?.outcome,
|
|
round?.settledAt,
|
|
round?.openPrice,
|
|
round?.highPrice,
|
|
round?.lowPrice,
|
|
round?.closePrice,
|
|
round?.shortPool,
|
|
round?.longPool,
|
|
round?.shortPoolPercent,
|
|
round?.longPoolPercent,
|
|
userBet?.id,
|
|
userBet?.roundId,
|
|
userBet?.status,
|
|
userBet?.payoutDisplay,
|
|
userBet?.stakeDisplay,
|
|
userBet?.candleOpenMs,
|
|
userMultiBet?.id,
|
|
userMultiBet?.status,
|
|
userMultiBet?.sequenceStep,
|
|
userMultiBet?.currentCandleOpenMs,
|
|
userMultiBet?.payoutDisplay,
|
|
userMultiBet?.stakeDisplay,
|
|
multiLevelFingerprint,
|
|
autoSettings?.enabled,
|
|
autoSettings?.direction,
|
|
autoSettings?.stakeDisplay,
|
|
autoSettings?.mode,
|
|
autoSettings?.periodMinutes,
|
|
autoSettings?.intervalSeconds,
|
|
autoSettings?.stakeAccountKind,
|
|
autoSettings?.lastAutoBetAt,
|
|
autoSettings?.autoBetError,
|
|
]
|
|
.map(compactPart)
|
|
.join('||');
|
|
}
|
|
|
|
|
|
|
|
function parseIntervalMinutes(value: unknown): number | undefined {
|
|
|
|
if (value == null || value === '') return undefined;
|
|
|
|
const n = Number(value);
|
|
|
|
return Number.isFinite(n) ? n : undefined;
|
|
|
|
}
|
|
|
|
|
|
|
|
function rememberStateCache(cacheKey: string, etag: string, body: unknown, now: number): void {
|
|
stateResponseCache.set(cacheKey, {
|
|
etag,
|
|
body,
|
|
expiresAt: now + STATE_CACHE_TTL_MS,
|
|
});
|
|
if (stateResponseCache.size <= STATE_CACHE_MAX_ENTRIES) return;
|
|
for (const [key, entry] of stateResponseCache) {
|
|
if (entry.expiresAt <= now) stateResponseCache.delete(key);
|
|
}
|
|
if (stateResponseCache.size > STATE_CACHE_MAX_ENTRIES) {
|
|
const oldestKey = stateResponseCache.keys().next().value;
|
|
if (oldestKey) stateResponseCache.delete(oldestKey);
|
|
}
|
|
}
|
|
|
|
export async function getState(req: AuthRequest, res: Response): Promise<void> {
|
|
try {
|
|
const intervalMinutes = parseIntervalMinutes(req.query.intervalMinutes);
|
|
const includeInternal = req.user ? hasAdminAccess(req.user) : false;
|
|
const cacheKey = JSON.stringify({
|
|
userId: req.user?.userId ?? 'anon',
|
|
intervalMinutes: intervalMinutes ?? null,
|
|
includeInternal,
|
|
});
|
|
const ifNoneMatch = String(req.header('if-none-match') ?? '').trim();
|
|
const now = Date.now();
|
|
const cached = stateResponseCache.get(cacheKey);
|
|
|
|
res.setHeader('Cache-Control', 'private, max-age=0, must-revalidate');
|
|
res.setHeader('Vary', 'Authorization');
|
|
|
|
if (cached && cached.expiresAt > now) {
|
|
res.setHeader('ETag', cached.etag);
|
|
if (ifNoneMatch && ifNoneMatch === cached.etag) {
|
|
res.status(304).end();
|
|
return;
|
|
}
|
|
res.json(cached.body);
|
|
return;
|
|
}
|
|
|
|
// Cheap path: Redis business versions → 304 before getGameState.
|
|
// Requires an explicit interval so we do not resolve defaults from DB first.
|
|
// Any Redis failure falls through to full getGameState + fingerprint ETag.
|
|
if (intervalMinutes != null) {
|
|
try {
|
|
const versions = await getStateVersions({
|
|
userId: req.user?.userId,
|
|
intervalMinutes,
|
|
});
|
|
if (versions) {
|
|
const versionEtag = buildVersionEtag({
|
|
versions,
|
|
intervalMinutes,
|
|
includeInternal,
|
|
});
|
|
res.setHeader(
|
|
'X-Prediqo-State-Versions',
|
|
`${versions.config}.${versions.round}.${versions.bet}.${versions.auto}`
|
|
);
|
|
if (ifNoneMatch && ifNoneMatch === versionEtag) {
|
|
res.setHeader('ETag', versionEtag);
|
|
res.status(304).end();
|
|
return;
|
|
}
|
|
|
|
const state = await candlePredictService.getGameState(req.user?.userId, intervalMinutes, {
|
|
includeInternal,
|
|
});
|
|
rememberStateCache(cacheKey, versionEtag, state, now);
|
|
res.setHeader('ETag', versionEtag);
|
|
res.json(state);
|
|
return;
|
|
}
|
|
} catch (e) {
|
|
console.error('[getState] version short-circuit failed, falling back:', e);
|
|
}
|
|
}
|
|
|
|
const state = await candlePredictService.getGameState(req.user?.userId, intervalMinutes, {
|
|
includeInternal,
|
|
});
|
|
|
|
// Prefer version ETag when Redis answers; otherwise fingerprint (no Redis required).
|
|
const resolvedInterval =
|
|
intervalMinutes ??
|
|
(typeof (state as { selectedIntervalMinutes?: unknown }).selectedIntervalMinutes === 'number'
|
|
? (state as { selectedIntervalMinutes: number }).selectedIntervalMinutes
|
|
: undefined);
|
|
let etag: string | null = null;
|
|
if (resolvedInterval != null) {
|
|
const versions = await getStateVersions({
|
|
userId: req.user?.userId,
|
|
intervalMinutes: resolvedInterval,
|
|
}).catch(() => null);
|
|
if (versions) {
|
|
etag = buildVersionEtag({
|
|
versions,
|
|
intervalMinutes: resolvedInterval,
|
|
includeInternal,
|
|
});
|
|
res.setHeader(
|
|
'X-Prediqo-State-Versions',
|
|
`${versions.config}.${versions.round}.${versions.bet}.${versions.auto}`
|
|
);
|
|
}
|
|
}
|
|
if (!etag) {
|
|
etag = `"cp-state-${createHash('sha1').update(businessFingerprint(state)).digest('hex')}"`;
|
|
}
|
|
|
|
rememberStateCache(cacheKey, etag, state, now);
|
|
res.setHeader('ETag', etag);
|
|
if (ifNoneMatch && ifNoneMatch === etag) {
|
|
res.status(304).end();
|
|
return;
|
|
}
|
|
res.json(state);
|
|
} catch (e) {
|
|
const msg = e instanceof Error ? e.message : 'Failed to load game state';
|
|
res.status(500).json({ error: msg });
|
|
}
|
|
}
|
|
|
|
|
|
|
|
export async function getCandles(req: AuthRequest, res: Response): Promise<void> {
|
|
|
|
try {
|
|
|
|
const limit = parseInt((req.query.limit as string) || '0', 10);
|
|
|
|
const intervalMinutes = parseIntervalMinutes(req.query.intervalMinutes);
|
|
|
|
const beforeRaw = req.query.beforeOpenMs as string | undefined;
|
|
|
|
const beforeOpenMs =
|
|
|
|
beforeRaw != null && beforeRaw !== '' && Number.isFinite(Number(beforeRaw))
|
|
|
|
? Number(beforeRaw)
|
|
|
|
: undefined;
|
|
|
|
const page = await candlePredictService.getCandlesPage({
|
|
|
|
limit: limit > 0 ? limit : undefined,
|
|
|
|
intervalMinutes,
|
|
|
|
beforeOpenMs,
|
|
|
|
includeInternal: req.user ? hasAdminAccess(req.user) : false,
|
|
|
|
});
|
|
|
|
res.json(page);
|
|
|
|
} catch (e) {
|
|
|
|
const msg = e instanceof Error ? e.message : 'Failed to load candles';
|
|
|
|
res.status(500).json({ error: msg });
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
export async function placeBet(req: AuthRequest, res: Response): Promise<void> {
|
|
|
|
try {
|
|
|
|
if (!req.user?.userId) {
|
|
|
|
res.status(401).json({ error: 'Unauthorized' });
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
const { direction, stakeAmount, intervalMinutes, stakeAccountKind } = req.body as {
|
|
|
|
direction?: string;
|
|
|
|
stakeAmount?: unknown;
|
|
|
|
intervalMinutes?: number;
|
|
|
|
stakeAccountKind?: 'main' | 'bonus' | 'test';
|
|
|
|
};
|
|
|
|
if (stakeAmount === undefined || stakeAmount === null) {
|
|
|
|
res.status(400).json({ error: 'stakeAmount is required' });
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
const parsedStake = parseStakeAmountFromBody(stakeAmount);
|
|
|
|
const result = await candlePredictService.placeBet(
|
|
req.user.userId,
|
|
direction ?? '',
|
|
parsedStake,
|
|
intervalMinutes,
|
|
stakeAccountKind,
|
|
{
|
|
idempotencyKey: readIdempotencyKey(req, req.body as Record<string, unknown>),
|
|
source: 'http',
|
|
}
|
|
);
|
|
|
|
sendPlaceBetResult(res, result);
|
|
|
|
} catch (e) {
|
|
|
|
const body = placeBetErrorBody(e, 'Failed to place prediction');
|
|
console.warn('[candle-predict] placeBet rejected:', body.error, {
|
|
userId: req.user?.userId,
|
|
});
|
|
|
|
res.status(400).json(body);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
export async function getBetOutcome(req: AuthRequest, res: Response): Promise<void> {
|
|
try {
|
|
if (!req.user?.userId) {
|
|
res.status(401).json({ error: 'Unauthorized' });
|
|
return;
|
|
}
|
|
|
|
const idempotencyKey = String(req.params.idempotencyKey ?? '').trim();
|
|
if (!idempotencyKey) {
|
|
res.status(400).json({ error: 'idempotencyKey is required' });
|
|
return;
|
|
}
|
|
|
|
const record = await candlePredictService.getBetIdempotency(idempotencyKey);
|
|
if (!record) {
|
|
res.status(404).json({ error: 'Bet outcome not found' });
|
|
return;
|
|
}
|
|
|
|
if (record.status === 'accepted') {
|
|
const betUserId = String(record.bet.user_id ?? record.bet.userId ?? '').trim();
|
|
if (betUserId && betUserId !== req.user.userId) {
|
|
res.status(403).json({ error: 'Forbidden' });
|
|
return;
|
|
}
|
|
res.json({ status: 'accepted', bet: record.bet });
|
|
return;
|
|
}
|
|
|
|
if (record.status === 'rejected') {
|
|
res.json({ status: 'rejected', error: record.error });
|
|
return;
|
|
}
|
|
|
|
res.json({ status: 'processing' });
|
|
} catch (e) {
|
|
const msg = e instanceof Error ? e.message : 'Failed to load bet outcome';
|
|
res.status(500).json({ error: msg });
|
|
}
|
|
}
|
|
|
|
export async function getMyBets(req: AuthRequest, res: Response): Promise<void> {
|
|
|
|
try {
|
|
|
|
if (!req.user?.userId) {
|
|
|
|
res.status(401).json({ error: 'Unauthorized' });
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
const page = Math.max(1, parseInt((req.query.page as string) || '1', 10));
|
|
|
|
const pageSize = Math.min(50, Math.max(1, parseInt((req.query.pageSize as string) || '10', 10)));
|
|
|
|
const intervalMinutes = parseIntervalMinutes(req.query.intervalMinutes);
|
|
|
|
const stakeAccountKind =
|
|
typeof req.query.stakeAccountKind === 'string' ? req.query.stakeAccountKind : undefined;
|
|
|
|
const status = typeof req.query.status === 'string' ? req.query.status : undefined;
|
|
|
|
const predictions = await candlePredictService.getRecentPredictions(
|
|
|
|
req.user.userId,
|
|
|
|
page,
|
|
|
|
pageSize,
|
|
|
|
intervalMinutes,
|
|
|
|
{ stakeAccountKind, status }
|
|
|
|
);
|
|
|
|
res.json(predictions);
|
|
|
|
} catch (e) {
|
|
|
|
const msg = e instanceof Error ? e.message : 'Failed to load predictions';
|
|
|
|
res.status(500).json({ error: msg });
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
export async function getAutoSettings(req: AuthRequest, res: Response): Promise<void> {
|
|
|
|
try {
|
|
|
|
if (!req.user?.userId) {
|
|
|
|
res.status(401).json({ error: 'Unauthorized' });
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
const settings = await candlePredictService.getAutoSettings(req.user.userId);
|
|
|
|
res.json(settings);
|
|
|
|
} catch (e) {
|
|
|
|
const msg = e instanceof Error ? e.message : 'Failed to load auto settings';
|
|
|
|
res.status(500).json({ error: msg });
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
export async function updateAutoSettings(req: AuthRequest, res: Response): Promise<void> {
|
|
|
|
try {
|
|
|
|
if (!req.user?.userId) {
|
|
|
|
res.status(401).json({ error: 'Unauthorized' });
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
const settings = await candlePredictService.saveAutoSettings(
|
|
|
|
req.user.userId,
|
|
|
|
req.body as Record<string, unknown>
|
|
|
|
);
|
|
|
|
res.json(settings);
|
|
|
|
} catch (e) {
|
|
|
|
const msg = e instanceof Error ? e.message : 'Failed to update auto settings';
|
|
|
|
res.status(400).json({ error: msg });
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
export async function getAdminConfig(req: AuthRequest, res: Response): Promise<void> {
|
|
|
|
try {
|
|
|
|
const config = await candlePredictService.getPublicConfig();
|
|
|
|
res.json(config);
|
|
|
|
} catch (e) {
|
|
|
|
const msg = e instanceof Error ? e.message : 'Failed to load config';
|
|
|
|
res.status(500).json({ error: msg });
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
export async function updateAdminConfig(req: AuthRequest, res: Response): Promise<void> {
|
|
|
|
try {
|
|
|
|
const config = await candlePredictService.updateAdminConfig(req.body as Record<string, unknown>);
|
|
|
|
res.json(config);
|
|
|
|
} catch (e) {
|
|
|
|
const msg = e instanceof Error ? e.message : 'Failed to update config';
|
|
|
|
res.status(400).json({ error: msg });
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
export async function listAdminIntervals(req: AuthRequest, res: Response): Promise<void> {
|
|
|
|
try {
|
|
|
|
const intervals = await candlePredictService.listAdminIntervals();
|
|
|
|
res.json(intervals);
|
|
|
|
} catch (e) {
|
|
|
|
const msg = e instanceof Error ? e.message : 'Failed to load intervals';
|
|
|
|
res.status(500).json({ error: msg });
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
export async function createAdminInterval(req: AuthRequest, res: Response): Promise<void> {
|
|
|
|
try {
|
|
|
|
const interval = await candlePredictService.createAdminInterval(
|
|
|
|
req.body as Record<string, unknown>
|
|
|
|
);
|
|
|
|
res.status(201).json(interval);
|
|
|
|
} catch (e) {
|
|
|
|
const msg = e instanceof Error ? e.message : 'Failed to create interval';
|
|
|
|
res.status(400).json({ error: msg });
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
export async function updateAdminInterval(req: AuthRequest, res: Response): Promise<void> {
|
|
|
|
try {
|
|
|
|
const id = Number(req.params.id);
|
|
|
|
if (!Number.isFinite(id)) {
|
|
|
|
res.status(400).json({ error: 'Invalid interval id' });
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
const interval = await candlePredictService.updateAdminInterval(
|
|
|
|
id,
|
|
|
|
req.body as Record<string, unknown>
|
|
|
|
);
|
|
|
|
res.json(interval);
|
|
|
|
} catch (e) {
|
|
|
|
const msg = e instanceof Error ? e.message : 'Failed to update interval';
|
|
|
|
res.status(400).json({ error: msg });
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
export async function deleteAdminInterval(req: AuthRequest, res: Response): Promise<void> {
|
|
|
|
try {
|
|
|
|
const id = Number(req.params.id);
|
|
|
|
if (!Number.isFinite(id)) {
|
|
|
|
res.status(400).json({ error: 'Invalid interval id' });
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
const result = await candlePredictService.deleteAdminInterval(id);
|
|
|
|
res.json(result);
|
|
|
|
} catch (e) {
|
|
|
|
const msg = e instanceof Error ? e.message : 'Failed to delete interval';
|
|
|
|
res.status(400).json({ error: msg });
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
export async function placeMultiBet(req: AuthRequest, res: Response): Promise<void> {
|
|
|
|
try {
|
|
|
|
if (!req.user?.userId) {
|
|
|
|
res.status(401).json({ error: 'Unauthorized' });
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
const { level, sequence, stakeAmount, intervalMinutes, stakeAccountKind } = req.body as {
|
|
|
|
level?: number;
|
|
|
|
sequence?: string[];
|
|
|
|
stakeAmount?: unknown;
|
|
|
|
intervalMinutes?: number;
|
|
|
|
stakeAccountKind?: 'main' | 'bonus' | 'test';
|
|
|
|
};
|
|
|
|
if (stakeAmount === undefined || stakeAmount === null) {
|
|
|
|
res.status(400).json({ error: 'stakeAmount is required' });
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
if (level == null || !Number.isFinite(Number(level))) {
|
|
|
|
res.status(400).json({ error: 'level is required' });
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
if (!Array.isArray(sequence) || sequence.length === 0) {
|
|
|
|
res.status(400).json({ error: 'sequence is required' });
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
const parsedStake = parseStakeAmountFromBody(stakeAmount);
|
|
|
|
const directions = sequence.filter(
|
|
|
|
(d): d is 'short' | 'long' => d === 'short' || d === 'long'
|
|
|
|
);
|
|
|
|
const bet = await candlePredictService.placeMultiCandleBet(req.user.userId, {
|
|
|
|
level: Number(level),
|
|
|
|
sequence: directions,
|
|
|
|
stakeDisplay: parsedStake,
|
|
|
|
intervalMinutes,
|
|
|
|
stakeAccountKind,
|
|
|
|
});
|
|
|
|
res.status(201).json(bet);
|
|
|
|
} catch (e) {
|
|
|
|
res.status(400).json(placeBetErrorBody(e, 'Failed to place multi-candle prediction'));
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
export async function listAdminMultiLevels(req: AuthRequest, res: Response): Promise<void> {
|
|
|
|
try {
|
|
|
|
const levels = await candlePredictService.listAdminMultiLevels();
|
|
|
|
res.json(levels);
|
|
|
|
} catch (e) {
|
|
|
|
const msg = e instanceof Error ? e.message : 'Failed to load multi levels';
|
|
|
|
res.status(500).json({ error: msg });
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
export async function updateAdminMultiLevels(req: AuthRequest, res: Response): Promise<void> {
|
|
|
|
try {
|
|
|
|
const levels = await candlePredictService.updateAdminMultiLevels(
|
|
|
|
req.body as Record<string, unknown>
|
|
|
|
);
|
|
|
|
res.json(levels);
|
|
|
|
} catch (e) {
|
|
|
|
const msg = e instanceof Error ? e.message : 'Failed to update multi levels';
|
|
|
|
res.status(400).json({ error: msg });
|
|
|
|
}
|
|
|
|
}
|
|
|