To test the production for prediction issue

This commit is contained in:
Your Name 2026-07-25 22:48:54 +02:00
parent 7b792a6036
commit 8e1b85c05a
213 changed files with 17161 additions and 2438 deletions

View File

@ -15,7 +15,9 @@
# Le fichier .env.docker reste local (gitignore) — le VPS garde son propre .env. # Le fichier .env.docker reste local (gitignore) — le VPS garde son propre .env.
# ============================================================================= # =============================================================================
NODE_ENV=production # Local Docker = Shasta testnet → must NOT be production (networkGuard blocks testnet URLs).
# VPS .env keeps NODE_ENV=production with mainnet TRON/Polygon.
NODE_ENV=development
POSTGRES_USER=postgres POSTGRES_USER=postgres
POSTGRES_PASSWORD=local_dev_postgres_password POSTGRES_PASSWORD=local_dev_postgres_password
@ -40,12 +42,20 @@ JWT_REFRESH_EXPIRY=7d
ENCRYPTION_KEY=0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef ENCRYPTION_KEY=0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef
PLATFORM_MNEMONIC=abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about PLATFORM_MNEMONIC=abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about
# TRON Shasta testnet (local Docker = testnet, pas mainnet)
TRON_NODE_URL=https://api.shasta.trongrid.io TRON_NODE_URL=https://api.shasta.trongrid.io
TRON_CONFIRMATIONS=3 TRON_CONFIRMATIONS=3
USDT_TRC20_CONTRACT= # OBLIGATOIRE sur Shasta : sans cette variable, le backend utilise le contrat USDT
# mainnet par défaut (TR7NHq… en base) alors que TRON_NODE_URL pointe Shasta — les
# dépôts test (Telegram !shasta_usdt, faucets) ne seront jamais détectés.
# Même adresse que .env.testnet — ne pas laisser vide.
USDT_TRC20_CONTRACT=TG3XXyExBkPp9nzdajDZsozEu4BkaSJozs
# Polygon Amoy testnet
POLYGON_RPC_URL=https://rpc-amoy.polygon.technology POLYGON_RPC_URL=https://rpc-amoy.polygon.technology
POLYGON_CONFIRMATIONS=8 POLYGON_CONFIRMATIONS=8
USDC_POLYGON_CONTRACT= # Même logique que USDT : contrat Amoy requis pour créditer les USDC de test (Circle faucet).
USDC_POLYGON_CONTRACT=0x41E94Eb019C0762f9Bfcf9Fb1E58725BfB0e7582
ALLOW_WITHDRAWALS=false ALLOW_WITHDRAWALS=false
RATE_LIMIT_MAX=2000 RATE_LIMIT_MAX=2000

View File

@ -1,13 +1,16 @@
# Docker Compose - copy to .env in this directory (repo root) # Docker Compose - copy to .env in this directory (repo root)
# Then: docker-compose up -d # Then: docker-compose up -d
# PostgreSQL (used by postgres service and DATABASE_URL for backend) # PostgreSQL — doit être la MÊME base que Docker local si vous vous êtes inscrit via :9080
DATABASE_URL=postgresql://postgres@localhost:5432/crypto_wallet # (sinon le moniteur de dépôts affiche « 0 wallets » et ne crédite rien).
DATABASE_URL=postgresql://postgres@localhost:5432/games_platform_db
DATABASE_PASSWORD=Japhni81! DATABASE_PASSWORD=Japhni81!
POSTGRES_USER=postgres POSTGRES_USER=postgres
POSTGRES_DB=crypto_wallet POSTGRES_DB=games_platform_db
POSTGRES_PORT=5432 POSTGRES_PORT=5432
# Backend seul (npm run dev:testnet) : pas de Redis Docker → désactiver pour éviter le spam de logs
REDIS_ENABLED=false
# Backend # Backend
BACKEND_PORT=4000 BACKEND_PORT=4000
JWT_SECRET=36763979244226452948404D635166546A576D5A7134743777217A25432A462D JWT_SECRET=36763979244226452948404D635166546A576D5A7134743777217A25432A462D
@ -20,8 +23,8 @@ LOGIN_RATE_LIMIT_MAX=20
ENCRYPTION_KEY=0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef ENCRYPTION_KEY=0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef
# Required: BIP39 mnemonic (24 words) for HD wallet - keep secret # Required: BIP39 mnemonic (24 words) for HD wallet - keep secret
PLATFORM_MNEMONIC=world access act denial panther slab target snap frequent loyal pigeon soldier angry vanish reduce tomato praise educate convince copper mistake truck ordinary pelican # Doit correspondre à .env.docker si vous alternez Docker et dev:testnet (même adresses de dépôt).
PLATFORM_MNEMONIC=abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about
# TRON Shasta testnet (test TRX and USDT) # TRON Shasta testnet (test TRX and USDT)
TRON_NODE_URL=https://api.shasta.trongrid.io TRON_NODE_URL=https://api.shasta.trongrid.io
# Use fewer confirmations on testnet so deposits credit quickly (mainnet .env uses 20) # Use fewer confirmations on testnet so deposits credit quickly (mainnet .env uses 20)

View File

@ -2,5 +2,8 @@
"yaml.schemaStore.enable": false, "yaml.schemaStore.enable": false,
"yaml.schemas": { "yaml.schemas": {
".vscode/schemas/pubspec-minimal.json": "**/pubspec.yaml" ".vscode/schemas/pubspec-minimal.json": "**/pubspec.yaml"
} },
"dart.flutterRunAdditionalArgs": [
"--dart-define-from-file=dart_defines.dev.json"
]
} }

View File

@ -24,6 +24,7 @@ TRON_NODE_URL=https://api.trongrid.io
TRON_API_KEY= TRON_API_KEY=
POLYGON_RPC_URL=https://polygon-rpc.com POLYGON_RPC_URL=https://polygon-rpc.com
USDC_POLYGON_CONTRACT=0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359 USDC_POLYGON_CONTRACT=0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359
# Leave empty in production (uses mainnet USDT from DB). Shasta contract is rejected at boot when NODE_ENV=production.
USDT_TRC20_CONTRACT= USDT_TRC20_CONTRACT=
# Safety (recommended for testing) # Safety (recommended for testing)

View File

@ -1 +1 @@
{"version":3,"file":"appBootstrap.d.ts","sourceRoot":"","sources":["../../src/bootstrap/appBootstrap.ts"],"names":[],"mappings":"AAAA;;GAEG;AAwHH,MAAM,MAAM,gBAAgB,GAAG;IAC7B,+EAA+E;IAC/E,YAAY,CAAC,EAAE,OAAO,CAAC;IACvB,2FAA2F;IAC3F,qBAAqB,CAAC,EAAE,OAAO,CAAC;IAChC,kCAAkC;IAClC,gBAAgB,CAAC,EAAE,OAAO,CAAC;CAC5B,CAAC;AAEF,yDAAyD;AACzD,wBAAsB,aAAa,CAAC,IAAI,GAAE,gBAAqB,GAAG,OAAO,CAAC,IAAI,CAAC,CAgD9E"} {"version":3,"file":"appBootstrap.d.ts","sourceRoot":"","sources":["../../src/bootstrap/appBootstrap.ts"],"names":[],"mappings":"AAAA;;GAEG;AA2HH,MAAM,MAAM,gBAAgB,GAAG;IAC7B,+EAA+E;IAC/E,YAAY,CAAC,EAAE,OAAO,CAAC;IACvB,2FAA2F;IAC3F,qBAAqB,CAAC,EAAE,OAAO,CAAC;IAChC,kCAAkC;IAClC,gBAAgB,CAAC,EAAE,OAAO,CAAC;CAC5B,CAAC;AAEF,yDAAyD;AACzD,wBAAsB,aAAa,CAAC,IAAI,GAAE,gBAAqB,GAAG,OAAO,CAAC,IAAI,CAAC,CAiD9E"}

View File

@ -118,6 +118,7 @@ function startReferralCommissionMonitor() {
async function bootstrapCore(opts = {}) { async function bootstrapCore(opts = {}) {
const { startEngines = config_1.config.engineEnabled, startPlatformMonitors = true, runDevMigrations = config_1.config.env === 'development', } = opts; const { startEngines = config_1.config.engineEnabled, startPlatformMonitors = true, runDevMigrations = config_1.config.env === 'development', } = opts;
(0, networkGuard_1.validateTestnetSafetyOrThrow)(); (0, networkGuard_1.validateTestnetSafetyOrThrow)();
(0, networkGuard_1.validateProductionMainnetOrThrow)();
(0, productionSecretsGuard_1.validateProductionSecretsOrThrow)(); (0, productionSecretsGuard_1.validateProductionSecretsOrThrow)();
if (runDevMigrations) { if (runDevMigrations) {
try { try {

View File

@ -1 +1 @@
{"version":3,"file":"appBootstrap.js","sourceRoot":"","sources":["../../src/bootstrap/appBootstrap.ts"],"names":[],"mappings":";AAAA;;GAEG;;AAkIH,sCAgDC;AAhLD,sCAAmC;AACnC,iDAAiD;AACjD,kDAA0D;AAC1D,wDAAmE;AACnE,6EAAwE;AACxE,iEAAmG;AACnG,2EAAyE;AACzE,iEAA8F;AAC9F,qEAGuC;AACvC,+DAAmE;AACnE,6EAA+E;AAC/E,+EAA4E;AAC5E,iEAGqC;AACrC,oFAA+F;AAC/F,qGAAsG;AACtG,yDAA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YACH,MAAM,IAAA,0BAAa,GAAE,CAAC;YACtB,OAAO,CAAC,GAAG,CAAC,eAAe,CAAC,CAAC;QAC/B,CAAC;QAAC,OAAO,CAAC,EAAE,CAAC;YACX,OAAO,CAAC,IAAI,CAAC,qBAAqB,EAAE,CAAC,CAAC,CAAC;QACzC,CAAC;IACH,CAAC;IAED,MAAM,IAAA,sCAAqB,GAAE,CAAC;IAE9B,IAAI,eAAM,CAAC,KAAK,CAAC,OAAO,EAAE,CAAC;QACzB,IAAI,CAAC;YACH,MAAM,IAAA,qBAAY,GAAE,CAAC;YACrB,OAAO,CAAC,GAAG,CAAC,mBAAmB,CAAC,CAAC;QACnC,CAAC;QAAC,OAAO,CAAC,EAAE,CAAC;YACX,OAAO,CAAC,IAAI,CAAC,uDAAuD,EAAE,CAAC,CAAC,CAAC;QAC3E,CAAC;IACH,CAAC;IAED,IAAA,gCAAoB,GAAE,CAAC;IAEvB,IAAI,qBAAqB,EAAE,CAAC;QAC1B,IAAA,kDAA0B,GAAE,CAAC;QAC7B,IAAA,+CAAsB,GAAE,CAAC;QACzB,IAAA,qEAAwC,GAAE,CAAC;QAC3C,mBAAmB,EAAE,CAAC;QACtB,2BAA2B,EAAE,CAAC;QAC9B,yBAAyB,EAAE,CAAC;QAC5B,oBAAoB,EAAE,CAAC;QACvB,sBAAsB,EAAE,CAAC;QACzB,8BAA8B,EAAE,CAAC;QACjC,IAAA,yEAAqC,GAAE,CAAC;IAC1C,CAAC;IAED,IAAI,YAAY,EAAE,CAAC;QACjB,IAAA,yCAA0B,GAAE,CAAC;IAC/B,CAAC;AACH,CAAC"}

View File

@ -1 +1 @@
{"version":3,"file":"authController.d.ts","sourceRoot":"","sources":["../../src/controllers/authController.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,EAAE,OAAO,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC;AAI5C,OAAO,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAC;AAMjD;;;;GAIG;AACH,w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AAsB,qBAAqB,CAAC,GAAG,EAAE,WAAW,EAAE,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,CAU1F;AAED;;;;GAIG;AACH,wBAAsB,WAAW,CAAC,GAAG,EAAE,OAAO,EAAE,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,CAW5E;AAED,wBAAsB,uBAAuB,CAAC,GAAG,EAAE,OAAO,EAAE,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,CAaxF;AAED,wBAAsB,cAAc,CAAC,GAAG,EAAE,OAAO,EAAE,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,CAa/E;AAED,wBAAsB,aAAa,CAAC,GAAG,EAAE,OAAO,EAAE,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,CAa9E;AAED,wBAAsB,kBAAkB,CAAC,GAAG,EAAE,OAAO,EAAE,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,CAUnF"}

View File

@ -90,11 +90,17 @@ async function register(req, res) {
}); });
res.status(201).json({ res.status(201).json({
message: 'Registered. Please check your email and click the verification link before signing in.', message: 'Registered. Please check your email and click the verification link before signing in.',
userId: result.userId,
referralCode: result.referralCode,
emailVerificationRequired: result.emailVerificationRequired, emailVerificationRequired: result.emailVerificationRequired,
}); });
} }
catch (e) { catch (e) {
res.status(400).json({ error: (0, safeError_1.clientErrorMessage)(e, 'Registration failed') }); const msg = (0, safeError_1.clientErrorMessage)(e, 'Registration failed');
const status = msg === 'Email is already registered' || msg === 'Phone number already registered'
? 409
: 400;
res.status(status).json({ error: msg });
} }
} }
async function validateReferralCode(req, res) { async function validateReferralCode(req, res) {

File diff suppressed because one or more lines are too long

View File

@ -1 +1 @@
{"version":3,"file":"candlePredictController.d.ts","sourceRoot":"","sources":["../../src/controllers/candlePredictController.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,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C,IAAI,CAAC,CAoB3F"}

View File

@ -165,7 +165,9 @@ async function getMyBets(req, res) {
const page = Math.max(1, parseInt(req.query.page || '1', 10)); const page = Math.max(1, parseInt(req.query.page || '1', 10));
const pageSize = Math.min(50, Math.max(1, parseInt(req.query.pageSize || '10', 10))); const pageSize = Math.min(50, Math.max(1, parseInt(req.query.pageSize || '10', 10)));
const intervalMinutes = parseIntervalMinutes(req.query.intervalMinutes); const intervalMinutes = parseIntervalMinutes(req.query.intervalMinutes);
const predictions = await candlePredictService.getRecentPredictions(req.user.userId, page, pageSize, 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); res.json(predictions);
} }
catch (e) { catch (e) {

File diff suppressed because one or more lines are too long

View File

@ -69,15 +69,15 @@ async function updateMe(req, res) {
const userId = req.user.userId; const userId = req.user.userId;
const { firstName, middleName, lastName, dateOfBirth, email, phone, countryOfResidence, nationality, gender } = req.body; const { firstName, middleName, lastName, dateOfBirth, email, phone, countryOfResidence, nationality, gender } = req.body;
await authService.updateProfile(userId, { await authService.updateProfile(userId, {
firstName: firstName ?? undefined, ...(firstName !== undefined ? { firstName } : {}),
middleName: middleName ?? undefined, ...(middleName !== undefined ? { middleName } : {}),
lastName: lastName ?? undefined, ...(lastName !== undefined ? { lastName } : {}),
dateOfBirth: dateOfBirth ?? undefined, ...(dateOfBirth !== undefined ? { dateOfBirth } : {}),
email: email ?? undefined, ...(email !== undefined ? { email } : {}),
phone: phone !== undefined ? phone : undefined, ...(phone !== undefined ? { phone } : {}),
countryOfResidence: countryOfResidence !== undefined ? countryOfResidence : undefined, ...(countryOfResidence !== undefined ? { countryOfResidence } : {}),
nationality: nationality !== undefined ? nationality : undefined, ...(nationality !== undefined ? { nationality } : {}),
gender: gender !== undefined ? gender : undefined, ...(gender !== undefined ? { gender } : {}),
}); });
res.json({ message: 'Profile updated' }); res.json({ message: 'Profile updated' });
} }

View File

@ -1 +1 @@
{"version":3,"file":"userController.js","sourceRoot":"","sources":["../../src/controllers/userController.ts"],"names":[],"mappings":";AAAA;;GAEG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAYH,sBASC;AAOD,4BAqBC;AAED,8DA4BC;AAED,oEAeC;AAED,4EAQC;AAvGD,qEAAuD;AACvD,uHAAyG;AAGzG;;;;GAIG;AACI,KAAK,UAAU,KAAK,CAAC,GAAgB,EAAE,GAAa;IACzD,IAAI,CAAC;QACH,MAAM,MAAM,GAAG,GAAG,CAAC,IAAK,CAAC,MAAM,CAAC;QAChC,MAAM,OAAO,GAAG,MAAM,WAAW,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC;QACrD,GAAG,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;IACpB,CAAC;IAAC,OAAO,CAAC,EAAE,CAAC;QACX,MAAM,GAAG,GAAG,CAAC,YAAY,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,wBAAwB,CAAC;QACtE,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,EAAE,KAAK,EAAE,GAAG,EAAE,CAAC,CAAC;IACvC,CAAC;AACH,CAAC;AAED;;;;GAIG;AACI,KAAK,UAAU,QAAQ,CAAC,GAAgB,EAAE,GAAa;IAC5D,IAAI,CAAC;QACH,MAAM,MAAM,GAAG,GAAG,CAAC,IAAK,CAAC,MAAM,CAAC;QAChC,MAAM,EAAE,SAAS,EAAE,UAAU,EAAE,QAAQ,EAAE,WAAW,EAAE,KAAK,EAAE,KAAK,EAAE,kBAAkB,EAAE,WAAW,EAAE,MAAM,EAAE,GAC3G,GAAG,CAAC,IAAI,CAAC;QACX,MAAM,WAAW,CAAC,aAAa,CAAC,MAAM,EAAE;YACtC,SAAS,EAAE,SAAS,IAAI,SAAS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AAC,EAAE,KAAK,EAAE,wBAAwB,EAAE,CAAC,CAAC;YAC1D,OAAO;QACT,CAAC;QACD,GAAG,CAAC,IAAI,CAAC,EAAE,OAAO,EAAE,gBAAgB,EAAE,CAAC,CAAC;IAC1C,CAAC;IAAC,OAAO,CAAC,EAAE,CAAC;QACX,MAAM,GAAG,GAAG,CAAC,YAAY,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,+BAA+B,CAAC;QAC7E,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,EAAE,KAAK,EAAE,GAAG,EAAE,CAAC,CAAC;IACvC,CAAC;AACH,CAAC;AAEM,KAAK,UAAU,gCAAgC,CAAC,GAAgB,EAAE,GAAa;IACpF,IAAI,CAAC;QACH,MAAM,KAAK,GAAG,MAAM,kCAAkC,CAAC,WAAW,CAAC,GAAG,CAAC,IAAK,CAAC,MAAM,CAAC,CAAC;QACrF,GAAG,CAAC,IAAI,CAAC,EAAE,MAAM,EAAE,KAAK,EAAE,CAAC,CAAC;IAC9B,CAAC;IAAC,OAAO,CAAC,EAAE,CAAC;QACX,MAAM,GAAG,GAAG,CAAC,YAAY,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,gCAAgC,CAAC;QAC9E,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,EAAE,KAAK,EAAE,GAAG,EAAE,CAAC,CAAC;IACvC,CAAC;AACH,CAAC"}

View File

@ -219,6 +219,7 @@ export declare function getGameState(userId?: string, intervalMinutes?: number,
level: number; level: number;
sequenceDirections: ("short" | "long")[]; sequenceDirections: ("short" | "long")[];
sequenceStep: number; sequenceStep: number;
stakeAccountKind: "test" | "main" | "bonus";
anchorCandleOpenMs: number | null; anchorCandleOpenMs: number | null;
currentCandleOpenMs: number | null; currentCandleOpenMs: number | null;
createdAt: string; createdAt: string;
@ -314,7 +315,10 @@ export type PlaceBetResult = {
idempotencyKey: string; idempotencyKey: string;
}; };
export declare function placeBet(userId: string, direction: string, stakeDisplay: number, intervalMinutes?: number, stakeAccountKind?: AccountKind, opts?: PlaceBetOptions): Promise<PlaceBetResult>; export declare function placeBet(userId: string, direction: string, stakeDisplay: number, intervalMinutes?: number, stakeAccountKind?: AccountKind, opts?: PlaceBetOptions): Promise<PlaceBetResult>;
export declare function getRecentPredictions(userId: string, page?: number, pageSize?: number, intervalMinutes?: number): Promise<{ export declare function getRecentPredictions(userId: string, page?: number, pageSize?: number, intervalMinutes?: number, filters?: {
stakeAccountKind?: string;
status?: string;
}): Promise<{
items: { items: {
id: string; id: string;
roundId: string; roundId: string;
@ -406,6 +410,7 @@ export declare function placeMultiCandleBet(userId: string, input: {
level: number; level: number;
sequenceDirections: ("short" | "long")[]; sequenceDirections: ("short" | "long")[];
sequenceStep: number; sequenceStep: number;
stakeAccountKind: "test" | "main" | "bonus";
anchorCandleOpenMs: number | null; anchorCandleOpenMs: number | null;
currentCandleOpenMs: number | null; currentCandleOpenMs: number | null;
createdAt: string; createdAt: string;

View File

@ -1 +1 @@
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/domain/candle-predict/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,IAAI,MAAM,4CAA4C,CAAC;AACnE,OAAO,KAAK,gBAAgB,MAAM,qCAAqC,CAAC;AACxE,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,qCAAqC,CAAC;AA4KvE,iBAAS,SAAS,CAAC,GAAG,EAAE,IAAI,CAAC,sBAAsB;;;;;;;;;;;;;;;;;;;;;;EAyBlD;AAED,KAAK,eAAe,GAAG,IAAI,CACzB,UAAU,CAAC,OAAO,SAAS,CAAC,EAC1B,gBAAgB,GAChB,gBAAgB,GAChB,qBAAqB,GACrB,wBAAwB,GACxB,wBAAwB,GACxB,wBAAwB,CAC3B,CAAC;AAeF,MAAM,MAAM,gBAAgB,GAAG;IAC7B,EAAE,EAAE,MAAM,CAAC;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E,WAAW,EAC9B,IAAI,CAAC,EAAE,eAAe,GACrB,OAAO,CAAC,cAAc,CAAC,CAgFzB;AAED,wBAAsB,oBAAoB,CACxC,MAAM,EAAE,MAAM,EACd,IAAI,SAAI,EACR,QAAQ,SAAK,EACb,eAAe,CAAC,EAAE,MAAM,EACxB,OAAO,CAAC,EAAE;IAAE,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAAC,MAAM,CAAC,EAAE,MAAM,CAAA;CAAE;;;;;;;;;;;;;wBAlyCD,IAAI,CAAC,cAAc;;;;;;;GAozC3E;AAED,wBAAsB,aAAa,CAAC,MAAM,EAAE,MAAM;;;;;;;;;;;;oBAtzCO,IAAI,CAAC,cAAc;;KAyzC3E;AAED,wBAAsB,gBAAgB,CAAC,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC;;;;;;;;;;kBAmE1D,MAAM,GAAG,IAAI;GAatC;AAED,wBAAsB,eAAe,CAAC,MAAM,EAAE,MAAM;;;;;;;;;GAwBnD;AAED,wBAAsB,oBAAoB;;;;;;;KAGzC;AAED,wBAAsB,sBAAsB,CAAC,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC;;;;;;;KA8BzE;AAED,wBAAsB,mBAAmB,CACvC,MAAM,EAAE,MAAM,EACd,KAAK,EAAE;IACL,KAAK,EAAE,MAAM,CAAC;IACd,QAAQ,EAAE,CAAC,OAAO,GAAG,MAAM,CAAC,EAAE,CAAC;IAC/B,YAAY,EAAE,MAAM,CAAC;IACrB,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,gBAAgB,CAAC,EAAE,WAAW,CAAC;CAChC;;;;;;;;;;;;;;;;GAuHF;AAED,wBAAgB,wBAAwB,IAAI,IAAI,CAW/C"}

View File

@ -154,8 +154,9 @@ function validateStakeLimits(minStakeAmount, maxStakeAmount) {
} }
} }
function parseStakeDisplay(body, fallback) { function parseStakeDisplay(body, fallback) {
if (body.stakeDisplay !== undefined) { const raw = body.stakeDisplay ?? body.stakeAmount ?? body.stake_amount;
return (0, stakeAmountValidation_1.parseStakeAmountFromBody)(body.stakeDisplay); if (raw !== undefined) {
return (0, stakeAmountValidation_1.parseStakeAmountFromBody)(raw);
} }
return fallback; return fallback;
} }
@ -791,15 +792,14 @@ async function backfillMissedAutoCandles(interval, nowMs, cfg, settings) {
} }
if (nextOpen > lastCompletedOpen) if (nextOpen > lastCompletedOpen)
return; return;
let recentOutcomes = await repo.listRecentCandleOutcomes(interval.intervalMinutes, 10);
let processed = 0; let processed = 0;
for (let openMs = nextOpen; openMs <= lastCompletedOpen && processed < settings.candle_predict_backfill_max_per_tick; openMs += intervalMs) { for (let openMs = nextOpen; openMs <= lastCompletedOpen && processed < settings.candle_predict_backfill_max_per_tick; openMs += intervalMs) {
if (!(0, gameTimingService_1.isMaturityBoundaryForInterval)(openMs, interval.intervalMinutes)) if (!(0, gameTimingService_1.isMaturityBoundaryForInterval)(openMs, interval.intervalMinutes))
continue; continue;
if (await repo.hasCandle(openMs, interval.intervalMinutes)) if (await repo.hasCandle(openMs, interval.intervalMinutes))
continue; continue;
// Per-interval 5-streak rule is applied inside settleMaturityAtOpenMs (auto mode).
await settleMaturityAtOpenMs(openMs, cfg); await settleMaturityAtOpenMs(openMs, cfg);
recentOutcomes = await repo.listRecentCandleOutcomes(interval.intervalMinutes, 10);
processed += 1; processed += 1;
} }
} }
@ -883,18 +883,28 @@ async function settleMaturityAtOpenMs(candleOpenMs, cfg) {
multiFinalPoolShort: multiContributions.shortPool, multiFinalPoolShort: multiContributions.shortPool,
multiFinalPoolLong: multiContributions.longPool, multiFinalPoolLong: multiContributions.longPool,
}); });
let outcome;
const { shortPool, longPool } = await multiService.buildMaturityPools(candleOpenMs); const { shortPool, longPool } = await multiService.buildMaturityPools(candleOpenMs);
const primary = aligning.find((i) => i.intervalMinutes === 1) ?? const primary = aligning.find((i) => i.intervalMinutes === 1) ??
aligning.sort((a, b) => a.intervalMinutes - b.intervalMinutes)[0]; aligning.sort((a, b) => a.intervalMinutes - b.intervalMinutes)[0];
/** Shared pool outcome, or per-interval auto outcomes (5-streak rule per chart). */
const outcomesByIntervalMinutes = new Map();
if (outcomeMode === 'pool') { if (outcomeMode === 'pool') {
const neutralityRules = buildPoolNeutralityRules(cfg, primary); const neutralityRules = buildPoolNeutralityRules(cfg, primary);
outcome = (0, candleGenerationService_1.resolvePoolOutcome)(shortPool, longPool, neutralityRules, parsePoolWinnerRule(cfg.pool_winner_rule)); const shared = (0, candleGenerationService_1.resolvePoolOutcome)(shortPool, longPool, neutralityRules, parsePoolWinnerRule(cfg.pool_winner_rule));
for (const interval of aligning) {
outcomesByIntervalMinutes.set(interval.intervalMinutes, shared);
}
} }
else { else {
const recentOutcomes = await repo.listRecentCandleOutcomes(primary.intervalMinutes, 10); // No real-money stake: each interval uses its own history so the
outcome = (0, candleGenerationService_1.resolveAutoNoBetOutcome)(recentOutcomes); // max-5 consecutive same-direction rule applies on every chart.
for (const interval of aligning) {
const recentOutcomes = await repo.listRecentCandleOutcomes(interval.intervalMinutes, 10);
outcomesByIntervalMinutes.set(interval.intervalMinutes, (0, candleGenerationService_1.resolveAutoNoBetOutcome)(recentOutcomes));
} }
}
const outcomeForInterval = (intervalMinutes) => outcomesByIntervalMinutes.get(intervalMinutes) ??
outcomesByIntervalMinutes.get(primary.intervalMinutes);
for (const interval of aligning) { for (const interval of aligning) {
let round = await repo.getRoundByOpenMs(candleOpenMs, interval.intervalMinutes); let round = await repo.getRoundByOpenMs(candleOpenMs, interval.intervalMinutes);
if (!round) { if (!round) {
@ -905,12 +915,12 @@ async function settleMaturityAtOpenMs(candleOpenMs, cfg) {
} }
} }
if (pendingCount > 0) { if (pendingCount > 0) {
await payOutBetsAtMaturity(candleOpenMs, outcome, cfg); await payOutBetsAtMaturity(candleOpenMs, outcomeForInterval, cfg);
} }
if (multiValidationCount > 0) { if (multiValidationCount > 0) {
const levelRows = await repo.listMultiLevels(); const levelRows = await repo.listMultiLevels();
const payoutMultiplierMap = new Map(levelRows.map((l) => [l.level, Number(l.payout_multiplier)])); const payoutMultiplierMap = new Map(levelRows.map((l) => [l.level, Number(l.payout_multiplier)]));
await multiService.processMultiBetsAtMaturity(candleOpenMs, outcome, payoutMultiplierMap); await multiService.processMultiBetsAtMaturity(candleOpenMs, outcomeForInterval, payoutMultiplierMap);
} }
for (const interval of aligning) { for (const interval of aligning) {
let round = await repo.getRoundByOpenMs(candleOpenMs, interval.intervalMinutes); let round = await repo.getRoundByOpenMs(candleOpenMs, interval.intervalMinutes);
@ -919,7 +929,7 @@ async function settleMaturityAtOpenMs(candleOpenMs, cfg) {
} }
if (round.settled_at) if (round.settled_at)
continue; continue;
await finalizeIntervalCandleAtMaturity(round, interval, outcome, shortPool, longPool); await finalizeIntervalCandleAtMaturity(round, interval, outcomeForInterval(interval.intervalMinutes), shortPool, longPool);
} }
} }
async function finalizeIntervalCandleAtMaturity(round, interval, outcome, shortPool, longPool) { async function finalizeIntervalCandleAtMaturity(round, interval, outcome, shortPool, longPool) {
@ -995,11 +1005,12 @@ async function finalizeIntervalCandleAtMaturity(round, interval, outcome, shortP
candleOpenMs: openMs, candleOpenMs: openMs,
}); });
} }
async function payOutBetsAtMaturity(candleOpenMs, outcome, cfg) { async function payOutBetsAtMaturity(candleOpenMs, outcomeForInterval, cfg) {
const bets = await repo.listPendingBetsForMaturity(candleOpenMs); const bets = await repo.listPendingBetsForMaturity(candleOpenMs);
const allIntervals = await loadResolvedIntervals(cfg, true); const allIntervals = await loadResolvedIntervals(cfg, true);
const intervalMap = new Map(allIntervals.map((i) => [i.intervalMinutes, i])); const intervalMap = new Map(allIntervals.map((i) => [i.intervalMinutes, i]));
for (const bet of bets) { for (const bet of bets) {
const outcome = outcomeForInterval(bet.interval_minutes);
const interval = intervalMap.get(bet.interval_minutes) ?? const interval = intervalMap.get(bet.interval_minutes) ??
{ {
intervalMinutes: bet.interval_minutes, intervalMinutes: bet.interval_minutes,
@ -1284,7 +1295,16 @@ async function executePlaceBetInternal(userId, input) {
}, },
}); });
(0, userAdminStatsService_1.queueUserAdminStatsRefresh)(userId); (0, userAdminStatsService_1.queueUserAdminStatsRefresh)(userId);
return mapBet(bet); const mapped = mapBet(bet);
if (config_1.config.redis.enabled) {
await (0, pubsub_2.publishUserEvent)(userId, {
type: 'bet.accepted',
payload: {
bet: mapped,
},
});
}
return mapped;
} }
async function placeBet(userId, direction, stakeDisplay, intervalMinutes, stakeAccountKind, opts) { async function placeBet(userId, direction, stakeDisplay, intervalMinutes, stakeAccountKind, opts) {
(0, stakeAmountValidation_1.assertPositiveStakeAmount)(stakeDisplay); (0, stakeAmountValidation_1.assertPositiveStakeAmount)(stakeDisplay);
@ -1350,13 +1370,15 @@ async function placeBet(userId, direction, stakeDisplay, intervalMinutes, stakeA
} }
return { status: 'accepted', bet }; return { status: 'accepted', bet };
} }
async function getRecentPredictions(userId, page = 1, pageSize = 10, intervalMinutes) { async function getRecentPredictions(userId, page = 1, pageSize = 10, intervalMinutes, filters) {
const safePage = Math.max(1, page); const safePage = Math.max(1, page);
const safeSize = Math.min(50, Math.max(1, pageSize)); const safeSize = Math.min(50, Math.max(1, pageSize));
const offset = (safePage - 1) * safeSize; const offset = (safePage - 1) * safeSize;
const stakeAccountKind = filters?.stakeAccountKind;
const status = filters?.status;
const [rows, total] = await Promise.all([ const [rows, total] = await Promise.all([
repo.listRecentBets(userId, safeSize, offset, intervalMinutes), repo.listRecentBets(userId, safeSize, offset, intervalMinutes, stakeAccountKind, status),
repo.countUserPredictions(userId, intervalMinutes), repo.countUserPredictions(userId, intervalMinutes, stakeAccountKind, status),
]); ]);
return { return {
items: rows.map(mapBet), items: rows.map(mapBet),

File diff suppressed because one or more lines are too long

View File

@ -250,10 +250,10 @@ export declare function getMultiCandlePoolContributions(candleOpenMs: number): P
shortPool: number; shortPool: number;
longPool: number; longPool: number;
}>; }>;
export declare function listRecentBets(userId: string, limit?: number, offset?: number, intervalMinutes?: number): Promise<Array<CandlePredictBetRow & { export declare function listRecentBets(userId: string, limit?: number, offset?: number, intervalMinutes?: number, stakeAccountKind?: string, status?: string): Promise<Array<CandlePredictBetRow & {
candle_open_ms: string; candle_open_ms: string;
}>>; }>>;
export declare function countUserPredictions(userId: string, intervalMinutes?: number): Promise<number>; export declare function countUserPredictions(userId: string, intervalMinutes?: number, stakeAccountKind?: string, status?: string): Promise<number>;
export declare function getAutoSettings(userId: string): Promise<AutoSettingsRow | null>; export declare function getAutoSettings(userId: string): Promise<AutoSettingsRow | null>;
export declare function upsertAutoSettings(userId: string, input: { export declare function upsertAutoSettings(userId: string, input: {
enabled: boolean; enabled: boolean;

File diff suppressed because one or more lines are too long

View File

@ -462,28 +462,48 @@ async function getMultiCandlePoolContributions(candleOpenMs) {
} }
return { shortPool, longPool }; return { shortPool, longPool };
} }
async function listRecentBets(userId, limit = 20, offset = 0, intervalMinutes) { async function listRecentBets(userId, limit = 20, offset = 0, intervalMinutes, stakeAccountKind, status) {
const where = ['b.user_id = $1'];
const params = [userId];
if (intervalMinutes != null) { if (intervalMinutes != null) {
return (0, connection_1.query)(`SELECT b.*, r.candle_open_ms params.push(intervalMinutes);
FROM candle_predict_bets b where.push(`b.interval_minutes = $${params.length}`);
INNER JOIN candle_predict_rounds r ON r.id = b.round_id
WHERE b.user_id = $1 AND b.interval_minutes = $4
ORDER BY b.created_at DESC
LIMIT $2 OFFSET $3`, [userId, limit, offset, intervalMinutes]);
} }
if (stakeAccountKind === 'main' || stakeAccountKind === 'bonus' || stakeAccountKind === 'test') {
params.push(stakeAccountKind);
where.push(`b.stake_account_kind = $${params.length}`);
}
if (status && ['pending', 'in_progress', 'won', 'lost', 'refunded'].includes(status)) {
params.push(status);
where.push(`b.status = $${params.length}`);
}
params.push(limit);
const limitIdx = params.length;
params.push(offset);
const offsetIdx = params.length;
return (0, connection_1.query)(`SELECT b.*, r.candle_open_ms return (0, connection_1.query)(`SELECT b.*, r.candle_open_ms
FROM candle_predict_bets b FROM candle_predict_bets b
INNER JOIN candle_predict_rounds r ON r.id = b.round_id INNER JOIN candle_predict_rounds r ON r.id = b.round_id
WHERE b.user_id = $1 WHERE ${where.join(' AND ')}
ORDER BY b.created_at DESC ORDER BY b.created_at DESC
LIMIT $2 OFFSET $3`, [userId, limit, offset]); LIMIT $${limitIdx} OFFSET $${offsetIdx}`, params);
} }
async function countUserPredictions(userId, intervalMinutes) { async function countUserPredictions(userId, intervalMinutes, stakeAccountKind, status) {
const where = ['user_id = $1'];
const params = [userId];
if (intervalMinutes != null) { if (intervalMinutes != null) {
const rows = await (0, connection_1.query)('SELECT COUNT(*)::text AS count FROM candle_predict_bets WHERE user_id = $1 AND interval_minutes = $2', [userId, intervalMinutes]); params.push(intervalMinutes);
return Number(rows[0]?.count ?? 0); where.push(`interval_minutes = $${params.length}`);
} }
const rows = await (0, connection_1.query)('SELECT COUNT(*)::text AS count FROM candle_predict_bets WHERE user_id = $1', [userId]); if (stakeAccountKind === 'main' || stakeAccountKind === 'bonus' || stakeAccountKind === 'test') {
params.push(stakeAccountKind);
where.push(`stake_account_kind = $${params.length}`);
}
if (status && ['pending', 'in_progress', 'won', 'lost', 'refunded'].includes(status)) {
params.push(status);
where.push(`status = $${params.length}`);
}
const rows = await (0, connection_1.query)(`SELECT COUNT(*)::text AS count FROM candle_predict_bets WHERE ${where.join(' AND ')}`, params);
return Number(rows[0]?.count ?? 0); return Number(rows[0]?.count ?? 0);
} }
async function getAutoSettings(userId) { async function getAutoSettings(userId) {

File diff suppressed because one or more lines are too long

View File

@ -1,28 +1,38 @@
/** /**
* Blockchain network safety guards. * Blockchain network safety guards.
* - Non-production: blocks accidental mainnet usage when testnet is expected.
* Blocks accidental mainnet usage in non-production when testnet mode is expected. * - Production: blocks testnet endpoints/contracts so fake test USDT cannot be credited.
*/ */
/** Official mainnet USDT TRC20 (Tether). */
export declare const MAINNET_USDT_TRC20_CONTRACT = "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t";
/** Shasta testnet USDT TRC20 — must never be used in production. */
export declare const SHASTA_USDT_TRC20_CONTRACT = "TG3XXyExBkPp9nzdajDZsozEu4BkaSJozs";
export type NetworkGuardConfig = {
env: string;
networkMode: string;
tronNodeUrl: string;
usdtTrc20Contract: string | null;
};
/**
* Validates production blockchain settings (testable with explicit config).
* @throws When production would use testnet TRON or Shasta USDT contract
*/
export declare function assertProductionMainnetConfig(cfg: NetworkGuardConfig): void;
/** /**
* Validates that non-production runs use testnet endpoints and contracts. * Validates that non-production runs use testnet endpoints and contracts.
* *
* For the expected testnet setup: * For the expected testnet setup:
* - TRON: Shasta (TRON_NODE_URL should include "shasta") * - TRON: Shasta (TRON_NODE_URL should include "shasta")
* - Asset: USDT TRC20 on Shasta * - Asset: USDT TRC20 on Shasta
* *
* Skipped in production or when NETWORK_MODE=mainnet. * Skipped in production or when NETWORK_MODE=mainnet.
* @throws When a configured URL or contract points at mainnet while testnet is required * @throws When a configured URL or contract points at mainnet while testnet is required
*/ */
export declare function validateTestnetSafetyOrThrow(): void; export declare function validateTestnetSafetyOrThrow(): void;
/**
* Validates that production runs use mainnet TRON and never the Shasta USDT contract.
* Skipped when NODE_ENV is not production.
* @throws When TRON_NODE_URL or USDT_TRC20_CONTRACT targets testnet
*/
export declare function validateProductionMainnetOrThrow(): void;
//# sourceMappingURL=networkGuard.d.ts.map //# sourceMappingURL=networkGuard.d.ts.map

View File

@ -1 +1 @@
{"version":3,"file":"networkGuard.d.ts","sourceRoot":"","sources":["../../src/safety/networkGuard.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AA0CH;;;;;;;;;;;;;;;;;;GAkBG;AAEH,wBAAgB,4BAA4B,IAAI,IAAI,CAoCnD"} {"version":3,"file":"networkGuard.d.ts","sourceRoot":"","sources":["../../src/safety/networkGuard.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAIH,4CAA4C;AAC5C,eAAO,MAAM,2BAA2B,uCAAuC,CAAC;AAEhF,oEAAoE;AACpE,eAAO,MAAM,0BAA0B,uCAAuC,CAAC;AAE/E,MAAM,MAAM,kBAAkB,GAAG;IAC/B,GAAG,EAAE,MAAM,CAAC;IACZ,WAAW,EAAE,MAAM,CAAC;IACpB,WAAW,EAAE,MAAM,CAAC;IACpB,iBAAiB,EAAE,MAAM,GAAG,IAAI,CAAC;CAClC,CAAC;AAkBF;;;GAGG;AACH,wBAAgB,6BAA6B,CAAC,GAAG,EAAE,kBAAkB,GAAG,IAAI,CAqB3E;AAED;;;;;;;;;GASG;AACH,wBAAgB,4BAA4B,IAAI,IAAI,CAgBnD;AAED;;;;GAIG;AACH,wBAAgB,gCAAgC,IAAI,IAAI,CAOvD"}

View File

@ -1,64 +1,77 @@
"use strict"; "use strict";
/** /**
* Blockchain network safety guards. * Blockchain network safety guards.
* - Non-production: blocks accidental mainnet usage when testnet is expected.
* Blocks accidental mainnet usage in non-production when testnet mode is expected. * - Production: blocks testnet endpoints/contracts so fake test USDT cannot be credited.
*/ */
Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "__esModule", { value: true });
exports.SHASTA_USDT_TRC20_CONTRACT = exports.MAINNET_USDT_TRC20_CONTRACT = void 0;
exports.assertProductionMainnetConfig = assertProductionMainnetConfig;
exports.validateTestnetSafetyOrThrow = validateTestnetSafetyOrThrow; exports.validateTestnetSafetyOrThrow = validateTestnetSafetyOrThrow;
exports.validateProductionMainnetOrThrow = validateProductionMainnetOrThrow;
const config_1 = require("../config"); const config_1 = require("../config");
/** /** Official mainnet USDT TRC20 (Tether). */
exports.MAINNET_USDT_TRC20_CONTRACT = 'TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t';
* Throws when a safety assertion fails. /** Shasta testnet USDT TRC20 — must never be used in production. */
exports.SHASTA_USDT_TRC20_CONTRACT = 'TG3XXyExBkPp9nzdajDZsozEu4BkaSJozs';
* @param condition Truthy when the check passes
* @param message Error message when condition is false
*/
function assert(condition, message) { function assert(condition, message) {
if (!condition) if (!condition)
throw new Error(message); throw new Error(message);
} }
/**
* Returns true when the URL appears to target TRON Shasta testnet.
* @param url TRON node URL
*/
function looksLikeShasta(url) { function looksLikeShasta(url) {
return /shasta/i.test(url); return /shasta/i.test(url);
} }
function looksLikeTronTestnet(url) {
return /shasta|nile/i.test(url);
}
function isShastaUsdtContract(contract) {
return contract.trim().toLowerCase() === exports.SHASTA_USDT_TRC20_CONTRACT.toLowerCase();
}
/**
* Validates production blockchain settings (testable with explicit config).
* @throws When production would use testnet TRON or Shasta USDT contract
*/
function assertProductionMainnetConfig(cfg) {
if (cfg.env !== 'production')
return;
assert(cfg.networkMode !== 'testnet', 'Safety check failed: NETWORK_MODE=testnet is not allowed when NODE_ENV=production.');
assert(!looksLikeTronTestnet(cfg.tronNodeUrl), `Safety check failed: TRON_NODE_URL must not point to a TRON testnet in production. Got: ${cfg.tronNodeUrl}`);
const contractOverride = cfg.usdtTrc20Contract?.trim() || '';
if (contractOverride) {
assert(!isShastaUsdtContract(contractOverride), `Safety check failed: USDT_TRC20_CONTRACT must not be the Shasta testnet token in production. ` +
`Use mainnet USDT (${exports.MAINNET_USDT_TRC20_CONTRACT}) or unset USDT_TRC20_CONTRACT to use the DB default.`);
}
}
/** /**
* Validates that non-production runs use testnet endpoints and contracts. * Validates that non-production runs use testnet endpoints and contracts.
* *
* For the expected testnet setup: * For the expected testnet setup:
* - TRON: Shasta (TRON_NODE_URL should include "shasta") * - TRON: Shasta (TRON_NODE_URL should include "shasta")
* - Asset: USDT TRC20 on Shasta * - Asset: USDT TRC20 on Shasta
* *
* Skipped in production or when NETWORK_MODE=mainnet. * Skipped in production or when NETWORK_MODE=mainnet.
* @throws When a configured URL or contract points at mainnet while testnet is required * @throws When a configured URL or contract points at mainnet while testnet is required
*/ */
function validateTestnetSafetyOrThrow() { function validateTestnetSafetyOrThrow() {
const mode = (process.env.NETWORK_MODE || '').toLowerCase(); // "testnet" | "mainnet" | "" const mode = (process.env.NETWORK_MODE || '').toLowerCase();
const isProd = config_1.config.env === 'production'; const isProd = config_1.config.env === 'production';
// Default to strict safety in non-production unless explicitly running mainnet mode.
const requireTestnet = !isProd && mode !== 'mainnet'; const requireTestnet = !isProd && mode !== 'mainnet';
if (!requireTestnet) if (!requireTestnet)
return; return;
assert(looksLikeShasta(config_1.config.blockchain.tron.nodeUrl), `Safety check failed: TRON_NODE_URL must point to Shasta (expected "shasta" in URL). Got: ${config_1.config.blockchain.tron.nodeUrl}`); assert(looksLikeShasta(config_1.config.blockchain.tron.nodeUrl), `Safety check failed: TRON_NODE_URL must point to Shasta (expected "shasta" in URL). Got: ${config_1.config.blockchain.tron.nodeUrl}`);
assert(!!config_1.config.blockchain.tron.usdtTrc20Contract && config_1.config.blockchain.tron.usdtTrc20Contract.trim().length > 0, 'Safety check failed: USDT_TRC20_CONTRACT must be set for Shasta (testnet) so we do not use the mainnet default from DB.'); assert(!!config_1.config.blockchain.tron.usdtTrc20Contract && config_1.config.blockchain.tron.usdtTrc20Contract.trim().length > 0, 'Safety check failed: USDT_TRC20_CONTRACT must be set for Shasta (testnet) so we do not use the mainnet default from DB.');
} }
/**
* Validates that production runs use mainnet TRON and never the Shasta USDT contract.
* Skipped when NODE_ENV is not production.
* @throws When TRON_NODE_URL or USDT_TRC20_CONTRACT targets testnet
*/
function validateProductionMainnetOrThrow() {
assertProductionMainnetConfig({
env: config_1.config.env,
networkMode: (process.env.NETWORK_MODE || '').toLowerCase(),
tronNodeUrl: config_1.config.blockchain.tron.nodeUrl,
usdtTrc20Contract: config_1.config.blockchain.tron.usdtTrc20Contract,
});
}
//# sourceMappingURL=networkGuard.js.map //# sourceMappingURL=networkGuard.js.map

View File

@ -1 +1 @@
{"version":3,"file":"networkGuard.js","sourceRoot":"","sources":["../../src/safety/networkGuard.ts"],"names":[],"mappings":";AAAA;;;;;;GAMG;;AA8DH,oEAoCC;AA9FD,sCAAmC;AAInC;;;;;;;;GAQG;AAEH,SAAS,MAAM,CAAC,SAAkB,EAAE,OAAe;IAEjD,IAAI,CAAC,SAAS;QAAE,MAAM,IAAI,KAAK,CAAC,OAA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,IAAI,CAAC,CAmBf;AAED;;GAEG;AACH,wBAAsB,uBAAuB,CAC3C,MAAM,EAAE,MAAM,EACd,QAAQ,EAAE,MAAM,EAChB,YAAY,CAAC,EAAE;IAAE,SAAS,CAAC,EAAE,MAAM,CAAC;IAAC,SAAS,CAAC,EAAE,MAAM,CAAA;CAAE,GACxD,OAAO,CAAC;IAAE,aAAa,EAAE,MAAM,EAAE,CAAA;CAAE,CAAC,CAoBtC;AAED;;;;;GAKG;AACH,wBAAsB,WAAW,CAAC,WAAW,EAAE,MAAM,GAAG,OAAO,CAAC,UAAU,CAAC,CAG1E;AAED;;;;;GAKG;AACH,wBAAgB,WAAW,CAAC,OAAO,EAAE,QAAQ,EAAE,GAAG,CAAC,OAAO,EAAE,UAAU,KAAK,IAAI,CAQ9E"}

View File

@ -214,12 +214,7 @@ async function register(input) {
const emailHash = (0, crypto_2.hashForIndex)(normalizedEmail); const emailHash = (0, crypto_2.hashForIndex)(normalizedEmail);
const existing = await userRepository.findByEmailHash(emailHash); const existing = await userRepository.findByEmailHash(emailHash);
if (existing) { if (existing) {
await new Promise((resolve) => setTimeout(resolve, 200 + Math.floor(Math.random() * 200))); throw new Error('Email is already registered');
return {
userId: '',
referralCode: '',
emailVerificationRequired: policy.require_email_verification_for_login,
};
} }
let phoneHash = null; let phoneHash = null;
let phoneEncrypted = null; let phoneEncrypted = null;

File diff suppressed because one or more lines are too long

View File

@ -2,11 +2,22 @@
* TRON blockchain integration via TronGrid. * TRON blockchain integration via TronGrid.
* Read incoming TRX/TRC20 transfers and broadcast outbound transactions. * Read incoming TRX/TRC20 transfers and broadcast outbound transactions.
*/ */
/** PostgreSQL signed BIGINT upper bound. */
export declare const PG_BIGINT_MAX = 9223372036854775807n;
/**
* Parses a TRC20 transfer `value` from TronGrid into smallest token units.
* Rejects non-decimal strings, floats, negative values, and amounts that do not fit in PG BIGINT.
*/
export declare function parseTrc20TokenAmount(raw: unknown): bigint | null;
/** /**
* Returns the current TRON block number from the node. * Returns the current TRON block number from the node.
* @returns Latest block height * @returns Latest block height
*/ */
export declare function getCurrentBlock(): Promise<number>; export declare function getCurrentBlock(): Promise<number>;
/**
* Returns the block timestamp in Unix ms for a given block height.
*/
export declare function getBlockTimestamp(blockNumber: number): Promise<number | null>;
/** Incoming native TRX transfer parsed from TronGrid account transactions. */ /** Incoming native TRX transfer parsed from TronGrid account transactions. */
export interface TronIncomingTx { export interface TronIncomingTx {
txId: string; txId: string;

View File

@ -1 +1 @@
{"version":3,"file":"tronService.d.ts","sourceRoot":"","sources":["../../../src/services/blockchain/tronService.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAsBH;;;GAGG;AACH,wBAAsB,eAAe,IAAI,OAAO,CAAC,MAAM,CAAC,CAIvD;AAED,8EAA8E;AAC9E,MAAM,WAAW,cAAc;IAC7B,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,MAAM,CAAC;IACb,EAAE,EAAE,MAAM,CAAC;IACX,MAAM,EAAE,MAAM,CAAC;IACf,KAAK,EAAE,MAAM,CAAC;IACd,aAAa,EAAE,MAAM,CAAC;CACvB;AAgCD;;;;;GAKG;AACH,wBAAsB,2BAA2B,CAAC,OAAO,EAAE,MAAM,EAAE,YAAY,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,cAAc,EAAE,CAAC,CA8CnH;AAED,kEAAkE;AAClE,MAAM,WAAW,aAAa;IAC5B,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,MAAM,CAAC;IACb,EAAE,EAAE,MAAM,CAAC;IACX,KAAK,EAAE,MAAM,CAAC;IACd,KAAK,EAAE,MAAM,CAAC;IACd,eAAe,EAAE,MAAM,CAAC;IACxB,iEAAiE;IACjE,aAAa,EAAE,MAAM,CAAC;CACvB;AAMD;;;;;;GAMG;AACH,wBAAsB,0BAA0B,CAAC,OAAO,EAAE,MAAM,EAAE,eAAe,EAAE,MAAM,EAAE,YAAY,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,aAAa,EAAE,C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,OAAO,EAAE,MAAM,EAAE,YAAY,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,cAAc,EAAE,CAAC,CA8CnH;AAED,kEAAkE;AAClE,MAAM,WAAW,aAAa;IAC5B,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,MAAM,CAAC;IACb,EAAE,EAAE,MAAM,CAAC;IACX,KAAK,EAAE,MAAM,CAAC;IACd,KAAK,EAAE,MAAM,CAAC;IACd,eAAe,EAAE,MAAM,CAAC;IACxB,iEAAiE;IACjE,aAAa,EAAE,MAAM,CAAC;CACvB;AAYD;;;;;;GAMG;AACH,wBAAsB,0BAA0B,CAAC,OAAO,EAAE,MAAM,EAAE,eAAe,EAAE,MAAM,EAAE,YAAY,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,aAAa,EAAE,CAAC,CAiC1I;AAED;;;;;;;GAOG;AACH,wBAAsB,OAAO,CAAC,iBAAiB,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAQ9G;AAED;;;;;;;GAOG;AACH,wBAAsB,SAAS,CAAC,iBAAiB,EAAE,MAAM,EAAE,eAAe,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAKzI;AAED;;GAEG;AACH,wBAAsB,gBAAgB,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAIvE;AAED;;GAEG;AACH,wBAAsB,kBAAkB,CAAC,OAAO,EAAE,MAAM,EAAE,eAAe,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAKlG"}

View File

@ -4,7 +4,10 @@
* Read incoming TRX/TRC20 transfers and broadcast outbound transactions. * Read incoming TRX/TRC20 transfers and broadcast outbound transactions.
*/ */
Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "__esModule", { value: true });
exports.PG_BIGINT_MAX = void 0;
exports.parseTrc20TokenAmount = parseTrc20TokenAmount;
exports.getCurrentBlock = getCurrentBlock; exports.getCurrentBlock = getCurrentBlock;
exports.getBlockTimestamp = getBlockTimestamp;
exports.getTrxTransactionsToAddress = getTrxTransactionsToAddress; exports.getTrxTransactionsToAddress = getTrxTransactionsToAddress;
exports.getTrc20TransfersToAddress = getTrc20TransfersToAddress; exports.getTrc20TransfersToAddress = getTrc20TransfersToAddress;
exports.sendTrx = sendTrx; exports.sendTrx = sendTrx;
@ -14,6 +17,43 @@ exports.getTrc20BalanceRaw = getTrc20BalanceRaw;
const hdWallet_1 = require("../hdWallet"); const hdWallet_1 = require("../hdWallet");
const TRON_GRID_URL = process.env.TRON_NODE_URL || 'https://api.trongrid.io'; const TRON_GRID_URL = process.env.TRON_NODE_URL || 'https://api.trongrid.io';
const TRON_API_KEY = process.env.TRON_API_KEY || ''; const TRON_API_KEY = process.env.TRON_API_KEY || '';
/** PostgreSQL signed BIGINT upper bound. */
exports.PG_BIGINT_MAX = 9223372036854775807n;
/**
* Parses a TRC20 transfer `value` from TronGrid into smallest token units.
* Rejects non-decimal strings, floats, negative values, and amounts that do not fit in PG BIGINT.
*/
function parseTrc20TokenAmount(raw) {
if (raw == null)
return null;
let digits;
if (typeof raw === 'bigint') {
digits = raw.toString();
}
else if (typeof raw === 'number') {
if (!Number.isFinite(raw) || raw <= 0 || !Number.isInteger(raw))
return null;
digits = raw.toString();
}
else if (typeof raw === 'string') {
const s = raw.trim();
if (!/^\d+$/.test(s))
return null;
digits = s;
}
else {
return null;
}
try {
const amount = BigInt(digits);
if (amount <= 0n || amount > exports.PG_BIGINT_MAX)
return null;
return amount;
}
catch {
return null;
}
}
/** /**
* Performs an authenticated GET request to TronGrid REST API. * Performs an authenticated GET request to TronGrid REST API.
* @param path API path including query string (e.g. /v1/accounts/...) * @param path API path including query string (e.g. /v1/accounts/...)
@ -39,6 +79,23 @@ async function getCurrentBlock() {
const block = await tronWeb.trx.getCurrentBlock(); const block = await tronWeb.trx.getCurrentBlock();
return block.block_header.raw_data.number; return block.block_header.raw_data.number;
} }
/**
* Returns the block timestamp in Unix ms for a given block height.
*/
async function getBlockTimestamp(blockNumber) {
if (!Number.isFinite(blockNumber) || blockNumber < 0)
return null;
try {
const tronWeb = (0, hdWallet_1.getTronWeb)();
const trx = tronWeb.trx;
const block = await trx.getBlock(blockNumber);
const ts = block?.block_header?.raw_data?.timestamp;
return typeof ts === 'number' && ts > 0 ? ts : null;
}
catch {
return null;
}
}
/** /**
* Normalizes a TRON address to lowercase hex for comparison (API raw_data often returns hex). * Normalizes a TRON address to lowercase hex for comparison (API raw_data often returns hex).
* @param address Base58 or hex TRON address * @param address Base58 or hex TRON address
@ -129,12 +186,19 @@ async function getTrc20TransfersToAddress(address, contractAddress, minTimestamp
for (const e of data.data || []) { for (const e of data.data || []) {
if (e.to?.toLowerCase() !== address.toLowerCase()) if (e.to?.toLowerCase() !== address.toLowerCase())
continue; continue;
const amount = parseTrc20TokenAmount(e.value);
if (amount == null) {
if (process.env.NODE_ENV !== 'production') {
console.warn(`[tron] TRC20: skip invalid amount for tx=${e.transaction_id} value=${String(e.value)}`);
}
continue;
}
const confirmations = Math.max(0, Math.floor((Date.now() - e.block_timestamp) / 3000)); const confirmations = Math.max(0, Math.floor((Date.now() - e.block_timestamp) / 3000));
out.push({ out.push({
txId: e.transaction_id, txId: e.transaction_id,
from: e.from, from: e.from,
to: e.to, to: e.to,
value: e.value, value: amount.toString(),
block: 0, block: 0,
block_timestamp: e.block_timestamp, block_timestamp: e.block_timestamp,
confirmations, confirmations,

File diff suppressed because one or more lines are too long

View File

@ -58,6 +58,7 @@ export declare function mapMultiBet(row: repo.CandlePredictBetRow): {
level: number; level: number;
sequenceDirections: ("short" | "long")[]; sequenceDirections: ("short" | "long")[];
sequenceStep: number; sequenceStep: number;
stakeAccountKind: AccountKind;
anchorCandleOpenMs: number | null; anchorCandleOpenMs: number | null;
currentCandleOpenMs: number | null; currentCandleOpenMs: number | null;
createdAt: string; createdAt: string;
@ -67,6 +68,6 @@ export declare function buildMaturityPools(candleOpenMs: number): Promise<{
shortPool: number; shortPool: number;
longPool: number; longPool: number;
}>; }>;
export declare function processMultiBetsAtMaturity(candleOpenMs: number, outcome: RoundOutcome, payoutMultiplierMap: Map<number, number>): Promise<void>; export declare function processMultiBetsAtMaturity(candleOpenMs: number, outcomeForInterval: RoundOutcome | ((intervalMinutes: number) => RoundOutcome), payoutMultiplierMap: Map<number, number>): Promise<void>;
export {}; export {};
//# sourceMappingURL=candlePredictMultiService.d.ts.map //# sourceMappingURL=candlePredictMultiService.d.ts.map

View File

@ -1 +1 @@
{"version":3,"file":"candlePredictMultiService.d.ts","sourceRoot":"","sources":["../../src/services/candlePredictMultiService.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,IAAI,MAAM,yCAAyC,CAAC;AAEhE,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,2BAA2B,CAAC;AAM9D,KAAK,WAAW,GAAG,MAAM,GAAG,OAAO,GAAG,MAAM,CAAC;AAsC7C;;;GAGG;AACH,wBAAgB,+BAA+B,CAC7C,YAAY,EAAE,MAAM,EACpB,cAAc,EAAE,MAAM,GACrB,MAAM,CAER;AAED;;GAEG;AACH,wBAAgB,kCAAkC,CAChD,YAAY,EAAE,MAAM,EACpB,cAAc,EAAE,MAAM,GACrB,MAAM,CAER;AAED;;;GAGG;AACH,wBAAgB,2BAA2B,CAAC,YAAY,EAAE,MAAM,EAAE,gBAAgB,EAAE,MAAM,GAAG,MAAM,CAElG;AAED,MAAM,MAAM,mBAAmB,GAAG,MAAM,GAAG,MAAM,CAAC;AAElD;;;;GAIG;AACH,wBAAgB,0BAA0B,CAAC,MAAM,EAAE;IACjD,sBAAsB,EAAE,OAAO,CAAC;IAChC,mBAAmB,EAAE,MAAM,CAAC;IAC5B,kBAAkB,EAAE,MAAM,CAAC;CAC5B,GAAG,mBAAmB,CAMtB;AAED,2FAA2F;AAC3F,wBAAgB,4BAA4B,CAC1C,gBAAgB,EAAE,WAAW,EAC7B,SAAS,EAAE,aAAa,GAAG,aAAa,GACvC,WAAW,CAKb;AAiBD,wBAAgB,aAAa,CAAC,GAAG,EAAE,IAAI,CAAC,0BAA0B;;;;IAK9D,sFAAsF;;IAEtF,8EAA8E;;;EAIjF;AAED,wBAAgB,sBAAsB,CAAC,GAAG,EAAE,IAAI,CAAC,0BAA0B;;;;IARvE,sFAAsF;;;EAWzF;AAED,wBAAgB,WAAW,CAAC,GAAG,EAAE,IAAI,CAAC,mBAAmB;;;;;;;;;;;;;;;EAyBxD;AAED,uFAAuF;AACvF,wBAAsB,kBAAkB,CAAC,YAAY,EAAE,MAAM,GAAG,OAAO,CAAC;IACtE,SAAS,EAAE,MAAM,CAAC;IAClB,QAAQ,EAAE,MAAM,CAAC;CAClB,CAAC,CASD;AAED,wBAAsB,0BAA0B,CAC9C,YAAY,EAAE,MAAM,EACpB,OAAO,EAAE,YAAY,EACrB,mBAAmB,EAAE,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,GACvC,OAAO,CAAC,IAAI,CAAC,CA+Gf"} {"version":3,"file":"candlePredictMultiService.d.ts","sourceRoot":"","sources":["../../src/services/candlePredictMultiService.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,IAAI,MAAM,yCAAyC,CAAC;AAEhE,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,2BAA2B,CAAC;AAM9D,KAAK,WAAW,GAAG,MAAM,GAAG,OAAO,GAAG,MAAM,CAAC;AAsC7C;;;GAGG;AACH,wBAAgB,+BAA+B,CAC7C,YAAY,EAAE,MAAM,EACpB,cAAc,EAAE,MAAM,GACrB,MAAM,CAER;AAED;;GAEG;AACH,wBAAgB,kCAAkC,CAChD,YAAY,EAAE,MAAM,EACpB,cAAc,EAAE,MAAM,GACrB,MAAM,CAER;AAED;;;GAGG;AACH,wBAAgB,2BAA2B,CAAC,YAAY,EAAE,MAAM,EAAE,gBAAgB,EAAE,MAAM,GAAG,MAAM,CAElG;AAED,MAAM,MAAM,mBAAmB,GAAG,MAAM,GAAG,MAAM,CAAC;AAElD;;;;GAIG;AACH,wBAAgB,0BAA0B,CAAC,MAAM,EAAE;IACjD,sBAAsB,EAAE,OAAO,CAAC;IAChC,mBAAmB,EAAE,MAAM,CAAC;IAC5B,kBAAkB,EAAE,MAAM,CAAC;CAC5B,GAAG,mBAAmB,CAMtB;AAED,2FAA2F;AAC3F,wBAAgB,4BAA4B,CAC1C,gBAAgB,EAAE,WAAW,EAC7B,SAAS,EAAE,aAAa,GAAG,aAAa,GACvC,WAAW,CAKb;AAiBD,wBAAgB,aAAa,CAAC,GAAG,EAAE,IAAI,CAAC,0BAA0B;;;;IAK9D,sFAAsF;;IAEtF,8EAA8E;;;EAIjF;AAED,wBAAgB,sBAAsB,CAAC,GAAG,EAAE,IAAI,CAAC,0BAA0B;;;;IARvE,sFAAsF;;;EAWzF;AAED,wBAAgB,WAAW,CAAC,GAAG,EAAE,IAAI,CAAC,mBAAmB;;;;;;;;;;;;;;;;EA0BxD;AAED,uFAAuF;AACvF,wBAAsB,kBAAkB,CAAC,YAAY,EAAE,MAAM,GAAG,OAAO,CAAC;IACtE,SAAS,EAAE,MAAM,CAAC;IAClB,QAAQ,EAAE,MAAM,CAAC;CAClB,CAAC,CASD;AAED,wBAAsB,0BAA0B,CAC9C,YAAY,EAAE,MAAM,EACpB,kBAAkB,EAAE,YAAY,GAAG,CAAC,CAAC,eAAe,EAAE,MAAM,KAAK,YAAY,CAAC,EAC9E,mBAAmB,EAAE,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,GACvC,OAAO,CAAC,IAAI,CAAC,CAqHf"}

View File

@ -159,6 +159,7 @@ function mapMultiBet(row) {
level: row.multi_level ?? 0, level: row.multi_level ?? 0,
sequenceDirections: parseSequenceDirections(row.sequence_directions), sequenceDirections: parseSequenceDirections(row.sequence_directions),
sequenceStep: step, sequenceStep: step,
stakeAccountKind: parseStakeAccountKind(row.stake_account_kind),
anchorCandleOpenMs: anchorMs, anchorCandleOpenMs: anchorMs,
currentCandleOpenMs, currentCandleOpenMs,
createdAt: row.created_at.toISOString(), createdAt: row.created_at.toISOString(),
@ -175,11 +176,15 @@ async function buildMaturityPools(candleOpenMs) {
longPool: single.longPool + multi.longPool, longPool: single.longPool + multi.longPool,
}; };
} }
async function processMultiBetsAtMaturity(candleOpenMs, outcome, payoutMultiplierMap) { async function processMultiBetsAtMaturity(candleOpenMs, outcomeForInterval, payoutMultiplierMap) {
const bets = await repo.listMultiBetsForValidationAtOpenMs(candleOpenMs); const bets = await repo.listMultiBetsForValidationAtOpenMs(candleOpenMs);
if (!bets.length) if (!bets.length)
return; return;
const resolveOutcome = typeof outcomeForInterval === 'function'
? outcomeForInterval
: (_intervalMinutes) => outcomeForInterval;
for (const bet of bets) { for (const bet of bets) {
const outcome = resolveOutcome(bet.interval_minutes);
const sequence = parseSequenceDirections(bet.sequence_directions); const sequence = parseSequenceDirections(bet.sequence_directions);
const level = bet.multi_level ?? sequence.length; const level = bet.multi_level ?? sequence.length;
const step = bet.sequence_step ?? 0; const step = bet.sequence_step ?? 0;

File diff suppressed because one or more lines are too long

View File

@ -1 +1 @@
{"version":3,"file":"depositMonitorService.d.ts","sourceRoot":"","sources":["../../src/services/depositMonitorService.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAiBH,8EAA8E;AAC9E,wBAAsB,mBAAmB,IAAI,OAAO,CAAC,IAAI,CAAC,CAiEzD"} {"version":3,"file":"depositMonitorService.d.ts","sourceRoot":"","sources":["../../src/services/depositMonitorService.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAiBH,8EAA8E;AAC9E,wBAAsB,mBAAmB,IAAI,OAAO,CAAC,IAAI,CAAC,CAmFzD"}

View File

@ -62,7 +62,7 @@ async function processTronDeposits() {
if (fromBlock > BigInt(currentBlock)) { if (fromBlock > BigInt(currentBlock)) {
fromBlock = 0n; fromBlock = 0n;
} }
const userWallets = await (0, connection_1.query)('SELECT address, user_id FROM user_wallets WHERE wallet_type_id = $1', [walletType.id]); const userWallets = await (0, connection_1.query)('SELECT address, user_id, created_at FROM user_wallets WHERE wallet_type_id = $1', [walletType.id]);
if (userWallets.length > 0) { if (userWallets.length > 0) {
const hasAnyUsdtTx = await (0, connection_1.query)('SELECT 1 as n FROM transactions WHERE wallet_type_id = $1 LIMIT 1', [walletType.id]).then((r) => r.length > 0); const hasAnyUsdtTx = await (0, connection_1.query)('SELECT 1 as n FROM transactions WHERE wallet_type_id = $1 LIMIT 1', [walletType.id]).then((r) => r.length > 0);
if (!hasAnyUsdtTx && fromBlock > 0n) { if (!hasAnyUsdtTx && fromBlock > 0n) {
@ -72,21 +72,40 @@ async function processTronDeposits() {
} }
} }
} }
const fromTimestamp = Number(fromBlock) * 3000; let scannerMinTimestamp = 0;
if (fromBlock > 0n) {
const blockTs = await tronService.getBlockTimestamp(Number(fromBlock));
if (blockTs != null)
scannerMinTimestamp = blockTs;
}
const trc20Contract = config_1.config.blockchain.tron.usdtTrc20Contract || walletType.contract_address || ''; const trc20Contract = config_1.config.blockchain.tron.usdtTrc20Contract || walletType.contract_address || '';
if (!trc20Contract) if (!trc20Contract)
return; return;
if (process.env.NODE_ENV !== 'production') { if (process.env.NODE_ENV !== 'production') {
console.log(`[deposit] USDT_TRC20 (id=${walletType.id}): ${userWallets.length} wallets, fromBlock=${fromBlock}`); console.log(`[deposit] USDT_TRC20 (id=${walletType.id}): ${userWallets.length} wallets, fromBlock=${fromBlock}`);
} }
for (const { address, user_id } of userWallets) { for (const { address, user_id, created_at } of userWallets) {
const transfers = await tronService.getTrc20TransfersToAddress(address, trc20Contract, fromTimestamp); const walletCreatedMs = new Date(created_at).getTime();
const minTimestamp = Math.max(scannerMinTimestamp, walletCreatedMs);
const transfers = await tronService.getTrc20TransfersToAddress(address, trc20Contract, minTimestamp);
if (process.env.NODE_ENV !== 'production' && transfers.length > 0) { if (process.env.NODE_ENV !== 'production' && transfers.length > 0) {
console.log(`[deposit] USDT ${address}: ${transfers.length} transfer(s)`); console.log(`[deposit] USDT ${address}: ${transfers.length} transfer(s)`);
} }
for (const t of transfers) { for (const t of transfers) {
const amount = tronService.parseTrc20TokenAmount(t.value);
if (amount == null) {
if (process.env.NODE_ENV !== 'production') {
console.warn(`[deposit] USDT ${address}: skip invalid amount tx=${t.txId} value=${t.value}`);
}
continue;
}
if (t.confirmations >= TRON_CONFIRMATIONS) { if (t.confirmations >= TRON_CONFIRMATIONS) {
await creditDeposit(user_id, walletType.id, BigInt(t.value), t.txId, t.from, address, t.confirmations); try {
await creditDeposit(user_id, walletType.id, amount, t.txId, t.from, address, t.confirmations);
}
catch (e) {
console.error(`[deposit] credit failed tx=${t.txId}:`, e);
}
} }
} }
} }

View File

@ -1 +1 @@
{"version":3,"file":"depositMonitorService.js","sourceRoot":"","sources":["../../src/services/depositMonitorService.ts"],"names":[],"mappings":";AAAA;;;GAGG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkBH,kDAiEC;AAjFD,sCAAmC;AACnC,iDAAgF;AAChF,mFAAqE;AACrE,mFAAqE;AACrE,6FAA+E;AAC/E,mGAAqF;AACrF,uFAAyE;AACzE,iDAA0D;AAC1D,mEAAqE;AACrE,mEAAqD;AACrD,6DAAwD;AACxD,sEAAwD;AAExD,MAAM,kBAAkB,GAAG,eAAM,CAAC,UAAU,CAAC,IAAI,CAAC,aAAa,CAAC;AAEhE,8EAA8E;AACvE,KAAK,UAAU,mBAAmB;IACvC,MAAM,UAAU,GAAG,MAAM,gBAAgB,CAAC,mBAAmB,CAAC,qCAAgB,CAAC,CAAC;IAChF,IAAI,CAAC,UAAU;QAAE,OAAO;IAExB,MAAM,YAAY,GAAG,MAAM,WAAW,CAAC,eAAe,EAAE,CAAC;IACzD,MAAM,KAAK,GAAG,MAAM,wBAAwB,CAAC,QAAQ,CAAC,UAAU,CAAC,EAAE,CAAC,CAAC;IACrE,IAAI,SAAS,GAAG,KAAK,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,UAAU,CA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S;YACT,aAAa,EAAE,KAAK;YACpB,qBAAqB,EAAE,kBAAkB;SAC1C,CAAC,CAAC;QACH,IAAI,CAAC,EAAE,EAAE,CAAC;YACR,MAAM,MAAM,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC;YAC7B,OAAO;QACT,CAAC;QACD,MAAM,gBAAgB,CAAC,iBAAiB,CACtC,MAAM,EACN,OAAO,CAAC,EAAE,EACV,MAAM,EACN,SAAS,EACT,aAAa,EACb,EAAE,CAAC,EAAE,CACN,CAAC;QACF,MAAM,MAAM,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC;IAC/B,CAAC;IAAC,OAAO,CAAC,EAAE,CAAC;QACX,MAAM,MAAM,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC;QAC/B,MAAM,CAAC,CAAC;IACV,CAAC;YAAS,CAAC;QACT,MAAM,CAAC,OAAO,EAAE,CAAC;IACnB,CAAC;IAED,IAAI,CAAC,EAAE;QAAE,OAAO;IAEhB,MAAM,eAAe,CAAC,sCAAsC,CAAC;QAC3D,MAAM;QACN,oBAAoB,EAAE,EAAE,CAAC,EAAE;QAC3B,aAAa,EAAE,MAAM;QACrB,YAAY;KACb,CAAC,CAAC;IACH,MAAM,kBAAkB,CAAC,MAAM,CAAC;QAC9B,MAAM;QACN,MAAM,EAAE,mBAAmB;QAC3B,YAAY,EAAE,aAAa;QAC3B,UAAU,EAAE,EAAE,CAAC,EAAE;QACjB,QAAQ,EAAE,EAAE,MAAM,EAAE,MAAM,CAAC,QAAQ,EAAE,EAAE,cAAc,EAAE;KACxD,CAAC,CAAC;IACH,MAAM,IAAA,uCAAwB,EAAC,MAAM,EAAE,YAAY,EAAE,MAAM,EAAE,EAAE,CAAC,EAAE,CAAC,CAAC;IACpE,IAAA,kDAA0B,EAAC,MAAM,CAAC,CAAC;AACrC,CAAC"} {"version":3,"file":"depositMonitorService.js","sourceRoot":"","sources":["../../src/services/depositMonitorService.ts"],"names":[],"mappings":";AAAA;;;GAGG;;;;;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EAAE,cAAc,EAAE;KACxD,CAAC,CAAC;IACH,MAAM,IAAA,uCAAwB,EAAC,MAAM,EAAE,YAAY,EAAE,MAAM,EAAE,EAAE,CAAC,EAAE,CAAC,CAAC;IACpE,IAAA,kDAA0B,EAAC,MAAM,CAAC,CAAC;AACrC,CAAC"}

View File

@ -27,6 +27,7 @@ export declare function isCommissionPendingExpired(createdAt: Date, maxPendingDa
export declare function validateReferralCode(code: string): Promise<{ export declare function validateReferralCode(code: string): Promise<{
valid: boolean; valid: boolean;
referrerId?: string; referrerId?: string;
reason?: string;
}>; }>;
export declare function resolveReferrerId(referralCode?: string | null): Promise<string | null>; export declare function resolveReferrerId(referralCode?: string | null): Promise<string | null>;
/** /**

View File

@ -1 +1 @@
{"version":3,"file":"referralService.d.ts","sourceRoot":"","sources":["../../src/services/referralService.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,KAAK,kBAAkB,MAAM,oCAAoC,CAAC;AACzE,OAAO,KAAK,EAA+B,uBAAuB,EAAE,MAAM,oCAAoC,CAAC;AAQ/G,OAAO,EAIL,KAAK,WAAW,EACjB,MAAM,wBAAwB,CAAC;AAOhC,qBAAa,aAAc,SAAQ,KAAK;gBAC1B,OAAO,EAAE,MAAM;CAI5B;AAED,MAAM,MAAM,wBAAwB,GAAG;IACrC,qBAAqB,EAAE,OAAO,CAAC;IAC/B,iBAAiB,EAAE,OAAO,CAAC;IAC3B,yBAAyB,EAAE,OAAO,CAAC;IACnC,2BAA2B,EAAE,MAAM,CAAC;IACpC,oBAAoB,EAAE,OAAO,CAAC;IAC9B,4BAA4B,EAAE,OAAO,CAAC;IACtC,wBAAwB,EAAE,OAAO,CAAC;IAClC,uBAAuB,EAAE,OAAO,CAAC;IACjC,QAAQ,EAAE,IAAI,CACZ,uBAAuB,EACrB,2BAA2B,GAC3B,8BAA8B,GAC9B,2BAA2B,GAC3B,0BAA0B,CAC7B,CAAC;CACH,CAAC;AAEF,MAAM,MAAM,yBAAyB,GAAG;IAC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,0BAA0B,CAAC,KAAK,EAAE;IACtD,QAAQ,EAAE,MAAM,CAAC;IACjB,OAAO,EAAE,MAAM,CAAC;IAChB,MAAM,EAAE,MAAM,CAAC;CAChB,GAAG,OAAO,CAAC;IAAE,UAAU,EAAE,MAAM,CAAC;IAAC,YAAY,EAAE,MAAM,CAAA;CAAE,CAAC,CAkExD;AAED,wBAAsB,yBAAyB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAuB9C;AAYD,wBAAsB,mBAAmB,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC;IACjE,YAAY,EAAE,MAAM,GAAG,IAAI,CAAC;IAC5B,YAAY,EAAE,MAAM,CAAC;IACrB,eAAe,EAAE,MAAM,CAAC;IACxB,iBAAiB,EAAE,OAAO,CAAC;CAC5B,CAAC,CAeD;AAED,wBAAsB,0BAA0B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAwC/C"}

View File

@ -69,6 +69,7 @@ const referralCapService_1 = require("./referralCapService");
const referralNotificationService_1 = require("./referralNotificationService"); const referralNotificationService_1 = require("./referralNotificationService");
const referralWithdrawalCommissionService_1 = require("./referralWithdrawalCommissionService"); const referralWithdrawalCommissionService_1 = require("./referralWithdrawalCommissionService");
const countryFormat_1 = require("../utils/countryFormat"); const countryFormat_1 = require("../utils/countryFormat");
const publicWebUrl_1 = require("../utils/publicWebUrl");
const fraudAutoBlockService_1 = require("./fraudAutoBlockService"); const fraudAutoBlockService_1 = require("./fraudAutoBlockService");
class ReferralError extends Error { class ReferralError extends Error {
constructor(message) { constructor(message) {
@ -108,10 +109,21 @@ function isCommissionPendingExpired(createdAt, maxPendingDays, now = new Date())
async function validateReferralCode(code) { async function validateReferralCode(code) {
const trimmed = code?.trim(); const trimmed = code?.trim();
if (!trimmed) if (!trimmed)
return { valid: false }; return { valid: false, reason: 'empty' };
const settings = await referralRepository.getSettings();
if (!settings.enabled) {
return { valid: false, reason: 'program_disabled' };
}
const referrer = await referralRepository.findUserByReferralCode(trimmed); const referrer = await referralRepository.findUserByReferralCode(trimmed);
if (!referrer) if (!referrer)
return { valid: false }; return { valid: false, reason: 'unknown_code' };
try {
await assertReferrerEligible(referrer.id);
}
catch (e) {
const reason = e instanceof ReferralError ? e.message : 'Referrer account is not eligible';
return { valid: false, reason };
}
return { valid: true, referrerId: referrer.id }; return { valid: true, referrerId: referrer.id };
} }
async function resolveReferrerId(referralCode) { async function resolveReferrerId(referralCode) {
@ -119,12 +131,14 @@ async function resolveReferrerId(referralCode) {
if (!settings.enabled) if (!settings.enabled)
return null; return null;
const trimmed = referralCode?.trim(); const trimmed = referralCode?.trim();
if (trimmed) { if (!trimmed) {
const referrer = await referralRepository.findUserByReferralCode(trimmed);
if (referrer)
return referrer.id;
}
return settings.default_referrer_user_id; return settings.default_referrer_user_id;
}
const referrer = await referralRepository.findUserByReferralCode(trimmed);
if (!referrer) {
throw new ReferralError('Invalid referral code');
}
return referrer.id;
} }
/** /**
* Bootstraps the referral network root during initial platform setup. * Bootstraps the referral network root during initial platform setup.
@ -900,8 +914,7 @@ async function getUserReferralInfo(userId) {
const rows = await (0, connection_1.query)('SELECT referral_code FROM users WHERE id = $1', [userId]); const rows = await (0, connection_1.query)('SELECT referral_code FROM users WHERE id = $1', [userId]);
const code = rows[0]?.referral_code ?? null; const code = rows[0]?.referral_code ?? null;
const settings = await referralRepository.getSettings(); const settings = await referralRepository.getSettings();
const baseUrl = process.env.PUBLIC_WEB_URL || 'http://localhost:5173'; const referralLink = code ? (0, publicWebUrl_1.buildReferralRegisterLink)(code) : '';
const referralLink = code ? `${baseUrl}/register?ref=${encodeURIComponent(code)}` : '';
const directReferrals = await referralRepository.countDirectReferrals(userId); const directReferrals = await referralRepository.countDirectReferrals(userId);
return { return {
referralCode: code, referralCode: code,

File diff suppressed because one or more lines are too long

View File

@ -48,4 +48,43 @@ const defaultRules = {
strict_1.default.equal(outcome.type, 'long_win'); strict_1.default.equal(outcome.type, 'long_win');
}); });
}); });
(0, node_test_1.describe)('resolveAutoNoBetOutcome consecutive direction cap', () => {
(0, node_test_1.test)('counts consecutive directional outcomes from newest', () => {
const { type, count } = (0, candleGenerationService_1.countConsecutiveDirectionalOutcomes)([
'long_win',
'long_win',
'long_win',
'short_win',
]);
strict_1.default.equal(type, 'long_win');
strict_1.default.equal(count, 3);
});
(0, node_test_1.test)('forces opposite direction after 5 consecutive same outcomes', () => {
const recent = [
'short_win',
'short_win',
'short_win',
'short_win',
'short_win',
];
const outcome = (0, candleGenerationService_1.resolveAutoNoBetOutcome)([...recent]);
strict_1.default.equal(outcome.type, 'long_win');
strict_1.default.equal(outcome.winner, 'long');
});
(0, node_test_1.test)('does not force flip before 5 consecutive', () => {
const recent = ['long_win', 'long_win', 'long_win', 'long_win'];
let sawLong = false;
let sawShort = false;
for (let i = 0; i < 40; i++) {
const outcome = (0, candleGenerationService_1.resolveAutoNoBetOutcome)([...recent]);
if (outcome.type === 'long_win')
sawLong = true;
if (outcome.type === 'short_win')
sawShort = true;
if (sawLong && sawShort)
break;
}
strict_1.default.equal(sawLong && sawShort, true);
});
});
//# sourceMappingURL=candleGenerationService.test.js.map //# sourceMappingURL=candleGenerationService.test.js.map

View File

@ -1 +1 @@
{"version":3,"file":"candleGenerationService.test.js","sourceRoot":"","sources":["../../src/tests/candleGenerationService.test.ts"],"names":[],"mappings":";;;;;AAAA,yCAA2C;AAC3C,gEAAwC;AACxC,iFAG6C;AAE7C,MAAM,YAAY,GAAwB;IACxC,mBAAmB,EAAE,CAAC;IACtB,mBAAmB,EAAE,EAAE;IACvB,mBAAmB,EAAE,IAAI;IACzB,mBAAmB,EAAE,IAAI;CAC1B,CAAC;AAEF,IAAA,oBAAQ,EAAC,qCAAqC,EAAE,GAAG,EAAE;IACnD,IAAA,gBAAI,EAAC,8DAA8D,EAAE,GAAG,EAAE;QACxE,MAAM,OAAO,GAAG,IAAA,4CAAkB,EAAC,EAAE,EAAE,EAAE,EAAE,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C,CAAC,CAAC;IAEH,IAAA,gBAAI,EAAC,6DAA6D,EAAE,GAAG,EAAE;QACvE,MAAM,MAAM,GAAG;YACb,WAAW;YACX,WAAW;YACX,WAAW;YACX,WAAW;YACX,WAAW;SACH,CAAC;QACX,MAAM,OAAO,GAAG,IAAA,iDAAuB,EAAC,CAAC,GAAG,MAAM,CAAC,CAAC,CAAC;QACrD,gBAAM,CAAC,KAAK,CAAC,OAAO,CAAC,IAAI,EAAE,UAAU,CAAC,CAAC;QACvC,gBAAM,CAAC,KAAK,CAAC,OAAO,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACvC,CAAC,CAAC,CAAC;IAEH,IAAA,gBAAI,EAAC,0CAA0C,EAAE,GAAG,EAAE;QACpD,MAAM,MAAM,GAAG,CAAC,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,CAAU,CAAC;QACzE,IAAI,OAAO,GAAG,KAAK,CAAC;QACpB,IAAI,QAAQ,GAAG,KAAK,CAAC;QACrB,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,EAAE,EAAE,CAAC,EAAE,EAAE,CAAC;YAC5B,MAAM,OAAO,GAAG,IAAA,iDAAuB,EAAC,CAAC,GAAG,MAAM,CAAC,CAAC,CAAC;YACrD,IAAI,OAAO,CAAC,IAAI,KAAK,UAAU;gBAAE,OAAO,GAAG,IAAI,CAAC;YAChD,IAAI,OAAO,CAAC,IAAI,KAAK,WAAW;gBAAE,QAAQ,GAAG,IAAI,CAAC;YAClD,IAAI,OAAO,IAAI,QAAQ;gBAAE,MAAM;QACjC,CAAC;QACD,gBAAM,CAAC,KAAK,CAAC,OAAO,IAAI,QAAQ,EAAE,IAAI,CAAC,CAAC;IAC1C,CAAC,CAAC,CAAC;AACL,CAAC,CAAC,CAAC"}

View File

@ -33,6 +33,8 @@
"rotate-encryption-key": "ts-node --transpile-only src/scripts/rotateEncryptionKey.ts", "rotate-encryption-key": "ts-node --transpile-only src/scripts/rotateEncryptionKey.ts",
"rotate-encryption-key:prod": "node dist/scripts/rotateEncryptionKey.js", "rotate-encryption-key:prod": "node dist/scripts/rotateEncryptionKey.js",
"test": "npm run build && cross-env NODE_ENV=test node --test dist/tests/*.test.js", "test": "npm run build && cross-env NODE_ENV=test node --test dist/tests/*.test.js",
"test:e2e": "npm run build && cross-env NODE_ENV=test node --test dist/tests/mobileApiE2e.test.js",
"test:e2e:db": "npm run build && cross-env RUN_DB_TESTS=1 NODE_ENV=test node --test dist/tests/mobileApiE2e.db.test.js",
"test:db": "node scripts/runDbTests.js" "test:db": "node scripts/runDbTests.js"
}, },
"dependencies": { "dependencies": {

View File

@ -23,7 +23,10 @@ import {
} from '../services/referralService'; } from '../services/referralService';
import { scheduleAnalyticsMaterializedViewRefresh } from '../utils/analyticsMaterializedViews'; import { scheduleAnalyticsMaterializedViewRefresh } from '../utils/analyticsMaterializedViews';
import { scheduleEncryptionKeyRotationReminder } from '../services/encryptionRotationReminderService'; import { scheduleEncryptionKeyRotationReminder } from '../services/encryptionRotationReminderService';
import { validateTestnetSafetyOrThrow } from '../safety/networkGuard'; import {
validateProductionMainnetOrThrow,
validateTestnetSafetyOrThrow,
} from '../safety/networkGuard';
import { validateProductionSecretsOrThrow } from '../safety/productionSecretsGuard'; import { validateProductionSecretsOrThrow } from '../safety/productionSecretsGuard';
import { connectRedis } from '../realtime/redis/client'; import { connectRedis } from '../realtime/redis/client';
@ -138,6 +141,7 @@ export async function bootstrapCore(opts: BootstrapOptions = {}): Promise<void>
} = opts; } = opts;
validateTestnetSafetyOrThrow(); validateTestnetSafetyOrThrow();
validateProductionMainnetOrThrow();
validateProductionSecretsOrThrow(); validateProductionSecretsOrThrow();
if (runDevMigrations) { if (runDevMigrations) {

View File

@ -51,10 +51,17 @@ export async function register(req: Request, res: Response): Promise<void> {
res.status(201).json({ res.status(201).json({
message: message:
'Registered. Please check your email and click the verification link before signing in.', 'Registered. Please check your email and click the verification link before signing in.',
userId: result.userId,
referralCode: result.referralCode,
emailVerificationRequired: result.emailVerificationRequired, emailVerificationRequired: result.emailVerificationRequired,
}); });
} catch (e) { } catch (e) {
res.status(400).json({ error: clientErrorMessage(e, 'Registration failed') }); const msg = clientErrorMessage(e, 'Registration failed');
const status =
msg === 'Email is already registered' || msg === 'Phone number already registered'
? 409
: 400;
res.status(status).json({ error: msg });
} }
} }

View File

@ -213,6 +213,11 @@ export async function getMyBets(req: AuthRequest, res: Response): Promise<void>
const intervalMinutes = parseIntervalMinutes(req.query.intervalMinutes); 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( const predictions = await candlePredictService.getRecentPredictions(
req.user.userId, req.user.userId,
@ -221,7 +226,9 @@ export async function getMyBets(req: AuthRequest, res: Response): Promise<void>
pageSize, pageSize,
intervalMinutes intervalMinutes,
{ stakeAccountKind, status }
); );

View File

@ -13,7 +13,6 @@ import { AuthRequest } from '../middleware/auth';
* @param res - JSON `{ transactionId, status }` on success, 400 on validation or transfer failure. * @param res - JSON `{ transactionId, status }` on success, 400 on validation or transfer failure.
*/ */
export async function transfer(req: AuthRequest, res: Response): Promise<void> { export async function transfer(req: AuthRequest, res: Response): Promise<void> {
try {
const userId = req.user!.userId; const userId = req.user!.userId;
const { toEmail, walletType, amount, totpCode } = req.body; const { toEmail, walletType, amount, totpCode } = req.body;
if (!toEmail || !walletType || amount == null) { if (!toEmail || !walletType || amount == null) {
@ -26,11 +25,7 @@ export async function transfer(req: AuthRequest, res: Response): Promise<void> {
toEmail, toEmail,
walletType, walletType,
amountRaw, amountRaw,
req.body.totpCode totpCode
); );
res.json({ transactionId, status }); res.json({ transactionId, status });
} catch (e) {
const msg = e instanceof Error ? e.message : 'Transfer failed';
res.status(400).json({ error: msg });
}
} }

View File

@ -34,15 +34,15 @@ export async function updateMe(req: AuthRequest, res: Response): Promise<void> {
const { firstName, middleName, lastName, dateOfBirth, email, phone, countryOfResidence, nationality, gender } = const { firstName, middleName, lastName, dateOfBirth, email, phone, countryOfResidence, nationality, gender } =
req.body; req.body;
await authService.updateProfile(userId, { await authService.updateProfile(userId, {
firstName: firstName ?? undefined, ...(firstName !== undefined ? { firstName } : {}),
middleName: middleName ?? undefined, ...(middleName !== undefined ? { middleName } : {}),
lastName: lastName ?? undefined, ...(lastName !== undefined ? { lastName } : {}),
dateOfBirth: dateOfBirth ?? undefined, ...(dateOfBirth !== undefined ? { dateOfBirth } : {}),
email: email ?? undefined, ...(email !== undefined ? { email } : {}),
phone: phone !== undefined ? phone : undefined, ...(phone !== undefined ? { phone } : {}),
countryOfResidence: countryOfResidence !== undefined ? countryOfResidence : undefined, ...(countryOfResidence !== undefined ? { countryOfResidence } : {}),
nationality: nationality !== undefined ? nationality : undefined, ...(nationality !== undefined ? { nationality } : {}),
gender: gender !== undefined ? gender : undefined, ...(gender !== undefined ? { gender } : {}),
}); });
res.json({ message: 'Profile updated' }); res.json({ message: 'Profile updated' });
} catch (e) { } catch (e) {

View File

@ -74,7 +74,10 @@ export async function getTransactions(req: AuthRequest, res: Response): Promise<
req.query.paginated === 'true' || req.query.paginated === '1'; req.query.paginated === 'true' || req.query.paginated === '1';
const categoryRaw = req.query.category as string | undefined; const categoryRaw = req.query.category as string | undefined;
const category = const category =
categoryRaw === 'deposits' || categoryRaw === 'withdrawals' || categoryRaw === 'predictions' categoryRaw === 'deposits' ||
categoryRaw === 'withdrawals' ||
categoryRaw === 'transfers' ||
categoryRaw === 'predictions'
? categoryRaw ? categoryRaw
: undefined; : undefined;
if (paginated) { if (paginated) {

View File

@ -4,7 +4,6 @@
import { Response } from 'express'; import { Response } from 'express';
import * as withdrawalService from '../services/withdrawalService'; import * as withdrawalService from '../services/withdrawalService';
import { SecurityBlockedError } from '../services/withdrawalService';
import { AuthRequest } from '../middleware/auth'; import { AuthRequest } from '../middleware/auth';
/** /**
@ -14,7 +13,6 @@ import { AuthRequest } from '../middleware/auth';
* @param res - JSON `{ transactionId, status }` on success, 400 on validation or withdrawal failure. * @param res - JSON `{ transactionId, status }` on success, 400 on validation or withdrawal failure.
*/ */
export async function withdraw(req: AuthRequest, res: Response): Promise<void> { export async function withdraw(req: AuthRequest, res: Response): Promise<void> {
try {
const userId = req.user!.userId; const userId = req.user!.userId;
const { walletType, toAddress, amount } = req.body; const { walletType, toAddress, amount } = req.body;
if (!walletType || !toAddress || amount == null) { if (!walletType || !toAddress || amount == null) {
@ -30,9 +28,4 @@ export async function withdraw(req: AuthRequest, res: Response): Promise<void> {
req.body.totpCode req.body.totpCode
); );
res.json(result); res.json(result);
} catch (e) {
const msg = e instanceof Error ? e.message : 'Withdrawal failed';
const status = e instanceof SecurityBlockedError ? 403 : 400;
res.status(status).json({ error: msg });
}
} }

View File

@ -1003,12 +1003,16 @@ INSERT INTO advertisements (placement, title, subtitle, cta_label, link_url, bac
SELECT * FROM (VALUES SELECT * FROM (VALUES
('home_hero', 'Welcome bonus', 'Deposit today and get a 100% match up to $50 on your first wallet top-up.', 'Fund wallet', '/wallet', 'linear-gradient(135deg, rgba(214,178,94,0.35) 0%, rgba(124,92,255,0.25) 100%)', '#D6B25E', TRUE, 1), ('home_hero', 'Welcome bonus', 'Deposit today and get a 100% match up to $50 on your first wallet top-up.', 'Fund wallet', '/wallet', 'linear-gradient(135deg, rgba(214,178,94,0.35) 0%, rgba(124,92,255,0.25) 100%)', '#D6B25E', TRUE, 1),
('home_hero', 'Daily spin', 'Spin the wheel every 24h for free credits and bonus multipliers.', 'Play now', '/home', 'linear-gradient(135deg, rgba(124,92,255,0.35) 0%, rgba(41,182,246,0.2) 100%)', '#7C5CFF', TRUE, 2), ('home_hero', 'Daily spin', 'Spin the wheel every 24h for free credits and bonus multipliers.', 'Play now', '/home', 'linear-gradient(135deg, rgba(124,92,255,0.35) 0%, rgba(41,182,246,0.2) 100%)', '#7C5CFF', TRUE, 2),
('home_hero', 'Weekend tournament', 'Compete on the Candle Predict leaderboard. Top players share the prize pool.', 'Join tournament', '/games/candle-predict', 'linear-gradient(135deg, rgba(76,175,80,0.3) 0%, rgba(214,178,94,0.2) 100%)', '#4CAF50', TRUE, 3), ('home_hero', 'Weekend tournament', 'Compete on the Candle Predict leaderboard. Top players share the prize pool.', 'Join tournament', '/games/candle-predict', 'linear-gradient(135deg, rgba(76,175,80,0.3) 0%, rgba(214,178,94,0.2) 100%)', '#4CAF50', TRUE, 3)
('home_strip', 'Secure wallet', 'USDT (TRC20) deposits with real-time balance tracking.', 'Open wallet', '/wallet', NULL, '#D6B25E', TRUE, 1),
('home_strip', 'Verify your email', 'Unlock full platform features and faster withdrawals.', 'Verify now', '/profile', NULL, '#7C5CFF', TRUE, 2)
) AS v(placement, title, subtitle, cta_label, link_url, background_gradient, accent_color, is_active, sort_order) ) AS v(placement, title, subtitle, cta_label, link_url, background_gradient, accent_color, is_active, sort_order)
WHERE NOT EXISTS (SELECT 1 FROM advertisements LIMIT 1); WHERE NOT EXISTS (SELECT 1 FROM advertisements LIMIT 1);
-- Mobile home no longer shows redundant strip promos (wallet / email verify).
UPDATE advertisements
SET is_active = FALSE
WHERE placement = 'home_strip'
AND title IN ('Secure wallet', 'Verify your email');
-- Dev cleanup: remove legacy TRX / USDC wallet types (platform is USDT-only) -- Dev cleanup: remove legacy TRX / USDC wallet types (platform is USDT-only)
DO $$ DO $$
DECLARE DECLARE
@ -1042,10 +1046,6 @@ BEGIN
END IF; END IF;
END $$; END $$;
UPDATE advertisements
SET subtitle = 'USDT (TRC20) deposits with real-time balance tracking.'
WHERE placement = 'home_strip' AND title = 'Secure wallet';
-- Denormalized admin list stats (refreshed incrementally + batch backfill) -- Denormalized admin list stats (refreshed incrementally + batch backfill)
CREATE TABLE IF NOT EXISTS user_admin_stats ( CREATE TABLE IF NOT EXISTS user_admin_stats (
user_id UUID PRIMARY KEY REFERENCES users(id) ON DELETE CASCADE, user_id UUID PRIMARY KEY REFERENCES users(id) ON DELETE CASCADE,

View File

@ -135,8 +135,9 @@ function validateStakeLimits(minStakeAmount: number, maxStakeAmount: number): vo
} }
function parseStakeDisplay(body: Record<string, unknown>, fallback: number): number { function parseStakeDisplay(body: Record<string, unknown>, fallback: number): number {
if (body.stakeDisplay !== undefined) { const raw = body.stakeDisplay ?? body.stakeAmount ?? body.stake_amount;
return parseStakeAmountFromBody(body.stakeDisplay); if (raw !== undefined) {
return parseStakeAmountFromBody(raw);
} }
return fallback; return fallback;
} }
@ -996,7 +997,6 @@ async function backfillMissedAutoCandles(
if (nextOpen > lastCompletedOpen) return; if (nextOpen > lastCompletedOpen) return;
let recentOutcomes = await repo.listRecentCandleOutcomes(interval.intervalMinutes, 10);
let processed = 0; let processed = 0;
for ( for (
@ -1007,8 +1007,8 @@ async function backfillMissedAutoCandles(
if (!isMaturityBoundaryForInterval(openMs, interval.intervalMinutes)) continue; if (!isMaturityBoundaryForInterval(openMs, interval.intervalMinutes)) continue;
if (await repo.hasCandle(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); await settleMaturityAtOpenMs(openMs, cfg);
recentOutcomes = await repo.listRecentCandleOutcomes(interval.intervalMinutes, 10);
processed += 1; processed += 1;
} }
} }
@ -1143,24 +1143,40 @@ async function settleMaturityAtOpenMs(
multiFinalPoolLong: multiContributions.longPool, multiFinalPoolLong: multiContributions.longPool,
}); });
let outcome: RoundOutcome;
const { shortPool, longPool } = await multiService.buildMaturityPools(candleOpenMs); const { shortPool, longPool } = await multiService.buildMaturityPools(candleOpenMs);
const primary = const primary =
aligning.find((i) => i.intervalMinutes === 1) ?? aligning.find((i) => i.intervalMinutes === 1) ??
aligning.sort((a, b) => a.intervalMinutes - b.intervalMinutes)[0]; 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>();
if (outcomeMode === 'pool') { if (outcomeMode === 'pool') {
const neutralityRules = buildPoolNeutralityRules(cfg, primary); const neutralityRules = buildPoolNeutralityRules(cfg, primary);
outcome = resolvePoolOutcome( const shared = resolvePoolOutcome(
shortPool, shortPool,
longPool, longPool,
neutralityRules, neutralityRules,
parsePoolWinnerRule(cfg.pool_winner_rule) parsePoolWinnerRule(cfg.pool_winner_rule)
); );
} else { for (const interval of aligning) {
const recentOutcomes = await repo.listRecentCandleOutcomes(primary.intervalMinutes, 10); outcomesByIntervalMinutes.set(interval.intervalMinutes, shared);
outcome = resolveAutoNoBetOutcome(recentOutcomes);
} }
} 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) { for (const interval of aligning) {
let round = await repo.getRoundByOpenMs(candleOpenMs, interval.intervalMinutes); let round = await repo.getRoundByOpenMs(candleOpenMs, interval.intervalMinutes);
@ -1172,14 +1188,18 @@ async function settleMaturityAtOpenMs(
} }
if (pendingCount > 0) { if (pendingCount > 0) {
await payOutBetsAtMaturity(candleOpenMs, outcome, cfg); await payOutBetsAtMaturity(candleOpenMs, outcomeForInterval, cfg);
} }
if (multiValidationCount > 0) { if (multiValidationCount > 0) {
const levelRows = await repo.listMultiLevels(); const levelRows = await repo.listMultiLevels();
const payoutMultiplierMap = new Map( const payoutMultiplierMap = new Map(
levelRows.map((l) => [l.level, Number(l.payout_multiplier)]) levelRows.map((l) => [l.level, Number(l.payout_multiplier)])
); );
await multiService.processMultiBetsAtMaturity(candleOpenMs, outcome, payoutMultiplierMap); await multiService.processMultiBetsAtMaturity(
candleOpenMs,
outcomeForInterval,
payoutMultiplierMap
);
} }
for (const interval of aligning) { for (const interval of aligning) {
@ -1192,7 +1212,7 @@ async function settleMaturityAtOpenMs(
await finalizeIntervalCandleAtMaturity( await finalizeIntervalCandleAtMaturity(
round, round,
interval, interval,
outcome, outcomeForInterval(interval.intervalMinutes),
shortPool, shortPool,
longPool longPool
); );
@ -1288,7 +1308,7 @@ async function finalizeIntervalCandleAtMaturity(
async function payOutBetsAtMaturity( async function payOutBetsAtMaturity(
candleOpenMs: number, candleOpenMs: number,
outcome: RoundOutcome, outcomeForInterval: (intervalMinutes: number) => RoundOutcome,
cfg: repo.CandlePredictConfigRow cfg: repo.CandlePredictConfigRow
): Promise<void> { ): Promise<void> {
const bets = await repo.listPendingBetsForMaturity(candleOpenMs); const bets = await repo.listPendingBetsForMaturity(candleOpenMs);
@ -1296,6 +1316,7 @@ async function payOutBetsAtMaturity(
const intervalMap = new Map(allIntervals.map((i) => [i.intervalMinutes, i])); const intervalMap = new Map(allIntervals.map((i) => [i.intervalMinutes, i]));
for (const bet of bets) { for (const bet of bets) {
const outcome = outcomeForInterval(bet.interval_minutes);
const interval = const interval =
intervalMap.get(bet.interval_minutes) ?? intervalMap.get(bet.interval_minutes) ??
({ ({
@ -1331,6 +1352,7 @@ async function payOutBetsAtMaturity(
round_id: bet.round_id, round_id: bet.round_id,
candle_open_ms: candleOpenMs, candle_open_ms: candleOpenMs,
outcome: 'neutral', outcome: 'neutral',
stake_account_kind: parseStakeAccountKind(bet.stake_account_kind),
}, },
}); });
queueUserAdminStatsRefresh(bet.user_id); queueUserAdminStatsRefresh(bet.user_id);
@ -1364,6 +1386,7 @@ async function payOutBetsAtMaturity(
round_id: bet.round_id, round_id: bet.round_id,
candle_open_ms: candleOpenMs, candle_open_ms: candleOpenMs,
outcome: outcome.type, outcome: outcome.type,
stake_account_kind: parseStakeAccountKind(bet.stake_account_kind),
}, },
}); });
} else { } else {
@ -1621,6 +1644,7 @@ export async function executePlaceBetInternal(
round_id: round.id, round_id: round.id,
direction: input.direction, direction: input.direction,
interval_minutes: interval.intervalMinutes, interval_minutes: interval.intervalMinutes,
stake_account_kind: stakeAccountKind,
}, },
}); });
@ -1639,7 +1663,17 @@ export async function executePlaceBetInternal(
queueUserAdminStatsRefresh(userId); queueUserAdminStatsRefresh(userId);
return mapBet(bet); const mapped = mapBet(bet);
if (config.redis.enabled) {
await publishUserEvent(userId, {
type: 'bet.accepted',
payload: {
bet: mapped as unknown as Record<string, unknown>,
},
});
}
return mapped;
} }
export type PlaceBetOptions = { export type PlaceBetOptions = {
@ -1744,14 +1778,17 @@ export async function getRecentPredictions(
userId: string, userId: string,
page = 1, page = 1,
pageSize = 10, pageSize = 10,
intervalMinutes?: number intervalMinutes?: number,
filters?: { stakeAccountKind?: string; status?: string }
) { ) {
const safePage = Math.max(1, page); const safePage = Math.max(1, page);
const safeSize = Math.min(50, Math.max(1, pageSize)); const safeSize = Math.min(50, Math.max(1, pageSize));
const offset = (safePage - 1) * safeSize; const offset = (safePage - 1) * safeSize;
const stakeAccountKind = filters?.stakeAccountKind;
const status = filters?.status;
const [rows, total] = await Promise.all([ const [rows, total] = await Promise.all([
repo.listRecentBets(userId, safeSize, offset, intervalMinutes), repo.listRecentBets(userId, safeSize, offset, intervalMinutes, stakeAccountKind, status),
repo.countUserPredictions(userId, intervalMinutes), repo.countUserPredictions(userId, intervalMinutes, stakeAccountKind, status),
]); ]);
return { return {
items: rows.map(mapBet), items: rows.map(mapBet),
@ -2021,6 +2058,7 @@ export async function placeMultiCandleBet(
multi_level: input.level, multi_level: input.level,
sequence: input.sequence, sequence: input.sequence,
interval_minutes: interval.intervalMinutes, interval_minutes: interval.intervalMinutes,
stake_account_kind: stakeAccountKind,
}, },
}); });

View File

@ -793,44 +793,67 @@ export async function listRecentBets(
userId: string, userId: string,
limit = 20, limit = 20,
offset = 0, offset = 0,
intervalMinutes?: number intervalMinutes?: number,
stakeAccountKind?: string,
status?: string
): Promise<Array<CandlePredictBetRow & { candle_open_ms: string }>> { ): Promise<Array<CandlePredictBetRow & { candle_open_ms: string }>> {
const where: string[] = ['b.user_id = $1'];
const params: unknown[] = [userId];
if (intervalMinutes != null) { if (intervalMinutes != null) {
return query( params.push(intervalMinutes);
`SELECT b.*, r.candle_open_ms where.push(`b.interval_minutes = $${params.length}`);
FROM candle_predict_bets b
INNER JOIN candle_predict_rounds r ON r.id = b.round_id
WHERE b.user_id = $1 AND b.interval_minutes = $4
ORDER BY b.created_at DESC
LIMIT $2 OFFSET $3`,
[userId, limit, offset, intervalMinutes]
);
} }
if (stakeAccountKind === 'main' || stakeAccountKind === 'bonus' || stakeAccountKind === 'test') {
params.push(stakeAccountKind);
where.push(`b.stake_account_kind = $${params.length}`);
}
if (status && ['pending', 'in_progress', 'won', 'lost', 'refunded'].includes(status)) {
params.push(status);
where.push(`b.status = $${params.length}`);
}
params.push(limit);
const limitIdx = params.length;
params.push(offset);
const offsetIdx = params.length;
return query( return query(
`SELECT b.*, r.candle_open_ms `SELECT b.*, r.candle_open_ms
FROM candle_predict_bets b FROM candle_predict_bets b
INNER JOIN candle_predict_rounds r ON r.id = b.round_id INNER JOIN candle_predict_rounds r ON r.id = b.round_id
WHERE b.user_id = $1 WHERE ${where.join(' AND ')}
ORDER BY b.created_at DESC ORDER BY b.created_at DESC
LIMIT $2 OFFSET $3`, LIMIT $${limitIdx} OFFSET $${offsetIdx}`,
[userId, limit, offset] params
); );
} }
export async function countUserPredictions( export async function countUserPredictions(
userId: string, userId: string,
intervalMinutes?: number intervalMinutes?: number,
stakeAccountKind?: string,
status?: string
): Promise<number> { ): Promise<number> {
const where: string[] = ['user_id = $1'];
const params: unknown[] = [userId];
if (intervalMinutes != null) { if (intervalMinutes != null) {
const rows = await query<{ count: string }[]>( params.push(intervalMinutes);
'SELECT COUNT(*)::text AS count FROM candle_predict_bets WHERE user_id = $1 AND interval_minutes = $2', where.push(`interval_minutes = $${params.length}`);
[userId, intervalMinutes]
);
return Number(rows[0]?.count ?? 0);
} }
if (stakeAccountKind === 'main' || stakeAccountKind === 'bonus' || stakeAccountKind === 'test') {
params.push(stakeAccountKind);
where.push(`stake_account_kind = $${params.length}`);
}
if (status && ['pending', 'in_progress', 'won', 'lost', 'refunded'].includes(status)) {
params.push(status);
where.push(`status = $${params.length}`);
}
const rows = await query<{ count: string }[]>( const rows = await query<{ count: string }[]>(
'SELECT COUNT(*)::text AS count FROM candle_predict_bets WHERE user_id = $1', `SELECT COUNT(*)::text AS count FROM candle_predict_bets WHERE ${where.join(' AND ')}`,
[userId] params
); );
return Number(rows[0]?.count ?? 0); return Number(rows[0]?.count ?? 0);
} }

View File

@ -3,20 +3,16 @@ import { PoolClient } from 'pg';
import { Transaction } from '../models'; import { Transaction } from '../models';
/** Wallet activity tabs on the player UI. */ /** Wallet activity tabs on the player UI. */
export type TransactionActivityCategory = 'deposits' | 'withdrawals' | 'predictions'; export type TransactionActivityCategory = 'deposits' | 'withdrawals' | 'transfers' | 'predictions';
function activityCategoryFilter(category?: TransactionActivityCategory): string { function activityCategoryFilter(category?: TransactionActivityCategory): string {
switch (category) { switch (category) {
case 'deposits': case 'deposits':
return ` AND ( return ` AND type IN ('deposit', 'bonus', 'admin_adjustment')`;
type IN ('deposit', 'bonus', 'admin_adjustment')
OR (type = 'transfer' AND COALESCE(metadata->>'direction', '') = 'in')
)`;
case 'withdrawals': case 'withdrawals':
return ` AND ( return ` AND type = 'withdrawal'`;
type = 'withdrawal' case 'transfers':
OR (type = 'transfer' AND COALESCE(metadata->>'direction', '') = 'out') return ` AND type = 'transfer'`;
)`;
case 'predictions': case 'predictions':
return ` AND type IN ('game_stake', 'game_payout', 'game_refund')`; return ` AND type IN ('game_stake', 'game_payout', 'game_refund')`;
default: default:

View File

@ -157,6 +157,10 @@ router.post('/faq/entries/:id/view', faqController.recordView);
router.post('/faq/entries/:id/helpful', optionalAuthMiddleware, validateBody(faqHelpfulBodySchema), faqController.recordHelpful); router.post('/faq/entries/:id/helpful', optionalAuthMiddleware, validateBody(faqHelpfulBodySchema), faqController.recordHelpful);
router.get('/faq/files/:filename', faqController.getFaqFile); router.get('/faq/files/:filename', faqController.getFaqFile);
/** Public marketing reads (landing / welcome) — catalogue only, no play/bets. */
router.get('/games', gameController.listGames);
router.get('/advertisements', advertisementController.listAdvertisements);
/** Support messaging — guests (visitor token) and optional authenticated users. */ /** Support messaging — guests (visitor token) and optional authenticated users. */
router.get('/support/files/:filename', supportController.getAttachment); router.get('/support/files/:filename', supportController.getAttachment);
router.post('/support/conversations/current', optionalAuthMiddleware, supportController.getOrCreateConversation); router.post('/support/conversations/current', optionalAuthMiddleware, supportController.getOrCreateConversation);
@ -212,7 +216,6 @@ router.post('/2fa/recovery/regenerate', authController.regenerateRecoveryCodes);
router.post('/withdraw', validateBody(withdrawBodySchema), auditAction('withdrawal_requested', 'wallet'), asyncHandler(withdrawalController.withdraw)); router.post('/withdraw', validateBody(withdrawBodySchema), auditAction('withdrawal_requested', 'wallet'), asyncHandler(withdrawalController.withdraw));
router.post('/transfer', validateBody(transferBodySchema), auditAction('transfer_requested', 'wallet'), asyncHandler(transferController.transfer)); router.post('/transfer', validateBody(transferBodySchema), auditAction('transfer_requested', 'wallet'), asyncHandler(transferController.transfer));
router.get('/games', gameController.listGames);
router.get('/games/candle-predict/state', candlePredictController.getState); router.get('/games/candle-predict/state', candlePredictController.getState);
router.get('/games/candle-predict/candles', candlePredictController.getCandles); router.get('/games/candle-predict/candles', candlePredictController.getCandles);
router.post('/games/candle-predict/bets', validateBody(candlePredictBetBodySchema), candlePredictController.placeBet); router.post('/games/candle-predict/bets', validateBody(candlePredictBetBodySchema), candlePredictController.placeBet);
@ -228,7 +231,6 @@ router.get('/games/:slug/auto', gamePlayController.getAutoSettings);
router.put('/games/:slug/auto', validateBody(candlePredictAutoBodySchema), gamePlayController.updateAutoSettings); router.put('/games/:slug/auto', validateBody(candlePredictAutoBodySchema), gamePlayController.updateAutoSettings);
router.get('/games/:slug/:customAction', gamePlayController.customGet); router.get('/games/:slug/:customAction', gamePlayController.customGet);
router.get('/games/:slug', gameController.getGame); router.get('/games/:slug', gameController.getGame);
router.get('/advertisements', advertisementController.listAdvertisements);
router.get('/admin/candle-predict/config', requireRoles('admin'), requirePermissions('games.admin'), candlePredictController.getAdminConfig); router.get('/admin/candle-predict/config', requireRoles('admin'), requirePermissions('games.admin'), candlePredictController.getAdminConfig);
router.patch('/admin/candle-predict/config', requireRoles('admin'), requirePermissions('games.admin'), validateBody(candlePredictAdminConfigBodySchema), candlePredictController.updateAdminConfig); router.patch('/admin/candle-predict/config', requireRoles('admin'), requirePermissions('games.admin'), validateBody(candlePredictAdminConfigBodySchema), candlePredictController.updateAdminConfig);

View File

@ -1,106 +1,105 @@
/** /**
* Blockchain network safety guards. * Blockchain network safety guards.
* - Non-production: blocks accidental mainnet usage when testnet is expected.
* Blocks accidental mainnet usage in non-production when testnet mode is expected. * - Production: blocks testnet endpoints/contracts so fake test USDT cannot be credited.
*/ */
import { config } from '../config'; import { config } from '../config';
/** Official mainnet USDT TRC20 (Tether). */
export const MAINNET_USDT_TRC20_CONTRACT = 'TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t';
/** Shasta testnet USDT TRC20 — must never be used in production. */
export const SHASTA_USDT_TRC20_CONTRACT = 'TG3XXyExBkPp9nzdajDZsozEu4BkaSJozs';
/** export type NetworkGuardConfig = {
env: string;
* Throws when a safety assertion fails. networkMode: string;
tronNodeUrl: string;
* @param condition Truthy when the check passes usdtTrc20Contract: string | null;
};
* @param message Error message when condition is false
*/
function assert(condition: boolean, message: string): void { function assert(condition: boolean, message: string): void {
if (!condition) throw new Error(message); if (!condition) throw new Error(message);
} }
/**
* Returns true when the URL appears to target TRON Shasta testnet.
* @param url TRON node URL
*/
function looksLikeShasta(url: string): boolean { function looksLikeShasta(url: string): boolean {
return /shasta/i.test(url); return /shasta/i.test(url);
} }
function looksLikeTronTestnet(url: string): boolean {
return /shasta|nile/i.test(url);
}
function isShastaUsdtContract(contract: string): boolean {
return contract.trim().toLowerCase() === SHASTA_USDT_TRC20_CONTRACT.toLowerCase();
}
/** /**
* Validates production blockchain settings (testable with explicit config).
* Validates that non-production runs use testnet endpoints and contracts. * @throws When production would use testnet TRON or Shasta USDT contract
*
* For the expected testnet setup:
* - TRON: Shasta (TRON_NODE_URL should include "shasta")
* - Asset: USDT TRC20 on Shasta
*
* Skipped in production or when NETWORK_MODE=mainnet.
* @throws When a configured URL or contract points at mainnet while testnet is required
*/ */
export function assertProductionMainnetConfig(cfg: NetworkGuardConfig): void {
if (cfg.env !== 'production') return;
assert(
cfg.networkMode !== 'testnet',
'Safety check failed: NETWORK_MODE=testnet is not allowed when NODE_ENV=production.'
);
assert(
!looksLikeTronTestnet(cfg.tronNodeUrl),
`Safety check failed: TRON_NODE_URL must not point to a TRON testnet in production. Got: ${cfg.tronNodeUrl}`
);
const contractOverride = cfg.usdtTrc20Contract?.trim() || '';
if (contractOverride) {
assert(
!isShastaUsdtContract(contractOverride),
`Safety check failed: USDT_TRC20_CONTRACT must not be the Shasta testnet token in production. ` +
`Use mainnet USDT (${MAINNET_USDT_TRC20_CONTRACT}) or unset USDT_TRC20_CONTRACT to use the DB default.`
);
}
}
/**
* Validates that non-production runs use testnet endpoints and contracts.
*
* For the expected testnet setup:
* - TRON: Shasta (TRON_NODE_URL should include "shasta")
* - Asset: USDT TRC20 on Shasta
*
* Skipped in production or when NETWORK_MODE=mainnet.
* @throws When a configured URL or contract points at mainnet while testnet is required
*/
export function validateTestnetSafetyOrThrow(): void { export function validateTestnetSafetyOrThrow(): void {
const mode = (process.env.NETWORK_MODE || '').toLowerCase();
const mode = (process.env.NETWORK_MODE || '').toLowerCase(); // "testnet" | "mainnet" | ""
const isProd = config.env === 'production'; const isProd = config.env === 'production';
// Default to strict safety in non-production unless explicitly running mainnet mode.
const requireTestnet = !isProd && mode !== 'mainnet'; const requireTestnet = !isProd && mode !== 'mainnet';
if (!requireTestnet) return; if (!requireTestnet) return;
assert( assert(
looksLikeShasta(config.blockchain.tron.nodeUrl), looksLikeShasta(config.blockchain.tron.nodeUrl),
`Safety check failed: TRON_NODE_URL must point to Shasta (expected "shasta" in URL). Got: ${config.blockchain.tron.nodeUrl}` `Safety check failed: TRON_NODE_URL must point to Shasta (expected "shasta" in URL). Got: ${config.blockchain.tron.nodeUrl}`
); );
assert( assert(
!!config.blockchain.tron.usdtTrc20Contract && config.blockchain.tron.usdtTrc20Contract.trim().length > 0, !!config.blockchain.tron.usdtTrc20Contract && config.blockchain.tron.usdtTrc20Contract.trim().length > 0,
'Safety check failed: USDT_TRC20_CONTRACT must be set for Shasta (testnet) so we do not use the mainnet default from DB.' 'Safety check failed: USDT_TRC20_CONTRACT must be set for Shasta (testnet) so we do not use the mainnet default from DB.'
); );
} }
/**
* Validates that production runs use mainnet TRON and never the Shasta USDT contract.
* Skipped when NODE_ENV is not production.
* @throws When TRON_NODE_URL or USDT_TRC20_CONTRACT targets testnet
*/
export function validateProductionMainnetOrThrow(): void {
assertProductionMainnetConfig({
env: config.env,
networkMode: (process.env.NETWORK_MODE || '').toLowerCase(),
tronNodeUrl: config.blockchain.tron.nodeUrl,
usdtTrc20Contract: config.blockchain.tron.usdtTrc20Contract,
});
}

View File

@ -183,12 +183,7 @@ export async function register(input: {
const emailHash = hashForIndex(normalizedEmail); const emailHash = hashForIndex(normalizedEmail);
const existing = await userRepository.findByEmailHash(emailHash); const existing = await userRepository.findByEmailHash(emailHash);
if (existing) { if (existing) {
await new Promise((resolve) => setTimeout(resolve, 200 + Math.floor(Math.random() * 200))); throw new Error('Email is already registered');
return {
userId: '',
referralCode: '',
emailVerificationRequired: policy.require_email_verification_for_login,
};
} }
let phoneHash: string | null = null; let phoneHash: string | null = null;

View File

@ -8,6 +8,39 @@ import { getTronWeb } from '../hdWallet';
const TRON_GRID_URL = process.env.TRON_NODE_URL || 'https://api.trongrid.io'; const TRON_GRID_URL = process.env.TRON_NODE_URL || 'https://api.trongrid.io';
const TRON_API_KEY = process.env.TRON_API_KEY || ''; const TRON_API_KEY = process.env.TRON_API_KEY || '';
/** PostgreSQL signed BIGINT upper bound. */
export const PG_BIGINT_MAX = 9223372036854775807n;
/**
* Parses a TRC20 transfer `value` from TronGrid into smallest token units.
* Rejects non-decimal strings, floats, negative values, and amounts that do not fit in PG BIGINT.
*/
export function parseTrc20TokenAmount(raw: unknown): bigint | null {
if (raw == null) return null;
let digits: string;
if (typeof raw === 'bigint') {
digits = raw.toString();
} else if (typeof raw === 'number') {
if (!Number.isFinite(raw) || raw <= 0 || !Number.isInteger(raw)) return null;
digits = raw.toString();
} else if (typeof raw === 'string') {
const s = raw.trim();
if (!/^\d+$/.test(s)) return null;
digits = s;
} else {
return null;
}
try {
const amount = BigInt(digits);
if (amount <= 0n || amount > PG_BIGINT_MAX) return null;
return amount;
} catch {
return null;
}
}
/** /**
* Performs an authenticated GET request to TronGrid REST API. * Performs an authenticated GET request to TronGrid REST API.
* @param path API path including query string (e.g. /v1/accounts/...) * @param path API path including query string (e.g. /v1/accounts/...)
@ -33,6 +66,24 @@ export async function getCurrentBlock(): Promise<number> {
return block.block_header.raw_data.number; return block.block_header.raw_data.number;
} }
/**
* Returns the block timestamp in Unix ms for a given block height.
*/
export async function getBlockTimestamp(blockNumber: number): Promise<number | null> {
if (!Number.isFinite(blockNumber) || blockNumber < 0) return null;
try {
const tronWeb = getTronWeb();
const trx = tronWeb.trx as typeof tronWeb.trx & {
getBlock(blockNumber: number): Promise<{ block_header?: { raw_data?: { timestamp?: number } } }>;
};
const block = await trx.getBlock(blockNumber);
const ts = block?.block_header?.raw_data?.timestamp;
return typeof ts === 'number' && ts > 0 ? ts : null;
} catch {
return null;
}
}
/** Incoming native TRX transfer parsed from TronGrid account transactions. */ /** Incoming native TRX transfer parsed from TronGrid account transactions. */
export interface TronIncomingTx { export interface TronIncomingTx {
txId: string; txId: string;
@ -140,7 +191,13 @@ export interface Trc20Transfer {
} }
interface TronGridTrc20Response { interface TronGridTrc20Response {
data?: Array<{ transaction_id: string; block_timestamp: number; from: string; to: string; value: string }>; data?: Array<{
transaction_id: string;
block_timestamp: number;
from: string;
to: string;
value: string | number;
}>;
} }
/** /**
@ -162,12 +219,21 @@ export async function getTrc20TransfersToAddress(address: string, contractAddres
const out: Trc20Transfer[] = []; const out: Trc20Transfer[] = [];
for (const e of data.data || []) { for (const e of data.data || []) {
if (e.to?.toLowerCase() !== address.toLowerCase()) continue; if (e.to?.toLowerCase() !== address.toLowerCase()) continue;
const amount = parseTrc20TokenAmount(e.value);
if (amount == null) {
if (process.env.NODE_ENV !== 'production') {
console.warn(
`[tron] TRC20: skip invalid amount for tx=${e.transaction_id} value=${String(e.value)}`
);
}
continue;
}
const confirmations = Math.max(0, Math.floor((Date.now() - e.block_timestamp) / 3000)); const confirmations = Math.max(0, Math.floor((Date.now() - e.block_timestamp) / 3000));
out.push({ out.push({
txId: e.transaction_id, txId: e.transaction_id,
from: e.from, from: e.from,
to: e.to, to: e.to,
value: e.value, value: amount.toString(),
block: 0, block: 0,
block_timestamp: e.block_timestamp, block_timestamp: e.block_timestamp,
confirmations, confirmations,

View File

@ -158,6 +158,7 @@ export function mapMultiBet(row: repo.CandlePredictBetRow) {
level: row.multi_level ?? 0, level: row.multi_level ?? 0,
sequenceDirections: parseSequenceDirections(row.sequence_directions), sequenceDirections: parseSequenceDirections(row.sequence_directions),
sequenceStep: step, sequenceStep: step,
stakeAccountKind: parseStakeAccountKind(row.stake_account_kind),
anchorCandleOpenMs: anchorMs, anchorCandleOpenMs: anchorMs,
currentCandleOpenMs, currentCandleOpenMs,
createdAt: row.created_at.toISOString(), createdAt: row.created_at.toISOString(),
@ -181,13 +182,19 @@ export async function buildMaturityPools(candleOpenMs: number): Promise<{
export async function processMultiBetsAtMaturity( export async function processMultiBetsAtMaturity(
candleOpenMs: number, candleOpenMs: number,
outcome: RoundOutcome, outcomeForInterval: RoundOutcome | ((intervalMinutes: number) => RoundOutcome),
payoutMultiplierMap: Map<number, number> payoutMultiplierMap: Map<number, number>
): Promise<void> { ): Promise<void> {
const bets = await repo.listMultiBetsForValidationAtOpenMs(candleOpenMs); const bets = await repo.listMultiBetsForValidationAtOpenMs(candleOpenMs);
if (!bets.length) return; if (!bets.length) return;
const resolveOutcome =
typeof outcomeForInterval === 'function'
? outcomeForInterval
: (_intervalMinutes: number) => outcomeForInterval;
for (const bet of bets) { for (const bet of bets) {
const outcome = resolveOutcome(bet.interval_minutes);
const sequence = parseSequenceDirections(bet.sequence_directions); const sequence = parseSequenceDirections(bet.sequence_directions);
const level = bet.multi_level ?? sequence.length; const level = bet.multi_level ?? sequence.length;
const step = bet.sequence_step ?? 0; const step = bet.sequence_step ?? 0;
@ -221,6 +228,7 @@ export async function processMultiBetsAtMaturity(
candle_open_ms: candleOpenMs, candle_open_ms: candleOpenMs,
outcome: 'neutral', outcome: 'neutral',
prediction_mode: 'multi_candle', prediction_mode: 'multi_candle',
stake_account_kind: parseStakeAccountKind(bet.stake_account_kind),
}, },
}); });
queueUserAdminStatsRefresh(bet.user_id); queueUserAdminStatsRefresh(bet.user_id);
@ -289,6 +297,7 @@ export async function processMultiBetsAtMaturity(
prediction_mode: 'multi_candle', prediction_mode: 'multi_candle',
multi_level: level, multi_level: level,
payout_multiplier: payoutMultiplier, payout_multiplier: payoutMultiplier,
stake_account_kind: parseStakeAccountKind(bet.stake_account_kind),
}, },
}); });
queueUserAdminStatsRefresh(bet.user_id); queueUserAdminStatsRefresh(bet.user_id);

View File

@ -30,25 +30,32 @@ export async function processTronDeposits(): Promise<void> {
fromBlock = 0n; fromBlock = 0n;
} }
const userWallets = await query<Array<{ address: string; user_id: string }>>( const userWallets = await query<Array<{ address: string; user_id: string; created_at: Date }>>(
'SELECT address, user_id FROM user_wallets WHERE wallet_type_id = $1', 'SELECT address, user_id, created_at FROM user_wallets WHERE wallet_type_id = $1',
[walletType.id] [walletType.id]
); );
if (userWallets.length > 0) { if (userWallets.length > 0) {
const hasAnyUsdtTx = await query<{ n: string }[]>( // Only *deposit* rows count — game_stake/transfer/etc. must not block backfill,
'SELECT 1 as n FROM transactions WHERE wallet_type_id = $1 LIMIT 1', // otherwise a missed faucet transfer is never scanned again (forward-only cursor).
const hasAnyUsdtDeposit = await query<{ n: string }[]>(
`SELECT 1 as n FROM transactions WHERE wallet_type_id = $1 AND type = 'deposit' LIMIT 1`,
[walletType.id] [walletType.id]
).then((r) => r.length > 0); ).then((r) => r.length > 0);
if (!hasAnyUsdtTx && fromBlock > 0n) { if (!hasAnyUsdtDeposit && fromBlock > 0n) {
fromBlock = 0n; fromBlock = 0n;
if (process.env.NODE_ENV !== 'production') { if (process.env.NODE_ENV !== 'production') {
console.log('[deposit] USDT_TRC20: no deposits in DB yet, scanning from start'); console.log('[deposit] USDT_TRC20: no deposit txs in DB yet, scanning from start');
} }
} }
} }
const fromTimestamp = Number(fromBlock) * 3000; let scannerMinTimestamp = 0;
if (fromBlock > 0n) {
const blockTs = await tronService.getBlockTimestamp(Number(fromBlock));
if (blockTs != null) scannerMinTimestamp = blockTs;
}
const trc20Contract = const trc20Contract =
config.blockchain.tron.usdtTrc20Contract || walletType.contract_address || ''; config.blockchain.tron.usdtTrc20Contract || walletType.contract_address || '';
if (!trc20Contract) return; if (!trc20Contract) return;
@ -59,26 +66,39 @@ export async function processTronDeposits(): Promise<void> {
); );
} }
for (const { address, user_id } of userWallets) { for (const { address, user_id, created_at } of userWallets) {
const walletCreatedMs = new Date(created_at).getTime();
const minTimestamp = Math.max(scannerMinTimestamp, walletCreatedMs);
const transfers = await tronService.getTrc20TransfersToAddress( const transfers = await tronService.getTrc20TransfersToAddress(
address, address,
trc20Contract, trc20Contract,
fromTimestamp minTimestamp
); );
if (process.env.NODE_ENV !== 'production' && transfers.length > 0) { if (process.env.NODE_ENV !== 'production' && transfers.length > 0) {
console.log(`[deposit] USDT ${address}: ${transfers.length} transfer(s)`); console.log(`[deposit] USDT ${address}: ${transfers.length} transfer(s)`);
} }
for (const t of transfers) { for (const t of transfers) {
const amount = tronService.parseTrc20TokenAmount(t.value);
if (amount == null) {
if (process.env.NODE_ENV !== 'production') {
console.warn(`[deposit] USDT ${address}: skip invalid amount tx=${t.txId} value=${t.value}`);
}
continue;
}
if (t.confirmations >= TRON_CONFIRMATIONS) { if (t.confirmations >= TRON_CONFIRMATIONS) {
try {
await creditDeposit( await creditDeposit(
user_id, user_id,
walletType.id, walletType.id,
BigInt(t.value), amount,
t.txId, t.txId,
t.from, t.from,
address, address,
t.confirmations t.confirmations
); );
} catch (e) {
console.error(`[deposit] credit failed tx=${t.txId}:`, e);
}
} }
} }
} }

View File

@ -44,7 +44,7 @@ export async function checkEncryptionKeyRotationDue(): Promise<void> {
try { try {
await adminNotificationRepository.createNotification({ await adminNotificationRepository.createNotification({
severity: 'warning', severity: 'medium',
title: 'Encryption key rotation due', title: 'Encryption key rotation due',
body: message, body: message,
}); });

View File

@ -21,6 +21,7 @@ import { wouldExceedMonthlyCommissionCap, wouldExceedMonthlyCapAtSettlement, res
import { notifyReferralSlack } from './referralNotificationService'; import { notifyReferralSlack } from './referralNotificationService';
import { computeCommissionableWithdrawalBase } from './referralWithdrawalCommissionService'; import { computeCommissionableWithdrawalBase } from './referralWithdrawalCommissionService';
import { formatCountryCode, getCountryNameMap } from '../utils/countryFormat'; import { formatCountryCode, getCountryNameMap } from '../utils/countryFormat';
import { buildReferralRegisterLink } from '../utils/publicWebUrl';
import { maybeAutoSuspendForSybilFraud } from './fraudAutoBlockService'; import { maybeAutoSuspendForSybilFraud } from './fraudAutoBlockService';
export class ReferralError extends Error { export class ReferralError extends Error {
@ -84,11 +85,27 @@ export function isCommissionPendingExpired(createdAt: Date, maxPendingDays: numb
return now.getTime() >= expiresAt; return now.getTime() >= expiresAt;
} }
export async function validateReferralCode(code: string): Promise<{ valid: boolean; referrerId?: string }> { export async function validateReferralCode(
code: string
): Promise<{ valid: boolean; referrerId?: string; reason?: string }> {
const trimmed = code?.trim(); const trimmed = code?.trim();
if (!trimmed) return { valid: false }; if (!trimmed) return { valid: false, reason: 'empty' };
const settings = await referralRepository.getSettings();
if (!settings.enabled) {
return { valid: false, reason: 'program_disabled' };
}
const referrer = await referralRepository.findUserByReferralCode(trimmed); const referrer = await referralRepository.findUserByReferralCode(trimmed);
if (!referrer) return { valid: false }; if (!referrer) return { valid: false, reason: 'unknown_code' };
try {
await assertReferrerEligible(referrer.id);
} catch (e) {
const reason = e instanceof ReferralError ? e.message : 'Referrer account is not eligible';
return { valid: false, reason };
}
return { valid: true, referrerId: referrer.id }; return { valid: true, referrerId: referrer.id };
} }
@ -97,12 +114,16 @@ export async function resolveReferrerId(referralCode?: string | null): Promise<s
if (!settings.enabled) return null; if (!settings.enabled) return null;
const trimmed = referralCode?.trim(); const trimmed = referralCode?.trim();
if (trimmed) { if (!trimmed) {
const referrer = await referralRepository.findUserByReferralCode(trimmed); return settings.default_referrer_user_id;
if (referrer) return referrer.id;
} }
return settings.default_referrer_user_id; const referrer = await referralRepository.findUserByReferralCode(trimmed);
if (!referrer) {
throw new ReferralError('Invalid referral code');
}
return referrer.id;
} }
/** /**
@ -1161,8 +1182,7 @@ export async function getUserReferralInfo(userId: string): Promise<{
); );
const code = rows[0]?.referral_code ?? null; const code = rows[0]?.referral_code ?? null;
const settings = await referralRepository.getSettings(); const settings = await referralRepository.getSettings();
const baseUrl = process.env.PUBLIC_WEB_URL || 'http://localhost:5173'; const referralLink = code ? buildReferralRegisterLink(code) : '';
const referralLink = code ? `${baseUrl}/register?ref=${encodeURIComponent(code)}` : '';
const directReferrals = await referralRepository.countDirectReferrals(userId); const directReferrals = await referralRepository.countDirectReferrals(userId);
return { return {
referralCode: code, referralCode: code,

View File

@ -2,6 +2,8 @@ import { describe, test } from 'node:test';
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
import { import {
resolvePoolOutcome, resolvePoolOutcome,
resolveAutoNoBetOutcome,
countConsecutiveDirectionalOutcomes,
type PoolNeutralityRules, type PoolNeutralityRules,
} from '../services/candleGenerationService'; } from '../services/candleGenerationService';
@ -55,3 +57,42 @@ describe('resolvePoolOutcome neutrality rules', () => {
assert.equal(outcome.type, 'long_win'); assert.equal(outcome.type, 'long_win');
}); });
}); });
describe('resolveAutoNoBetOutcome consecutive direction cap', () => {
test('counts consecutive directional outcomes from newest', () => {
const { type, count } = countConsecutiveDirectionalOutcomes([
'long_win',
'long_win',
'long_win',
'short_win',
]);
assert.equal(type, 'long_win');
assert.equal(count, 3);
});
test('forces opposite direction after 5 consecutive same outcomes', () => {
const recent = [
'short_win',
'short_win',
'short_win',
'short_win',
'short_win',
] as const;
const outcome = resolveAutoNoBetOutcome([...recent]);
assert.equal(outcome.type, 'long_win');
assert.equal(outcome.winner, 'long');
});
test('does not force flip before 5 consecutive', () => {
const recent = ['long_win', 'long_win', 'long_win', 'long_win'] as const;
let sawLong = false;
let sawShort = false;
for (let i = 0; i < 40; i++) {
const outcome = resolveAutoNoBetOutcome([...recent]);
if (outcome.type === 'long_win') sawLong = true;
if (outcome.type === 'short_win') sawShort = true;
if (sawLong && sawShort) break;
}
assert.equal(sawLong && sawShort, true);
});
});

View File

@ -0,0 +1,67 @@
/**
* Database-backed E2E tests for mobile-facing public/read endpoints.
* Run with: npm run test:e2e:db (from backend/)
*/
import { test, describe, before } from 'node:test';
import assert from 'node:assert/strict';
import request from 'supertest';
import app from '../app';
import { config } from '../config';
import { runMigrations } from '../db/connection';
import { registerBuiltinGames } from '../games/bootstrap';
import { authHeader, createTestAccessToken } from './helpers/testAuth';
import { isDbTestEnabled } from './helpers/testDb';
const prefix = config.apiPrefix;
const dbDescribe = isDbTestEnabled() ? describe : describe.skip;
dbDescribe('mobile API E2E (database)', () => {
before(async () => {
registerBuiltinGames();
await runMigrations();
});
test('GET /health returns live settings from database', async () => {
const res = await request(app).get('/health');
assert.equal(res.status, 200);
assert.equal(res.body.status, 'ok');
assert.ok(res.body.network);
assert.ok('withdrawalsEnabled' in res.body);
});
test('GET /faq/entries returns array (may be empty)', async () => {
const res = await request(app).get(`${prefix}/faq/entries`);
assert.equal(res.status, 200);
assert.ok(Array.isArray(res.body.items));
});
test('GET /games/candle-predict/state returns betting-capable round', async () => {
const token = createTestAccessToken();
const res = await request(app)
.get(`${prefix}/games/candle-predict/state`)
.query({ intervalMinutes: 1 })
.set(authHeader(token));
assert.equal(res.status, 200);
assert.ok(res.body.config);
assert.ok(res.body.round);
assert.ok(['waiting', 'betting', 'locked', 'settled'].includes(res.body.round.status));
assert.ok(Array.isArray(res.body.config.stakeAmounts));
});
test('GET /games/candle-predict/candles returns OHLC items', async () => {
const token = createTestAccessToken();
const res = await request(app)
.get(`${prefix}/games/candle-predict/candles`)
.query({ intervalMinutes: 1, limit: 5 })
.set(authHeader(token));
assert.equal(res.status, 200);
assert.ok(Array.isArray(res.body.items));
if (res.body.items.length > 0) {
const candle = res.body.items[0];
assert.ok('open' in candle && 'close' in candle && 'time' in candle);
}
});
});

View File

@ -0,0 +1,284 @@
/**
* E2E API contract tests for the Prediqo mobile app.
* Validates endpoints, payloads, and response shapes the Flutter client relies on.
*/
import { test, describe, mock, afterEach, before } from 'node:test';
import assert from 'node:assert/strict';
import request from 'supertest';
import app from '../app';
import { config } from '../config';
import { registerBuiltinGames } from '../games/bootstrap';
import type { GameRow } from '../models/game.model';
import * as gameRepository from '../repositories/gameRepository';
import * as candlePredictService from '../services/candlePredictService';
import * as referralService from '../services/referralService';
import * as faqService from '../services/faqService';
import * as passwordResetService from '../services/passwordResetService';
import * as bonusService from '../services/bonusService';
import { authHeader, createTestAccessToken } from './helpers/testAuth';
registerBuiltinGames();
const prefix = config.apiPrefix;
function mockGameRow(overrides: Partial<GameRow> = {}): GameRow {
return {
id: '00000000-0000-4000-8000-000000000001',
slug: 'candle-predict',
title: 'Candle Predict',
description: null,
category: 'prediction',
thumbnail_url: null,
accent_color: '#D6B25E',
status: 'active',
sort_order: 1,
is_featured: true,
implementation_key: 'candle-predict',
created_at: new Date('2024-01-01'),
updated_at: new Date('2024-01-01'),
...overrides,
};
}
const sampleGameState = () => ({
config: {
stakeAmounts: [1, 5, 10],
minStakeAmount: 1,
maxStakeAmount: 1000,
payoutMultiplier: 1.8,
predictionWindowSeconds: 30,
isActive: true,
predictionTypes: { single: true, auto: true, multiCandle: true },
autoModes: ['each_round'],
},
intervals: [{ id: 1, intervalMinutes: 1, label: '1m', isDefault: true, isActive: true, payoutMultiplier: 1.8 }],
selectedIntervalMinutes: 1,
interval: { id: 1, intervalMinutes: 1, label: '1m', isDefault: true, isActive: true, payoutMultiplier: 1.8 },
round: {
id: 'round-1',
status: 'betting',
secondsToBettingEnd: 25,
secondsToBettingStart: 0,
secondsToClose: 60,
longPoolPercent: 55,
shortPoolPercent: 45,
},
multiLevels: [{ level: 2, candleCount: 2, enabled: true, payoutMultiplier: 3.2 }],
autoSettings: { enabled: false, mode: 'each_round', periodMinutes: 1, stakeAccountKind: 'main' },
});
describe('mobile API E2E (mocked services)', () => {
afterEach(() => {
mock.restoreAll();
});
test('GET /health returns network and withdrawal flags', async () => {
const res = await request(app).get('/health');
assert.equal(res.status, 200);
assert.equal(res.body.status, 'ok');
assert.ok(typeof res.body.network === 'string');
assert.ok(typeof res.body.withdrawalsEnabled === 'boolean');
assert.ok(res.body.withdrawalNetworkFeeRaw != null);
});
test('GET /faq/entries returns public FAQ list (no auth)', async () => {
mock.method(faqService, 'listPublicFaqs', async () => [
{ id: 1, question: 'How to deposit?', answer: 'Use Deposit tab.', category: 'wallet', viewCount: 10 },
]);
const res = await request(app).get(`${prefix}/faq/entries`);
assert.equal(res.status, 200);
assert.ok(Array.isArray(res.body.items));
assert.equal(res.body.items[0].question, 'How to deposit?');
});
test('POST /auth/forgot-password accepts email', async () => {
mock.method(passwordResetService, 'requestPasswordReset', async () => ({
message: 'If an account exists, a reset email was sent.',
}));
const res = await request(app)
.post(`${prefix}/auth/forgot-password`)
.send({ email: 'user@example.com' });
assert.equal(res.status, 200);
assert.ok(res.body.message);
});
test('POST /auth/forgot-password rejects empty email', async () => {
const res = await request(app).post(`${prefix}/auth/forgot-password`).send({});
assert.equal(res.status, 400);
});
test('GET /referral/dashboard returns mobile dashboard shape', async () => {
mock.method(referralService, 'getUserReferralDashboard', async () => ({
referralCode: 'PREDIQO99',
referralLink: 'https://app.example/register?ref=PREDIQO99',
directReferrals: 3,
bonusWithdrawable: true,
programEnabled: true,
commissionModes: { depositEnabled: true, withdrawalEnabled: false },
levels: [{ levelNumber: 1, commissionPercent: 5 }],
maxNetworkDepth: 5,
referrer: null,
summary: {
networkSize: 12,
totalEarnedRaw: '1000000',
paidRaw: '500000',
pendingRaw: '500000',
reviewRaw: '0',
payoutCount: 2,
},
network: [],
}));
const token = createTestAccessToken();
const res = await request(app)
.get(`${prefix}/referral/dashboard`)
.set(authHeader(token));
assert.equal(res.status, 200);
assert.equal(res.body.referralCode, 'PREDIQO99');
assert.ok(res.body.summary);
assert.equal(res.body.summary.networkSize, 12);
});
test('GET /bonus/balances returns bonus wallet list', async () => {
mock.method(bonusService, 'getUserBonusBalances', async () => [
{
walletType: { id: 2, code: 'USDT', name: 'USDT Bonus', decimals: 6 },
available: '2500000',
},
]);
mock.method(bonusService, 'isBonusWithdrawable', async () => true);
const token = createTestAccessToken();
const res = await request(app).get(`${prefix}/bonus/balances`).set(authHeader(token));
assert.equal(res.status, 200);
assert.ok(Array.isArray(res.body.balances));
assert.equal(res.body.bonusWithdrawable, true);
});
test('GET /games/candle-predict/state returns full mobile game state', async () => {
mock.method(gameRepository, 'getGameBySlug', async () => mockGameRow());
mock.method(candlePredictService, 'getGameState', async () => sampleGameState());
const token = createTestAccessToken();
const res = await request(app)
.get(`${prefix}/games/candle-predict/state`)
.query({ intervalMinutes: 1 })
.set(authHeader(token));
assert.equal(res.status, 200);
assert.ok(res.body.config.stakeAmounts);
assert.equal(res.body.round.status, 'betting');
assert.ok(Array.isArray(res.body.multiLevels));
assert.ok(res.body.config.predictionTypes.multiCandle);
});
test('POST /games/candle-predict/bets accepts stakeAmount (not stakeDisplay)', async () => {
mock.method(gameRepository, 'getGameBySlug', async () => mockGameRow());
let capturedStake: number | null = null;
mock.method(candlePredictService, 'placeBet', async (_userId: string, direction: string, stake: number) => {
capturedStake = stake;
assert.equal(direction, 'long');
return { status: 'accepted' as const, bet: { id: 'bet-1', direction, stakeDisplay: stake } };
});
const token = createTestAccessToken();
const res = await request(app)
.post(`${prefix}/games/candle-predict/bets`)
.set(authHeader(token))
.send({
direction: 'long',
stakeAmount: 5,
intervalMinutes: 1,
stakeAccountKind: 'main',
});
assert.equal(res.status, 201);
assert.equal(capturedStake, 5);
assert.equal(res.body.id, 'bet-1');
});
test('POST /games/candle-predict/bets rejects stakeDisplay-only payload', async () => {
const token = createTestAccessToken();
const res = await request(app)
.post(`${prefix}/games/candle-predict/bets`)
.set(authHeader(token))
.send({ direction: 'long', stakeDisplay: 5 });
assert.equal(res.status, 400);
});
test('POST /games/candle-predict/bets/multi accepts sequence and level', async () => {
mock.method(gameRepository, 'getGameBySlug', async () => mockGameRow());
mock.method(candlePredictService, 'placeMultiCandleBet', async () => ({
id: 'multi-1',
level: 2,
status: 'pending',
}));
const token = createTestAccessToken();
const res = await request(app)
.post(`${prefix}/games/candle-predict/bets/multi`)
.set(authHeader(token))
.send({
level: 2,
sequence: ['long', 'short'],
stakeAmount: 10,
intervalMinutes: 1,
stakeAccountKind: 'bonus',
});
assert.equal(res.status, 201);
assert.equal(res.body.id, 'multi-1');
});
test('PUT /games/candle-predict/auto saves auto settings with stakeAmount', async () => {
mock.method(gameRepository, 'getGameBySlug', async () => mockGameRow());
mock.method(candlePredictService, 'saveAutoSettings', async () => ({
enabled: true,
direction: 'long',
stakeDisplay: 5,
mode: 'each_round',
periodMinutes: 1,
stakeAccountKind: 'main',
}));
const token = createTestAccessToken();
const res = await request(app)
.put(`${prefix}/games/candle-predict/auto`)
.set(authHeader(token))
.send({
enabled: true,
direction: 'long',
stakeAmount: 5,
mode: 'each_round',
periodMinutes: 1,
stakeAccountKind: 'main',
attemptImmediateBet: true,
validateWalletBalance: true,
});
assert.equal(res.status, 200);
assert.equal(res.body.enabled, true);
assert.equal(res.body.direction, 'long');
});
test('mobile-critical routes return 401 without auth', async () => {
const protectedRoutes = [
['get', `${prefix}/games/candle-predict/state`],
['get', `${prefix}/referral/dashboard`],
['get', `${prefix}/bonus/balances`],
['post', `${prefix}/games/candle-predict/bets`],
] as const;
for (const [method, path] of protectedRoutes) {
const res = await request(app)[method](path);
assert.equal(res.status, 401, `${method.toUpperCase()} ${path} should require auth`);
}
});
});

View File

@ -0,0 +1,84 @@
import { describe, test } from 'node:test';
import assert from 'node:assert/strict';
import {
assertProductionMainnetConfig,
MAINNET_USDT_TRC20_CONTRACT,
SHASTA_USDT_TRC20_CONTRACT,
} from '../safety/networkGuard';
const prodMainnet = {
env: 'production',
networkMode: '',
tronNodeUrl: 'https://api.trongrid.io',
usdtTrc20Contract: null,
};
describe('assertProductionMainnetConfig', () => {
test('allows mainnet TRON with no contract override', () => {
assert.doesNotThrow(() => assertProductionMainnetConfig(prodMainnet));
});
test('allows mainnet USDT contract override', () => {
assert.doesNotThrow(() =>
assertProductionMainnetConfig({
...prodMainnet,
usdtTrc20Contract: MAINNET_USDT_TRC20_CONTRACT,
})
);
});
test('skips checks outside production', () => {
assert.doesNotThrow(() =>
assertProductionMainnetConfig({
env: 'development',
networkMode: 'testnet',
tronNodeUrl: 'https://api.shasta.trongrid.io',
usdtTrc20Contract: SHASTA_USDT_TRC20_CONTRACT,
})
);
});
test('rejects Shasta TRON node URL', () => {
assert.throws(
() =>
assertProductionMainnetConfig({
...prodMainnet,
tronNodeUrl: 'https://api.shasta.trongrid.io',
}),
/TRON_NODE_URL must not point to a TRON testnet/
);
});
test('rejects Nile TRON node URL', () => {
assert.throws(
() =>
assertProductionMainnetConfig({
...prodMainnet,
tronNodeUrl: 'https://nile.trongrid.io',
}),
/TRON_NODE_URL must not point to a TRON testnet/
);
});
test('rejects Shasta USDT contract override', () => {
assert.throws(
() =>
assertProductionMainnetConfig({
...prodMainnet,
usdtTrc20Contract: SHASTA_USDT_TRC20_CONTRACT,
}),
/USDT_TRC20_CONTRACT must not be the Shasta testnet token/
);
});
test('rejects NETWORK_MODE=testnet in production', () => {
assert.throws(
() =>
assertProductionMainnetConfig({
...prodMainnet,
networkMode: 'testnet',
}),
/NETWORK_MODE=testnet is not allowed/
);
});
});

View File

@ -0,0 +1,12 @@
import { config } from '../config';
/** Public web app base URL without trailing slash (APP_PUBLIC_URL). */
export function getPublicWebBaseUrl(): string {
return config.app.publicUrl.replace(/\/$/, '');
}
/** Registration invite link for a referral code. */
export function buildReferralRegisterLink(referralCode: string): string {
const code = referralCode.trim();
return `${getPublicWebBaseUrl()}/register?ref=${encodeURIComponent(code)}`;
}

View File

@ -9,7 +9,7 @@ export function clientErrorMessage(error: unknown, fallback = 'Request failed'):
} }
if (error instanceof Error && error.message) { if (error instanceof Error && error.message) {
const msg = error.message; const msg = error.message;
if (/^(Invalid|Unauthorized|Forbidden|Not found|2FA|Account|Password|Email)/i.test(msg)) { if (/^(Invalid|Unauthorized|Forbidden|Not found|2FA|Account|Password|Email|Phone|Referrer|referral)/i.test(msg)) {
return msg; return msg;
} }
} }

View File

@ -4,6 +4,10 @@ const roleNameSchema = z.enum(['user', 'moderator', 'admin', 'super_admin']);
const uuidSchema = z.string().uuid(); const uuidSchema = z.string().uuid();
const userIdsSchema = z.array(uuidSchema).min(1).max(500); const userIdsSchema = z.array(uuidSchema).min(1).max(500);
/** Optional profile string; frontend may send null to clear a nullable column. */
const nullableProfileString = (max: number) =>
z.union([z.string().trim().max(max), z.null()]).optional();
export const forgotPasswordBodySchema = z.object({ export const forgotPasswordBodySchema = z.object({
email: z.string().trim().min(1).max(255).email(), email: z.string().trim().min(1).max(255).email(),
}); });
@ -15,14 +19,14 @@ export const resetPasswordBodySchema = z.object({
export const updateProfileBodySchema = z export const updateProfileBodySchema = z
.object({ .object({
firstName: z.string().trim().max(100).optional(), firstName: nullableProfileString(100),
middleName: z.string().trim().max(100).optional(), middleName: nullableProfileString(100),
lastName: z.string().trim().max(100).optional(), lastName: nullableProfileString(100),
dateOfBirth: z.string().trim().max(32).optional(), dateOfBirth: nullableProfileString(32),
email: z.string().trim().max(255).email().optional(), email: z.string().trim().max(255).email().optional(),
phone: z.string().trim().max(32).optional(), phone: nullableProfileString(32),
countryOfResidence: z.string().trim().length(2).optional(), countryOfResidence: z.string().trim().length(2).optional(),
nationality: z.string().trim().length(2).optional(), nationality: z.union([z.string().trim().length(2), z.null()]).optional(),
gender: z.enum(['male', 'female', 'other']).optional(), gender: z.enum(['male', 'female', 'other']).optional(),
}) })
.refine((obj) => Object.keys(obj).length > 0, 'At least one field is required'); .refine((obj) => Object.keys(obj).length > 0, 'At least one field is required');

View File

@ -122,7 +122,7 @@ export const dbTamperEventsQuerySchema = paginationQuerySchema.extend({
}); });
export const walletTransactionsQuerySchema = paginationQuerySchema.extend({ export const walletTransactionsQuerySchema = paginationQuerySchema.extend({
category: z.enum(['deposits', 'withdrawals', 'predictions']).optional(), category: z.enum(['deposits', 'withdrawals', 'transfers', 'predictions']).optional(),
paginated: z.enum(['true', 'false', '1', '0']).optional(), paginated: z.enum(['true', 'false', '1', '0']).optional(),
}); });

View File

@ -19,6 +19,15 @@ server {
proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header X-Forwarded-Proto $scheme;
} }
location = /health {
proxy_pass http://crypto_wallet_api:4000/health;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
location /ws/ { location /ws/ {
proxy_pass http://crypto_wallet_ws:4001; proxy_pass http://crypto_wallet_ws:4001;
proxy_http_version 1.1; proxy_http_version 1.1;

View File

@ -273,6 +273,7 @@ Fichier d’environnement dédié : **`.env.docker`** (non versionné).
cp .env.docker.example .env.docker cp .env.docker.example .env.docker
# Éditer .env.docker : POSTGRES_PASSWORD, JWT_SECRET, ENCRYPTION_KEY, # Éditer .env.docker : POSTGRES_PASSWORD, JWT_SECRET, ENCRYPTION_KEY,
# PLATFORM_MNEMONIC, INITIAL_SETUP_TOKEN # PLATFORM_MNEMONIC, INITIAL_SETUP_TOKEN
# Garder NODE_ENV=development + Shasta (production + testnet = crash au boot).
# Créer la base vide sur PostgreSQL local, ex. games_platform_db # Créer la base vide sur PostgreSQL local, ex. games_platform_db
``` ```

View File

@ -22,6 +22,16 @@ server {
proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header X-Forwarded-Proto $scheme;
} }
location = /health {
set $backend_api backend;
proxy_pass http://$backend_api:4000/health;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
location /ws/ { location /ws/ {
set $backend_ws backend-ws; set $backend_ws backend-ws;
proxy_pass http://$backend_ws:4001; proxy_pass http://$backend_ws:4001;

View File

@ -37,6 +37,16 @@ server {
proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header X-Forwarded-Proto $scheme;
} }
location = /health {
set $backend_api backend;
proxy_pass http://$backend_api:4000/health;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
location /ws/ { location /ws/ {
set $backend_ws backend-ws; set $backend_ws backend-ws;
proxy_pass http://$backend_ws:4001; proxy_pass http://$backend_ws:4001;

View File

@ -35,6 +35,16 @@ server {
proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header X-Forwarded-Proto $scheme;
} }
location = /health {
set $backend_api backend;
proxy_pass http://$backend_api:4000/health;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
location /ws/ { location /ws/ {
set $backend_ws backend-ws; set $backend_ws backend-ws;
proxy_pass http://$backend_ws:4001; proxy_pass http://$backend_ws:4001;

View File

@ -23,6 +23,9 @@ migrate_working_dir/
# is commented out by default. # is commented out by default.
#.vscode/ #.vscode/
# Local device API URL (copy from dart_defines.dev.example.json)
dart_defines.dev.json
# Flutter/Dart/Pub related # Flutter/Dart/Pub related
**/doc/api/ **/doc/api/
**/ios/Flutter/.last_build_id **/ios/Flutter/.last_build_id

View File

@ -15,7 +15,7 @@ migration:
- platform: root - platform: root
create_revision: adc901062556672b4138e18a4dc62a4be8f4b3c2 create_revision: adc901062556672b4138e18a4dc62a4be8f4b3c2
base_revision: adc901062556672b4138e18a4dc62a4be8f4b3c2 base_revision: adc901062556672b4138e18a4dc62a4be8f4b3c2
- platform: web - platform: android
create_revision: adc901062556672b4138e18a4dc62a4be8f4b3c2 create_revision: adc901062556672b4138e18a4dc62a4be8f4b3c2
base_revision: adc901062556672b4138e18a4dc62a4be8f4b3c2 base_revision: adc901062556672b4138e18a4dc62a4be8f4b3c2

128
prediqo_mobile/TESTING.md Normal file
View File

@ -0,0 +1,128 @@
# Prediqo Mobile — Tests E2E
Guide pour exécuter les tests end-to-end de l'application mobile et des contrats API associés.
## Backend — contrats API mobile
Les tests vérifient les endpoints utilisés par le client Flutter (`stakeAmount`, multi-bougies, auto, referral, FAQ, health).
### Tests mockés (CI, sans base de données)
```bash
cd backend
npm run test:e2e
```
Couvre :
- `GET /health`
- `GET /faq/entries`
- `POST /auth/forgot-password`
- `GET /referral/dashboard`, `GET /bonus/balances`
- `GET /games/candle-predict/state`
- `POST /games/candle-predict/bets` (avec `stakeAmount`)
- `POST /games/candle-predict/bets/multi`
- `PUT /games/candle-predict/auto`
- Routes protégées → `401` sans token
### Tests avec base de données
Nécessite `DATABASE_URL` et `RUN_DB_TESTS=1` :
```bash
cd backend
npm run test:e2e:db
```
Ou la suite DB complète :
```bash
npm run test:db
```
## Flutter — tests d'intégration UI
Les tests E2E UI utilisent des **fakes** (pas de backend live) pour valider les parcours :
- Splash → accueil public (`/welcome`) si non connecté
- Welcome → Login → Dashboard (`/home`)
- Navigation Predict → Profile (session authentifiée)
### Lancer les tests E2E UI (VM — recommandé)
```bash
cd prediqo_mobile
flutter pub get
flutter test test/
```
### Tests sur appareil / émulateur (optionnel)
```bash
flutter test integration_test/app_e2e_test.dart -d <device_id>
```
Lister les appareils : `flutter devices`
## Flux démarrage (splash / public / dashboard)
| Étape | Route | Qui |
|-------|-------|-----|
| Splash | `/` | Tout le monde au lancement (~1.2s + check session) |
| Accueil public | `/welcome` | Visiteurs (marketing, FAQ, CTA login/register) |
| Dashboard | `/home` | Utilisateurs authentifiés (données perso) |
`GET /api/v1/games` et `GET /api/v1/advertisements` sont **publics** (lecture seule). Les routes de jeu/bets restent protégées.
## Connexion mobile → API Docker locale
Docker expose l’API via nginx sur **9080** (le port 4000 n’est pas publié sur l’hôte).
| Cible | Commande |
|-------|----------|
| **Émulateur Android** | launch config **prediqo (emulator)** ou `flutter run --dart-define=API_BASE_URL=http://10.0.2.2:9080` |
| **Appareil physique** | mettre l’IP Wi‑Fi du PC dans `dart_defines.dev.json`, puis full restart (pas hot reload) |
Fichier local (gitignored) : copier `dart_defines.dev.example.json` → `dart_defines.dev.json` :
```json
{ "API_BASE_URL": "http://10.10.16.78:9080" }
```
Ce fichier est lu via `--dart-define-from-file` (`.vscode/settings.json` à la racine du repo **et** dans `prediqo_mobile/.vscode/`).
**Ne plus mettre d’IP en dur** dans `.vscode/settings.json` : les defines sont compilées au build — un hot restart / une réinstallation ne change rien si Flutter a été lancé avec l’ancienne IP.
Après chaque changement d’`API_BASE_URL` : **Stop** puis **Run** (ou `flutter run` à neuf). Hot restart ne suffit pas.
Par défaut (sans dart-define) : `http://10.0.2.2:9080`.
L’écran login affiche une bannière d’erreur en cas d’échec (sans URL API ni détails d’infra).
## E2E contre un backend live (manuel)
1. Démarrer Docker : `npm run docker:local:up` (ou `npm run dev:testnet` hors Docker)
2. Lancer l’app avec l’URL ci-dessus
3. Suivre le guide [TESTING.md](../TESTING.md) pour dépôts / retraits testnet
## Clés de test (finders)
| Clé | Écran |
|-----|-------|
| `splash_screen` | Splash de démarrage |
| `welcome_screen`, `welcome_get_started`, `welcome_help`, `welcome_app_update`, `language_toggle` | Accueil public |
| `login_screen` | Connexion |
| `login_email`, `login_password`, `login_submit` | Formulaire login |
| `forgot_password_link` | Lien mot de passe oublié |
| `nav_home`, `nav_predict`, `nav_wallet`, `nav_profile` | Bottom nav (Dashboard / …) |
| `prediction_games_screen`, `game_card_candle-predict` | Catalogue Predict |
| `prediction_screen` | Page prédiction (Candle Predict) |
## Fichiers
```
backend/src/tests/mobileApiE2e.test.ts # API E2E mockée
backend/src/tests/mobileApiE2e.db.test.ts # API E2E avec DB
prediqo_mobile/test/
e2e_app_flow_test.dart # E2E UI (VM)
support/e2e_fixtures.dart # Fakes + setup DI
prediqo_mobile/integration_test/
app_e2e_test.dart # E2E sur appareil
```

View File

@ -1,8 +1,10 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android"> <manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.INTERNET"/>
<application <application
android:label="Prediqo" android:label="Prediqo"
android:name="${applicationName}" android:name="${applicationName}"
android:icon="@mipmap/ic_launcher"> android:icon="@mipmap/ic_launcher"
android:usesCleartextTraffic="true">
<activity <activity
android:name=".MainActivity" android:name=".MainActivity"
android:exported="true" android:exported="true"
@ -12,10 +14,6 @@
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode" android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
android:hardwareAccelerated="true" android:hardwareAccelerated="true"
android:windowSoftInputMode="adjustResize"> android:windowSoftInputMode="adjustResize">
<!-- Specifies an Android theme to apply to this Activity as soon as
the Android process has started. This theme is visible to the user
while the Flutter UI initializes. After that, this theme continues
to determine the Window background behind the Flutter UI. -->
<meta-data <meta-data
android:name="io.flutter.embedding.android.NormalTheme" android:name="io.flutter.embedding.android.NormalTheme"
android:resource="@style/NormalTheme" android:resource="@style/NormalTheme"
@ -25,21 +23,22 @@
<category android:name="android.intent.category.LAUNCHER"/> <category android:name="android.intent.category.LAUNCHER"/>
</intent-filter> </intent-filter>
</activity> </activity>
<!-- Don't delete the meta-data below.
This is used by the Flutter tool to generate GeneratedPluginRegistrant.java -->
<meta-data <meta-data
android:name="flutterEmbedding" android:name="flutterEmbedding"
android:value="2" /> android:value="2" />
</application> </application>
<!-- Required to query activities that can process text, see:
https://developer.android.com/training/package-visibility and
https://developer.android.com/reference/android/content/Intent#ACTION_PROCESS_TEXT.
In particular, this is used by the Flutter engine in io.flutter.plugin.text.ProcessTextPlugin. -->
<queries> <queries>
<intent> <intent>
<action android:name="android.intent.action.PROCESS_TEXT"/> <action android:name="android.intent.action.PROCESS_TEXT"/>
<data android:mimeType="text/plain"/> <data android:mimeType="text/plain"/>
</intent> </intent>
<intent>
<action android:name="android.intent.action.VIEW"/>
<data android:scheme="https"/>
</intent>
<intent>
<action android:name="android.intent.action.VIEW"/>
<data android:scheme="http"/>
</intent>
</queries> </queries>
</manifest> </manifest>

View File

@ -0,0 +1,5 @@
package com.prediqo.prediqo_mobile
import io.flutter.embedding.android.FlutterActivity
class MainActivity : FlutterActivity()

View File

@ -0,0 +1,3 @@
{
"API_BASE_URL": "http://YOUR_PC_WIFI_IP:9080"
}

View File

@ -0,0 +1,98 @@
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:integration_test/integration_test.dart';
import 'package:prediqo_mobile/app.dart';
import 'package:prediqo_mobile/core/config/app_config.dart';
import 'package:prediqo_mobile/core/di/injection.dart';
import '../test/support/e2e_fixtures.dart';
void main() {
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
group('Prediqo mobile E2E', () {
tearDown(() async {
if (sl.isRegistered<AppConfig>()) {
await sl.reset();
}
});
testWidgets('unauthenticated user sees public welcome after splash', (tester) async {
await setupE2eDependencies(loggedIn: false);
await tester.pumpWidget(const PrediqoApp());
await e2ePumpPastSplash(tester);
expect(find.byKey(const Key('welcome_screen')), findsOneWidget);
expect(find.byKey(const Key('welcome_get_started')), findsOneWidget);
expect(find.byKey(const Key('login_screen')), findsNothing);
});
testWidgets('login flow reaches dashboard', (tester) async {
await setupE2eDependencies(loggedIn: false);
await tester.pumpWidget(const PrediqoApp());
await e2ePumpPastSplash(tester);
await tester.tap(find.byKey(const Key('welcome_get_started')));
await e2ePump(tester, frames: 5);
await tester.enterText(find.byKey(const Key('login_email')), 'e2e@prediqo.test');
await tester.enterText(find.byKey(const Key('login_password')), 'password123');
await tester.tap(find.byKey(const Key('login_submit')));
await e2ePump(tester, frames: 8);
expect(find.byKey(const Key('nav_home')), findsOneWidget);
expect(find.byKey(const Key('login_screen')), findsNothing);
});
testWidgets('authenticated user navigates predict catalog and wallet tabs', (tester) async {
await setupE2eDependencies(loggedIn: true);
await tester.pumpWidget(const PrediqoApp());
await e2ePumpPastSplash(tester);
await tester.tap(find.byKey(const Key('nav_predict')));
await e2ePump(tester, frames: 20);
expect(find.byKey(const Key('prediction_games_screen')), findsOneWidget);
expect(find.byKey(const Key('game_card_candle-predict')), findsOneWidget);
await tester.tap(find.byKey(const Key('nav_wallet')));
await e2ePump(tester, frames: 5);
expect(find.text('Wallet'), findsWidgets);
await tester.tap(find.byKey(const Key('nav_profile')));
await e2ePump(tester, frames: 5);
expect(find.text('Account'), findsOneWidget);
});
testWidgets('forgot password link opens reset screen', (tester) async {
await setupE2eDependencies(loggedIn: false);
await tester.pumpWidget(const PrediqoApp());
await e2ePumpPastSplash(tester);
await tester.tap(find.byKey(const Key('welcome_get_started')));
await e2ePump(tester, frames: 5);
await tester.tap(find.byKey(const Key('forgot_password_link')));
await e2ePump(tester, frames: 5);
expect(find.text('Forgot password?'), findsWidgets);
expect(find.text('Send reset link'), findsOneWidget);
});
testWidgets('prediction screen shows single and multi mode controls', (tester) async {
await setupE2eDependencies(loggedIn: true);
await tester.pumpWidget(const PrediqoApp());
await e2ePumpPastSplash(tester);
await tester.tap(find.byKey(const Key('nav_predict')));
await e2ePump(tester, frames: 20);
await tester.tap(find.byKey(const Key('game_card_candle-predict')));
await e2ePump(tester, frames: 20);
expect(find.text('Single'), findsOneWidget);
expect(find.text('Multi'), findsOneWidget);
expect(find.text('Auto'), findsOneWidget);
expect(find.text('Long'), findsOneWidget);
expect(find.text('Short'), findsOneWidget);
});
});
}

View File

@ -0,0 +1,96 @@
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:go_router/go_router.dart';
import 'core/di/injection.dart';
import 'core/network/api_client.dart';
import 'core/router/app_router.dart';
import 'core/theme/app_theme.dart';
import 'data/repositories/admin_repository_impl.dart';
import 'data/repositories/wallet_repository_impl.dart';
import 'domain/repositories/faq_repository.dart';
import 'domain/repositories/health_repository.dart';
import 'domain/repositories/prediction_repository.dart';
import 'domain/repositories/referral_repository.dart';
import 'domain/repositories/repositories.dart';
import 'features/auth/bloc/auth_bloc.dart';
import 'features/prediction/bloc/prediction_bloc.dart';
import 'features/wallet/bloc/wallet_bloc.dart';
import 'l10n/app_locale.dart';
import 'l10n/locale_controller.dart';
class PrediqoApp extends StatefulWidget {
const PrediqoApp({super.key});
@override
State<PrediqoApp> createState() => _PrediqoAppState();
}
class _PrediqoAppState extends State<PrediqoApp> {
late final AuthBloc _authBloc;
late final GoRouter _router;
late final LocaleController _localeController;
@override
void initState() {
super.initState();
_localeController = sl<LocaleController>();
_authBloc = sl<AuthBloc>();
sl<ApiClient>().onSessionExpired = () {
if (!_authBloc.isClosed) {
_authBloc.add(const AuthSessionExpired());
}
};
_router = createAppRouter(_authBloc);
}
@override
void dispose() {
sl<ApiClient>().onSessionExpired = null;
_authBloc.close();
super.dispose();
}
@override
Widget build(BuildContext context) {
return MultiRepositoryProvider(
providers: [
RepositoryProvider<ApiClient>.value(value: sl()),
RepositoryProvider<AuthRepository>.value(value: sl<AuthRepository>()),
RepositoryProvider<WalletRepositoryImpl>.value(value: sl()),
RepositoryProvider<AdminRepositoryImpl>.value(value: sl()),
RepositoryProvider<HealthRepository>.value(value: sl()),
RepositoryProvider<PredictionRepository>.value(value: sl()),
RepositoryProvider<ReferralRepository>.value(value: sl()),
RepositoryProvider<FaqRepository>.value(value: sl()),
],
child: MultiBlocProvider(
providers: [
BlocProvider.value(value: _authBloc),
BlocProvider(create: (_) => sl<WalletBloc>()),
BlocProvider(create: (_) => sl<PredictionBloc>()),
],
child: ListenableBuilder(
listenable: _localeController,
builder: (context, _) {
return MaterialApp.router(
title: 'Prediqo',
debugShowCheckedModeBanner: false,
theme: AppTheme.light,
darkTheme: AppTheme.dark,
themeMode: ThemeMode.dark,
locale: _localeController.locale,
supportedLocales: AppLocale.supported,
localizationsDelegates: const [
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
GlobalCupertinoLocalizations.delegate,
],
routerConfig: _router,
);
},
),
),
);
}
}

View File

@ -1,212 +1 @@
/// Application navigation configuration using go_router. export 'core/router/app_router.dart';
///
/// Defines auth, wallet, account, and admin routes with shell-based dashboard layout.
library;
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:go_router/go_router.dart';
import 'data/repositories/admin_repository_impl.dart';
import 'features/admin/presentation/options_screen.dart';
import 'features/admin/presentation/settings_screen.dart';
import 'features/admin/presentation/user_detail_screen.dart';
import 'features/admin/presentation/user_management_screen.dart';
import 'features/auth/bloc/auth_bloc.dart';
import 'features/auth/presentation/login_screen.dart';
import 'features/auth/presentation/register_screen.dart';
import 'features/auth/presentation/totp_setup_screen.dart';
import 'features/wallet/presentation/dashboard_screen.dart';
import 'features/wallet/presentation/dashboard_shell.dart';
import 'features/wallet/presentation/deposit_asset_select_screen.dart';
import 'features/wallet/presentation/deposit_screen.dart';
import 'features/wallet/presentation/transaction_history_screen.dart';
import 'features/wallet/presentation/withdraw_screen.dart';
import 'features/wallet/presentation/transfer_screen.dart';
import 'features/wallet/presentation/account_screen.dart';
import 'features/wallet/presentation/profile_edit_screen.dart';
import 'features/wallet/presentation/change_password_screen.dart';
final _rootNavigatorKey = GlobalKey<NavigatorState>();
/// Builds the app's [GoRouter] with auth-gated and admin-protected routes.
GoRouter createAppRouter() {
return GoRouter(
navigatorKey: _rootNavigatorKey,
initialLocation: '/',
routes: [
GoRoute(path: '/', builder: (context, __) => const _SplashRedirect()),
GoRoute(path: '/login', builder: (_, __) => const LoginScreen()),
GoRoute(path: '/register', builder: (_, __) => const RegisterScreen()),
ShellRoute(
builder: (context, state, child) =>
DashboardShell(state: state, child: child),
routes: [
GoRoute(
path: '/dashboard',
builder: (_, state) {
final tab =
int.tryParse(state.uri.queryParameters['tab'] ?? '0') ?? 0;
return DashboardScreen(initialTab: tab);
},
),
GoRoute(
path: '/deposit',
builder: (_, __) => const DepositAssetSelectScreen(),
),
GoRoute(
path: '/deposit/:walletType',
builder: (c, state) {
final wt = state.pathParameters['walletType']!;
return DepositScreen(walletTypeCode: wt);
},
),
GoRoute(
path: '/withdraw',
builder: (_, __) => const WithdrawScreen(),
),
GoRoute(
path: '/transfer',
builder: (_, __) => const TransferScreen(),
),
GoRoute(
path: '/transactions',
builder: (_, __) => const TransactionHistoryScreen(),
),
GoRoute(
path: '/totp-setup',
builder: (_, __) => const TotpSetupScreen(),
),
GoRoute(path: '/account', builder: (_, __) => const AccountScreen()),
GoRoute(
path: '/account/profile',
builder: (_, __) => const ProfileEditScreen(),
),
GoRoute(
path: '/account/change-password',
builder: (_, __) => const ChangePasswordScreen(),
),
GoRoute(path: '/options', builder: (_, __) => const OptionsScreen()),
GoRoute(
path: '/options/settings',
builder: (context, __) {
final adminRepo = context.read<AdminRepositoryImpl>();
final isAdmin = context.read<AuthBloc>().state.isAdmin;
if (!isAdmin) {
return Scaffold(
appBar: AppBar(title: const Text('Settings')),
body: const Center(child: Text('Access denied. Admin only.')),
);
}
return SettingsScreen(adminRepo: adminRepo);
},
),
GoRoute(
path: '/admin/users',
builder: (context, __) {
final adminRepo = context.read<AdminRepositoryImpl>();
final isAdmin = context.read<AuthBloc>().state.isAdmin;
if (!isAdmin) {
return Scaffold(
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Icon(
Icons.block_rounded,
size: 48,
color: Colors.grey,
),
const SizedBox(height: 16),
const Text('Access denied. Admin only.'),
const SizedBox(height: 16),
FilledButton(
onPressed: () => context.go('/dashboard'),
child: const Text('Back to Dashboard'),
),
],
),
),
);
}
return UserManagementScreen(adminRepo: adminRepo);
},
),
GoRoute(
path: '/admin/users/:userId',
builder: (context, state) {
final userId = state.pathParameters['userId']!;
final adminRepo = context.read<AdminRepositoryImpl>();
final isAdmin = context.read<AuthBloc>().state.isAdmin;
if (!isAdmin) {
return Scaffold(
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Icon(
Icons.block_rounded,
size: 48,
color: Colors.grey,
),
const SizedBox(height: 16),
const Text('Access denied. Admin only.'),
const SizedBox(height: 16),
FilledButton(
onPressed: () => context.go('/dashboard'),
child: const Text('Back to Dashboard'),
),
],
),
),
);
}
return UserDetailScreen(userId: userId, adminRepo: adminRepo);
},
),
],
),
],
);
}
/// Initial route that redirects to login or dashboard based on auth state.
class _SplashRedirect extends StatefulWidget {
const _SplashRedirect();
@override
State<_SplashRedirect> createState() => _SplashRedirectState();
}
class _SplashRedirectState extends State<_SplashRedirect> {
@override
Widget build(BuildContext context) {
return BlocListener<AuthBloc, AuthState>(
listenWhen: (prev, curr) => prev.status != curr.status,
listener: (context, state) {
if (state.status == AuthStatus.loading) return;
if (!context.mounted) return;
if (state.status == AuthStatus.authenticated) {
context.go('/dashboard');
} else {
context.go('/login');
}
},
child: const Scaffold(body: Center(child: CircularProgressIndicator())),
);
}
/// Performs an immediate redirect when auth state is already resolved.
@override
void initState() {
super.initState();
WidgetsBinding.instance.addPostFrameCallback((_) {
if (!mounted) return;
final state = context.read<AuthBloc>().state;
if (state.status == AuthStatus.authenticated) {
context.go('/dashboard');
} else if (state.status != AuthStatus.loading) {
context.go('/login');
}
});
}
}

View File

@ -1,114 +1 @@
/// HTTP client wrapper for backend API communication. export '../network/api_client.dart';
///
/// Configures Dio with auth interceptors, token persistence, and request logging.
library;
import 'package:dio/dio.dart';
import '../storage/secure_storage.dart';
/// Dio-based API client with secure token storage and automatic refresh on 401.
class ApiClient {
/// Creates a client targeting [baseUrl] with optional custom [storage].
ApiClient({required this.baseUrl, SecureStorage? storage})
: _storage = storage ?? SecureStorage() {
_dio = Dio(
BaseOptions(
baseUrl: baseUrl,
connectTimeout: const Duration(seconds: 30),
receiveTimeout: const Duration(seconds: 30),
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
},
),
);
_dio.interceptors.addAll([
_AuthInterceptor(_storage),
LogInterceptor(requestBody: true, responseBody: true),
]);
}
final String baseUrl;
final SecureStorage _storage;
late final Dio _dio;
/// Underlying Dio instance for repository HTTP calls.
Dio get dio => _dio;
/// Persists auth tokens and user metadata to secure storage.
Future<void> setTokens({
String? accessToken,
String? refreshToken,
String? userId,
String? role,
}) async {
if (accessToken != null) await _storage.writeAccessToken(accessToken);
if (refreshToken != null) await _storage.writeRefreshToken(refreshToken);
if (userId != null) await _storage.writeUserId(userId);
if (role != null) await _storage.writeUserRole(role);
}
/// Clears all stored auth credentials.
Future<void> clearTokens() async {
await _storage.deleteAccessToken();
await _storage.deleteRefreshToken();
await _storage.deleteUserId();
await _storage.deleteUserRole();
}
/// Returns the persisted user id, if any.
Future<String?> getStoredUserId() => _storage.readUserId();
/// Returns the persisted user role, if any.
Future<String?> getStoredUserRole() => _storage.readUserRole();
}
/// Attaches bearer tokens to requests and retries once after token refresh.
class _AuthInterceptor extends Interceptor {
_AuthInterceptor(this._storage);
final SecureStorage _storage;
/// Adds the stored access token to outgoing request headers.
@override
void onRequest(
RequestOptions options,
RequestInterceptorHandler handler,
) async {
final token = await _storage.readAccessToken();
if (token != null && token.isNotEmpty) {
options.headers['Authorization'] = 'Bearer $token';
}
handler.next(options);
}
/// Attempts token refresh and retries the failed request on 401 responses.
@override
void onError(DioException err, ErrorInterceptorHandler handler) async {
if (err.response?.statusCode == 401) {
final refreshToken = await _storage.readRefreshToken();
if (refreshToken != null) {
try {
final dio = Dio(BaseOptions(baseUrl: err.requestOptions.baseUrl));
final r = await dio.post<Map<String, dynamic>>(
'/api/v1/auth/refresh',
data: {'refreshToken': refreshToken},
);
final accessToken = r.data?['accessToken'] as String?;
final newRefreshToken = r.data?['refreshToken'] as String?;
if (accessToken != null) {
await _storage.writeAccessToken(accessToken);
if (newRefreshToken != null) {
await _storage.writeRefreshToken(newRefreshToken);
}
final opts = err.requestOptions;
opts.headers['Authorization'] = 'Bearer $accessToken';
final response = await Dio().fetch(opts);
return handler.resolve(response);
}
} catch (_) {}
}
}
handler.next(err);
}
}

View File

@ -0,0 +1,77 @@
/// Application-wide configuration from compile-time defines and environment.
class AppConfig {
const AppConfig({
required this.apiBaseUrl,
required this.isProduction,
this.enableApiLogging = false,
this.wsEnabled = true,
this.wsUrl,
this.latestAppVersion,
this.appStoreUrl,
});
final String apiBaseUrl;
final bool isProduction;
final bool enableApiLogging;
final bool wsEnabled;
final String? wsUrl;
/// When set and greater than the installed app version, the home update badge appears.
final String? latestAppVersion;
/// Store / APK URL opened from the home update icon when an update is available.
final String? appStoreUrl;
/// WebSocket URL for candle-predict.
///
/// Defaults to the same host/port as [apiBaseUrl] with path `/ws/...`
/// (Docker/nginx proxies `/ws/` on 9080). Override with `--dart-define=WS_URL=...`
/// or `--dart-define=WS_PORT=4001` for a dedicated WS port.
String get resolvedWsUrl {
if (wsUrl != null && wsUrl!.isNotEmpty) return wsUrl!;
final api = Uri.parse(apiBaseUrl);
final wsScheme = api.scheme == 'https' ? 'wss' : 'ws';
const wsPortOverride = String.fromEnvironment('WS_PORT', defaultValue: '');
final int? port;
if (wsPortOverride.isNotEmpty) {
port = int.tryParse(wsPortOverride);
} else if (api.hasPort) {
port = api.port;
} else {
port = null;
}
return Uri(
scheme: wsScheme,
host: api.host,
port: port,
path: '/ws/v1/games/candle-predict',
).toString();
}
static AppConfig fromEnvironment() {
// Docker local exposes the API via nginx on 9080 (port 4000 is internal only).
// Emulator → 10.0.2.2 ; physical device → --dart-define=API_BASE_URL=http://<PC_LAN_IP>:9080
const apiBaseUrl = String.fromEnvironment(
'API_BASE_URL',
defaultValue: 'http://10.0.2.2:9080',
);
const wsUrl = String.fromEnvironment('WS_URL', defaultValue: '');
// Enabled by default so local Docker (nginx /ws/) works without extra flags.
const wsEnabled = bool.fromEnvironment('WS_ENABLED', defaultValue: true);
const env = String.fromEnvironment('APP_ENV', defaultValue: '');
final isProd = env == 'production' ||
const bool.fromEnvironment('dart.vm.product', defaultValue: false);
const latestAppVersion =
String.fromEnvironment('LATEST_APP_VERSION', defaultValue: '');
const appStoreUrl = String.fromEnvironment('APP_STORE_URL', defaultValue: '');
return AppConfig(
apiBaseUrl: apiBaseUrl,
isProduction: isProd,
enableApiLogging: !isProd,
wsEnabled: wsEnabled,
wsUrl: wsUrl.isEmpty ? null : wsUrl,
latestAppVersion: latestAppVersion.isEmpty ? null : latestAppVersion,
appStoreUrl: appStoreUrl.isEmpty ? null : appStoreUrl,
);
}
}

View File

@ -0,0 +1,92 @@
import 'package:get_it/get_it.dart';
import '../../data/repositories/admin_repository_impl.dart';
import '../../data/repositories/advertisement_repository_impl.dart';
import '../../data/repositories/auth_repository_impl.dart';
import '../../data/repositories/faq_repository_impl.dart';
import '../../data/repositories/game_catalog_repository_impl.dart';
import '../../data/repositories/health_repository_impl.dart';
import '../../data/repositories/notification_repository_impl.dart';
import '../../data/repositories/prediction_repository_impl.dart';
import '../../data/repositories/referral_repository_impl.dart';
import '../../data/repositories/wallet_repository_impl.dart';
import '../../domain/repositories/advertisement_repository.dart';
import '../../domain/repositories/faq_repository.dart';
import '../../domain/repositories/game_catalog_repository.dart';
import '../../domain/repositories/health_repository.dart';
import '../../domain/repositories/notification_repository.dart';
import '../../domain/repositories/prediction_repository.dart';
import '../../domain/repositories/referral_repository.dart';
import '../../domain/repositories/repositories.dart';
import '../../features/auth/bloc/auth_bloc.dart';
import '../../features/prediction/bloc/prediction_bloc.dart';
import '../../features/wallet/bloc/wallet_bloc.dart';
import '../config/app_config.dart';
import '../network/api_client.dart';
import '../realtime/game_socket_service.dart';
import '../../l10n/locale_controller.dart';
final sl = GetIt.instance;
Future<void> configureDependencies({AppConfig? config}) async {
final appConfig = config ?? AppConfig.fromEnvironment();
if (!sl.isRegistered<AppConfig>()) {
sl.registerSingleton<AppConfig>(appConfig);
}
if (!sl.isRegistered<LocaleController>()) {
final localeController = LocaleController();
await localeController.load();
sl.registerSingleton<LocaleController>(localeController);
}
if (!sl.isRegistered<ApiClient>()) {
sl.registerLazySingleton<ApiClient>(() => ApiClient(config: sl()));
}
if (!sl.isRegistered<GameSocketService>()) {
sl.registerLazySingleton<GameSocketService>(() => GameSocketService(sl(), sl()));
}
if (!sl.isRegistered<AuthRepository>()) {
sl.registerLazySingleton<AuthRepository>(() => AuthRepositoryImpl(sl()));
}
if (!sl.isRegistered<WalletRepositoryImpl>()) {
sl.registerLazySingleton<WalletRepositoryImpl>(() => WalletRepositoryImpl(sl()));
}
if (!sl.isRegistered<AdminRepositoryImpl>()) {
sl.registerLazySingleton<AdminRepositoryImpl>(() => AdminRepositoryImpl(sl()));
}
if (!sl.isRegistered<HealthRepository>()) {
sl.registerLazySingleton<HealthRepository>(() => HealthRepositoryImpl(sl()));
}
if (!sl.isRegistered<PredictionRepository>()) {
sl.registerLazySingleton<PredictionRepository>(() => PredictionRepositoryImpl(sl()));
}
if (!sl.isRegistered<ReferralRepository>()) {
sl.registerLazySingleton<ReferralRepository>(() => ReferralRepositoryImpl(sl()));
}
if (!sl.isRegistered<FaqRepository>()) {
sl.registerLazySingleton<FaqRepository>(() => FaqRepositoryImpl(sl()));
}
if (!sl.isRegistered<AdvertisementRepository>()) {
sl.registerLazySingleton<AdvertisementRepository>(
() => AdvertisementRepositoryImpl(sl()),
);
}
if (!sl.isRegistered<NotificationRepository>()) {
sl.registerLazySingleton<NotificationRepository>(
() => NotificationRepositoryImpl(sl()),
);
}
if (!sl.isRegistered<GameCatalogRepository>()) {
sl.registerLazySingleton<GameCatalogRepository>(
() => GameCatalogRepositoryImpl(sl()),
);
}
if (!sl.isRegistered<AuthBloc>()) {
sl.registerFactory<AuthBloc>(() => AuthBloc(sl())..add(const AuthCheckRequested()));
}
if (!sl.isRegistered<WalletBloc>()) {
sl.registerFactory<WalletBloc>(() => WalletBloc(sl<WalletRepositoryImpl>()));
}
if (!sl.isRegistered<PredictionBloc>()) {
sl.registerFactory<PredictionBloc>(() => PredictionBloc(sl(), sl(), sl()));
}
}

View File

@ -0,0 +1,114 @@
import 'package:dio/dio.dart';
import '../di/injection.dart';
import '../../l10n/locale_controller.dart';
/// User-facing application error with optional HTTP status and API error code.
class AppException implements Exception {
const AppException(this.message, {this.statusCode, this.code});
final String message;
final int? statusCode;
/// Backend machine code when present (e.g. `EMAIL_NOT_VERIFIED`).
final String? code;
@override
String toString() => message;
static String _t(String en, String fr) {
try {
if (sl.isRegistered<LocaleController>() &&
sl<LocaleController>().locale.languageCode == 'fr') {
return fr;
}
} catch (_) {}
return en;
}
/// Connection / device network failure — ask the user to check connectivity.
static String get connectionFailedMessage => _t(
'Connection failed. Please check your internet connection and try again.',
'Échec de connexion. Veuillez vérifier votre connexion internet et réessayer.',
);
/// API unreachable, timeouts, or gateway errors — no infra details exposed.
static String get serviceUnavailableMessage => _t(
'The service is temporarily unavailable. Please try again later. '
'If the problem persists, contact an administrator.',
'Le service est indisponible pour le moment. Veuillez réessayer ultérieurement. '
'Si le problème persiste, veuillez contacter l’administrateur.',
);
static final RegExp _technicalLeak = RegExp(
r'https?://|API_BASE|VITE_|localhost|\b\d{1,3}(?:\.\d{1,3}){3}\b|10\.0\.2\.2|cleartext|INITIAL_SETUP|Bearer\s',
caseSensitive: false,
);
static bool looksTechnical(String message) => _technicalLeak.hasMatch(message);
static String sanitizeApiMessage(String message, {String? fallback}) {
final trimmed = message.trim();
if (trimmed.isEmpty) return fallback ?? serviceUnavailableMessage;
if (looksTechnical(trimmed)) return fallback ?? serviceUnavailableMessage;
return trimmed;
}
static AppException fromDio(DioException error, {String fallback = 'Request failed'}) {
final status = error.response?.statusCode;
final data = error.response?.data;
if (data is Map) {
final msg = data['error'] ?? data['message'];
final code = data['code'];
if (msg is String && msg.isNotEmpty) {
return AppException(
sanitizeApiMessage(msg, fallback: fallback),
statusCode: status,
code: code is String ? code : null,
);
}
}
if (status == 502 || status == 503 || status == 504) {
return AppException(
serviceUnavailableMessage,
statusCode: status,
code: 'SERVICE_UNAVAILABLE',
);
}
switch (error.type) {
case DioExceptionType.connectionTimeout:
case DioExceptionType.sendTimeout:
case DioExceptionType.receiveTimeout:
return AppException(
serviceUnavailableMessage,
statusCode: status,
code: 'SERVICE_UNAVAILABLE',
);
case DioExceptionType.connectionError:
return AppException(
connectionFailedMessage,
statusCode: status,
code: 'CONNECTION_FAILED',
);
case DioExceptionType.badResponse:
return AppException(
sanitizeApiMessage(fallback),
statusCode: status,
);
default:
break;
}
final raw = error.message?.trim();
if (raw != null && raw.isNotEmpty) {
return AppException(
sanitizeApiMessage(raw, fallback: connectionFailedMessage),
statusCode: status,
);
}
return AppException(
sanitizeApiMessage(fallback),
statusCode: status,
);
}
}

View File

@ -0,0 +1,165 @@
import 'dart:async';
import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
import '../config/app_config.dart';
import '../storage/secure_storage.dart';
/// Dio-based HTTP client with auth interceptors and secure token storage.
class ApiClient {
ApiClient({
required AppConfig config,
SecureStorage? storage,
}) : _config = config,
_storage = storage ?? SecureStorage() {
_dio = Dio(
BaseOptions(
baseUrl: config.apiBaseUrl,
connectTimeout: const Duration(seconds: 12),
receiveTimeout: const Duration(seconds: 20),
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
},
),
);
_dio.interceptors.add(_AuthInterceptor(this));
if (config.enableApiLogging && kDebugMode) {
_dio.interceptors.add(
LogInterceptor(requestBody: true, responseBody: true),
);
}
}
final AppConfig _config;
final SecureStorage _storage;
late final Dio _dio;
/// Invoked once when access+refresh are unusable (401 and refresh failed).
void Function()? onSessionExpired;
bool _sessionExpiredNotified = false;
Dio get dio => _dio;
SecureStorage get storage => _storage;
String get baseUrl => _config.apiBaseUrl;
Future<void> setTokens({
String? accessToken,
String? refreshToken,
String? userId,
String? role,
}) async {
if (accessToken != null) await _storage.writeAccessToken(accessToken);
if (refreshToken != null) await _storage.writeRefreshToken(refreshToken);
if (userId != null) await _storage.writeUserId(userId);
if (role != null) await _storage.writeUserRole(role);
if (accessToken != null || refreshToken != null) {
_sessionExpiredNotified = false;
}
}
Future<void> clearTokens() async {
await _storage.deleteAccessToken();
await _storage.deleteRefreshToken();
await _storage.deleteUserId();
await _storage.deleteUserRole();
}
Future<String?> getStoredUserId() => _storage.readUserId();
Future<String?> getStoredUserRole() => _storage.readUserRole();
Future<String?> readRefreshToken() => _storage.readRefreshToken();
Future<String?> readAccessToken() => _storage.readAccessToken();
}
class _AuthInterceptor extends Interceptor {
_AuthInterceptor(this._client);
final ApiClient _client;
Completer<bool>? _refreshCompleter;
@override
void onRequest(RequestOptions options, RequestInterceptorHandler handler) async {
final token = await _client.readAccessToken();
if (token != null && token.isNotEmpty) {
options.headers['Authorization'] = 'Bearer $token';
}
handler.next(options);
}
@override
void onError(DioException err, ErrorInterceptorHandler handler) async {
final path = err.requestOptions.path;
final isAuthEndpoint = path.contains('/auth/login') ||
path.contains('/auth/register') ||
path.contains('/auth/refresh') ||
path.contains('/auth/forgot-password') ||
path.contains('/auth/resend-verification');
if (err.response?.statusCode == 401 && !isAuthEndpoint) {
final refreshed = await _refreshAccessToken();
if (refreshed) {
try {
final opts = err.requestOptions;
final accessToken = await _client.readAccessToken();
if (accessToken != null) {
opts.headers['Authorization'] = 'Bearer $accessToken';
}
final response = await _client.dio.fetch(opts);
return handler.resolve(response);
} catch (e) {
if (e is DioException) {
return handler.next(e);
}
return handler.next(err);
}
}
await _expireSession();
}
handler.next(err);
}
Future<bool> _refreshAccessToken() async {
if (_refreshCompleter != null) {
return _refreshCompleter!.future;
}
final completer = Completer<bool>();
_refreshCompleter = completer;
try {
final refreshToken = await _client.readRefreshToken();
if (refreshToken == null || refreshToken.isEmpty) {
completer.complete(false);
return false;
}
final r = await Dio(BaseOptions(baseUrl: _client.baseUrl)).post<Map<String, dynamic>>(
'/api/v1/auth/refresh',
data: {'refreshToken': refreshToken},
);
final accessToken = r.data?['accessToken'] as String?;
final newRefresh = r.data?['refreshToken'] as String?;
if (accessToken == null || accessToken.isEmpty) {
completer.complete(false);
return false;
}
await _client.setTokens(
accessToken: accessToken,
refreshToken: newRefresh,
);
completer.complete(true);
return true;
} catch (_) {
completer.complete(false);
return false;
} finally {
_refreshCompleter = null;
}
}
Future<void> _expireSession() async {
await _client.clearTokens();
if (_client._sessionExpiredNotified) return;
_client._sessionExpiredNotified = true;
_client.onSessionExpired?.call();
}
}

View File

@ -0,0 +1,126 @@
import 'dart:async';
import 'dart:convert';
import 'package:web_socket_channel/web_socket_channel.dart';
import '../config/app_config.dart';
import '../network/api_client.dart';
typedef GameSocketListener = void Function(Map<String, dynamic> message);
/// WebSocket client for candle-predict realtime updates (mirrors web GameSocketClient).
class GameSocketService {
GameSocketService(this._config, this._api);
final AppConfig _config;
final ApiClient _api;
WebSocketChannel? _channel;
StreamSubscription? _sub;
int? _subscribedInterval;
final _listeners = <GameSocketListener>{};
Timer? _heartbeat;
Timer? _reconnectTimer;
int _reconnectAttempt = 0;
bool _connecting = false;
bool get isConnected => _channel != null;
bool get isEnabled => _config.wsEnabled;
void addListener(GameSocketListener listener) => _listeners.add(listener);
void removeListener(GameSocketListener listener) => _listeners.remove(listener);
Future<void> connect() async {
if (!isEnabled || _channel != null || _connecting) return;
_connecting = true;
final token = await _api.readAccessToken();
var url = _config.resolvedWsUrl;
if (token != null && token.isNotEmpty) {
final uri = Uri.parse(url);
url = uri.replace(queryParameters: {
...uri.queryParameters,
'token': token,
}).toString();
}
try {
final channel = WebSocketChannel.connect(Uri.parse(url));
// Wait briefly for the handshake so subscribe() is less likely to race.
await channel.ready.timeout(const Duration(seconds: 8));
_channel = channel;
_sub = channel.stream.listen(
_onMessage,
onError: (_) => _scheduleReconnect(),
onDone: _scheduleReconnect,
cancelOnError: true,
);
_reconnectAttempt = 0;
_heartbeat?.cancel();
_heartbeat = Timer.periodic(const Duration(seconds: 30), (_) {
_send({'type': 'ping', 'ts': DateTime.now().millisecondsSinceEpoch});
});
final interval = _subscribedInterval;
if (interval != null) subscribe(interval);
} catch (_) {
_disposeChannel();
_scheduleReconnect();
} finally {
_connecting = false;
}
}
void subscribe(int intervalMinutes) {
_subscribedInterval = intervalMinutes;
_send({'type': 'subscribe', 'intervalMinutes': intervalMinutes});
}
void unsubscribe(int intervalMinutes) {
_send({'type': 'unsubscribe', 'intervalMinutes': intervalMinutes});
}
void _onMessage(dynamic raw) {
try {
final map = jsonDecode(raw as String) as Map<String, dynamic>;
for (final l in _listeners) {
l(map);
}
} catch (_) {}
}
void _send(Map<String, dynamic> msg) {
final ch = _channel;
if (ch == null) return;
try {
ch.sink.add(jsonEncode(msg));
} catch (_) {}
}
void _scheduleReconnect() {
_disposeChannel();
if (!isEnabled) return;
_reconnectTimer?.cancel();
final delay = Duration(
milliseconds: (1000 * (1 << _reconnectAttempt.clamp(0, 5))).clamp(1000, 30000),
);
_reconnectAttempt++;
_reconnectTimer = Timer(delay, () async {
await connect();
final interval = _subscribedInterval;
if (interval != null && isConnected) subscribe(interval);
});
}
void _disposeChannel() {
_heartbeat?.cancel();
_heartbeat = null;
_sub?.cancel();
_sub = null;
try {
_channel?.sink.close();
} catch (_) {}
_channel = null;
}
Future<void> dispose() async {
_reconnectTimer?.cancel();
_disposeChannel();
_listeners.clear();
}
}

View File

@ -0,0 +1,148 @@
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:go_router/go_router.dart';
import '../../data/repositories/admin_repository_impl.dart';
import '../../features/admin/presentation/network_screen.dart';
import '../../features/admin/presentation/options_screen.dart';
import '../../features/admin/presentation/settings_screen.dart';
import '../../features/admin/presentation/user_detail_screen.dart';
import '../../features/admin/presentation/user_management_screen.dart';
import '../../features/auth/bloc/auth_bloc.dart';
import '../../features/auth/presentation/forgot_password_screen.dart';
import '../../features/auth/presentation/login_screen.dart';
import '../../features/auth/presentation/register_screen.dart';
import '../../features/auth/presentation/totp_setup_screen.dart';
import '../../features/faq/presentation/faq_screen.dart';
import '../../features/home/presentation/home_screen.dart';
import '../../features/notifications/presentation/notifications_screen.dart';
import '../../features/prediction/presentation/prediction_games_screen.dart';
import '../../features/prediction/presentation/prediction_screen.dart';
import '../../features/referral/presentation/referral_directs_screen.dart';
import '../../features/referral/presentation/referral_network_screen.dart';
import '../../features/referral/presentation/referral_screen.dart';
import '../../features/splash/presentation/splash_screen.dart';
import '../../features/wallet/presentation/account_screen.dart';
import '../../features/wallet/presentation/change_password_screen.dart';
import '../../features/wallet/presentation/deposit_asset_select_screen.dart';
import '../../features/wallet/presentation/deposit_screen.dart';
import '../../features/wallet/presentation/profile_edit_screen.dart';
import '../../features/wallet/presentation/transaction_history_screen.dart';
import '../../features/wallet/presentation/transfer_screen.dart';
import '../../features/wallet/presentation/wallet_overview_screen.dart';
import '../../features/wallet/presentation/withdraw_screen.dart';
import '../../features/welcome/presentation/welcome_screen.dart';
import '../../shared/layout/app_shell.dart';
final _rootNavigatorKey = GlobalKey<NavigatorState>();
GoRouter createAppRouter(AuthBloc authBloc) {
return GoRouter(
navigatorKey: _rootNavigatorKey,
initialLocation: '/',
refreshListenable: GoRouterRefreshStream(authBloc.stream),
redirect: (context, state) {
final auth = authBloc.state;
final path = state.uri.path;
final isAuthRoute =
path == '/login' || path == '/register' || path == '/forgot-password';
final isBoot = path == '/';
final isGuestPublic = path == '/welcome' || path == '/faq' || isAuthRoute;
if (auth.status == AuthStatus.loading || auth.status == AuthStatus.initial) {
// Stay on splash; allow auth forms; otherwise hold on splash.
if (isBoot || isAuthRoute) return null;
return '/';
}
if (!auth.isSignedIn) {
// Splash decides when to leave `/` after min display time.
if (isBoot) return null;
if (isGuestPublic) return null;
return '/welcome';
}
// Signed in: leave splash / welcome / auth for dashboard.
if (isBoot || path == '/welcome' || isAuthRoute) return '/home';
if ((path.startsWith('/options') || path.startsWith('/admin/')) && !auth.isAdmin) {
return '/home';
}
return null;
},
routes: [
GoRoute(path: '/', builder: (_, __) => const SplashScreen()),
GoRoute(path: '/welcome', builder: (_, __) => const WelcomeScreen()),
GoRoute(
path: '/login',
builder: (_, state) {
final extra = state.extra;
final verifyEmail = extra is Map && extra['verifyEmail'] == true;
return LoginScreen(showVerifyEmailHint: verifyEmail);
},
),
GoRoute(
path: '/register',
builder: (_, state) => RegisterScreen(
initialReferralCode: state.uri.queryParameters['ref'],
),
),
GoRoute(path: '/forgot-password', builder: (_, __) => const ForgotPasswordScreen()),
GoRoute(
path: '/faq',
builder: (_, state) => FaqScreen(
initialCategory: state.uri.queryParameters['category'],
),
),
ShellRoute(
builder: (context, state, child) => AppShell(state: state, child: child),
routes: [
GoRoute(path: '/home', builder: (_, __) => const HomeScreen()),
GoRoute(
path: '/notifications',
builder: (_, __) => const NotificationsScreen(),
),
GoRoute(path: '/predict', builder: (_, __) => const PredictionGamesScreen()),
GoRoute(
path: '/predict/candle-predict',
builder: (_, __) => const PredictionScreen(),
),
GoRoute(path: '/wallet', builder: (_, __) => const WalletOverviewScreen()),
GoRoute(path: '/deposit', builder: (_, __) => const DepositAssetSelectScreen()),
GoRoute(
path: '/deposit/:walletType',
builder: (c, state) => DepositScreen(walletTypeCode: state.pathParameters['walletType']!),
),
GoRoute(path: '/withdraw', builder: (_, __) => const WithdrawScreen()),
GoRoute(path: '/transfer', builder: (_, __) => const TransferScreen()),
GoRoute(path: '/transactions', builder: (_, __) => const TransactionHistoryScreen()),
GoRoute(path: '/totp-setup', builder: (_, __) => const TotpSetupScreen()),
GoRoute(path: '/account', builder: (_, __) => const AccountScreen()),
GoRoute(path: '/account/profile', builder: (_, __) => const ProfileEditScreen()),
GoRoute(path: '/account/change-password', builder: (_, __) => const ChangePasswordScreen()),
GoRoute(path: '/referral', builder: (_, __) => const ReferralScreen()),
GoRoute(path: '/referral/directs', builder: (_, __) => const ReferralDirectsScreen()),
GoRoute(path: '/referral/network', builder: (_, __) => const ReferralNetworkScreen()),
GoRoute(path: '/options', builder: (_, __) => const OptionsScreen()),
GoRoute(
path: '/options/settings',
builder: (context, __) => SettingsScreen(adminRepo: context.read<AdminRepositoryImpl>()),
),
GoRoute(path: '/admin/network', builder: (_, __) => const NetworkScreen()),
GoRoute(
path: '/admin/users',
builder: (context, __) => UserManagementScreen(adminRepo: context.read<AdminRepositoryImpl>()),
),
GoRoute(
path: '/admin/users/:userId',
builder: (context, state) => UserDetailScreen(
userId: state.pathParameters['userId']!,
adminRepo: context.read<AdminRepositoryImpl>(),
),
),
],
),
],
);
}

View File

@ -1,48 +0,0 @@
/// Fiat/stablecoin-to-TRX conversion for dashboard display.
///
/// Uses configurable rates until a live pricing API is integrated.
class ExchangeRateService {
/// Creates a service with optional USDT/USDC-to-TRX rates.
ExchangeRateService({
double? usdtToTrx,
double? usdcToTrx,
}) : _usdtToTrx = usdtToTrx ?? 15.0,
_usdcToTrx = usdcToTrx ?? 15.0;
final double _usdtToTrx;
final double _usdcToTrx;
/// TRX per 1 USDT (e.g. 15).
double get usdtToTrx => _usdtToTrx;
/// TRX per 1 USDC (e.g. 15).
double get usdcToTrx => _usdcToTrx;
/// Returns how many TRX one unit of [currencyCode] is worth.
/// [currencyCode] is e.g. TRX, USDT, USDC or USDT_TRC20, USDC_POLYGON.
double trxPerUnit(String currencyCode) {
final upper = currencyCode.toUpperCase();
if (upper == 'TRX') return 1.0;
if (upper.contains('USDT')) return _usdtToTrx;
if (upper.contains('USDC')) return _usdcToTrx;
return 0.0;
}
/// Convert raw amount (in smallest unit) to TRX value for display.
/// [rawAmount] is the balance in smallest unit (e.g. 6 decimals).
double rawToTrxValue(String rawAmount, int decimals, String currencyCode) {
final n = double.tryParse(rawAmount) ?? 0;
final divisor = _pow10(decimals);
final amount = n / divisor;
return amount * trxPerUnit(currencyCode);
}
/// Computes 10 raised to [d] for decimal scaling.
static double _pow10(int d) {
double r = 1;
for (int i = 0; i < d; i++) {
r *= 10;
}
return r;
}
}

View File

@ -0,0 +1,67 @@
import 'package:flutter/material.dart';
/// Premium fintech palette — deep navy, emerald accent, refined gold highlights.
class AppColors {
AppColors._();
// Brand
static const Color primary = Color(0xFF10B981);
static const Color primaryDark = Color(0xFF059669);
static const Color primaryLight = Color(0xFF34D399);
static const Color accentGold = Color(0xFFD4AF37);
// Surfaces — dark (default premium look)
static const Color bgDark = Color(0xFF0B0F1A);
static const Color surfaceDark = Color(0xFF12182B);
static const Color surfaceElevated = Color(0xFF1A2238);
static const Color surfaceCard = Color(0xFF1E2740);
static const Color border = Color(0xFF2A3555);
// Surfaces — light
static const Color bgLight = Color(0xFFF4F6FB);
static const Color surfaceLight = Color(0xFFFFFFFF);
// Semantic
static const Color success = Color(0xFF22C55E);
static const Color danger = Color(0xFFEF4444);
static const Color warning = Color(0xFFF59E0B);
static const Color info = Color(0xFF3B82F6);
// Wallet identities
static const Color walletMain = Color(0xFF10B981);
static const Color walletMainDeep = Color(0xFF047857);
static const Color walletBonus = Color(0xFF7C5CFF);
static const Color walletBonusDeep = Color(0xFF5A3FD4);
static const Color walletTest = Color(0xFF4CAF50);
static const Color walletTestDeep = Color(0xFF2E7D32);
// Legacy aliases (older screens)
static const Color goldPrimary = accentGold;
static const Color goldLight = primaryLight;
static const Color goldDark = primaryDark;
static const Color navy = surfaceElevated;
static const Color navyLight = surfaceCard;
static const Color candleGreen = Color(0xFF22C55E);
static const Color candleRed = Color(0xFFEF4444);
// Text on dark
static const Color textPrimary = Color(0xFFF8FAFC);
static const Color textSecondary = Color(0xFF94A3B8);
static const Color textMuted = Color(0xFF64748B);
static LinearGradient heroGradient(bool isDark) => LinearGradient(
begin: Alignment.topLeft,
end: Alignment.bottomRight,
colors: isDark
? [const Color(0xFF0F172A), const Color(0xFF1E3A5F), const Color(0xFF065F46)]
: [const Color(0xFFECFDF5), const Color(0xFFD1FAE5), const Color(0xFFDBEAFE)],
);
static LinearGradient cardShine(bool isDark) => LinearGradient(
begin: Alignment.topLeft,
end: Alignment.bottomRight,
colors: isDark
? [surfaceCard, surfaceElevated]
: [Colors.white, const Color(0xFFF8FAFC)],
);
}

View File

@ -1,140 +1,114 @@
/// Shared color palette and Material themes for the Prediqo mobile app.
///
/// Provides light/dark themes and gradient accents for navigation chrome.
library;
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'app_colors.dart';
import 'app_typography.dart';
/// Golden + deep navy palette for a premium game-style look. export 'app_colors.dart';
class AppColors {
static const Color goldPrimary = Color(0xFFD4AF37);
static const Color goldLight = Color(0xFFF4D03F);
static const Color goldDark = Color(0xFFB8860B);
static const Color navy = Color(0xFF1a1a2e);
static const Color navyLight = Color(0xFF16213e);
static const Color accent = Color(0xFF0f3460);
static const Color surfaceDark = Color(0xFF0d0d1a);
}
/// Central theme definitions for [MaterialApp] light and dark modes. /// Material 3 themes for Prediqo — dark-first premium fintech aesthetic.
class AppTheme { class AppTheme {
/// Light theme with gold primary and warm surface background. static ThemeData get dark => _build(Brightness.dark);
static ThemeData get light => ThemeData( static ThemeData get light => _build(Brightness.light);
static ThemeData _build(Brightness brightness) {
final isDark = brightness == Brightness.dark;
final scheme = ColorScheme(
brightness: brightness,
primary: AppColors.primary,
onPrimary: Colors.white,
secondary: AppColors.accentGold,
onSecondary: Colors.black,
error: AppColors.danger,
onError: Colors.white,
surface: isDark ? AppColors.surfaceDark : AppColors.surfaceLight,
onSurface: isDark ? AppColors.textPrimary : const Color(0xFF0F172A),
);
return ThemeData(
useMaterial3: true, useMaterial3: true,
colorScheme: ColorScheme.fromSeed( brightness: brightness,
seedColor: AppColors.goldPrimary, colorScheme: scheme,
brightness: Brightness.light, scaffoldBackgroundColor: isDark ? AppColors.bgDark : AppColors.bgLight,
primary: AppColors.goldDark, textTheme: AppTypography.textTheme(brightness),
secondary: AppColors.navy,
surface: const Color(0xFFF8F6F0),
),
scaffoldBackgroundColor: const Color(0xFFF8F6F0),
appBarTheme: AppBarTheme( appBarTheme: AppBarTheme(
centerTitle: true,
elevation: 0, elevation: 0,
scrolledUnderElevation: 0, scrolledUnderElevation: 0,
centerTitle: true,
backgroundColor: Colors.transparent, backgroundColor: Colors.transparent,
foregroundColor: AppColors.navy, foregroundColor: scheme.onSurface,
iconTheme: const IconThemeData(color: AppColors.navy), systemOverlayStyle: isDark ? SystemUiOverlayStyle.light : SystemUiOverlayStyle.dark,
titleTextStyle: const TextStyle( titleTextStyle: AppTypography.textTheme(brightness).titleLarge,
color: AppColors.navy,
fontSize: 20,
fontWeight: FontWeight.w600,
),
),
bottomNavigationBarTheme: BottomNavigationBarThemeData(
backgroundColor: AppColors.navy,
selectedItemColor: AppColors.goldLight,
unselectedItemColor: Colors.white70,
type: BottomNavigationBarType.fixed,
elevation: 24,
), ),
cardTheme: CardThemeData( cardTheme: CardThemeData(
elevation: 2, elevation: 0,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)), color: isDark ? AppColors.surfaceCard : Colors.white,
margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 8), shape: RoundedRectangleBorder(
color: Colors.white, borderRadius: BorderRadius.circular(20),
side: BorderSide(color: isDark ? AppColors.border : const Color(0xFFE2E8F0)),
),
margin: EdgeInsets.zero,
), ),
inputDecorationTheme: InputDecorationTheme( inputDecorationTheme: InputDecorationTheme(
border: OutlineInputBorder(borderRadius: BorderRadius.circular(12)),
filled: true, filled: true,
contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 14), fillColor: isDark ? AppColors.surfaceElevated : const Color(0xFFF1F5F9),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(16),
borderSide: BorderSide(color: isDark ? AppColors.border : const Color(0xFFE2E8F0)),
),
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(16),
borderSide: BorderSide(color: isDark ? AppColors.border : const Color(0xFFE2E8F0)),
),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(16),
borderSide: const BorderSide(color: AppColors.primary, width: 2),
),
contentPadding: const EdgeInsets.symmetric(horizontal: 18, vertical: 16),
hintStyle: TextStyle(color: isDark ? AppColors.textMuted : const Color(0xFF94A3B8)),
), ),
filledButtonTheme: FilledButtonThemeData( filledButtonTheme: FilledButtonThemeData(
style: FilledButton.styleFrom( style: FilledButton.styleFrom(
backgroundColor: AppColors.goldDark, backgroundColor: AppColors.primary,
foregroundColor: Colors.white, foregroundColor: Colors.white,
padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 14), disabledBackgroundColor: isDark ? AppColors.border : const Color(0xFFCBD5E1),
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)), padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 16),
),
),
);
/// Dark theme with navy surfaces and gold accent foreground.
static ThemeData get dark => ThemeData(
useMaterial3: true,
colorScheme: ColorScheme.fromSeed(
seedColor: AppColors.goldPrimary,
brightness: Brightness.dark,
primary: AppColors.goldLight,
secondary: AppColors.navyLight,
surface: AppColors.surfaceDark,
),
scaffoldBackgroundColor: AppColors.surfaceDark,
appBarTheme: AppBarTheme(
centerTitle: true,
elevation: 0,
scrolledUnderElevation: 0,
backgroundColor: Colors.transparent,
foregroundColor: AppColors.goldLight,
iconTheme: const IconThemeData(color: AppColors.goldLight),
titleTextStyle: const TextStyle(
color: AppColors.goldLight,
fontSize: 20,
fontWeight: FontWeight.w600,
),
),
bottomNavigationBarTheme: BottomNavigationBarThemeData(
backgroundColor: AppColors.navy,
selectedItemColor: AppColors.goldLight,
unselectedItemColor: Colors.white54,
type: BottomNavigationBarType.fixed,
elevation: 24,
),
cardTheme: CardThemeData(
elevation: 2,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)), shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 8), textStyle: const TextStyle(fontWeight: FontWeight.w700, fontSize: 15),
color: AppColors.navyLight,
), ),
inputDecorationTheme: InputDecorationTheme(
border: OutlineInputBorder(borderRadius: BorderRadius.circular(12)),
filled: true,
contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 14),
), ),
filledButtonTheme: FilledButtonThemeData( outlinedButtonTheme: OutlinedButtonThemeData(
style: FilledButton.styleFrom( style: OutlinedButton.styleFrom(
backgroundColor: AppColors.goldDark, foregroundColor: scheme.onSurface,
foregroundColor: Colors.white, side: BorderSide(color: isDark ? AppColors.border : const Color(0xFFCBD5E1)),
padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 14), padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 14),
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)), shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
),
),
snackBarTheme: SnackBarThemeData(
behavior: SnackBarBehavior.floating,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(14)),
backgroundColor: isDark ? AppColors.surfaceElevated : const Color(0xFF1E293B),
),
dividerTheme: DividerThemeData(color: isDark ? AppColors.border : const Color(0xFFE2E8F0)),
bottomSheetTheme: const BottomSheetThemeData(
showDragHandle: true,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.vertical(top: Radius.circular(24)),
), ),
), ),
); );
}
/// Gradient for app bar and bottom nav (gold to dark). /// Legacy gradient alias used by older wallet/admin screens.
static const LinearGradient goldGradient = LinearGradient( static const LinearGradient goldGradient = LinearGradient(
begin: Alignment.topLeft, begin: Alignment.topLeft,
end: Alignment.bottomRight, end: Alignment.bottomRight,
colors: [Color(0xFF1a1a2e), Color(0xFF16213e), Color(0xFF0f3460)], colors: [AppColors.surfaceElevated, AppColors.surfaceCard, Color(0xFF0F172A)],
stops: [0.0, 0.5, 1.0],
); );
/// Gold accent gradient for highlights and call-to-action surfaces.
static const LinearGradient goldAccentGradient = LinearGradient( static const LinearGradient goldAccentGradient = LinearGradient(
begin: Alignment.topLeft, begin: Alignment.topLeft,
end: Alignment.bottomRight, end: Alignment.bottomRight,
colors: [AppColors.goldDark, AppColors.goldPrimary, AppColors.goldLight], colors: [AppColors.primaryDark, AppColors.primary, AppColors.primaryLight],
stops: [0.0, 0.5, 1.0],
); );
} }

View File

@ -0,0 +1,27 @@
import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import 'app_colors.dart';
/// Typography scale using Plus Jakarta Sans for a modern fintech look.
class AppTypography {
static TextTheme textTheme(Brightness brightness) {
final base = GoogleFonts.plusJakartaSansTextTheme();
final color = brightness == Brightness.dark ? AppColors.textPrimary : const Color(0xFF0F172A);
final secondary = brightness == Brightness.dark ? AppColors.textSecondary : const Color(0xFF475569);
return base.copyWith(
displayLarge: base.displayLarge?.copyWith(color: color, fontWeight: FontWeight.w700),
displayMedium: base.displayMedium?.copyWith(color: color, fontWeight: FontWeight.w700),
headlineLarge: base.headlineLarge?.copyWith(color: color, fontWeight: FontWeight.w700, fontSize: 28),
headlineMedium: base.headlineMedium?.copyWith(color: color, fontWeight: FontWeight.w700, fontSize: 22),
headlineSmall: base.headlineSmall?.copyWith(color: color, fontWeight: FontWeight.w600, fontSize: 18),
titleLarge: base.titleLarge?.copyWith(color: color, fontWeight: FontWeight.w600),
titleMedium: base.titleMedium?.copyWith(color: color, fontWeight: FontWeight.w600),
titleSmall: base.titleSmall?.copyWith(color: secondary, fontWeight: FontWeight.w500),
bodyLarge: base.bodyLarge?.copyWith(color: color),
bodyMedium: base.bodyMedium?.copyWith(color: color),
bodySmall: base.bodySmall?.copyWith(color: secondary),
labelLarge: base.labelLarge?.copyWith(fontWeight: FontWeight.w600, letterSpacing: 0.4),
);
}
}

Some files were not shown because too many files have changed in this diff Show More