After adding the BSC option

This commit is contained in:
Your Name 2026-08-24 13:41:54 +02:00
parent efae596a97
commit 342e84b6ef
41 changed files with 1252 additions and 374 deletions

View File

@ -60,10 +60,16 @@ TURNSTILE_SITE_KEY=
TURNSTILE_SECRET_KEY=
PLATFORM_MNEMONIC=word1 word2 ... word24
# Blockchain (testnet example)
# Blockchain (testnet example for TRON; BSC mainnet for dual-chain USDT)
TRON_NODE_URL=https://api.shasta.trongrid.io
TRON_CONFIRMATIONS=3
USDT_TRC20_CONTRACT=
# BSC (USDT BEP20) — use a reliable mainnet RPC in production
BSC_RPC_URL=https://bsc-dataseed.binance.org
BSC_CONFIRMATIONS=15
# Leave empty to use official USDT BEP20 from DB (0x55d3…7955)
USDT_BEP20_CONTRACT=
BSC_GETLOGS_BLOCK_RANGE=2000
POLYGON_RPC_URL=https://rpc-amoy.polygon.technology
POLYGON_CONFIRMATIONS=8
USDC_POLYGON_CONTRACT=

View File

@ -28,6 +28,11 @@ POLYGON_RPC_URL=https://polygon-rpc.com
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=
# BSC mainnet for USDT BEP20 (parallel to TRC20)
BSC_RPC_URL=https://bsc-dataseed.binance.org
# Leave empty to use official USDT BEP20 from DB
USDT_BEP20_CONTRACT=
BSC_GETLOGS_BLOCK_RANGE=2000
# Safety (recommended for testing)
# NETWORK_MODE=testnet # default behavior in non-production is testnet safety
@ -35,6 +40,7 @@ USDT_TRC20_CONTRACT=
# Deposit confirmations
TRON_CONFIRMATIONS=20
BSC_CONFIRMATIONS=15
POLYGON_CONFIRMATIONS=64
# Rate limiting

View File

@ -65,23 +65,40 @@ function maskAddress(addr: string | null | undefined): string | null {
app.get('/health', async (_req, res) => {
const settings = await settingsRepository.getSettings();
const feeRaw = getWithdrawalNetworkFeeRaw(settings);
/** Fee in 6-decimal micro-USDT; clients scale to wallet decimals (e.g. BEP20 18). */
const feeRaw = getWithdrawalNetworkFeeRaw(settings, 6);
res.json({
status: 'ok',
timestamp: new Date().toISOString(),
env: config.env,
emailTransport: config.email.transport,
emailConsoleMode: usesConsoleEmailTransport(),
/** @deprecated Prefer `assets` — primary prediction ledger remains TRC20. */
asset: 'USDT_TRC20',
network: labelTronNetwork(config.blockchain.tron.nodeUrl),
assets: ['USDT_TRC20', 'USDT_BEP20'],
networks: {
USDT_TRC20: {
depositEnabled: settings.network_usdt_trc20_deposit_enabled,
withdrawEnabled: settings.network_usdt_trc20_withdraw_enabled,
label: labelTronNetwork(config.blockchain.tron.nodeUrl),
},
USDT_BEP20: {
depositEnabled: settings.network_usdt_bep20_deposit_enabled,
withdrawEnabled: settings.network_usdt_bep20_withdraw_enabled,
label: 'bsc',
},
},
withdrawalsEnabled: settings.allow_withdrawals,
requireWithdrawal2fa: settings.require_withdrawal_2fa,
withdrawalNetworkFeeRaw: feeRaw.toString(),
rpc: {
tronNodeUrl: config.blockchain.tron.nodeUrl,
bscRpcUrl: config.blockchain.bsc.rpcUrl,
},
contracts: {
usdtTrc20: maskAddress(config.blockchain.tron.usdtTrc20Contract),
usdtBep20: maskAddress(config.blockchain.bsc.usdtBep20Contract),
},
});
});

View File

@ -6,7 +6,7 @@ import { config } from '../config';
import { runMigrations } from '../db/connection';
import { registerBuiltinGames } from '../games/bootstrap';
import { startRegisteredGameEngines } from '../games/engineRunner';
import { processTronDeposits } from '../services/depositMonitorService';
import { processAllDeposits } from '../services/depositMonitorService';
import { runLedgerIntegrityCheck, getIntegrityCheckIntervalMs } from '../services/securityService';
import { runFileIntegrityCheck } from '../services/fileIntegrityService';
import { processDbTamperEvents, getTamperCheckIntervalMs } from '../services/dbTamperService';
@ -35,7 +35,7 @@ const DEPOSIT_POLL_INTERVAL_MS = 60 * 1000;
async function startDepositMonitor(): Promise<void> {
const run = async () => {
try {
await processTronDeposits();
await processAllDeposits();
} catch (e) {
console.error('Deposit monitor error:', e);
}

View File

@ -99,6 +99,15 @@ export const config = {
/** Max blocks per eth_getLogs call; Amoy public RPC rejects ~500-block ranges */
getLogsBlockRange: parseInt(process.env.POLYGON_GETLOGS_BLOCK_RANGE || '100', 10),
},
bsc: {
rpcUrl: process.env.BSC_RPC_URL || 'https://bsc-dataseed.binance.org',
/** Optional override; otherwise DB wallet_types.contract_address for USDT_BEP20 */
usdtBep20Contract: process.env.USDT_BEP20_CONTRACT || null,
confirmations: parseInt(process.env.BSC_CONFIRMATIONS || '15', 10),
getLogsBlockRange: parseInt(process.env.BSC_GETLOGS_BLOCK_RANGE || '2000', 10),
/** Native BNB top-up for sweeps (wei); default 0.001 BNB */
gasTopUpWei: process.env.SWEEP_BSC_GAS_TOPUP_WEI || '1000000000000000',
},
},
rateLimit: {
windowMs: parseInt(process.env.RATE_LIMIT_WINDOW_MS || '900000', 10),

View File

@ -177,7 +177,7 @@ CREATE TABLE IF NOT EXISTS refresh_tokens (
CREATE INDEX IF NOT EXISTS idx_refresh_tokens_user ON refresh_tokens(user_id);
CREATE INDEX IF NOT EXISTS idx_refresh_tokens_expires ON refresh_tokens(expires_at);
-- Wallet types (USDT TRC20 only — platform stablecoin for deposits and predictions)
-- Wallet types (USDT on TRON TRC20 + BSC BEP20)
CREATE TABLE IF NOT EXISTS wallet_types (
id SERIAL PRIMARY KEY,
code VARCHAR(32) UNIQUE NOT NULL,
@ -188,7 +188,8 @@ CREATE TABLE IF NOT EXISTS wallet_types (
);
INSERT INTO wallet_types (code, name, network, decimals, contract_address) VALUES
('USDT_TRC20', 'USDT (TRC20)', 'TRON', 6, 'TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t')
('USDT_TRC20', 'USDT (TRC20)', 'TRON', 6, 'TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t'),
('USDT_BEP20', 'USDT (BEP20)', 'BSC', 18, '0x55d398326f99059fF775485246999027B3197955')
ON CONFLICT (code) DO NOTHING;
-- User deposit addresses (derived from HD wallet; only public address stored)
@ -430,6 +431,10 @@ ON CONFLICT (key) DO NOTHING;
-- Runtime ops defaults (env-backed until admin overrides via Settings UI)
INSERT INTO system_settings (key, value) VALUES
('allow_withdrawals', 'false'),
('network_usdt_trc20_deposit_enabled', 'true'),
('network_usdt_trc20_withdraw_enabled', 'true'),
('network_usdt_bep20_deposit_enabled', 'true'),
('network_usdt_bep20_withdraw_enabled', 'true'),
('rate_limit_window_ms', '900000'),
('rate_limit_max', '2000'),
('login_rate_limit_max', '20'),

View File

@ -15,6 +15,11 @@ export interface SystemSettings {
require_email_verification_for_login: boolean;
/** Kill-switch for on-chain withdrawal broadcasts. */
allow_withdrawals: boolean;
/** Per-network deposit/withdraw gates (USDT TRC20 / BEP20). */
network_usdt_trc20_deposit_enabled: boolean;
network_usdt_trc20_withdraw_enabled: boolean;
network_usdt_bep20_deposit_enabled: boolean;
network_usdt_bep20_withdraw_enabled: boolean;
/** Global API rate limit window (ms). Takes effect after server restart. */
rate_limit_window_ms: number;
/** Max requests per IP per rate_limit_window_ms. */

View File

@ -44,6 +44,14 @@ function buildDefaults(): SystemSettings {
allow_withdrawals: config.withdrawal.allowWithdrawals,
network_usdt_trc20_deposit_enabled: true,
network_usdt_trc20_withdraw_enabled: true,
network_usdt_bep20_deposit_enabled: true,
network_usdt_bep20_withdraw_enabled: true,
rate_limit_window_ms: config.rateLimit.windowMs,
rate_limit_max: config.rateLimit.max,
@ -103,6 +111,14 @@ const BOOLEAN_KEYS = new Set([
'allow_withdrawals',
'network_usdt_trc20_deposit_enabled',
'network_usdt_trc20_withdraw_enabled',
'network_usdt_bep20_deposit_enabled',
'network_usdt_bep20_withdraw_enabled',
'require_admin_2fa',
'require_withdrawal_2fa',
@ -249,6 +265,14 @@ const UPDATABLE_KEYS = [
'allow_withdrawals',
'network_usdt_trc20_deposit_enabled',
'network_usdt_trc20_withdraw_enabled',
'network_usdt_bep20_deposit_enabled',
'network_usdt_bep20_withdraw_enabled',
'rate_limit_window_ms',
'rate_limit_max',

View File

@ -12,11 +12,16 @@ export const MAINNET_USDT_TRC20_CONTRACT = 'TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t';
/** Shasta testnet USDT TRC20 — must never be used in production. */
export const SHASTA_USDT_TRC20_CONTRACT = 'TG3XXyExBkPp9nzdajDZsozEu4BkaSJozs';
/** Official mainnet USDT on BSC (BEP20). */
export const MAINNET_USDT_BEP20_CONTRACT = '0x55d398326f99059fF775485246999027B3197955';
export type NetworkGuardConfig = {
env: string;
networkMode: string;
tronNodeUrl: string;
usdtTrc20Contract: string | null;
bscRpcUrl?: string;
usdtBep20Contract?: string | null;
};
function assert(condition: boolean, message: string): void {
@ -35,9 +40,13 @@ function isShastaUsdtContract(contract: string): boolean {
return contract.trim().toLowerCase() === SHASTA_USDT_TRC20_CONTRACT.toLowerCase();
}
function looksLikeBscTestnet(url: string): boolean {
return /testnet|chapel|amoy/i.test(url);
}
/**
* Validates production blockchain settings (testable with explicit config).
* @throws When production would use testnet TRON or Shasta USDT contract
* @throws When production would use testnet TRON/BSC or Shasta USDT contract
*/
export function assertProductionMainnetConfig(cfg: NetworkGuardConfig): void {
if (cfg.env !== 'production') return;
@ -60,6 +69,14 @@ export function assertProductionMainnetConfig(cfg: NetworkGuardConfig): void {
`Use mainnet USDT (${MAINNET_USDT_TRC20_CONTRACT}) or unset USDT_TRC20_CONTRACT to use the DB default.`
);
}
const bscUrl = (cfg.bscRpcUrl || '').trim();
if (bscUrl) {
assert(
!looksLikeBscTestnet(bscUrl),
`Safety check failed: BSC_RPC_URL must not point to a BSC testnet in production. Got: ${bscUrl}`
);
}
}
/**
@ -91,9 +108,9 @@ export function validateTestnetSafetyOrThrow(): void {
}
/**
* Validates that production runs use mainnet TRON and never the Shasta USDT contract.
* Validates that production runs use mainnet TRON/BSC and never the Shasta USDT contract.
* Skipped when NODE_ENV is not production.
* @throws When TRON_NODE_URL or USDT_TRC20_CONTRACT targets testnet
* @throws When TRON_NODE_URL, BSC_RPC_URL, or USDT_TRC20_CONTRACT targets testnet
*/
export function validateProductionMainnetOrThrow(): void {
assertProductionMainnetConfig({
@ -101,5 +118,7 @@ export function validateProductionMainnetOrThrow(): void {
networkMode: (process.env.NETWORK_MODE || '').toLowerCase(),
tronNodeUrl: config.blockchain.tron.nodeUrl,
usdtTrc20Contract: config.blockchain.tron.usdtTrc20Contract,
bscRpcUrl: config.blockchain.bsc.rpcUrl,
usdtBep20Contract: config.blockchain.bsc.usdtBep20Contract,
});
}

View File

@ -1,42 +1,41 @@
/**
* Replace USDT deposit addresses so they derive from the current PLATFORM_MNEMONIC.
* Replace deposit addresses so they derive from the current PLATFORM_MNEMONIC.
*
* Use after rotating PLATFORM_MNEMONIC when old addresses were derived from a previous phrase.
* Does NOT touch hot_wallets, cold_wallets, or ledger balances.
* Supports USDT_TRC20 (TRON) and USDT_BEP20 (BSC). Does NOT touch hot/cold wallets or ledger.
*
* WARNING: Any USDT still on the OLD on-chain addresses becomes unreachable unless you still
* have the previous mnemonic. Only run this when old addresses hold no real funds (or after
* sweeping them with the old mnemonic).
* WARNING: Any funds still on OLD on-chain addresses become unreachable without the previous mnemonic.
*
* VPS:
* sudo docker compose run --rm --no-deps --build backend \
* node dist/scripts/rotateDepositAddresses.js \
* --confirm=ROTATE_DEPOSIT_ADDRESSES \
* --scope=existing
* --scope=existing \
* --wallet-type=ALL
*
* --scope=existing users who already have a USDT deposit address
* --scope=all every non-deleted user (creates addresses if missing)
* --email=a@b.com only that user
* --wallet-type=USDT_TRC20 | USDT_BEP20 | ALL (default ALL)
* --scope=existing | --scope=all | --email=a@b.com
*/
import './loadEnv';
import * as bip39 from 'bip39';
import { hashForIndex } from '../utils/crypto';
import { query } from '../db/connection';
import { deriveTronFromMnemonic } from '../services/hdWallet';
import { deriveEvmFromMnemonic, deriveTronFromMnemonic } from '../services/hdWallet';
import * as userRepository from '../repositories/userRepository';
import * as walletRepository from '../repositories/walletRepository';
import * as auditLogRepository from '../repositories/auditLogRepository';
import { USDT_WALLET_CODE } from '../services/walletCapabilities';
import { USDT_BEP20_CODE, USDT_TRC20_CODE } from '../services/walletCapabilities';
const CONFIRM_PHRASE = 'ROTATE_DEPOSIT_ADDRESSES';
type Scope = 'existing' | 'all';
type Code = typeof USDT_TRC20_CODE | typeof USDT_BEP20_CODE;
type Args = {
confirm: string;
scope: Scope | null;
email: string | null;
walletTypes: Code[];
};
type WalletRow = {
@ -49,11 +48,8 @@ function printUsageAndExit(code = 1): never {
console.error(`Usage:
node dist/scripts/rotateDepositAddresses.js \\
--confirm=${CONFIRM_PHRASE} \\
(--scope=existing | --scope=all | --email=user@example.com)
--scope=existing Rotate only users who already have a USDT deposit address
--scope=all Ensure every active user has a new address from current mnemonic
--email=... Rotate a single user
(--scope=existing | --scope=all | --email=user@example.com) \\
[--wallet-type=ALL|USDT_TRC20|USDT_BEP20]
`);
process.exit(code);
}
@ -71,8 +67,14 @@ function parseArgs(argv: string[]): Args {
const email = (map.get('email') || '').trim().toLowerCase() || null;
const scope: Scope | null =
scopeRaw === 'existing' || scopeRaw === 'all' ? (scopeRaw as Scope) : null;
const wtRaw = (map.get('wallet-type') || 'ALL').trim().toUpperCase();
let walletTypes: Code[];
if (wtRaw === 'ALL') walletTypes = [USDT_TRC20_CODE, USDT_BEP20_CODE];
else if (wtRaw === USDT_TRC20_CODE || wtRaw === USDT_BEP20_CODE) walletTypes = [wtRaw];
else printUsageAndExit(1);
if (!confirm || (!scope && !email) || (scope && email)) printUsageAndExit(1);
return { confirm, scope, email };
return { confirm, scope, email, walletTypes };
}
function requireCurrentMnemonic(): string {
@ -86,6 +88,81 @@ function requireCurrentMnemonic(): string {
return raw;
}
function deriveAddress(mnemonic: string, code: Code, index: number): { address: string } {
if (code === USDT_BEP20_CODE) return deriveEvmFromMnemonic(mnemonic, index);
return deriveTronFromMnemonic(mnemonic, index);
}
async function rotateOne(opts: {
mnemonic: string;
code: Code;
userIds: string[];
scope: Scope | null;
email: string | null;
}): Promise<void> {
const wt = await walletRepository.getWalletTypeByCode(opts.code);
if (!wt) {
console.log(`[${opts.code}] wallet type not found — skip (run migrations).`);
return;
}
const before = await query<WalletRow[]>(
`SELECT user_id, address, derivation_index
FROM user_wallets
WHERE wallet_type_id = $1 AND user_id = ANY($2::uuid[])
ORDER BY derivation_index ASC`,
[wt.id, opts.userIds]
);
console.log(`\n[${opts.code}] Users: ${opts.userIds.length}; addresses to replace: ${before.length}`);
for (const row of before.slice(0, 10)) {
console.log(` old index=${row.derivation_index} user=${row.user_id} ${row.address}`);
}
if (before.length > 10) console.log(` … and ${before.length - 10} more`);
await query(`DELETE FROM user_wallets WHERE wallet_type_id = $1 AND user_id = ANY($2::uuid[])`, [
wt.id,
opts.userIds,
]);
let nextIndex = await walletRepository.getNextDerivationIndex(wt.id);
const created: Array<{ userId: string; address: string; index: number }> = [];
for (const userId of opts.userIds) {
const derived = deriveAddress(opts.mnemonic, opts.code, nextIndex);
await walletRepository.createUserWallet({
userId,
walletTypeId: wt.id,
address: derived.address,
derivationIndex: nextIndex,
});
created.push({ userId, address: derived.address, index: nextIndex });
nextIndex += 1;
}
await auditLogRepository.create({
userId: null,
action: 'deposit_addresses_rotated',
resourceType: 'user_wallets',
metadata: {
channel: 'cli_rotate_deposit_addresses',
walletType: opts.code,
scope: opts.scope ?? 'email',
email: opts.email,
usersProcessed: opts.userIds.length,
addressesReplaced: before.length,
oldAddressesSample: before.slice(0, 10).map((r) => r.address),
newAddressesSample: created.slice(0, 10).map((c) => c.address),
},
});
console.log(`[${opts.code}] Created ${created.length} new deposit address(es).`);
for (const row of created.slice(0, 15)) {
console.log(` new index=${row.index} user=${row.userId} ${row.address}`);
}
if (created.length > 15) console.log(` … and ${created.length - 15} more`);
}
async function main(): Promise<void> {
const args = parseArgs(process.argv.slice(2));
if (args.confirm !== CONFIRM_PHRASE) {
@ -93,8 +170,6 @@ async function main(): Promise<void> {
}
const mnemonic = requireCurrentMnemonic();
const usdt = await walletRepository.getWalletTypeByCode(USDT_WALLET_CODE);
if (!usdt) throw new Error('USDT_TRC20 wallet type not found — run migrations first.');
let userIds: string[] = [];
@ -103,13 +178,23 @@ async function main(): Promise<void> {
if (!user) throw new Error(`No active user for email: ${args.email}`);
userIds = [user.id];
} else if (args.scope === 'existing') {
// Users who have at least one deposit address for any selected type
const typeIds: number[] = [];
for (const code of args.walletTypes) {
const wt = await walletRepository.getWalletTypeByCode(code);
if (wt) typeIds.push(wt.id);
}
if (typeIds.length === 0) {
console.log('No wallet types found. Nothing to do.');
return;
}
const rows = await query<{ user_id: string }[]>(
`SELECT uw.user_id
`SELECT DISTINCT uw.user_id
FROM user_wallets uw
JOIN users u ON u.id = uw.user_id
WHERE uw.wallet_type_id = $1 AND u.deleted_at IS NULL
ORDER BY uw.derivation_index ASC, uw.created_at ASC`,
[usdt.id]
WHERE uw.wallet_type_id = ANY($1::int[]) AND u.deleted_at IS NULL
ORDER BY uw.user_id`,
[typeIds]
);
userIds = rows.map((r) => r.user_id);
} else {
@ -124,69 +209,23 @@ async function main(): Promise<void> {
return;
}
const before = await query<WalletRow[]>(
`SELECT user_id, address, derivation_index
FROM user_wallets
WHERE wallet_type_id = $1 AND user_id = ANY($2::uuid[])
ORDER BY derivation_index ASC`,
[usdt.id, userIds]
);
console.log(`PLATFORM_MNEMONIC: valid (${mnemonic.split(/\s+/).length} words)`);
console.log(`Users to process: ${userIds.length}`);
console.log(`Existing USDT deposit addresses that will be replaced: ${before.length}`);
for (const row of before.slice(0, 20)) {
console.log(` old index=${row.derivation_index} user=${row.user_id} ${row.address}`);
}
if (before.length > 20) console.log(` … and ${before.length - 20} more`);
console.log(
'\nWARNING: Do not send real USDT to the old addresses above after this rotation.\n'
'\nWARNING: Do not send real USDT to old addresses after this rotation.\n'
);
await query(`DELETE FROM user_wallets WHERE wallet_type_id = $1 AND user_id = ANY($2::uuid[])`, [
usdt.id,
userIds,
]);
// Start indices after any remaining wallets (other users not in this batch).
let nextIndex = await walletRepository.getNextDerivationIndex(usdt.id);
const created: Array<{ userId: string; address: string; index: number }> = [];
for (const userId of userIds) {
const derived = deriveTronFromMnemonic(mnemonic, nextIndex);
await walletRepository.createUserWallet({
userId,
walletTypeId: usdt.id,
address: derived.address,
derivationIndex: nextIndex,
});
created.push({ userId, address: derived.address, index: nextIndex });
nextIndex += 1;
}
await auditLogRepository.create({
userId: null,
action: 'deposit_addresses_rotated',
resourceType: 'user_wallets',
metadata: {
channel: 'cli_rotate_deposit_addresses',
scope: args.scope ?? 'email',
for (const code of args.walletTypes) {
await rotateOne({
mnemonic,
code,
userIds,
scope: args.scope,
email: args.email,
usersProcessed: userIds.length,
addressesReplaced: before.length,
oldAddressesSample: before.slice(0, 10).map((r) => r.address),
newAddressesSample: created.slice(0, 10).map((c) => c.address),
},
});
console.log(`Created ${created.length} new USDT deposit address(es) from current mnemonic:`);
for (const row of created.slice(0, 30)) {
console.log(` new index=${row.index} user=${row.userId} ${row.address}`);
});
}
if (created.length > 30) console.log(` … and ${created.length - 30} more`);
console.log('\nHot wallet unchanged. Ledger balances unchanged.');
console.log('Open Deposit in the app to verify the new address matches the list above.');
console.log('\nHot wallets unchanged. Ledger balances unchanged.');
console.log('Open Deposit in the app and verify the new address for each network.');
}
main()

View File

@ -1,19 +1,56 @@
/**
* Seed hot wallet for USDT TRC20 withdrawals.
* Derives one TRON address from PLATFORM_MNEMONIC at a fixed high index.
* Seed hot wallets for USDT TRC20 (TRON) and USDT BEP20 (BSC) withdrawals.
*
* Usage (from backend/):
* npm run seed-hot-wallets
*
* VPS:
* sudo docker compose run --rm --no-deps --build backend node dist/scripts/seedHotWallets.js
*/
import './loadEnv';
import { query } from '../db/connection';
import { deriveTronFromMnemonic, encryptPrivateKey } from '../services/hdWallet';
import {
deriveEvmFromMnemonic,
deriveTronFromMnemonic,
encryptPrivateKey,
} from '../services/hdWallet';
import * as hotWalletRepository from '../repositories/hotWalletRepository';
import * as walletRepository from '../repositories/walletRepository';
import { USDT_WALLET_CODE } from '../services/walletCapabilities';
import { USDT_BEP20_CODE, USDT_TRC20_CODE } from '../services/walletCapabilities';
const HOT_DERIVATION_INDEX = 1_000_000;
const HOT_DERIVATION_INDEX_TRON = 1_000_000;
const HOT_DERIVATION_INDEX_BSC = 1_000_001;
async function seedOne(opts: {
code: string;
address: string;
encryptedPrivateKey: string;
derivationIndex: number;
fundHint: string;
}): Promise<void> {
const wt = await walletRepository.getWalletTypeByCode(opts.code);
if (!wt) throw new Error(`${opts.code} wallet type not found — run migrations first.`);
const existing = await query<{ wallet_type_id: number }[]>(
'SELECT wallet_type_id FROM hot_wallets WHERE is_active = TRUE AND wallet_type_id = $1',
[wt.id]
);
if (existing.length > 0) {
console.log(`Hot wallet already exists for ${opts.code}. Skipping.`);
console.log(' ', opts.address);
} else {
await hotWalletRepository.create({
walletTypeId: wt.id,
address: opts.address,
encryptedPrivateKey: opts.encryptedPrivateKey,
derivationIndex: opts.derivationIndex,
});
console.log(`Created hot wallet for ${opts.code}:`, opts.address);
}
console.log(` Fund with: ${opts.fundHint}`);
}
async function main(): Promise<void> {
const mnemonic = (process.env.PLATFORM_MNEMONIC || '').trim();
@ -25,32 +62,23 @@ async function main(): Promise<void> {
throw new Error('ENCRYPTION_KEY must be 32-byte hex (64 chars) in .env.');
}
const usdt = await walletRepository.getWalletTypeByCode(USDT_WALLET_CODE);
if (!usdt) throw new Error('USDT_TRC20 wallet type not found — run migrations first.');
const tron = deriveTronFromMnemonic(mnemonic, HOT_DERIVATION_INDEX_TRON);
await seedOne({
code: USDT_TRC20_CODE,
address: tron.address,
encryptedPrivateKey: encryptPrivateKey(tron.privateKey),
derivationIndex: HOT_DERIVATION_INDEX_TRON,
fundHint: 'TRX (gas) + USDT TRC20 on TRON mainnet',
});
const existing = await query<{ wallet_type_id: number }[]>(
'SELECT wallet_type_id FROM hot_wallets WHERE is_active = TRUE AND wallet_type_id = $1',
[usdt.id]
);
const tronDerived = deriveTronFromMnemonic(mnemonic, HOT_DERIVATION_INDEX);
const tronEncrypted = encryptPrivateKey(tronDerived.privateKey);
if (existing.length > 0) {
console.log('Hot wallet already exists for USDT_TRC20. Skipping.');
} else {
await hotWalletRepository.create({
walletTypeId: usdt.id,
address: tronDerived.address,
encryptedPrivateKey: tronEncrypted,
derivationIndex: HOT_DERIVATION_INDEX,
});
console.log('Created hot wallet for USDT_TRC20:', tronDerived.address);
}
console.log('\nFund this address on your TRON network (Shasta testnet or mainnet):');
console.log(' ', tronDerived.address);
console.log('\nUsers need TRX on-chain for gas when sweeping; fund hot wallet with TRX + USDT.');
const bsc = deriveEvmFromMnemonic(mnemonic, HOT_DERIVATION_INDEX_BSC);
await seedOne({
code: USDT_BEP20_CODE,
address: bsc.address,
encryptedPrivateKey: encryptPrivateKey(bsc.privateKey),
derivationIndex: HOT_DERIVATION_INDEX_BSC,
fundHint: 'BNB (gas) + USDT BEP20 on BSC mainnet',
});
}
main()

View File

@ -1,49 +1,58 @@
/**
* Verify that every USDT row in user_wallets matches PLATFORM_MNEMONIC + derivation_index.
* Verify that user_wallets rows match PLATFORM_MNEMONIC + derivation_index.
* Supports USDT_TRC20 (TRON) and USDT_BEP20 (BSC).
*
* VPS:
* sudo docker compose run --rm --no-deps --build backend \
* node dist/scripts/verifyDepositAddresses.js
*
* Optional: --wallet-type=USDT_TRC20 | USDT_BEP20 | ALL (default ALL)
*/
import './loadEnv';
import * as bip39 from 'bip39';
import { query } from '../db/connection';
import { deriveTronFromMnemonic } from '../services/hdWallet';
import { deriveEvmFromMnemonic, deriveTronFromMnemonic } from '../services/hdWallet';
import * as walletRepository from '../repositories/walletRepository';
import { USDT_WALLET_CODE } from '../services/walletCapabilities';
import { USDT_BEP20_CODE, USDT_TRC20_CODE } from '../services/walletCapabilities';
async function main(): Promise<void> {
const mnemonic = (process.env.PLATFORM_MNEMONIC || '').trim();
if (!mnemonic || !bip39.validateMnemonic(mnemonic)) {
throw new Error('PLATFORM_MNEMONIC missing or invalid BIP39 phrase.');
type Code = typeof USDT_TRC20_CODE | typeof USDT_BEP20_CODE;
function parseWalletTypes(argv: string[]): Code[] {
const raw = argv.find((a) => a.startsWith('--wallet-type='))?.slice('--wallet-type='.length).trim().toUpperCase();
if (!raw || raw === 'ALL') return [USDT_TRC20_CODE, USDT_BEP20_CODE];
if (raw === USDT_TRC20_CODE || raw === USDT_BEP20_CODE) return [raw];
throw new Error(`--wallet-type must be ${USDT_TRC20_CODE}, ${USDT_BEP20_CODE}, or ALL`);
}
function deriveAddress(mnemonic: string, code: Code, index: number): string {
if (code === USDT_BEP20_CODE) return deriveEvmFromMnemonic(mnemonic, index).address;
return deriveTronFromMnemonic(mnemonic, index).address;
}
async function verifyOne(mnemonic: string, code: Code): Promise<number> {
const wt = await walletRepository.getWalletTypeByCode(code);
if (!wt) {
console.log(`\n[${code}] wallet type not found — skip (run migrations).`);
return 0;
}
const usdt = await walletRepository.getWalletTypeByCode(USDT_WALLET_CODE);
if (!usdt) throw new Error('USDT_TRC20 wallet type not found.');
const counts = await query<
Array<{ source: string; count: string }>
>(`
SELECT 'user_wallets_usdt' AS source, COUNT(*)::text AS count
const counts = await query<Array<{ source: string; count: string }>>(
`
SELECT 'user_wallets' AS source, COUNT(*)::text AS count
FROM user_wallets WHERE wallet_type_id = $1
UNION ALL
SELECT 'user_wallets_other_types', COUNT(*)::text
FROM user_wallets WHERE wallet_type_id <> $1
SELECT 'hot_wallets', COUNT(*)::text FROM hot_wallets WHERE wallet_type_id = $1
UNION ALL
SELECT 'hot_wallets', COUNT(*)::text FROM hot_wallets
UNION ALL
SELECT 'cold_wallets', COUNT(*)::text FROM cold_wallets
UNION ALL
SELECT 'users_active', COUNT(*)::text FROM users WHERE deleted_at IS NULL
UNION ALL
SELECT 'users_with_usdt_deposit', COUNT(DISTINCT uw.user_id)::text
SELECT 'users_with_deposit', COUNT(DISTINCT uw.user_id)::text
FROM user_wallets uw
JOIN users u ON u.id = uw.user_id
WHERE uw.wallet_type_id = $1 AND u.deleted_at IS NULL
`, [usdt.id]);
`,
[wt.id]
);
console.log('Address-related counts:');
console.log(`\n[${code}] counts:`);
for (const row of counts) {
console.log(` ${row.source}: ${row.count}`);
}
@ -61,16 +70,19 @@ async function main(): Promise<void> {
JOIN users u ON u.id = uw.user_id
WHERE uw.wallet_type_id = $1
ORDER BY uw.derivation_index ASC`,
[usdt.id]
[wt.id]
);
console.log(`\nVerifying ${rows.length} USDT user_wallets against current PLATFORM_MNEMONIC…`);
console.log(`Verifying ${rows.length} ${code} user_wallets against PLATFORM_MNEMONIC…`);
let ok = 0;
let mismatch = 0;
for (const row of rows) {
const expected = deriveTronFromMnemonic(mnemonic, row.derivation_index).address;
const match = expected === row.address;
const expected = deriveAddress(mnemonic, code, row.derivation_index);
const match =
code === USDT_BEP20_CODE
? expected.toLowerCase() === row.address.toLowerCase()
: expected === row.address;
if (match) {
ok += 1;
console.log(
@ -90,23 +102,40 @@ async function main(): Promise<void> {
const hot = await query<Array<{ address: string; derivation_index: number | null; is_active: boolean }>>(
`SELECT address, derivation_index, is_active FROM hot_wallets WHERE wallet_type_id = $1`,
[usdt.id]
[wt.id]
);
console.log(`\nHot wallets (${hot.length}) — not user deposit addresses:`);
console.log(`Hot wallets (${hot.length}):`);
for (const h of hot) {
const idx = h.derivation_index;
if (idx == null) {
console.log(` ${h.address} active=${h.is_active} (no derivation_index)`);
continue;
}
const expected = deriveTronFromMnemonic(mnemonic, idx).address;
console.log(
` ${expected === h.address ? 'OK' : 'FAIL'} index=${idx} active=${h.is_active} ${h.address}`
);
const expected = deriveAddress(mnemonic, code, idx);
const match =
code === USDT_BEP20_CODE
? expected.toLowerCase() === h.address.toLowerCase()
: expected === h.address;
console.log(` ${match ? 'OK' : 'FAIL'} index=${idx} active=${h.is_active} ${h.address}`);
}
console.log(`\nSummary: ${ok} match, ${mismatch} mismatch out of ${rows.length} user deposit address(es).`);
if (mismatch > 0) {
console.log(`Summary [${code}]: ${ok} match, ${mismatch} mismatch out of ${rows.length}.`);
return mismatch;
}
async function main(): Promise<void> {
const mnemonic = (process.env.PLATFORM_MNEMONIC || '').trim();
if (!mnemonic || !bip39.validateMnemonic(mnemonic)) {
throw new Error('PLATFORM_MNEMONIC missing or invalid BIP39 phrase.');
}
const codes = parseWalletTypes(process.argv.slice(2));
let totalMismatch = 0;
for (const code of codes) {
totalMismatch += await verifyOne(mnemonic, code);
}
if (totalMismatch > 0) {
throw new Error(
'Some deposit addresses do NOT match the current PLATFORM_MNEMONIC. ' +
'Do not send real funds to FAIL rows; run rotateDepositAddresses for those users.'

View File

@ -0,0 +1,143 @@
/**
* BSC (EVM) blockchain integration via JSON-RPC.
* USDT BEP20 Transfer event scanning and outbound ERC-20 transfers.
*/
import { ethers } from 'ethers';
import { config } from '../../config';
const ERC20_ABI = [
'function transfer(address to, uint256 amount) returns (bool)',
'function balanceOf(address) view returns (uint256)',
'event Transfer(address indexed from, address indexed to, uint256 value)',
];
const RPC_TIMEOUT_MS = 60_000;
const MIN_GETLOGS_BLOCK_RANGE = 10;
function isBlockRangeLimitError(err: unknown): boolean {
const parts = [
(err as { message?: string })?.message,
(err as { shortMessage?: string })?.shortMessage,
(err as { error?: { message?: string } })?.error?.message,
];
return parts.some((m) => typeof m === 'string' && /block range exceeds|query returned more than|limit exceeded/i.test(m));
}
let provider: ethers.JsonRpcProvider | null = null;
function getProvider(): ethers.JsonRpcProvider {
if (!provider) {
const req = new ethers.FetchRequest(config.blockchain.bsc.rpcUrl);
req.timeout = RPC_TIMEOUT_MS;
provider = new ethers.JsonRpcProvider(req, 56);
}
return provider;
}
export function resolveUsdtContract(dbContract: string | null | undefined): string {
const fromEnv = config.blockchain.bsc.usdtBep20Contract?.trim();
if (fromEnv) return ethers.getAddress(fromEnv);
if (dbContract?.trim()) return ethers.getAddress(dbContract.trim());
return ethers.getAddress('0x55d398326f99059fF775485246999027B3197955');
}
export async function getCurrentBlock(): Promise<number> {
return getProvider().getBlockNumber();
}
export async function getUsdtTransfersToAddress(
toAddress: string,
contractAddress: string,
fromBlock: number,
maxEndBlock?: number
): Promise<
Array<{
txHash: string;
from: string;
to: string;
value: bigint;
blockNumber: number;
}>
> {
const p = getProvider();
const contract = new ethers.Contract(resolveUsdtContract(contractAddress), ERC20_ABI, p);
const toNormalized = ethers.getAddress(toAddress.startsWith('0x') ? toAddress : '0x' + toAddress);
const filter = contract.filters.Transfer(null, toNormalized);
const currentBlock = await p.getBlockNumber();
const endCap = maxEndBlock != null ? Math.min(maxEndBlock, currentBlock) : currentBlock;
const out: Array<{ txHash: string; from: string; to: string; value: bigint; blockNumber: number }> = [];
let chunkSize = config.blockchain.bsc.getLogsBlockRange;
for (let start = fromBlock; start <= endCap; ) {
let chunk = chunkSize;
while (true) {
const end = Math.min(start + chunk - 1, endCap);
try {
const events = await contract.queryFilter(filter, start, end);
for (const e of events) {
const args = 'args' in e ? e.args : undefined;
if (args && e.blockNumber !== null) {
out.push({
txHash: e.transactionHash,
from: String(args[0]),
to: String(args[1]),
value: BigInt(args[2]),
blockNumber: e.blockNumber,
});
}
}
start = end + 1;
break;
} catch (err) {
if (isBlockRangeLimitError(err) && chunk > MIN_GETLOGS_BLOCK_RANGE) {
chunk = Math.max(MIN_GETLOGS_BLOCK_RANGE, Math.floor(chunk / 2));
continue;
}
throw err;
}
}
}
return out;
}
export async function sendUsdt(
fromPrivateKeyHex: string,
contractAddress: string,
toAddress: string,
amountRaw: bigint
): Promise<string> {
const p = getProvider();
const wallet = new ethers.Wallet(
fromPrivateKeyHex.startsWith('0x') ? fromPrivateKeyHex : '0x' + fromPrivateKeyHex,
p
);
const contract = new ethers.Contract(resolveUsdtContract(contractAddress), ERC20_ABI, wallet);
const tx = await contract.transfer(toAddress, amountRaw);
const receipt = await tx.wait();
return receipt.hash;
}
export async function getNativeBalanceWei(address: string): Promise<bigint> {
return getProvider().getBalance(address);
}
export async function getUsdtBalanceRaw(address: string, contractAddress: string): Promise<bigint> {
const p = getProvider();
const contract = new ethers.Contract(resolveUsdtContract(contractAddress), ERC20_ABI, p);
return contract.balanceOf(address);
}
export async function sendBnb(
fromPrivateKeyHex: string,
toAddress: string,
amountWei: bigint
): Promise<string> {
const p = getProvider();
const wallet = new ethers.Wallet(
fromPrivateKeyHex.startsWith('0x') ? fromPrivateKeyHex : '0x' + fromPrivateKeyHex,
p
);
const tx = await wallet.sendTransaction({ to: toAddress, value: amountWei });
const receipt = await tx.wait();
return receipt!.hash;
}

View File

@ -13,14 +13,26 @@ import * as auditLogRepository from '../repositories/auditLogRepository';
import { enqueueSweepAfterDeposit } from './sweepService';
import { queueUserAdminStatsRefresh } from './userAdminStatsService';
import * as referralService from './referralService';
import { USDT_WALLET_CODE } from './walletCapabilities';
import { USDT_BEP20_CODE, USDT_TRC20_CODE } from './walletCapabilities';
import * as tronService from './blockchain/tronService';
import * as bscService from './blockchain/bscService';
import * as settingsRepository from '../repositories/settingsRepository';
const TRON_CONFIRMATIONS = config.blockchain.tron.confirmations;
const BSC_CONFIRMATIONS = config.blockchain.bsc.confirmations;
/** Scans TRON + BSC for new USDT deposits and credits confirmed transfers. */
export async function processAllDeposits(): Promise<void> {
await processTronDeposits();
await processBscDeposits();
}
/** Scans TRON for new USDT TRC20 deposits and credits confirmed transfers. */
export async function processTronDeposits(): Promise<void> {
const walletType = await walletRepository.getWalletTypeByCode(USDT_WALLET_CODE);
const settings = await settingsRepository.getSettings();
if (!settings.network_usdt_trc20_deposit_enabled) return;
const walletType = await walletRepository.getWalletTypeByCode(USDT_TRC20_CODE);
if (!walletType) return;
const currentBlock = await tronService.getCurrentBlock();
@ -36,8 +48,6 @@ export async function processTronDeposits(): Promise<void> {
);
if (userWallets.length > 0) {
// Only *deposit* rows count — game_stake/transfer/etc. must not block backfill,
// 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]
@ -75,16 +85,11 @@ export async function processTronDeposits(): Promise<void> {
minTimestamp
);
if (process.env.NODE_ENV !== 'production' && transfers.length > 0) {
console.log(`[deposit] USDT ${address}: ${transfers.length} transfer(s)`);
console.log(`[deposit] USDT TRC20 ${address}: ${transfers.length} transfer(s)`);
}
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 (amount == null) continue;
if (t.confirmations >= TRON_CONFIRMATIONS) {
try {
await creditDeposit(
@ -94,10 +99,11 @@ export async function processTronDeposits(): Promise<void> {
t.txId,
t.from,
address,
t.confirmations
t.confirmations,
TRON_CONFIRMATIONS
);
} catch (e) {
console.error(`[deposit] credit failed tx=${t.txId}:`, e);
console.error(`[deposit] TRC20 credit failed tx=${t.txId}:`, e);
}
}
}
@ -106,6 +112,71 @@ export async function processTronDeposits(): Promise<void> {
await depositScannerRepository.updateState(walletType.id, BigInt(currentBlock));
}
/** Scans BSC for new USDT BEP20 deposits and credits confirmed transfers. */
export async function processBscDeposits(): Promise<void> {
const settings = await settingsRepository.getSettings();
if (!settings.network_usdt_bep20_deposit_enabled) return;
const walletType = await walletRepository.getWalletTypeByCode(USDT_BEP20_CODE);
if (!walletType) return;
const currentBlock = await bscService.getCurrentBlock();
const state = await depositScannerRepository.getState(walletType.id);
let fromBlock = state ? Number(state.last_block) + 1 : 0;
if (fromBlock > currentBlock) fromBlock = 0;
const userWallets = await query<Array<{ address: string; user_id: string; created_at: Date }>>(
'SELECT address, user_id, created_at FROM user_wallets WHERE wallet_type_id = $1',
[walletType.id]
);
if (userWallets.length === 0) {
await depositScannerRepository.updateState(walletType.id, BigInt(currentBlock));
return;
}
if (fromBlock === 0) {
// Avoid full-chain scan: start a safe lookback window
fromBlock = Math.max(0, currentBlock - 5_000);
}
const contract = bscService.resolveUsdtContract(walletType.contract_address);
if (process.env.NODE_ENV !== 'production') {
console.log(
`[deposit] USDT_BEP20 (id=${walletType.id}): ${userWallets.length} wallets, fromBlock=${fromBlock}`
);
}
for (const { address, user_id } of userWallets) {
const transfers = await bscService.getUsdtTransfersToAddress(
address,
contract,
fromBlock,
currentBlock
);
for (const t of transfers) {
const confirmations = currentBlock - t.blockNumber + 1;
if (confirmations < BSC_CONFIRMATIONS) continue;
try {
await creditDeposit(
user_id,
walletType.id,
t.value,
t.txHash,
t.from,
address,
confirmations,
BSC_CONFIRMATIONS
);
} catch (e) {
console.error(`[deposit] BEP20 credit failed tx=${t.txHash}:`, e);
}
}
}
await depositScannerRepository.updateState(walletType.id, BigInt(currentBlock));
}
async function creditDeposit(
userId: string,
walletTypeId: number,
@ -113,7 +184,8 @@ async function creditDeposit(
blockchainTxId: string,
fromAddress: string,
toAddress: string,
block: number
block: number,
requiredConfirmations: number
): Promise<void> {
const account = await ledgerRepository.getOrCreateAccount(userId, walletTypeId, 'main');
const client = await getClient();
@ -128,7 +200,7 @@ async function creditDeposit(
fromAddress,
toAddress,
confirmations: block,
requiredConfirmations: TRON_CONFIRMATIONS,
requiredConfirmations,
});
if (!tx) {
await client.query('COMMIT');

View File

@ -58,18 +58,22 @@ export function deriveTronFromMnemonic(mnemonic: string, index: number): { addre
}
/**
* Derives Polygon (Ethereum-compatible) address and private key at index using BIP44 path m/44'/60'/0'/0/index.
* @param mnemonic Platform BIP39 mnemonic
* @param index Derivation index (0-based)
* @returns Checksummed 0x address and hex private key (without 0x prefix)
* Derives EVM (Ethereum / Polygon / BSC) address and private key at index using BIP44 path m/44'/60'/0'/0/index.
*/
export function derivePolygonFromMnemonic(mnemonic: string, index: number): { address: string; privateKey: string } {
export function deriveEvmFromMnemonic(mnemonic: string, index: number): { address: string; privateKey: string } {
const path = `${POLYGON_PATH_PREFIX}${index}`;
const wallet = HDNodeWallet.fromPhrase(mnemonic, undefined, path);
const privateKey = wallet.privateKey?.slice(2) || '';
return { address: wallet.address, privateKey };
}
/**
* @deprecated Prefer deriveEvmFromMnemonic — same BIP44 coin type 60'.
*/
export function derivePolygonFromMnemonic(mnemonic: string, index: number): { address: string; privateKey: string } {
return deriveEvmFromMnemonic(mnemonic, index);
}
/**
* Encrypts a private key for storage (AES via app crypto utils).
* @param privateKey Hex private key string

View File

@ -269,6 +269,19 @@ export function parseSettingsUpdates(body: Record<string, unknown>): Partial<Sys
}
if (typeof body.network_usdt_trc20_deposit_enabled === 'boolean') {
updates.network_usdt_trc20_deposit_enabled = body.network_usdt_trc20_deposit_enabled;
}
if (typeof body.network_usdt_trc20_withdraw_enabled === 'boolean') {
updates.network_usdt_trc20_withdraw_enabled = body.network_usdt_trc20_withdraw_enabled;
}
if (typeof body.network_usdt_bep20_deposit_enabled === 'boolean') {
updates.network_usdt_bep20_deposit_enabled = body.network_usdt_bep20_deposit_enabled;
}
if (typeof body.network_usdt_bep20_withdraw_enabled === 'boolean') {
updates.network_usdt_bep20_withdraw_enabled = body.network_usdt_bep20_withdraw_enabled;
}
if (typeof body.rate_limit_window_ms === 'number') {
updates.rate_limit_window_ms = body.rate_limit_window_ms;

View File

@ -6,7 +6,7 @@ import * as bip39 from 'bip39';
import { config } from '../config';
import {
deriveTronFromMnemonic,
derivePolygonFromMnemonic,
deriveEvmFromMnemonic,
decryptPrivateKey,
} from './hdWallet';
import * as walletRepository from '../repositories/walletRepository';
@ -16,11 +16,12 @@ import * as depositSweepBatchRepository from '../repositories/depositSweepBatchR
import * as hotWalletRepository from '../repositories/hotWalletRepository';
import * as tronService from './blockchain/tronService';
import * as polygonService from './blockchain/polygonService';
import * as bscService from './blockchain/bscService';
import { USDT_BEP20_CODE, USDT_TRC20_CODE } from './walletCapabilities';
const PLATFORM_MNEMONIC = process.env.PLATFORM_MNEMONIC || '';
const TRON_WALLET_TYPE_IDS = [1, 2];
const POLYGON_WALLET_TYPE_ID = 3;
const MIN_TRX_FOR_TRC20_SWEEP = 3_000_000n;
const MIN_BNB_WEI = 50_000_000_000_000n; // 0.00005 BNB
function getMnemonic(): string {
const raw = PLATFORM_MNEMONIC.trim();
@ -34,15 +35,15 @@ function minSweepAmount(): bigint {
return BigInt(config.treasury.sweepMinAmountRaw);
}
function deriveDepositPrivateKey(walletTypeId: number, derivationIndex: number): string {
function deriveDepositPrivateKey(network: string, derivationIndex: number): string {
const mnemonic = getMnemonic();
if (TRON_WALLET_TYPE_IDS.includes(walletTypeId)) {
if (network === 'TRON') {
return deriveTronFromMnemonic(mnemonic, derivationIndex).privateKey;
}
if (walletTypeId === POLYGON_WALLET_TYPE_ID) {
return derivePolygonFromMnemonic(mnemonic, derivationIndex).privateKey;
if (network === 'BSC' || network === 'POLYGON') {
return deriveEvmFromMnemonic(mnemonic, derivationIndex).privateKey;
}
throw new Error('Unsupported wallet type for sweep');
throw new Error(`Unsupported network for sweep: ${network}`);
}
export async function enqueueSweepAfterDeposit(
@ -82,17 +83,25 @@ export async function enqueueSweepAfterDeposit(
await depositSweepBatchRepository.incrementBatchCount(batch.id);
}
async function ensureTronGasForTokenSweep(depositAddress: string): Promise<void> {
async function ensureTronGasForTokenSweep(depositAddress: string, usdtWalletTypeId: number): Promise<void> {
const trxBalance = await tronService.getTrxBalanceSun(depositAddress);
if (trxBalance >= MIN_TRX_FOR_TRC20_SWEEP) return;
const hot = await hotWalletRepository.getActiveHotWallet(1);
if (!hot) throw new Error('No TRX hot wallet for gas top-up');
// Prefer USDT TRC20 hot wallet (same TRON address holds TRX for gas)
const hot = await hotWalletRepository.getActiveHotWallet(usdtWalletTypeId);
if (!hot) throw new Error('No TRON hot wallet for gas top-up');
const hotKey = decryptPrivateKey(hot.encrypted_private_key);
const topUp = BigInt(config.treasury.tronGasTopUpSun);
await tronService.sendTrx(hotKey, depositAddress, topUp);
}
async function ensureBscGasForUsdtSweep(depositAddress: string, hotPrivateKey: string): Promise<void> {
const bnb = await bscService.getNativeBalanceWei(depositAddress);
if (bnb >= MIN_BNB_WEI) return;
const topUp = BigInt(config.blockchain.bsc.gasTopUpWei);
await bscService.sendBnb(hotPrivateKey, depositAddress, topUp);
}
async function ensurePolygonGasForUsdcSweep(depositAddress: string, hotPrivateKey: string): Promise<void> {
const matic = await polygonService.getNativeBalanceWei(depositAddress);
const minGas = 50_000_000_000_000_000n;
@ -102,19 +111,14 @@ async function ensurePolygonGasForUsdcSweep(depositAddress: string, hotPrivateKe
}
async function executeSweep(sweep: depositSweepRepository.DepositSweepRow): Promise<void> {
const walletType =
sweep.wallet_type_id === 1
? await walletRepository.getWalletTypeByCode('TRX')
: sweep.wallet_type_id === 2
? await walletRepository.getWalletTypeByCode('USDT_TRC20')
: await walletRepository.getWalletTypeByCode('USDC_POLYGON');
const walletType = await walletRepository.getWalletTypeById(sweep.wallet_type_id);
if (!walletType) throw new Error('Unknown wallet type');
const userWallet = await walletRepository.getUserWallet(sweep.user_id, sweep.wallet_type_id);
if (!userWallet) throw new Error('User deposit wallet not found');
const amount = BigInt(sweep.amount);
const privateKey = deriveDepositPrivateKey(sweep.wallet_type_id, userWallet.derivation_index);
const privateKey = deriveDepositPrivateKey(walletType.network, userWallet.derivation_index);
await depositSweepRepository.updateSweepStatus(sweep.id, 'broadcasting');
@ -122,13 +126,13 @@ async function executeSweep(sweep: depositSweepRepository.DepositSweepRow): Prom
if (walletType.network === 'TRON') {
const trc20Contract =
walletType.code === 'USDT_TRC20' && config.blockchain.tron.usdtTrc20Contract
walletType.code === USDT_TRC20_CODE && config.blockchain.tron.usdtTrc20Contract
? config.blockchain.tron.usdtTrc20Contract
: walletType.contract_address;
if (trc20Contract) {
await depositSweepRepository.updateSweepStatus(sweep.id, 'gas_funding');
await ensureTronGasForTokenSweep(sweep.from_address);
await ensureTronGasForTokenSweep(sweep.from_address, walletType.id);
await depositSweepRepository.updateSweepStatus(sweep.id, 'broadcasting');
txId = await tronService.sendTrc20(
privateKey,
@ -139,8 +143,17 @@ async function executeSweep(sweep: depositSweepRepository.DepositSweepRow): Prom
} else {
txId = await tronService.sendTrx(privateKey, sweep.to_cold_address, amount);
}
} else if (walletType.network === 'BSC' || walletType.code === USDT_BEP20_CODE) {
const hot = await hotWalletRepository.getActiveHotWallet(walletType.id);
if (!hot) throw new Error('No BSC hot wallet for gas');
const hotKey = decryptPrivateKey(hot.encrypted_private_key);
await depositSweepRepository.updateSweepStatus(sweep.id, 'gas_funding');
await ensureBscGasForUsdtSweep(sweep.from_address, hotKey);
await depositSweepRepository.updateSweepStatus(sweep.id, 'broadcasting');
const contract = bscService.resolveUsdtContract(walletType.contract_address);
txId = await bscService.sendUsdt(privateKey, contract, sweep.to_cold_address, amount);
} else if (walletType.network === 'POLYGON') {
const hot = await hotWalletRepository.getActiveHotWallet(POLYGON_WALLET_TYPE_ID);
const hot = await hotWalletRepository.getActiveHotWallet(walletType.id);
if (!hot) throw new Error('No Polygon hot wallet for gas');
const hotKey = decryptPrivateKey(hot.encrypted_private_key);
await depositSweepRepository.updateSweepStatus(sweep.id, 'gas_funding');

View File

@ -1,27 +1,68 @@
/**
* USDT-only wallet capabilities for deposits and Candle Predict stakes.
* Platform deposit/withdraw wallet capabilities (USDT TRC20 + USDT BEP20).
*/
import { WalletType } from '../models';
import type { SystemSettings } from '../models/settings.model';
export const USDT_WALLET_CODE = 'USDT_TRC20';
export const USDT_TRC20_CODE = 'USDT_TRC20';
export const USDT_BEP20_CODE = 'USDT_BEP20';
/** @deprecated Prefer USDT_TRC20_CODE — kept for prediction default / legacy imports */
export const USDT_WALLET_CODE = USDT_TRC20_CODE;
export const SUPPORTED_USDT_CODES = [USDT_TRC20_CODE, USDT_BEP20_CODE] as const;
export type SupportedUsdtCode = (typeof SUPPORTED_USDT_CODES)[number];
export type WalletTypeCapabilities = WalletType & {
depositEnabled: boolean;
withdrawEnabled: boolean;
predictionEnabled: boolean;
};
export function enrichWalletType(walletType: WalletType): WalletTypeCapabilities {
const enabled = walletType.code === USDT_WALLET_CODE;
return {
...walletType,
depositEnabled: enabled,
predictionEnabled: enabled,
};
export function isSupportedUsdtCode(code: string): code is SupportedUsdtCode {
return (SUPPORTED_USDT_CODES as readonly string[]).includes(code);
}
export function assertUsdtWalletType(code: string): void {
if (code !== USDT_WALLET_CODE) {
throw new Error(`Only ${USDT_WALLET_CODE} is supported`);
if (!isSupportedUsdtCode(code)) {
throw new Error(`Only ${SUPPORTED_USDT_CODES.join(' or ')} is supported`);
}
}
function depositFlagForCode(code: string, settings: SystemSettings): boolean {
if (code === USDT_TRC20_CODE) return settings.network_usdt_trc20_deposit_enabled;
if (code === USDT_BEP20_CODE) return settings.network_usdt_bep20_deposit_enabled;
return false;
}
function withdrawFlagForCode(code: string, settings: SystemSettings): boolean {
if (code === USDT_TRC20_CODE) return settings.network_usdt_trc20_withdraw_enabled;
if (code === USDT_BEP20_CODE) return settings.network_usdt_bep20_withdraw_enabled;
return false;
}
/**
* Sync enrich when settings are not needed (prediction still TRC20-primary).
* Prefer enrichWalletTypeAsync for deposit/withdraw gates.
*/
export function enrichWalletType(walletType: WalletType, settings?: SystemSettings): WalletTypeCapabilities {
const isUsdt = isSupportedUsdtCode(walletType.code);
const depositEnabled = settings
? isUsdt && depositFlagForCode(walletType.code, settings)
: walletType.code === USDT_TRC20_CODE;
const withdrawEnabled = settings
? isUsdt && withdrawFlagForCode(walletType.code, settings)
: isUsdt;
return {
...walletType,
depositEnabled,
withdrawEnabled,
predictionEnabled: walletType.code === USDT_TRC20_CODE,
};
}
export async function enrichWalletTypeAsync(walletType: WalletType): Promise<WalletTypeCapabilities> {
const { getSettings } = await import('../repositories/settingsRepository');
const settings = await getSettings();
return enrichWalletType(walletType, settings);
}

View File

@ -1,18 +1,19 @@
/**
* User wallet and deposit address service.
* Derives TRON deposit addresses for USDT (TRC20) only.
* Derives TRON (TRC20) and BSC (BEP20) deposit addresses for USDT.
*/
import * as bip39 from 'bip39';
import { deriveTronFromMnemonic } from './hdWallet';
import { deriveEvmFromMnemonic, deriveTronFromMnemonic } from './hdWallet';
import { query } from '../db/connection';
import * as walletRepository from '../repositories/walletRepository';
import * as transactionRepository from '../repositories/transactionRepository';
import { Transaction } from '../models';
import {
assertUsdtWalletType,
enrichWalletType,
USDT_WALLET_CODE,
enrichWalletTypeAsync,
USDT_BEP20_CODE,
USDT_TRC20_CODE,
type WalletTypeCapabilities,
} from './walletCapabilities';
@ -32,7 +33,7 @@ function getMnemonic(): string {
}
/**
* Gets or creates a USDT TRC20 deposit address for a user.
* Gets or creates a USDT deposit address for a user (TRC20 or BEP20).
*/
export async function getOrCreateDepositAddress(
userId: string,
@ -40,16 +41,26 @@ export async function getOrCreateDepositAddress(
): Promise<{ address: string; walletType: WalletTypeCapabilities }> {
assertUsdtWalletType(walletTypeCode);
const walletType = await walletRepository.getWalletTypeByCode(USDT_WALLET_CODE);
if (!walletType) throw new Error('USDT wallet type is not configured');
const walletType = await walletRepository.getWalletTypeByCode(walletTypeCode);
if (!walletType) throw new Error(`Wallet type ${walletTypeCode} is not configured`);
const caps = await enrichWalletTypeAsync(walletType);
if (!caps.depositEnabled) {
throw new Error(`Deposits are disabled for ${walletTypeCode}`);
}
const existing = await walletRepository.getUserWallet(userId, walletType.id);
if (existing) {
return { address: existing.address, walletType: enrichWalletType(walletType) };
return { address: existing.address, walletType: caps };
}
const maxIndex = await getNextDerivationIndex(walletType.id);
const derived = deriveTronFromMnemonic(getMnemonic(), maxIndex);
const mnemonic = getMnemonic();
const derived =
walletTypeCode === USDT_BEP20_CODE
? deriveEvmFromMnemonic(mnemonic, maxIndex)
: deriveTronFromMnemonic(mnemonic, maxIndex);
await walletRepository.createUserWallet({
userId,
walletTypeId: walletType.id,
@ -57,7 +68,7 @@ export async function getOrCreateDepositAddress(
derivationIndex: maxIndex,
});
return { address: derived.address, walletType: enrichWalletType(walletType) };
return { address: derived.address, walletType: caps };
}
async function getNextDerivationIndex(walletTypeId: number): Promise<number> {
@ -71,7 +82,10 @@ async function getNextDerivationIndex(walletTypeId: number): Promise<number> {
export async function getWalletTypes(): Promise<WalletTypeCapabilities[]> {
const types = await walletRepository.getWalletTypes();
return types.map(enrichWalletType);
const { getSettings } = await import('../repositories/settingsRepository');
const settings = await getSettings();
const { enrichWalletType } = await import('./walletCapabilities');
return types.map((wt) => enrichWalletType(wt, settings));
}
export async function getUserBalances(userId: string): Promise<
@ -85,6 +99,9 @@ export async function getUserBalances(userId: string): Promise<
> {
const types = await walletRepository.getWalletTypes();
const { getOrCreateAccount, getAccount } = await import('../repositories/ledgerRepository');
const { getSettings } = await import('../repositories/settingsRepository');
const { enrichWalletType } = await import('./walletCapabilities');
const settings = await getSettings();
const result: Array<{
walletType: WalletTypeCapabilities;
available: string;
@ -93,11 +110,12 @@ export async function getUserBalances(userId: string): Promise<
testAvailable: string;
}> = [];
for (const wt of types) {
if (wt.code !== USDT_TRC20_CODE && wt.code !== USDT_BEP20_CODE) continue;
const account = await getOrCreateAccount(userId, wt.id, 'main');
const bonus = await getAccount(userId, wt.id, 'bonus');
const test = await getAccount(userId, wt.id, 'test');
result.push({
walletType: enrichWalletType(wt),
walletType: enrichWalletType(wt, settings),
available: account.available_balance,
locked: account.locked_balance,
bonusAvailable: bonus?.available_balance ?? '0',

View File

@ -14,6 +14,7 @@ import * as walletRepository from '../repositories/walletRepository';
import * as settingsRepository from '../repositories/settingsRepository';
import * as tronService from './blockchain/tronService';
import * as polygonService from './blockchain/polygonService';
import * as bscService from './blockchain/bscService';
import { getWithdrawalNetworkFeeRaw } from '../utils/withdrawalFee';
import {
assertUserCanWithdraw,
@ -26,6 +27,7 @@ import * as referralService from './referralService';
import { rawAmountToUsdApprox } from '../utils/withdrawalLimits';
import type { SystemSettings } from '../models/settings.model';
import type { WalletType } from '../models/wallet.model';
import { enrichWalletType, isSupportedUsdtCode } from './walletCapabilities';
async function assertWithdrawalWithinLimits(
userId: string,
@ -108,13 +110,20 @@ export async function requestWithdrawal(
await authService.assertWithdrawalSecondFactor(userId, totpCode);
await assertUserCanWithdraw(userId);
const feeRaw = getWithdrawalNetworkFeeRaw(settings);
const totalDebit = amountRaw + feeRaw;
const walletType = await walletRepository.getWalletTypeByCode(walletTypeCode);
if (!walletType) throw new Error('Unknown wallet type');
if (!isSupportedUsdtCode(walletTypeCode)) {
throw new Error(`Withdrawals are only supported for USDT networks`);
}
const caps = enrichWalletType(walletType, settings);
if (!caps.withdrawEnabled) {
throw new Error(`Withdrawals are disabled for ${walletTypeCode}`);
}
if (amountRaw <= 0n) throw new Error('Invalid amount');
const feeRaw = getWithdrawalNetworkFeeRaw(settings, walletType.decimals);
const totalDebit = amountRaw + feeRaw;
await assertWithdrawalWithinLimits(userId, walletType, amountRaw, feeRaw, settings);
const account = await ledgerRepository.getOrCreateAccount(userId, walletType.id);
@ -142,7 +151,9 @@ export async function requestWithdrawal(
requiredConfirmations:
walletType.network === 'TRON'
? config.blockchain.tron.confirmations
: config.blockchain.polygon.confirmations,
: walletType.network === 'BSC'
? config.blockchain.bsc.confirmations
: config.blockchain.polygon.confirmations,
});
await withdrawalLockRepository.create({
@ -185,6 +196,9 @@ export async function requestWithdrawal(
} else {
blockchainTxId = await tronService.sendTrx(privateKey, toAddress, amountRaw);
}
} else if (walletType.network === 'BSC') {
const contract = bscService.resolveUsdtContract(walletType.contract_address);
blockchainTxId = await bscService.sendUsdt(privateKey, contract, toAddress, amountRaw);
} else if (walletType.network === 'POLYGON') {
blockchainTxId = await polygonService.sendUsdc(privateKey, toAddress, amountRaw);
} else {

View File

@ -81,4 +81,24 @@ describe('assertProductionMainnetConfig', () => {
/NETWORK_MODE=testnet is not allowed/
);
});
test('allows BSC mainnet RPC URL', () => {
assert.doesNotThrow(() =>
assertProductionMainnetConfig({
...prodMainnet,
bscRpcUrl: 'https://bsc-dataseed.binance.org',
})
);
});
test('rejects BSC testnet / Chapel RPC URL', () => {
assert.throws(
() =>
assertProductionMainnetConfig({
...prodMainnet,
bscRpcUrl: 'https://bsc-testnet-rpc.publicnode.com',
}),
/BSC_RPC_URL must not point to a BSC testnet/
);
});
});

View File

@ -0,0 +1,56 @@
import { describe, test } from 'node:test';
import assert from 'node:assert/strict';
import { enrichWalletType, USDT_BEP20_CODE, USDT_TRC20_CODE } from '../services/walletCapabilities';
import type { SystemSettings } from '../models/settings.model';
import type { WalletType } from '../models';
const trc20: WalletType = {
id: 1,
code: USDT_TRC20_CODE,
name: 'USDT (TRC20)',
network: 'TRON',
decimals: 6,
contract_address: 'TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t',
};
const bep20: WalletType = {
id: 2,
code: USDT_BEP20_CODE,
name: 'USDT (BEP20)',
network: 'BSC',
decimals: 18,
contract_address: '0x55d398326f99059fF775485246999027B3197955',
};
const settingsOn = {
network_usdt_trc20_deposit_enabled: true,
network_usdt_trc20_withdraw_enabled: true,
network_usdt_bep20_deposit_enabled: true,
network_usdt_bep20_withdraw_enabled: true,
} as SystemSettings;
describe('enrichWalletType network flags', () => {
test('respects per-network deposit/withdraw flags', () => {
const caps = enrichWalletType(bep20, {
...settingsOn,
network_usdt_bep20_deposit_enabled: false,
network_usdt_bep20_withdraw_enabled: false,
} as SystemSettings);
assert.equal(caps.depositEnabled, false);
assert.equal(caps.withdrawEnabled, false);
assert.equal(caps.predictionEnabled, false);
});
test('prediction stays on TRC20 only', () => {
assert.equal(enrichWalletType(trc20, settingsOn).predictionEnabled, true);
assert.equal(enrichWalletType(bep20, settingsOn).predictionEnabled, false);
});
test('TRC20 withdraw off does not affect BEP20', () => {
const caps = enrichWalletType(bep20, {
...settingsOn,
network_usdt_trc20_withdraw_enabled: false,
} as SystemSettings);
assert.equal(caps.withdrawEnabled, true);
});
});

View File

@ -0,0 +1,18 @@
import { describe, test } from 'node:test';
import assert from 'node:assert/strict';
import { getWithdrawalNetworkFeeRaw } from '../utils/withdrawalFee';
import type { SystemSettings } from '../models/settings.model';
const baseSettings = {
withdrawal_network_fee_usdt_micro: 2_000_000, // 2 USDT
} as SystemSettings;
describe('getWithdrawalNetworkFeeRaw', () => {
test('keeps 6-decimal micro for TRC20', () => {
assert.equal(getWithdrawalNetworkFeeRaw(baseSettings, 6), 2_000_000n);
});
test('scales to 18 decimals for BEP20', () => {
assert.equal(getWithdrawalNetworkFeeRaw(baseSettings, 18), 2_000_000n * 10n ** 12n);
});
});

View File

@ -4,22 +4,30 @@
import { SystemSettings } from '../models';
/** USDT uses 6 decimal places on TRON TRC20. */
export const USDT_DECIMALS = 6;
/** Canonical micro units for the admin setting (6 decimal places). */
export const USDT_FEE_SETTING_DECIMALS = 6;
/** @deprecated Use USDT_FEE_SETTING_DECIMALS */
export const USDT_DECIMALS = USDT_FEE_SETTING_DECIMALS;
/**
* Returns the configured network fee in smallest USDT units.
* Returns the configured network fee in smallest units for the given wallet decimals.
* Setting is stored as 6-decimal micro-USDT; scaled when wallet decimals differ (e.g. BEP20 18).
*/
export function getWithdrawalNetworkFeeRaw(settings: SystemSettings): bigint {
export function getWithdrawalNetworkFeeRaw(settings: SystemSettings, walletDecimals = 6): bigint {
const micro = settings.withdrawal_network_fee_usdt_micro;
if (!Number.isFinite(micro) || micro < 0) return 0n;
return BigInt(Math.floor(micro));
const base = BigInt(Math.floor(micro));
if (walletDecimals === USDT_FEE_SETTING_DECIMALS) return base;
if (walletDecimals > USDT_FEE_SETTING_DECIMALS) {
return base * 10n ** BigInt(walletDecimals - USDT_FEE_SETTING_DECIMALS);
}
return base / 10n ** BigInt(USDT_FEE_SETTING_DECIMALS - walletDecimals);
}
/**
* Formats a raw USDT amount for display (trims trailing zeros).
*/
export function formatUsdtRawHuman(raw: bigint, decimals = USDT_DECIMALS): string {
export function formatUsdtRawHuman(raw: bigint, decimals = USDT_FEE_SETTING_DECIMALS): string {
if (decimals <= 0) return raw.toString();
const divisor = 10n ** BigInt(decimals);
const intPart = raw / divisor;

View File

@ -40,6 +40,10 @@ x-backend-common: &backend-common
TRON_API_KEY: ${TRON_API_KEY:-}
TRON_CONFIRMATIONS: ${TRON_CONFIRMATIONS:-3}
USDT_TRC20_CONTRACT: ${USDT_TRC20_CONTRACT:-}
BSC_RPC_URL: ${BSC_RPC_URL:-https://bsc-dataseed.binance.org}
BSC_CONFIRMATIONS: ${BSC_CONFIRMATIONS:-15}
USDT_BEP20_CONTRACT: ${USDT_BEP20_CONTRACT:-}
BSC_GETLOGS_BLOCK_RANGE: ${BSC_GETLOGS_BLOCK_RANGE:-2000}
POLYGON_RPC_URL: ${POLYGON_RPC_URL}
POLYGON_CONFIRMATIONS: ${POLYGON_CONFIRMATIONS:-8}
USDC_POLYGON_CONTRACT: ${USDC_POLYGON_CONTRACT:-}

View File

@ -70,6 +70,9 @@ nano .env # ou vim
| `TRON_API_KEY` | Clé TronGrid (recommandée en prod) |
| `TRON_CONFIRMATIONS` | Ex. `20` |
| `USDT_TRC20_CONTRACT` | Laisser **vide** en mainnet (contrat Tether par défaut en DB) |
| `BSC_RPC_URL` | Mainnet : `https://bsc-dataseed.binance.org` (ou RPC fiable) |
| `BSC_CONFIRMATIONS` | Ex. `15` |
| `USDT_BEP20_CONTRACT` | Laisser **vide** en mainnet (USDT officiel BSC en DB) |
| `ALLOW_WITHDRAWALS` | `false` jusqu’à validation des dépôts (le kill-switch admin Settings prime aussi) |
| `APP_PUBLIC_URL` | Ex. HTTP test : `http://prediqo.redirectme.net:9080` · HTTPS : `https://…:9443` |
| `CORS_ORIGINS` | Même origine que le front (schéma + hôte + port) |
@ -138,7 +141,10 @@ npm install # si besoin (inclut ts-node)
npm run seed-hot-wallets
```
Une seule fois suffit : si le hot wallet existe déjà, le script affiche `Skipping` et ne recrée rien.
Une seule fois suffit : si un hot wallet existe déjà pour un réseau, le script affiche `Skipping` pour ce type. Le seed crée **deux** hot wallets : `USDT_TRC20` (TRON, index `1000000`) et `USDT_BEP20` (BSC, index `1000001`).
- Hot **TRON** : financer en **TRX** (gas) + USDT TRC20 avant retraits TRC20.
- Hot **BSC** : financer en **BNB** (gas) + USDT BEP20 avant retraits BEP20.
#### Rotation des adresses de dépôt (après changement de `PLATFORM_MNEMONIC`)
@ -149,31 +155,34 @@ Si des utilisateurs ont déjà une adresse créée avec un **ancien** mnémoniqu
```bash
cd ~/projects_repository/game-project
# Tous les users qui ont déjà une adresse USDT
# Tous les users qui ont déjà une adresse (TRC20 + BEP20)
sudo docker compose run --rm --no-deps --build backend \
node dist/scripts/rotateDepositAddresses.js \
--confirm=ROTATE_DEPOSIT_ADDRESSES \
--scope=existing
--scope=existing \
--wallet-type=ALL
# Ou un seul compte de test
sudo docker compose run --rm --no-deps --build backend \
node dist/scripts/rotateDepositAddresses.js \
--confirm=ROTATE_DEPOSIT_ADDRESSES \
--email=test@example.com
--email=test@example.com \
--wallet-type=ALL
```
Équivalent : `npm run phase-b:rotate-deposit-addresses -- --confirm=ROTATE_DEPOSIT_ADDRESSES --scope=existing`
Équivalent : `npm run phase-b:rotate-deposit-addresses -- --confirm=ROTATE_DEPOSIT_ADDRESSES --scope=existing --wallet-type=ALL`
Le script ne touche **pas** au hot wallet ni aux soldes ledger. Ensuite, ouvrir **Dépôt** dans l’app et n’envoyer de l’USDT réel **que** vers la nouvelle adresse affichée.
Le script ne touche **pas** aux hot wallets ni aux soldes ledger. Ensuite, ouvrir **Dépôt** dans l’app et n’envoyer de l’USDT réel **que** vers la nouvelle adresse affichée (bon réseau : `T…` = TRC20, `0x…` = BEP20).
Pour **vérifier** que chaque adresse `user_wallets` USDT correspond au mnémonique actuel (et voir pourquoi d’autres tables ont des adresses) :
Pour **vérifier** que chaque adresse `user_wallets` correspond au mnémonique actuel :
```bash
sudo docker compose run --rm --no-deps --build backend \
node dist/scripts/verifyDepositAddresses.js
# optionnel : --wallet-type=USDT_BEP20
```
`--scope=existing` ne traite que les lignes **`user_wallets` USDT** d’utilisateurs non supprimés. Le hot wallet, le cold wallet, et les adresses dans `transactions` ne sont pas des adresses de dépôt user.
`--scope=existing` ne traite que les lignes **`user_wallets`** d’utilisateurs non supprimés. Les hot/cold wallets et les adresses dans `transactions` ne sont pas des adresses de dépôt user.
#### `JWT_SECRET` et `INITIAL_SETUP_TOKEN`
@ -372,19 +381,29 @@ Cette section regroupe les commandes lorsque PostgreSQL est **vide** (base cré
| # | Étape | Détail |
|---|--------|--------|
| 1 | `.env` complet | Secrets générés **une fois** + backup hors git · TRON mainnet · URLs HTTP ou HTTPS cohérentes · `ALLOW_WITHDRAWALS=false` |
| 1 | `.env` complet | Secrets générés **une fois** + backup hors git · TRON + BSC mainnet · URLs HTTP ou HTTPS cohérentes · `ALLOW_WITHDRAWALS=false` |
| 2 | Base Postgres | Créée (ou DROP + CREATE) avec le nom `POSTGRES_DB` |
| 3 | Migrations + stack | `phase-b:init` (HTTP) ou `phase-b:init:https` |
| 4 | Santé | `curl` `/health` → `network: mainnet`, `asset: USDT_TRC20` · `/setup/status` → `needsSetup: true` |
| 4 | Santé | `curl` `/health` → `assets` inclut `USDT_TRC20` + `USDT_BEP20` · `/setup/status` → `needsSetup: true` |
| 5 | Premier Super Admin | Page `/setup` + `INITIAL_SETUP_TOKEN` |
| 6 | 2FA + recovery codes | Profil → activer 2FA · sauvegarder les codes hors ligne |
| 7 | (Recommandé) 2ᵉ admin | Ne pas dépendre d’un seul Super Admin |
| 8 | Hot wallet | `seedHotWallets.js` **une fois** · noter l’adresse |
| 9 | Vérifier HD | `verifyDepositAddresses.js` → 0 mismatch |
| 10 | Prêt dépôt test | Micro USDT **TRC20** seulement · retraits encore **off** |
| 8 | Hot wallets | `seedHotWallets.js` **une fois** · noter adresses TRON **et** BSC |
| 9 | Vérifier HD | `verifyDepositAddresses.js` → 0 mismatch (les deux réseaux) |
| 10 | Prêt dépôt test | **Priorité BEP20** (Binance → BSC) · retraits encore **off** · TRC20 optionnel ensuite |
> **Ne changez plus** `ENCRYPTION_KEY` ni `PLATFORM_MNEMONIC` après l’étape 8 sans procédure de rotation (sinon PII / hot wallet / adresses orphelines).
### Test argent réel — ordre BEP20 d’abord
1. Admin → Settings → **USDT networks** : activer dépôt (et plus tard retrait) **BEP20** ; TRC20 selon besoin.
2. Financer le hot BSC avec un peu de **BNB** + USDT BEP20 (pour retraits).
3. User test → Receive → réseau **BSC (BEP20)** → copier l’adresse `0x…`.
4. Depuis Binance (ou wallet) : retirer USDT en réseau **BEP20 / BSC** uniquement (pas TRC20).
5. Attendre confirmations → solde ledger `USDT_BEP20` crédité.
6. Micro-retrait : activer kill-switch global + flag withdraw BEP20 → retirer vers une adresse BSC contrôlée.
7. (Optionnel) répéter sur TRC20 avec adresse `T…` et réseau TRON.
### Prérequis communs
| Étape | Détail |
@ -401,7 +420,7 @@ curl -s http://127.0.0.1:9080/api/v1/setup/status
# attendu : {"needsSetup":true,"setupEnabled":true}
curl -s http://127.0.0.1:9080/health
# attendu : "network":"mainnet", "asset":"USDT_TRC20", "withdrawalsEnabled": false (ou selon Settings)
# attendu : "assets":["USDT_TRC20","USDT_BEP20"], "withdrawalsEnabled": false (ou selon Settings)
```
### 4.1 Remise à zéro — supprimer et recréer la base (avant tests réels)
@ -430,7 +449,7 @@ SQL
# JWT_SECRET, INITIAL_SETUP_TOKEN — une seule fois — et les sauvegarder hors git.
# Ne pas réutiliser un mnémonique / ENCRYPTION_KEY déjà exposés dans un chat.
# 4) Vérifier .env : TRON mainnet, TRON_API_KEY, ALLOW_WITHDRAWALS=false,
# 4) Vérifier .env : TRON + BSC mainnet, TRON_API_KEY, BSC_RPC_URL, ALLOW_WITHDRAWALS=false,
# APP_PUBLIC_URL / VITE_* / CORS_ORIGINS alignés (http://…:9080 ou https://…:9443)
# 5) Migrations + démarrage HTTP
@ -441,16 +460,16 @@ sudo npm run phase-b:init
# 6) Setup navigateur → /setup → premier Super Admin → login → 2FA + recovery codes
# 7) Hot wallet (une fois)
# 7) Hot wallets TRON + BSC (une fois)
sudo docker compose run --rm --no-deps --build backend \
node dist/scripts/seedHotWallets.js
# 8) Vérifier les adresses HD
# 8) Vérifier les adresses HD (les deux réseaux)
sudo docker compose run --rm --no-deps --build backend \
node dist/scripts/verifyDepositAddresses.js
```
Ensuite seulement : créer un user de test → Dépôt → micro USDT TRC20 → (plus tard) financer le hot puis activer les retraits dans Admin Settings.
Ensuite seulement : créer un user de test → Dépôt → micro USDT **BEP20** (priorité) → (plus tard) financer les hots puis activer les retraits dans Admin Settings (réseau + kill-switch global).
### Sur le VPS
@ -774,7 +793,7 @@ Local Docker : `npm run docker:local:break-glass-reset-2fa -- …` (fichier `.en
| Redémarrer | `npm run phase-b:restart` |
| Arrêter | `npm run phase-b:down` |
| Remise à zéro DB | [§4.1](#41-remise-à-zéro--supprimer-et-recréer-la-base-avant-tests-réels) |
| Seed hot wallet | `docker compose run --rm --no-deps backend node dist/scripts/seedHotWallets.js` |
| Seed hot wallets (TRON + BSC) | `docker compose run --rm --no-deps backend node dist/scripts/seedHotWallets.js` |
| Vérifier adresses HD | `npm run phase-b:verify-deposit-addresses` |
| Reconstruire après changement `VITE_*` | `npm run phase-b:up` (HTTP) ou `phase-b:up:https` |

View File

@ -68,7 +68,27 @@ class CoinDisplay {
/// Human-readable network label for USDT deposits and withdrawals.
static String networkLabel(String code) {
final upper = code.toUpperCase();
if (upper.contains('BEP20') || upper.contains('BSC')) return 'BSC (BEP20)';
if (upper.contains('TRC20') || upper.contains('TRON')) return 'TRON (TRC20)';
if (upper.contains('USDT')) return 'TRON (TRC20)';
return upper;
}
/// Placeholder hint for destination address fields.
static String addressPlaceholder(String code) {
final label = networkLabel(code);
if (label.startsWith('BSC')) return '0x…';
return 'T…';
}
/// Scale health fee (6-decimal micro-USDT) to wallet raw units.
static BigInt scaleWithdrawalFeeRaw(String microRaw, int walletDecimals) {
final base = BigInt.tryParse(microRaw.trim()) ?? BigInt.zero;
if (base < BigInt.zero) return BigInt.zero;
if (walletDecimals == 6) return base;
if (walletDecimals > 6) {
return base * BigInt.from(10).pow(walletDecimals - 6);
}
return base ~/ BigInt.from(10).pow(6 - walletDecimals);
}
}

View File

@ -9,15 +9,21 @@ class WalletTypeModel {
required this.network,
required this.decimals,
this.contractAddress,
this.depositEnabled = true,
this.withdrawEnabled = true,
this.predictionEnabled = false,
});
final int id;
/// Asset identifier used in API paths (e.g. TRX, USDT_TRC20).
/// Asset identifier used in API paths (e.g. USDT_TRC20, USDT_BEP20).
final String code;
final String name;
final String network;
final int decimals;
final String? contractAddress;
final bool depositEnabled;
final bool withdrawEnabled;
final bool predictionEnabled;
/// Parses wallet type metadata from backend JSON.
factory WalletTypeModel.fromJson(Map<String, dynamic> json) {
@ -28,6 +34,9 @@ class WalletTypeModel {
network: json['network'] as String,
decimals: json['decimals'] as int? ?? 6,
contractAddress: json['contract_address'] as String?,
depositEnabled: json['depositEnabled'] as bool? ?? true,
withdrawEnabled: json['withdrawEnabled'] as bool? ?? true,
predictionEnabled: json['predictionEnabled'] as bool? ?? false,
);
}
}

View File

@ -39,7 +39,7 @@ class _DepositAssetSelectScreenState extends State<DepositAssetSelectScreen> {
if (state.isLoading && state.walletTypes.isEmpty) {
return const Center(child: CircularProgressIndicator());
}
final types = state.walletTypes;
final types = state.walletTypes.where((t) => t.depositEnabled).toList();
if (types.isEmpty) {
return Center(
child: Padding(
@ -75,7 +75,7 @@ class _DepositAssetSelectScreenState extends State<DepositAssetSelectScreen> {
),
const SizedBox(height: 8),
Text(
'Select USDT (TRC20). You will then see the deposit address and QR code.',
'Select USDT on TRON (TRC20) or BSC (BEP20). You will then see the matching deposit address and QR code.',
style: Theme.of(context).textTheme.bodyMedium?.copyWith(
color: Theme.of(context).colorScheme.onSurfaceVariant,
),

View File

@ -75,7 +75,7 @@ class _WithdrawScreenState extends State<WithdrawScreen> {
);
return;
}
final feeRaw = BigInt.tryParse(_networkFeeRaw) ?? BigInt.zero;
final feeRaw = CoinDisplay.scaleWithdrawalFeeRaw(_networkFeeRaw, selectedType.decimals);
final totalRaw = BigInt.parse(amountRaw) + feeRaw;
if (state.balances.isEmpty) {
ScaffoldMessenger.of(context).showSnackBar(
@ -96,7 +96,7 @@ class _WithdrawScreenState extends State<WithdrawScreen> {
);
return;
}
final feeHuman = rawAmountToHuman(_networkFeeRaw, selectedType.decimals);
final feeHuman = rawAmountToHuman(feeRaw.toString(), selectedType.decimals);
final address = _addressController.text.trim();
showDialog<bool>(
context: context,
@ -180,17 +180,17 @@ class _WithdrawScreenState extends State<WithdrawScreen> {
if (!state.isLoaded && state.balances.isEmpty) {
return const Center(child: CircularProgressIndicator());
}
final types = state.walletTypes;
final types = state.walletTypes.where((t) => t.withdrawEnabled).toList();
final balances = state.balances;
if (types.isEmpty) {
return const Center(child: Text('No wallet types'));
return const Center(child: Text('No withdrawal networks enabled'));
}
_selectedWalletType ??= types.first.code;
final selectedTypeList = types.where((t) => t.code == _selectedWalletType);
final selectedType = selectedTypeList.isEmpty ? types.first : selectedTypeList.first;
final networkLabel = CoinDisplay.networkLabel(selectedType.code);
final feeRaw = BigInt.tryParse(_networkFeeRaw) ?? BigInt.zero;
final feeHuman = rawAmountToHuman(_networkFeeRaw, selectedType.decimals);
final feeRaw = CoinDisplay.scaleWithdrawalFeeRaw(_networkFeeRaw, selectedType.decimals);
final feeHuman = rawAmountToHuman(feeRaw.toString(), selectedType.decimals);
return SingleChildScrollView(
padding: const EdgeInsets.all(24),
child: Column(
@ -199,12 +199,14 @@ class _WithdrawScreenState extends State<WithdrawScreen> {
const Text('Asset'),
const SizedBox(height: 8),
DropdownButtonFormField<String>(
initialValue: _selectedWalletType,
initialValue: types.any((t) => t.code == _selectedWalletType)
? _selectedWalletType
: types.first.code,
items: types
.map(
(t) => DropdownMenuItem(
value: t.code,
child: Text(t.name),
child: Text('${t.name} — ${CoinDisplay.networkLabel(t.code)}'),
),
)
.toList(),
@ -234,9 +236,10 @@ class _WithdrawScreenState extends State<WithdrawScreen> {
const SizedBox(height: 16),
TextField(
controller: _addressController,
decoration: const InputDecoration(
decoration: InputDecoration(
labelText: 'Destination address',
prefixIcon: Icon(Icons.account_balance_wallet),
hintText: CoinDisplay.addressPlaceholder(selectedType.code),
prefixIcon: const Icon(Icons.account_balance_wallet),
),
),
const SizedBox(height: 16),
@ -292,7 +295,7 @@ class _WithdrawScreenState extends State<WithdrawScreen> {
borderRadius: BorderRadius.circular(12),
),
child: Text(
'Only send to addresses that support $networkLabel. Wrong network may result in permanent loss of funds.',
'Only send to addresses that support $networkLabel. Wrong network (TRC20 vs BEP20) may result in permanent loss of funds.',
style: Theme.of(context).textTheme.bodySmall,
),
),

View File

@ -48,8 +48,8 @@ class AppStrings {
'Prédictions sur bougies en direct, résultats Short / Long clairs.',
);
String get welcomeWhyWallet => t(
'USDT (TRC20) deposits with real-time balance tracking, and near-instant withdrawals.',
'Dépôts USDT (TRC20), soldes en temps réel, et retraits quasi instantanés.',
'USDT deposits on TRON (TRC20) or BSC (BEP20), real-time balances, and near-instant withdrawals.',
'Dépôts USDT sur TRON (TRC20) ou BSC (BEP20), soldes en temps réel, et retraits quasi instantanés.',
);
String get welcomeWhyReferral => t(
'Invite friends and earn commissions across your network.',

View File

@ -43,6 +43,10 @@ export function SettingsPage() {
refresh_token_expiry: string;
require_email_verification_for_login: boolean;
allow_withdrawals: boolean;
network_usdt_trc20_deposit_enabled: boolean;
network_usdt_trc20_withdraw_enabled: boolean;
network_usdt_bep20_deposit_enabled: boolean;
network_usdt_bep20_withdraw_enabled: boolean;
rate_limit_window_ms: number;
rate_limit_max: number;
login_rate_limit_max: number;
@ -287,6 +291,63 @@ export function SettingsPage() {
</AccordionDetails>
</Accordion>
<Accordion defaultExpanded={false} sx={{ borderRadius: 2, overflow: 'hidden' }}>
<AccordionSummary expandIcon={<ExpandMoreRoundedIcon />}>
<Box>
<Typography sx={{ fontWeight: 900 }}>{t('admin.settings.sections.networks.title')}</Typography>
<Typography variant="body2" sx={{ opacity: 0.7 }}>
{t('admin.settings.sections.networks.subtitle')}
</Typography>
</Box>
</AccordionSummary>
<AccordionDetails>
<Stack spacing={2}>
<Typography variant="subtitle2" sx={{ fontWeight: 800 }}>
{t('admin.settings.sections.networks.trc20')}
</Typography>
<FormControlLabel
control={
<Checkbox
checked={effective.network_usdt_trc20_deposit_enabled ?? true}
onChange={(e) => set('network_usdt_trc20_deposit_enabled', e.target.checked)}
/>
}
label={t('admin.settings.sections.networks.depositEnabled')}
/>
<FormControlLabel
control={
<Checkbox
checked={effective.network_usdt_trc20_withdraw_enabled ?? true}
onChange={(e) => set('network_usdt_trc20_withdraw_enabled', e.target.checked)}
/>
}
label={t('admin.settings.sections.networks.withdrawEnabled')}
/>
<Typography variant="subtitle2" sx={{ fontWeight: 800, pt: 1 }}>
{t('admin.settings.sections.networks.bep20')}
</Typography>
<FormControlLabel
control={
<Checkbox
checked={effective.network_usdt_bep20_deposit_enabled ?? true}
onChange={(e) => set('network_usdt_bep20_deposit_enabled', e.target.checked)}
/>
}
label={t('admin.settings.sections.networks.depositEnabled')}
/>
<FormControlLabel
control={
<Checkbox
checked={effective.network_usdt_bep20_withdraw_enabled ?? true}
onChange={(e) => set('network_usdt_bep20_withdraw_enabled', e.target.checked)}
/>
}
label={t('admin.settings.sections.networks.withdrawEnabled')}
/>
</Stack>
</AccordionDetails>
</Accordion>
<Accordion defaultExpanded={false} sx={{ borderRadius: 2, overflow: 'hidden' }}>
<AccordionSummary expandIcon={<ExpandMoreRoundedIcon />}>
<Box>

View File

@ -1,5 +1,5 @@
/**
* Player wallet page — USDT (TRC20) only.
* Player wallet page — USDT on TRC20 and/or BEP20 (separate ledgers).
*/
import {
Alert,
@ -32,7 +32,8 @@ import { WithdrawDialog } from './components/WithdrawDialog';
import { TransactionList } from './components/TransactionList';
import { DEFAULT_TX_PAGE_SIZE, useBalances, useTransactions } from './hooks/useWalletData';
import type { WalletActivityCategory } from './types';
import { USDT_WALLET_CODE } from './utils/walletCapabilities';
import { networkLabel } from './utils/coinDisplay';
import { USDT_WALLET_CODE, isSupportedUsdtCode } from './utils/walletCapabilities';
import { rawToHuman, shortSymbol } from './utils/walletFormat';
type DialogKind = 'receive' | 'transfer' | 'withdraw' | null;
@ -42,6 +43,7 @@ export function WalletPage() {
const [tab, setTab] = useState(0);
const [activityCategory, setActivityCategory] = useState<WalletActivityCategory>('deposits');
const [dialog, setDialog] = useState<DialogKind>(null);
const [dialogAsset, setDialogAsset] = useState<string | null>(null);
const [toast, setToast] = useState<string | null>(null);
const [txPage, setTxPage] = useState(0);
@ -59,26 +61,37 @@ export function WalletPage() {
});
const balances = balancesQ.data ?? [];
const usdtBalances = useMemo(
() => balances.filter((b) => isSupportedUsdtCode(b.walletType.code)),
[balances]
);
const transactions = txQ.data?.items ?? [];
const txTotal = txQ.data?.total ?? 0;
const usdtBalance = balances.find((b) => b.walletType.code === USDT_WALLET_CODE) ?? balances[0];
const primaryBalance =
usdtBalances.find((b) => b.walletType.code === USDT_WALLET_CODE) ?? usdtBalances[0];
const portfolioSummary = useMemo(() => {
if (!usdtBalance) return null;
const b = usdtBalance;
return {
if (usdtBalances.length === 0) return null;
const lines = usdtBalances.map((b) => ({
code: b.walletType.code,
human: rawToHuman(b.available, b.walletType.decimals),
locked: rawToHuman(b.locked, b.walletType.decimals),
bonus: rawToHuman(b.bonusAvailable ?? '0', b.walletType.decimals),
hasLocked: BigInt(b.locked || '0') > 0n,
};
}, [usdtBalance]);
network: networkLabel(b.walletType.code),
}));
return { lines };
}, [usdtBalances]);
const refreshAll = async () => {
await Promise.all([balancesQ.refetch(), txQ.refetch(), healthQ.refetch()]);
setToast(t('common.walletRefreshed'));
};
const openDialog = (kind: DialogKind, asset?: string) => {
setDialogAsset(asset ?? null);
setDialog(kind);
};
const loading = balancesQ.isLoading;
return (
@ -121,12 +134,19 @@ export function WalletPage() {
<Skeleton variant="text" width={200} height={48} sx={{ mt: 1 }} />
) : portfolioSummary ? (
<Stack spacing={1} sx={{ mt: 1 }}>
<Typography variant="h4" sx={{ fontWeight: 900 }}>
{portfolioSummary.human} {shortSymbol(USDT_WALLET_CODE)}
</Typography>
{portfolioSummary.hasLocked && (
<Chip size="small" variant="outlined" label={t('wallet.locked', { amount: portfolioSummary.locked })} />
)}
{portfolioSummary.lines.map((line) => (
<Stack key={line.code} spacing={0.5}>
<Typography variant="h5" sx={{ fontWeight: 900 }}>
{line.human} {shortSymbol(line.code)}
</Typography>
<Typography variant="body2" sx={{ opacity: 0.7 }}>
{line.network}
</Typography>
{line.hasLocked && (
<Chip size="small" variant="outlined" label={t('wallet.locked', { amount: line.locked })} />
)}
</Stack>
))}
</Stack>
) : (
<Typography sx={{ opacity: 0.7, mt: 1 }}>{t('wallet.noBalance')}</Typography>
@ -136,7 +156,7 @@ export function WalletPage() {
<Button
variant="contained"
startIcon={<CallReceivedRoundedIcon />}
onClick={() => setDialog('receive')}
onClick={() => openDialog('receive')}
sx={{ flex: 1 }}
>
{t('wallet.receiveUsdt')}
@ -144,7 +164,7 @@ export function WalletPage() {
<Button
variant="outlined"
startIcon={<SendRoundedIcon />}
onClick={() => setDialog('transfer')}
onClick={() => openDialog('transfer', USDT_WALLET_CODE)}
sx={{ flex: 1 }}
>
{t('wallet.send')}
@ -153,7 +173,7 @@ export function WalletPage() {
variant="outlined"
color="warning"
startIcon={<SouthWestRoundedIcon />}
onClick={() => setDialog('withdraw')}
onClick={() => openDialog('withdraw')}
sx={{ flex: 1 }}
>
{t('wallet.withdraw')}
@ -188,25 +208,32 @@ export function WalletPage() {
<Skeleton variant="rounded" height={220} sx={{ borderRadius: 2 }} />
<Skeleton variant="rounded" height={220} sx={{ borderRadius: 2 }} />
</>
) : usdtBalance ? (
) : (
<>
<MainAssetCard
balance={usdtBalance}
onReceive={() => setDialog('receive')}
onSend={() => setDialog('transfer')}
/>
<BonusWalletCard
balance={usdtBalance}
onSuccess={setToast}
onError={setToast}
/>
<TestWalletCard
balance={usdtBalance}
onSuccess={setToast}
onError={setToast}
/>
{usdtBalances.map((b) => (
<MainAssetCard
key={b.walletType.code}
balance={b}
onReceive={() => openDialog('receive', b.walletType.code)}
onSend={() => openDialog('transfer', b.walletType.code)}
/>
))}
{primaryBalance ? (
<>
<BonusWalletCard
balance={primaryBalance}
onSuccess={setToast}
onError={setToast}
/>
<TestWalletCard
balance={primaryBalance}
onSuccess={setToast}
onError={setToast}
/>
</>
) : null}
</>
) : null}
)}
</Box>
)}
@ -242,12 +269,17 @@ export function WalletPage() {
</Box>
)}
<ReceiveDialog open={dialog === 'receive'} onClose={() => setDialog(null)} onCopied={setToast} />
<ReceiveDialog
open={dialog === 'receive'}
initialAsset={dialogAsset}
onClose={() => setDialog(null)}
onCopied={setToast}
/>
<TransferDialog
open={dialog === 'transfer'}
balances={balances}
initialAsset={USDT_WALLET_CODE}
balances={usdtBalances}
initialAsset={dialogAsset ?? USDT_WALLET_CODE}
onClose={() => setDialog(null)}
onSuccess={setToast}
onError={setToast}
@ -255,10 +287,10 @@ export function WalletPage() {
<WithdrawDialog
open={dialog === 'withdraw'}
balances={balances}
balances={usdtBalances}
withdrawalsEnabled={healthQ.data?.withdrawalsEnabled ?? false}
networkFeeRaw={healthQ.data?.withdrawalNetworkFeeRaw ?? '0'}
initialAsset={USDT_WALLET_CODE}
initialAsset={dialogAsset}
onClose={() => setDialog(null)}
onSuccess={setToast}
onError={setToast}

View File

@ -1,5 +1,5 @@
/**
* Main USDT wallet card (deposits, withdrawals, transfers).
* Main USDT wallet card (one network / ledger).
*/
import {
Box,
@ -15,7 +15,6 @@ import QrCode2RoundedIcon from '@mui/icons-material/QrCode2Rounded';
import { useTranslation } from 'react-i18next';
import type { BalanceEntry } from '../types';
import { coinColors, coinSymbol, networkLabel } from '../utils/coinDisplay';
import { USDT_WALLET_CODE } from '../utils/walletCapabilities';
import { formatBalance } from '../utils/walletFormat';
type MainAssetCardProps = {
@ -26,7 +25,8 @@ type MainAssetCardProps = {
export function MainAssetCard({ balance, onReceive, onSend }: MainAssetCardProps) {
const { t } = useTranslation();
const [c1, c2] = coinColors(USDT_WALLET_CODE);
const code = balance.walletType.code;
const [c1, c2] = coinColors(code);
const hasLocked = BigInt(balance.locked || '0') > 0n;
return (
@ -46,19 +46,21 @@ export function MainAssetCard({ balance, onReceive, onSend }: MainAssetCardProps
boxShadow: `0 4px 14px ${c1}55`,
}}
>
{coinSymbol(USDT_WALLET_CODE)}
{coinSymbol(code)}
</Box>
<Box sx={{ flex: 1 }}>
<Typography sx={{ fontWeight: 800 }}>{t('wallet.mainCard.title')}</Typography>
<Typography sx={{ fontWeight: 800 }}>{balance.walletType.name}</Typography>
<Typography variant="body2" sx={{ opacity: 0.65 }}>
{balance.walletType.name} · {networkLabel(USDT_WALLET_CODE)}
{networkLabel(code)}
</Typography>
<Chip
size="small"
color="primary"
label={t('wallet.mainCard.badge')}
sx={{ mt: 0.75, fontWeight: 700 }}
/>
{balance.walletType.predictionEnabled ? (
<Chip
size="small"
color="primary"
label={t('wallet.mainCard.badge')}
sx={{ mt: 0.75, fontWeight: 700 }}
/>
) : null}
</Box>
<IconButton size="small" aria-label={t('wallet.mainCard.receiveAria')} onClick={onReceive}>
<QrCode2RoundedIcon fontSize="small" />
@ -69,13 +71,13 @@ export function MainAssetCard({ balance, onReceive, onSend }: MainAssetCardProps
{t('wallet.mainCard.availableBalance')}
</Typography>
<Typography variant="h5" sx={{ fontWeight: 900 }}>
{formatBalance(balance.available, balance.walletType.decimals, USDT_WALLET_CODE)}
{formatBalance(balance.available, balance.walletType.decimals, code)}
</Typography>
{hasLocked && (
<Typography variant="body2" sx={{ opacity: 0.65, mt: 0.5 }}>
{t('wallet.mainCard.locked')}{' '}
{formatBalance(balance.locked, balance.walletType.decimals, USDT_WALLET_CODE)}
{formatBalance(balance.locked, balance.walletType.decimals, code)}
</Typography>
)}

View File

@ -1,5 +1,5 @@
/**
* Receive (deposit) dialog — USDT TRC20 on TRON only.
* Receive (deposit) dialog — choose TRC20 or BEP20 when enabled.
*/
import {
Alert,
@ -10,26 +10,55 @@ import {
DialogActions,
DialogContent,
DialogTitle,
FormControl,
IconButton,
InputLabel,
MenuItem,
Select,
Stack,
Typography,
} from '@mui/material';
import ContentCopyRoundedIcon from '@mui/icons-material/ContentCopyRounded';
import QRCode from 'react-qr-code';
import { useEffect, useMemo, useState } from 'react';
import { Trans, useTranslation } from 'react-i18next';
import { useDepositAddress } from '../hooks/useWalletData';
import { useBalances, useDepositAddress } from '../hooks/useWalletData';
import { networkLabel } from '../utils/coinDisplay';
import { USDT_WALLET_CODE } from '../utils/walletCapabilities';
import { USDT_BEP20_CODE, USDT_TRC20_CODE } from '../utils/walletCapabilities';
type ReceiveDialogProps = {
open: boolean;
onClose: () => void;
onCopied?: (message: string) => void;
initialAsset?: string | null;
};
export function ReceiveDialog({ open, onClose, onCopied }: ReceiveDialogProps) {
export function ReceiveDialog({ open, onClose, onCopied, initialAsset }: ReceiveDialogProps) {
const { t } = useTranslation();
const depositQ = useDepositAddress(USDT_WALLET_CODE, open);
const balancesQ = useBalances();
const depositOptions = useMemo(() => {
const rows = balancesQ.data ?? [];
return rows.filter(
(b) =>
(b.walletType.code === USDT_TRC20_CODE || b.walletType.code === USDT_BEP20_CODE) &&
b.walletType.depositEnabled !== false
);
}, [balancesQ.data]);
const [asset, setAsset] = useState('');
useEffect(() => {
if (!open) return;
const preferred =
(initialAsset && depositOptions.some((b) => b.walletType.code === initialAsset)
? initialAsset
: null) ??
depositOptions[0]?.walletType.code ??
'';
setAsset(preferred);
}, [open, initialAsset, depositOptions]);
const depositQ = useDepositAddress(asset || null, open && !!asset);
const copyAddress = async () => {
const addr = depositQ.data?.address;
@ -47,19 +76,45 @@ export function ReceiveDialog({ open, onClose, onCopied }: ReceiveDialogProps) {
<DialogTitle sx={{ fontWeight: 900 }}>{t('wallet.receiveDialog.title')}</DialogTitle>
<DialogContent>
<Stack spacing={2.5} sx={{ pt: 0.5 }}>
<Alert severity="info" sx={{ borderRadius: 2 }}>
<Trans
i18nKey="wallet.receiveDialog.info"
values={{ network: networkLabel(USDT_WALLET_CODE) }}
components={{ b: <b /> }}
/>
</Alert>
{depositOptions.length === 0 ? (
<Alert severity="warning" sx={{ borderRadius: 2 }}>
{t('wallet.receiveDialog.noNetworks')}
</Alert>
) : (
<FormControl fullWidth>
<InputLabel id="receive-network-label">{t('wallet.receiveDialog.network')}</InputLabel>
<Select
labelId="receive-network-label"
label={t('wallet.receiveDialog.network')}
value={asset}
onChange={(e) => setAsset(e.target.value)}
>
{depositOptions.map((b) => (
<MenuItem key={b.walletType.code} value={b.walletType.code}>
{b.walletType.name} — {networkLabel(b.walletType.code)}
</MenuItem>
))}
</Select>
</FormControl>
)}
<Alert severity="warning" sx={{ borderRadius: 2 }}>
{t('wallet.receiveDialog.wrongNetwork')}
</Alert>
{asset ? (
<>
<Alert severity="info" sx={{ borderRadius: 2 }}>
<Trans
i18nKey="wallet.receiveDialog.info"
values={{ network: networkLabel(asset) }}
components={{ b: <b /> }}
/>
</Alert>
{depositQ.isLoading ? (
<Alert severity="warning" sx={{ borderRadius: 2 }}>
{t('wallet.receiveDialog.wrongNetwork')}
</Alert>
</>
) : null}
{!asset ? null : depositQ.isLoading ? (
<Box sx={{ display: 'grid', placeItems: 'center', py: 4 }}>
<CircularProgress size={32} />
</Box>

View File

@ -24,7 +24,7 @@ import { api } from '../../../shared/services/api';
import { apiErrorMessage } from '../../../shared/utils/apiError';
import { useProfile } from '../../profile/hooks/useProfile';
import type { BalanceEntry } from '../types';
import { networkLabel } from '../utils/coinDisplay';
import { addressPlaceholder, networkLabel, scaleWithdrawalFeeRaw } from '../utils/coinDisplay';
import { formatBalance, humanToRaw, rawToHuman, shortSymbol } from '../utils/walletFormat';
type WithdrawDialogProps = {
@ -58,6 +58,11 @@ export function WithdrawDialog({
const [confirmOpen, setConfirmOpen] = useState(false);
const [submitting, setSubmitting] = useState(false);
const withdrawBalances = useMemo(
() => balances.filter((b) => b.walletType.withdrawEnabled !== false),
[balances]
);
const policyQ = useQuery({
queryKey: ['health-withdrawal-policy'],
queryFn: async () => {
@ -71,30 +76,26 @@ export function WithdrawDialog({
const totpEnabled = profileQ.data?.totpEnabled ?? false;
const needs2faSetup = requireWithdrawal2fa && !totpEnabled;
const feeRaw = useMemo(() => {
try {
const n = BigInt(networkFeeRaw.trim() || '0');
return n >= 0n ? n : 0n;
} catch {
return 0n;
}
}, [networkFeeRaw]);
useEffect(() => {
if (open) {
setAsset(initialAsset ?? balances[0]?.walletType.code ?? '');
setAsset(initialAsset ?? withdrawBalances[0]?.walletType.code ?? '');
setToAddress('');
setAmount('');
setTotpCode('');
setConfirmOpen(false);
}
}, [open, initialAsset, balances]);
}, [open, initialAsset, withdrawBalances]);
const selected = useMemo(
() => balances.find((b) => b.walletType.code === asset),
[balances, asset]
() => withdrawBalances.find((b) => b.walletType.code === asset),
[withdrawBalances, asset]
);
const feeRaw = useMemo(() => {
if (!selected) return 0n;
return scaleWithdrawalFeeRaw(networkFeeRaw, selected.walletType.decimals);
}, [networkFeeRaw, selected]);
const amountRaw = useMemo(() => {
if (!selected) return 0n;
try {
@ -115,7 +116,7 @@ export function WithdrawDialog({
}, [selected]);
const feeLabel = selected
? `${rawToHuman(networkFeeRaw, selected.walletType.decimals)} ${shortSymbol(asset)}`
? `${rawToHuman(feeRaw.toString(), selected.walletType.decimals)} ${shortSymbol(asset)}`
: rawToHuman(networkFeeRaw, 6);
const totalDebitLabel = selected
@ -196,6 +197,12 @@ export function WithdrawDialog({
</Alert>
)}
{withdrawBalances.length === 0 && (
<Alert severity="warning" sx={{ borderRadius: 2 }}>
{t('wallet.withdrawDialog.noNetworks')}
</Alert>
)}
{needs2faSetup && (
<Alert severity="warning" sx={{ borderRadius: 2 }}>
<Typography variant="body2" sx={{ mb: 1 }}>
@ -217,7 +224,7 @@ export function WithdrawDialog({
</Alert>
)}
<FormControl fullWidth disabled={!withdrawalsEnabled || needs2faSetup}>
<FormControl fullWidth disabled={!withdrawalsEnabled || needs2faSetup || withdrawBalances.length === 0}>
<InputLabel id="withdraw-asset-label">{t('common.asset')}</InputLabel>
<Select
labelId="withdraw-asset-label"
@ -225,7 +232,7 @@ export function WithdrawDialog({
value={asset}
onChange={(e) => setAsset(e.target.value)}
>
{balances.map((b) => (
{withdrawBalances.map((b) => (
<MenuItem key={b.walletType.code} value={b.walletType.code}>
{b.walletType.name} — {networkLabel(b.walletType.code)}
</MenuItem>
@ -247,7 +254,7 @@ export function WithdrawDialog({
value={toAddress}
onChange={(e) => setToAddress(e.target.value)}
disabled={!withdrawalsEnabled || needs2faSetup}
placeholder="T…"
placeholder={addressPlaceholder(asset)}
slotProps={{
htmlInput: { style: { fontFamily: 'monospace', fontSize: 13 } },
}}

View File

@ -12,6 +12,8 @@ export type WalletType = {
contract_address: string | null;
/** Whether new on-chain deposits are accepted for this asset. */
depositEnabled?: boolean;
/** Whether on-chain withdrawals are accepted for this asset (also needs global kill-switch). */
withdrawEnabled?: boolean;
/** Whether this asset is used for Candle Predict stakes. */
predictionEnabled?: boolean;
};

View File

@ -1,6 +1,5 @@
/**
* Visual identity helpers for wallet assets (colors, symbols, network labels).
* Mirrors prediqo_mobile CoinDisplay for consistent branding across clients.
*/
/** Gradient colors for asset avatar circles. */
@ -18,6 +17,30 @@ export function coinSymbol(code: string): string {
}
/** Human-readable network label for deposit/withdraw warnings. */
export function networkLabel(_code: string): string {
return 'TRON (TRC20)';
export function networkLabel(code: string): string {
const upper = code.toUpperCase();
if (upper.includes('BEP20') || upper.includes('BSC')) return 'BSC (BEP20)';
if (upper.includes('TRC20') || upper.includes('TRON')) return 'TRON (TRC20)';
if (upper.includes('USDT')) return 'TRON (TRC20)';
return upper;
}
/** Address placeholder hint for the selected network. */
export function addressPlaceholder(code: string): string {
const label = networkLabel(code);
if (label.startsWith('BSC')) return '0x…';
return 'T…';
}
/** Scale health fee (6-decimal micro-USDT) to wallet raw units. */
export function scaleWithdrawalFeeRaw(microRaw: string, walletDecimals: number): bigint {
try {
const base = BigInt((microRaw || '0').trim() || '0');
if (base < 0n) return 0n;
if (walletDecimals === 6) return base;
if (walletDecimals > 6) return base * 10n ** BigInt(walletDecimals - 6);
return base / 10n ** BigInt(6 - walletDecimals);
} catch {
return 0n;
}
}

View File

@ -1,2 +1,13 @@
/** Platform stablecoin used for deposits and Candle Predict. */
export const USDT_WALLET_CODE = 'USDT_TRC20';
/**
* Platform USDT codes used for deposits, withdrawals, and Candle Predict primary.
*/
export const USDT_TRC20_CODE = 'USDT_TRC20';
export const USDT_BEP20_CODE = 'USDT_BEP20';
/** @deprecated Prefer USDT_TRC20_CODE — prediction primary ledger */
export const USDT_WALLET_CODE = USDT_TRC20_CODE;
export const SUPPORTED_USDT_CODES = [USDT_TRC20_CODE, USDT_BEP20_CODE] as const;
export function isSupportedUsdtCode(code: string): boolean {
return (SUPPORTED_USDT_CODES as readonly string[]).includes(code);
}

View File

@ -299,10 +299,10 @@ export const en = {
wallet: {
title: 'Wallet',
subtitle:
'Deposit <b>USDT (TRC20)</b> on TRON to fund your account and play Candle Predict.',
'Deposit <b>USDT</b> on <b>TRON (TRC20)</b> or <b>BSC (BEP20)</b>. Candle Predict stakes use your TRC20 balance.',
refreshWallet: 'Refresh wallet',
loadError: 'Failed to load balances. Make sure you are logged in and the API is running.',
mainBalance: 'Main USDT balance',
mainBalance: 'USDT balances by network',
locked: '{{amount}} locked',
noBalance: 'No balance yet — receive USDT to get started.',
receiveUsdt: 'Receive USDT',
@ -318,8 +318,10 @@ export const en = {
},
receiveDialog: {
title: 'Receive USDT',
info: 'Send <b>USDT</b> on <b>{{network}}</b> only. This balance is used for Candle Predict stakes.',
wrongNetwork: 'Wrong asset or network may result in permanent loss.',
network: 'Network',
noNetworks: 'No deposit networks are enabled right now. Contact support or try again later.',
info: 'Send <b>USDT</b> on <b>{{network}}</b> only. Wrong network may result in permanent loss.',
wrongNetwork: 'Use the exact network shown above (TRC20 ≠ BEP20). Wrong network transfers cannot be recovered.',
loadAddressFailed: 'Failed to load deposit address',
copyAddressAria: 'Copy address',
confirmationsHint: 'Deposits are credited after the required on-chain confirmations.',
@ -343,8 +345,9 @@ export const en = {
title: 'Withdraw',
disabled: 'Withdrawals are disabled on this server (testnet safety). Contact an administrator to enable <code>ALLOW_WITHDRAWALS=true</code> when ready.',
networkWarning: 'Double-check the destination address and network. Wrong network transfers are irreversible.',
networkFee: 'A network fee of <b>{{fee}}</b> is deducted from your balance in addition to the withdrawal amount (covers TRON gas for the on-chain transfer).',
networkFee: 'A network fee of <b>{{fee}}</b> is deducted from your balance in addition to the withdrawal amount (covers on-chain gas).',
networkFixed: 'Network: <b>{{network}}</b> (cannot be changed)',
noNetworks: 'No withdrawal networks are enabled right now.',
destinationAddress: 'Destination address',
amountToReceive: 'Amount to receive',
totpOptional: '2FA code (optional)',
@ -976,7 +979,7 @@ export const en = {
},
network: {
title: 'Network & environment',
description: 'Testnet, USDT (TRC20) withdrawal status, and server environment.',
description: 'Testnet, USDT network status, and server environment.',
},
faq: {
title: 'FAQ',
@ -1707,15 +1710,23 @@ export const en = {
examplesShort: 'Examples: 15m, 1h',
examplesLong: 'Examples: 7d, 30d',
},
networks: {
title: 'USDT networks',
subtitle: 'Enable or disable deposits and withdrawals per chain (TRC20 / BEP20).',
trc20: 'TRON — USDT (TRC20)',
bep20: 'BSC — USDT (BEP20)',
depositEnabled: 'Deposits enabled',
withdrawEnabled: 'Withdrawals enabled (also requires global kill-switch below)',
},
withdrawals: {
title: 'Withdrawals & safety',
subtitle: 'Kill-switch and withdrawal limits (applied immediately after save).',
allowOnChain: 'Allow on-chain withdrawals',
allowOnChain: 'Allow on-chain withdrawals (global kill-switch)',
dailyLimit: 'Daily withdrawal limit (USD)',
largeThreshold: 'Large withdrawal threshold (USD)',
networkFee: 'Withdrawal network fee (USDT)',
networkFeeHelper:
"Deducted from the user's USDT balance per withdrawal (covers on-chain TRON gas).",
"Deducted from the user's USDT balance per withdrawal (scaled per network decimals; covers on-chain gas).",
},
rateLimiting: {
title: 'Rate limiting',

View File

@ -306,11 +306,11 @@ export const fr = {
wallet: {
title: 'Portefeuille',
subtitle:
'Déposez des <b>USDT (TRC20)</b> sur TRON pour alimenter votre compte et jouer à Candle Predict.',
'Déposez des <b>USDT</b> sur <b>TRON (TRC20)</b> ou <b>BSC (BEP20)</b>. Les mises Candle Predict utilisent votre solde TRC20.',
refreshWallet: 'Actualiser le portefeuille',
loadError:
'Impossible de charger les soldes. Vérifiez que vous êtes connecté et que l’API est active.',
mainBalance: 'Solde USDT principal',
mainBalance: 'Soldes USDT par réseau',
locked: '{{amount}} bloqué',
noBalance: 'Aucun solde — recevez des USDT pour commencer.',
receiveUsdt: 'Recevoir USDT',
@ -326,8 +326,11 @@ export const fr = {
},
receiveDialog: {
title: 'Recevoir USDT',
info: 'Envoyez des <b>USDT</b> sur <b>{{network}}</b> uniquement. Ce solde sert aux mises Candle Predict.',
wrongNetwork: 'Un mauvais actif ou réseau peut entraîner une perte définitive.',
network: 'Réseau',
noNetworks: 'Aucun réseau de dépôt n’est activé pour le moment. Contactez le support ou réessayez plus tard.',
info: 'Envoyez des <b>USDT</b> sur <b>{{network}}</b> uniquement. Un mauvais réseau peut entraîner une perte définitive.',
wrongNetwork:
'Utilisez exactement le réseau indiqué ci-dessus (TRC20 ≠ BEP20). Les transferts sur le mauvais réseau sont irrécupérables.',
loadAddressFailed: 'Impossible de charger l’adresse de dépôt',
copyAddressAria: 'Copier l’adresse',
confirmationsHint: 'Les dépôts sont crédités après les confirmations blockchain requises.',
@ -351,8 +354,9 @@ export const fr = {
title: 'Retirer',
disabled: 'Les retraits sont désactivés sur ce serveur (sécurité testnet). Contactez un administrateur pour activer <code>ALLOW_WITHDRAWALS=true</code> lorsque vous êtes prêt.',
networkWarning: 'Vérifiez l’adresse et le réseau de destination. Les transferts sur le mauvais réseau sont irréversibles.',
networkFee: 'Des frais réseau de <b>{{fee}}</b> sont déduits de votre solde en plus du montant du retrait (couvre le gas TRON).',
networkFee: 'Des frais réseau de <b>{{fee}}</b> sont déduits de votre solde en plus du montant du retrait (couvre le gas on-chain).',
networkFixed: 'Réseau : <b>{{network}}</b> (non modifiable)',
noNetworks: 'Aucun réseau de retrait n’est activé pour le moment.',
destinationAddress: 'Adresse de destination',
amountToReceive: 'Montant à recevoir',
totpOptional: 'Code 2FA (optionnel)',
@ -1724,15 +1728,23 @@ export const fr = {
examplesShort: 'Exemples : 15m, 1h',
examplesLong: 'Exemples : 7d, 30d',
},
networks: {
title: 'Réseaux USDT',
subtitle: 'Activer ou désactiver dépôts et retraits par chaîne (TRC20 / BEP20).',
trc20: 'TRON — USDT (TRC20)',
bep20: 'BSC — USDT (BEP20)',
depositEnabled: 'Dépôts activés',
withdrawEnabled: 'Retraits activés (nécessite aussi l’interrupteur global ci-dessous)',
},
withdrawals: {
title: 'Retraits & sécurité',
subtitle: 'Interrupteur d’urgence et limites de retrait (appliqués immédiatement après enregistrement).',
allowOnChain: 'Autoriser les retraits on-chain',
allowOnChain: 'Autoriser les retraits on-chain (interrupteur global)',
dailyLimit: 'Limite de retrait quotidienne (USD)',
largeThreshold: 'Seuil de gros retrait (USD)',
networkFee: 'Frais réseau de retrait (USDT)',
networkFeeHelper:
'Déduit du solde USDT de l’utilisateur par retrait (couvre le gas TRON on-chain).',
'Déduit du solde USDT de l’utilisateur par retrait (adapté aux décimales du réseau ; couvre le gas on-chain).',
},
rateLimiting: {
title: 'Limitation de débit',