From 342e84b6ef415eb258f8116d6a98990d507924c4 Mon Sep 17 00:00:00 2001 From: Your Name Date: Mon, 24 Aug 2026 13:41:54 +0200 Subject: [PATCH] After adding the BSC option --- .env.example | 8 +- backend/.env.example | 6 + backend/src/app.ts | 19 +- backend/src/bootstrap/appBootstrap.ts | 4 +- backend/src/config/index.ts | 9 + backend/src/db/schema.sql | 9 +- backend/src/models/settings.model.ts | 5 + .../src/repositories/settingsRepository.ts | 24 +++ backend/src/safety/networkGuard.ts | 25 ++- backend/src/scripts/rotateDepositAddresses.ts | 201 +++++++++++------- backend/src/scripts/seedHotWallets.ts | 88 +++++--- backend/src/scripts/verifyDepositAddresses.ts | 103 +++++---- backend/src/services/blockchain/bscService.ts | 143 +++++++++++++ backend/src/services/depositMonitorService.ts | 102 +++++++-- backend/src/services/hdWallet.ts | 14 +- backend/src/services/settingsService.ts | 13 ++ backend/src/services/sweepService.ts | 55 +++-- backend/src/services/walletCapabilities.ts | 63 +++++- backend/src/services/walletService.ts | 42 ++-- backend/src/services/withdrawalService.ts | 22 +- backend/src/tests/networkGuard.test.ts | 20 ++ backend/src/tests/walletCapabilities.test.ts | 56 +++++ backend/src/tests/withdrawalFee.test.ts | 18 ++ backend/src/utils/withdrawalFee.ts | 20 +- docker-compose.yml | 4 + docs/DEPLOY-VPS.md | 57 +++-- .../lib/core/utils/coin_display.dart | 20 ++ .../lib/data/models/wallet_type_model.dart | 11 +- .../deposit_asset_select_screen.dart | 4 +- .../wallet/presentation/withdraw_screen.dart | 25 ++- prediqo_mobile/lib/l10n/app_strings.dart | 4 +- .../src/features/settings/SettingsPage.tsx | 61 ++++++ .../src/features/wallet/WalletPage.tsx | 112 ++++++---- .../wallet/components/MainAssetCard.tsx | 30 +-- .../wallet/components/ReceiveDialog.tsx | 87 ++++++-- .../wallet/components/WithdrawDialog.tsx | 43 ++-- prediqo_web/src/features/wallet/types.ts | 2 + .../src/features/wallet/utils/coinDisplay.ts | 29 ++- .../wallet/utils/walletCapabilities.ts | 15 +- prediqo_web/src/shared/i18n/locales/en.ts | 27 ++- prediqo_web/src/shared/i18n/locales/fr.ts | 26 ++- 41 files changed, 1252 insertions(+), 374 deletions(-) create mode 100644 backend/src/services/blockchain/bscService.ts create mode 100644 backend/src/tests/walletCapabilities.test.ts create mode 100644 backend/src/tests/withdrawalFee.test.ts diff --git a/.env.example b/.env.example index cd916d57..98f9280d 100644 --- a/.env.example +++ b/.env.example @@ -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= diff --git a/backend/.env.example b/backend/.env.example index ffb7bed6..8cdb1862 100644 --- a/backend/.env.example +++ b/backend/.env.example @@ -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 diff --git a/backend/src/app.ts b/backend/src/app.ts index 1f5740e6..d51f3f27 100644 --- a/backend/src/app.ts +++ b/backend/src/app.ts @@ -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), }, }); }); diff --git a/backend/src/bootstrap/appBootstrap.ts b/backend/src/bootstrap/appBootstrap.ts index 27c47dfc..8952d17b 100644 --- a/backend/src/bootstrap/appBootstrap.ts +++ b/backend/src/bootstrap/appBootstrap.ts @@ -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 { const run = async () => { try { - await processTronDeposits(); + await processAllDeposits(); } catch (e) { console.error('Deposit monitor error:', e); } diff --git a/backend/src/config/index.ts b/backend/src/config/index.ts index fd081ebe..80461715 100644 --- a/backend/src/config/index.ts +++ b/backend/src/config/index.ts @@ -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), diff --git a/backend/src/db/schema.sql b/backend/src/db/schema.sql index 965c24f5..3e240079 100644 --- a/backend/src/db/schema.sql +++ b/backend/src/db/schema.sql @@ -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'), diff --git a/backend/src/models/settings.model.ts b/backend/src/models/settings.model.ts index d99e1597..0a1ca055 100644 --- a/backend/src/models/settings.model.ts +++ b/backend/src/models/settings.model.ts @@ -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. */ diff --git a/backend/src/repositories/settingsRepository.ts b/backend/src/repositories/settingsRepository.ts index 433ac198..1ba25315 100644 --- a/backend/src/repositories/settingsRepository.ts +++ b/backend/src/repositories/settingsRepository.ts @@ -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', diff --git a/backend/src/safety/networkGuard.ts b/backend/src/safety/networkGuard.ts index 56196a0b..31e7ee3e 100644 --- a/backend/src/safety/networkGuard.ts +++ b/backend/src/safety/networkGuard.ts @@ -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, }); } diff --git a/backend/src/scripts/rotateDepositAddresses.ts b/backend/src/scripts/rotateDepositAddresses.ts index 14cd8d89..7d7cbf97 100644 --- a/backend/src/scripts/rotateDepositAddresses.ts +++ b/backend/src/scripts/rotateDepositAddresses.ts @@ -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 { + 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( + `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 { const args = parseArgs(process.argv.slice(2)); if (args.confirm !== CONFIRM_PHRASE) { @@ -93,8 +170,6 @@ async function main(): Promise { } 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 { 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 { return; } - const before = await query( - `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() diff --git a/backend/src/scripts/seedHotWallets.ts b/backend/src/scripts/seedHotWallets.ts index 0b913eb7..00b63646 100644 --- a/backend/src/scripts/seedHotWallets.ts +++ b/backend/src/scripts/seedHotWallets.ts @@ -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 { + 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 { const mnemonic = (process.env.PLATFORM_MNEMONIC || '').trim(); @@ -25,32 +62,23 @@ async function main(): Promise { 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() diff --git a/backend/src/scripts/verifyDepositAddresses.ts b/backend/src/scripts/verifyDepositAddresses.ts index 3409c5b9..1b4de1cd 100644 --- a/backend/src/scripts/verifyDepositAddresses.ts +++ b/backend/src/scripts/verifyDepositAddresses.ts @@ -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 { - 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 { + 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>( + ` + 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 { 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 { const hot = await query>( `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 { + 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.' diff --git a/backend/src/services/blockchain/bscService.ts b/backend/src/services/blockchain/bscService.ts new file mode 100644 index 00000000..69a3475d --- /dev/null +++ b/backend/src/services/blockchain/bscService.ts @@ -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 { + 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 { + 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 { + return getProvider().getBalance(address); +} + +export async function getUsdtBalanceRaw(address: string, contractAddress: string): Promise { + 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 { + 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; +} diff --git a/backend/src/services/depositMonitorService.ts b/backend/src/services/depositMonitorService.ts index 8bbbdc5e..ca6be306 100644 --- a/backend/src/services/depositMonitorService.ts +++ b/backend/src/services/depositMonitorService.ts @@ -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 { + await processTronDeposits(); + await processBscDeposits(); +} /** Scans TRON for new USDT TRC20 deposits and credits confirmed transfers. */ export async function processTronDeposits(): Promise { - 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 { ); 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 { 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 { 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 { await depositScannerRepository.updateState(walletType.id, BigInt(currentBlock)); } +/** Scans BSC for new USDT BEP20 deposits and credits confirmed transfers. */ +export async function processBscDeposits(): Promise { + 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>( + '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 { 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'); diff --git a/backend/src/services/hdWallet.ts b/backend/src/services/hdWallet.ts index f5c36dc2..b28b77cb 100644 --- a/backend/src/services/hdWallet.ts +++ b/backend/src/services/hdWallet.ts @@ -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 diff --git a/backend/src/services/settingsService.ts b/backend/src/services/settingsService.ts index 6c8fb88e..a0116ee1 100644 --- a/backend/src/services/settingsService.ts +++ b/backend/src/services/settingsService.ts @@ -269,6 +269,19 @@ export function parseSettingsUpdates(body: Record): Partial { +async function ensureTronGasForTokenSweep(depositAddress: string, usdtWalletTypeId: number): Promise { 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 { + 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 { 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 { - 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'); diff --git a/backend/src/services/walletCapabilities.ts b/backend/src/services/walletCapabilities.ts index bb483dff..d5da0916 100644 --- a/backend/src/services/walletCapabilities.ts +++ b/backend/src/services/walletCapabilities.ts @@ -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 { + const { getSettings } = await import('../repositories/settingsRepository'); + const settings = await getSettings(); + return enrichWalletType(walletType, settings); +} diff --git a/backend/src/services/walletService.ts b/backend/src/services/walletService.ts index 3fe6f400..8cdf61b5 100644 --- a/backend/src/services/walletService.ts +++ b/backend/src/services/walletService.ts @@ -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 { @@ -71,7 +82,10 @@ async function getNextDerivationIndex(walletTypeId: number): Promise { export async function getWalletTypes(): Promise { 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', diff --git a/backend/src/services/withdrawalService.ts b/backend/src/services/withdrawalService.ts index 39902d6a..4d5499f8 100644 --- a/backend/src/services/withdrawalService.ts +++ b/backend/src/services/withdrawalService.ts @@ -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 { diff --git a/backend/src/tests/networkGuard.test.ts b/backend/src/tests/networkGuard.test.ts index 979c899d..68c72199 100644 --- a/backend/src/tests/networkGuard.test.ts +++ b/backend/src/tests/networkGuard.test.ts @@ -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/ + ); + }); }); diff --git a/backend/src/tests/walletCapabilities.test.ts b/backend/src/tests/walletCapabilities.test.ts new file mode 100644 index 00000000..d0f49a88 --- /dev/null +++ b/backend/src/tests/walletCapabilities.test.ts @@ -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); + }); +}); diff --git a/backend/src/tests/withdrawalFee.test.ts b/backend/src/tests/withdrawalFee.test.ts new file mode 100644 index 00000000..25859806 --- /dev/null +++ b/backend/src/tests/withdrawalFee.test.ts @@ -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); + }); +}); diff --git a/backend/src/utils/withdrawalFee.ts b/backend/src/utils/withdrawalFee.ts index 03292cee..4a9d26b5 100644 --- a/backend/src/utils/withdrawalFee.ts +++ b/backend/src/utils/withdrawalFee.ts @@ -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; diff --git a/docker-compose.yml b/docker-compose.yml index 41b5dfb1..60a6f781 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -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:-} diff --git a/docs/DEPLOY-VPS.md b/docs/DEPLOY-VPS.md index d9158a99..f0f7a4d3 100644 --- a/docs/DEPLOY-VPS.md +++ b/docs/DEPLOY-VPS.md @@ -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` | diff --git a/prediqo_mobile/lib/core/utils/coin_display.dart b/prediqo_mobile/lib/core/utils/coin_display.dart index f519d572..e00e8174 100644 --- a/prediqo_mobile/lib/core/utils/coin_display.dart +++ b/prediqo_mobile/lib/core/utils/coin_display.dart @@ -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); + } } diff --git a/prediqo_mobile/lib/data/models/wallet_type_model.dart b/prediqo_mobile/lib/data/models/wallet_type_model.dart index f138588d..034a696c 100644 --- a/prediqo_mobile/lib/data/models/wallet_type_model.dart +++ b/prediqo_mobile/lib/data/models/wallet_type_model.dart @@ -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 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, ); } } diff --git a/prediqo_mobile/lib/features/wallet/presentation/deposit_asset_select_screen.dart b/prediqo_mobile/lib/features/wallet/presentation/deposit_asset_select_screen.dart index 34f391bf..c6c0a7eb 100644 --- a/prediqo_mobile/lib/features/wallet/presentation/deposit_asset_select_screen.dart +++ b/prediqo_mobile/lib/features/wallet/presentation/deposit_asset_select_screen.dart @@ -39,7 +39,7 @@ class _DepositAssetSelectScreenState extends State { 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 { ), 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, ), diff --git a/prediqo_mobile/lib/features/wallet/presentation/withdraw_screen.dart b/prediqo_mobile/lib/features/wallet/presentation/withdraw_screen.dart index 5e0c62d8..7cc30843 100644 --- a/prediqo_mobile/lib/features/wallet/presentation/withdraw_screen.dart +++ b/prediqo_mobile/lib/features/wallet/presentation/withdraw_screen.dart @@ -75,7 +75,7 @@ class _WithdrawScreenState extends State { ); 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 { ); return; } - final feeHuman = rawAmountToHuman(_networkFeeRaw, selectedType.decimals); + final feeHuman = rawAmountToHuman(feeRaw.toString(), selectedType.decimals); final address = _addressController.text.trim(); showDialog( context: context, @@ -180,17 +180,17 @@ class _WithdrawScreenState extends State { 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 { const Text('Asset'), const SizedBox(height: 8), DropdownButtonFormField( - 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 { 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 { 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, ), ), diff --git a/prediqo_mobile/lib/l10n/app_strings.dart b/prediqo_mobile/lib/l10n/app_strings.dart index 62c0fc44..b6bacaa5 100644 --- a/prediqo_mobile/lib/l10n/app_strings.dart +++ b/prediqo_mobile/lib/l10n/app_strings.dart @@ -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.', diff --git a/prediqo_web/src/features/settings/SettingsPage.tsx b/prediqo_web/src/features/settings/SettingsPage.tsx index 17fa947e..a38a1a97 100644 --- a/prediqo_web/src/features/settings/SettingsPage.tsx +++ b/prediqo_web/src/features/settings/SettingsPage.tsx @@ -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() { + + }> + + {t('admin.settings.sections.networks.title')} + + {t('admin.settings.sections.networks.subtitle')} + + + + + + + {t('admin.settings.sections.networks.trc20')} + + set('network_usdt_trc20_deposit_enabled', e.target.checked)} + /> + } + label={t('admin.settings.sections.networks.depositEnabled')} + /> + set('network_usdt_trc20_withdraw_enabled', e.target.checked)} + /> + } + label={t('admin.settings.sections.networks.withdrawEnabled')} + /> + + {t('admin.settings.sections.networks.bep20')} + + set('network_usdt_bep20_deposit_enabled', e.target.checked)} + /> + } + label={t('admin.settings.sections.networks.depositEnabled')} + /> + set('network_usdt_bep20_withdraw_enabled', e.target.checked)} + /> + } + label={t('admin.settings.sections.networks.withdrawEnabled')} + /> + + + + }> diff --git a/prediqo_web/src/features/wallet/WalletPage.tsx b/prediqo_web/src/features/wallet/WalletPage.tsx index 8ca676c0..5ce0a4f0 100644 --- a/prediqo_web/src/features/wallet/WalletPage.tsx +++ b/prediqo_web/src/features/wallet/WalletPage.tsx @@ -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('deposits'); const [dialog, setDialog] = useState(null); + const [dialogAsset, setDialogAsset] = useState(null); const [toast, setToast] = useState(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() { ) : portfolioSummary ? ( - - {portfolioSummary.human} {shortSymbol(USDT_WALLET_CODE)} - - {portfolioSummary.hasLocked && ( - - )} + {portfolioSummary.lines.map((line) => ( + + + {line.human} {shortSymbol(line.code)} + + + {line.network} + + {line.hasLocked && ( + + )} + + ))} ) : ( {t('wallet.noBalance')} @@ -136,7 +156,7 @@ export function WalletPage() {