From d8f94f86508eea7ec6c4e9db70e6847aea17aaaa Mon Sep 17 00:00:00 2001 From: Your Name Date: Tue, 25 Aug 2026 17:59:10 +0200 Subject: [PATCH] After adding the BSC option4 --- backend/src/db/schema.sql | 11 ++ .../networkInventoryRepository.ts | 90 +++++++++ .../src/repositories/transactionRepository.ts | 6 +- backend/src/services/adminService.ts | 13 +- backend/src/services/depositMonitorService.ts | 181 +++++++++++------- backend/src/services/hotLiquidityService.ts | 125 ++++++++++++ backend/src/services/walletService.ts | 98 +++++++--- backend/src/services/withdrawalService.ts | 105 ++++++---- backend/src/tests/hotLiquidity.test.ts | 73 +++++++ backend/src/tests/usdtUnits.test.ts | 30 +++ backend/src/utils/usdtUnits.ts | 34 ++++ docs/DEPLOY-VPS.md | 15 +- .../repositories/wallet_repository_impl.dart | 26 ++- .../deposit_asset_select_screen.dart | 2 +- .../src/features/wallet/WalletPage.tsx | 140 ++++++-------- .../wallet/components/MainAssetCard.tsx | 83 ++++---- .../wallet/components/ReceiveDialog.tsx | 33 ++-- .../wallet/components/WithdrawDialog.tsx | 140 +++++++------- .../features/wallet/hooks/useWalletData.ts | 53 +++-- prediqo_web/src/features/wallet/types.ts | 21 +- prediqo_web/src/shared/i18n/locales/en.ts | 25 ++- prediqo_web/src/shared/i18n/locales/fr.ts | 24 ++- 22 files changed, 942 insertions(+), 386 deletions(-) create mode 100644 backend/src/repositories/networkInventoryRepository.ts create mode 100644 backend/src/services/hotLiquidityService.ts create mode 100644 backend/src/tests/hotLiquidity.test.ts create mode 100644 backend/src/tests/usdtUnits.test.ts create mode 100644 backend/src/utils/usdtUnits.ts diff --git a/backend/src/db/schema.sql b/backend/src/db/schema.sql index 3e240079..3633ddcf 100644 --- a/backend/src/db/schema.sql +++ b/backend/src/db/schema.sql @@ -207,6 +207,17 @@ CREATE INDEX IF NOT EXISTS idx_user_wallets_user ON user_wallets(user_id); CREATE INDEX IF NOT EXISTS idx_user_wallets_address ON user_wallets(address); CREATE INDEX IF NOT EXISTS idx_user_wallets_type ON user_wallets(wallet_type_id); +-- Per-network deposit inventory (ops telemetry; micro-USDT 6 decimals). Not a withdrawal cap. +CREATE TABLE IF NOT EXISTS user_network_inventory ( + user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, + network VARCHAR(16) NOT NULL CHECK (network IN ('TRON', 'BSC')), + amount BIGINT NOT NULL DEFAULT 0 CHECK (amount >= 0), + updated_at TIMESTAMPTZ DEFAULT NOW(), + PRIMARY KEY (user_id, network) +); + +CREATE INDEX IF NOT EXISTS idx_user_network_inventory_user ON user_network_inventory(user_id); + -- Hot wallet addresses (platform signs withdrawals from these) CREATE TABLE IF NOT EXISTS hot_wallets ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), diff --git a/backend/src/repositories/networkInventoryRepository.ts b/backend/src/repositories/networkInventoryRepository.ts new file mode 100644 index 00000000..d7b04eba --- /dev/null +++ b/backend/src/repositories/networkInventoryRepository.ts @@ -0,0 +1,90 @@ +/** + * Per-network USDT deposit inventory (ops telemetry; not a withdrawal cap). + */ + +import { PoolClient } from 'pg'; +import { query } from '../db/connection'; +import type { CustodyNetwork } from '../utils/usdtUnits'; + +export async function getAmount(userId: string, network: CustodyNetwork): Promise { + const rows = await query<{ amount: string }[]>( + `SELECT amount::text AS amount FROM user_network_inventory WHERE user_id = $1 AND network = $2`, + [userId, network] + ); + return BigInt(rows[0]?.amount ?? '0'); +} + +export async function getAllForUser(userId: string): Promise<{ TRON: bigint; BSC: bigint }> { + const rows = await query<{ network: CustodyNetwork; amount: string }[]>( + `SELECT network, amount::text AS amount FROM user_network_inventory WHERE user_id = $1`, + [userId] + ); + const out = { TRON: 0n, BSC: 0n }; + for (const row of rows) { + if (row.network === 'TRON' || row.network === 'BSC') { + out[row.network] = BigInt(row.amount); + } + } + return out; +} + +/** Credit inventory inside an open DB transaction. */ +export async function creditUsingClient( + client: PoolClient, + userId: string, + network: CustodyNetwork, + amount: bigint +): Promise { + if (amount <= 0n) return; + await client.query( + `INSERT INTO user_network_inventory (user_id, network, amount, updated_at) + VALUES ($1, $2, $3, NOW()) + ON CONFLICT (user_id, network) DO UPDATE + SET amount = user_network_inventory.amount + EXCLUDED.amount, + updated_at = NOW()`, + [userId, network, amount.toString()] + ); +} + +/** Debit inventory inside an open DB transaction; throws if insufficient. */ +export async function debitUsingClient( + client: PoolClient, + userId: string, + network: CustodyNetwork, + amount: bigint +): Promise { + if (amount <= 0n) return; + const res = await client.query( + `UPDATE user_network_inventory + SET amount = amount - $3, updated_at = NOW() + WHERE user_id = $1 AND network = $2 AND amount >= $3 + RETURNING amount`, + [userId, network, amount.toString()] + ); + if (res.rowCount === 0) { + const err = new Error(`Insufficient ${network} network inventory for withdrawal`) as Error & { + code?: string; + }; + err.code = 'INSUFFICIENT_NETWORK_INVENTORY'; + throw err; + } +} + +/** Debit inventory (own connection). */ +export async function debit(userId: string, network: CustodyNetwork, amount: bigint): Promise { + if (amount <= 0n) return; + const rows = await query<{ amount: string }[]>( + `UPDATE user_network_inventory + SET amount = amount - $3, updated_at = NOW() + WHERE user_id = $1 AND network = $2 AND amount >= $3 + RETURNING amount::text AS amount`, + [userId, network, amount.toString()] + ); + if (rows.length === 0) { + const err = new Error(`Insufficient ${network} network inventory for withdrawal`) as Error & { + code?: string; + }; + err.code = 'INSUFFICIENT_NETWORK_INVENTORY'; + throw err; + } +} diff --git a/backend/src/repositories/transactionRepository.ts b/backend/src/repositories/transactionRepository.ts index b115f8a2..199220bf 100644 --- a/backend/src/repositories/transactionRepository.ts +++ b/backend/src/repositories/transactionRepository.ts @@ -93,14 +93,15 @@ export async function insertDepositIfNew( toAddress: string; confirmations: number; requiredConfirmations: number; + metadata?: Record | null; } ): Promise { const res = await client.query( `INSERT INTO transactions ( user_id, wallet_type_id, type, amount, fee, status, - blockchain_tx_id, from_address, to_address, confirmations, required_confirmations + blockchain_tx_id, from_address, to_address, confirmations, required_confirmations, metadata ) - VALUES ($1, $2, 'deposit', $3, 0, 'completed', $4, $5, $6, $7, $8) + VALUES ($1, $2, 'deposit', $3, 0, 'completed', $4, $5, $6, $7, $8, $9) ON CONFLICT (blockchain_tx_id) WHERE blockchain_tx_id IS NOT NULL DO NOTHING RETURNING id, user_id, wallet_type_id, type, amount::text, fee::text, status, @@ -115,6 +116,7 @@ export async function insertDepositIfNew( data.toAddress, data.confirmations, data.requiredConfirmations, + data.metadata ? JSON.stringify(data.metadata) : null, ] ); return res.rows[0] ?? null; diff --git a/backend/src/services/adminService.ts b/backend/src/services/adminService.ts index df48622b..2ea1caa1 100644 --- a/backend/src/services/adminService.ts +++ b/backend/src/services/adminService.ts @@ -548,6 +548,15 @@ export async function getUserDetails(userId: string): Promise<{ available: string; locked: string; }>; + inventory: { TRON: string; BSC: string }; + networks: Array<{ + code: string; + network: string; + depositEnabled: boolean; + withdrawEnabled: boolean; + inventory: string; + withdrawable: string; + }>; }> { const row = await userRepository.getForAdmin(userId); if (!row) { @@ -572,12 +581,14 @@ export async function getUserDetails(userId: string): Promise<{ security_suspended_at: row.security_suspended_at, created_at: row.created_at, }, - balances: balances.map((b) => ({ + balances: balances.balances.map((b) => ({ wallet_type: b.walletType.code, wallet_name: b.walletType.name, available: b.available, locked: b.locked, })), + inventory: balances.inventory, + networks: balances.networks, }; } diff --git a/backend/src/services/depositMonitorService.ts b/backend/src/services/depositMonitorService.ts index ca6be306..1a511da7 100644 --- a/backend/src/services/depositMonitorService.ts +++ b/backend/src/services/depositMonitorService.ts @@ -1,6 +1,7 @@ /** * Deposit scanner and crediting service. - * Polls TRON for incoming USDT (TRC20) transfers and credits user ledger accounts. + * Credits a unified USDT ledger (USDT_TRC20, 6 decimals) and per-network inventory. + * Custody scans remain on TRON (TRC20) and BSC (BEP20) deposit addresses. */ import { config } from '../config'; @@ -9,6 +10,7 @@ import * as walletRepository from '../repositories/walletRepository'; import * as ledgerRepository from '../repositories/ledgerRepository'; import * as transactionRepository from '../repositories/transactionRepository'; import * as depositScannerRepository from '../repositories/depositScannerRepository'; +import * as networkInventoryRepository from '../repositories/networkInventoryRepository'; import * as auditLogRepository from '../repositories/auditLogRepository'; import { enqueueSweepAfterDeposit } from './sweepService'; import { queueUserAdminStatsRefresh } from './userAdminStatsService'; @@ -17,6 +19,12 @@ 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'; +import { + BEP20_USDT_DECIMALS, + LEDGER_USDT_DECIMALS, + scaleChainToLedger, + type CustodyNetwork, +} from '../utils/usdtUnits'; const TRON_CONFIRMATIONS = config.blockchain.tron.confirmations; const BSC_CONFIRMATIONS = config.blockchain.bsc.confirmations; @@ -32,11 +40,12 @@ export async function processTronDeposits(): Promise { 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 custodyType = await walletRepository.getWalletTypeByCode(USDT_TRC20_CODE); + const ledgerType = custodyType; + if (!custodyType || !ledgerType) return; const currentBlock = await tronService.getCurrentBlock(); - const state = await depositScannerRepository.getState(walletType.id); + const state = await depositScannerRepository.getState(custodyType.id); let fromBlock = state ? BigInt(state.last_block) + 1n : 0n; if (fromBlock > BigInt(currentBlock)) { fromBlock = 0n; @@ -44,13 +53,13 @@ export async function processTronDeposits(): Promise { const userWallets = await query>( 'SELECT address, user_id, created_at FROM user_wallets WHERE wallet_type_id = $1', - [walletType.id] + [custodyType.id] ); if (userWallets.length > 0) { const hasAnyUsdtDeposit = await query<{ n: string }[]>( `SELECT 1 as n FROM transactions WHERE wallet_type_id = $1 AND type = 'deposit' LIMIT 1`, - [walletType.id] + [ledgerType.id] ).then((r) => r.length > 0); if (!hasAnyUsdtDeposit && fromBlock > 0n) { fromBlock = 0n; @@ -67,12 +76,12 @@ export async function processTronDeposits(): Promise { } const trc20Contract = - config.blockchain.tron.usdtTrc20Contract || walletType.contract_address || ''; + config.blockchain.tron.usdtTrc20Contract || custodyType.contract_address || ''; if (!trc20Contract) return; if (process.env.NODE_ENV !== 'production') { console.log( - `[deposit] USDT_TRC20 (id=${walletType.id}): ${userWallets.length} wallets, fromBlock=${fromBlock}` + `[deposit] USDT_TRC20 (id=${custodyType.id}): ${userWallets.length} wallets, fromBlock=${fromBlock}` ); } @@ -92,16 +101,20 @@ export async function processTronDeposits(): Promise { if (amount == null) continue; if (t.confirmations >= TRON_CONFIRMATIONS) { try { - await creditDeposit( - user_id, - walletType.id, - amount, - t.txId, - t.from, - address, - t.confirmations, - TRON_CONFIRMATIONS - ); + await creditDeposit({ + userId: user_id, + ledgerWalletTypeId: ledgerType.id, + custodyWalletTypeId: custodyType.id, + network: 'TRON', + sourceWalletCode: USDT_TRC20_CODE, + ledgerAmount: amount, + chainAmount: amount, + blockchainTxId: t.txId, + fromAddress: t.from, + toAddress: address, + confirmations: t.confirmations, + requiredConfirmations: TRON_CONFIRMATIONS, + }); } catch (e) { console.error(`[deposit] TRC20 credit failed tx=${t.txId}:`, e); } @@ -109,41 +122,41 @@ export async function processTronDeposits(): Promise { } } - await depositScannerRepository.updateState(walletType.id, BigInt(currentBlock)); + await depositScannerRepository.updateState(custodyType.id, BigInt(currentBlock)); } -/** Scans BSC for new USDT BEP20 deposits and credits confirmed transfers. */ +/** Scans BSC for new USDT BEP20 deposits; credits unified ledger (6 dec) + BSC inventory. */ 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 custodyType = await walletRepository.getWalletTypeByCode(USDT_BEP20_CODE); + const ledgerType = await walletRepository.getWalletTypeByCode(USDT_TRC20_CODE); + if (!custodyType || !ledgerType) return; const currentBlock = await bscService.getCurrentBlock(); - const state = await depositScannerRepository.getState(walletType.id); + const state = await depositScannerRepository.getState(custodyType.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] + [custodyType.id] ); if (userWallets.length === 0) { - await depositScannerRepository.updateState(walletType.id, BigInt(currentBlock)); + await depositScannerRepository.updateState(custodyType.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); + const contract = bscService.resolveUsdtContract(custodyType.contract_address); if (process.env.NODE_ENV !== 'production') { console.log( - `[deposit] USDT_BEP20 (id=${walletType.id}): ${userWallets.length} wallets, fromBlock=${fromBlock}` + `[deposit] USDT_BEP20 (id=${custodyType.id}): ${userWallets.length} wallets, fromBlock=${fromBlock}` ); } @@ -157,50 +170,70 @@ export async function processBscDeposits(): Promise { for (const t of transfers) { const confirmations = currentBlock - t.blockNumber + 1; if (confirmations < BSC_CONFIRMATIONS) continue; + const ledgerAmount = scaleChainToLedger(t.value, BEP20_USDT_DECIMALS, LEDGER_USDT_DECIMALS); + if (ledgerAmount <= 0n) continue; try { - await creditDeposit( - user_id, - walletType.id, - t.value, - t.txHash, - t.from, - address, + await creditDeposit({ + userId: user_id, + ledgerWalletTypeId: ledgerType.id, + custodyWalletTypeId: custodyType.id, + network: 'BSC', + sourceWalletCode: USDT_BEP20_CODE, + ledgerAmount, + chainAmount: t.value, + blockchainTxId: t.txHash, + fromAddress: t.from, + toAddress: address, confirmations, - BSC_CONFIRMATIONS - ); + requiredConfirmations: BSC_CONFIRMATIONS, + }); } catch (e) { console.error(`[deposit] BEP20 credit failed tx=${t.txHash}:`, e); } } } - await depositScannerRepository.updateState(walletType.id, BigInt(currentBlock)); + await depositScannerRepository.updateState(custodyType.id, BigInt(currentBlock)); } -async function creditDeposit( - userId: string, - walletTypeId: number, - amount: bigint, - blockchainTxId: string, - fromAddress: string, - toAddress: string, - block: number, - requiredConfirmations: number -): Promise { - const account = await ledgerRepository.getOrCreateAccount(userId, walletTypeId, 'main'); +async function creditDeposit(opts: { + userId: string; + ledgerWalletTypeId: number; + custodyWalletTypeId: number; + network: CustodyNetwork; + sourceWalletCode: string; + ledgerAmount: bigint; + chainAmount: bigint; + blockchainTxId: string; + fromAddress: string; + toAddress: string; + confirmations: number; + requiredConfirmations: number; +}): Promise { + const account = await ledgerRepository.getOrCreateAccount( + opts.userId, + opts.ledgerWalletTypeId, + 'main' + ); const client = await getClient(); let tx: Awaited> = null; try { await beginAuthorizedTransaction(client); tx = await transactionRepository.insertDepositIfNew(client, { - userId, - walletTypeId, - amount, - blockchainTxId, - fromAddress, - toAddress, - confirmations: block, - requiredConfirmations, + userId: opts.userId, + walletTypeId: opts.ledgerWalletTypeId, + amount: opts.ledgerAmount, + blockchainTxId: opts.blockchainTxId, + fromAddress: opts.fromAddress, + toAddress: opts.toAddress, + confirmations: opts.confirmations, + requiredConfirmations: opts.requiredConfirmations, + metadata: { + network: opts.network, + source_wallet_type: opts.sourceWalletCode, + chain_amount: opts.chainAmount.toString(), + ledger_amount: opts.ledgerAmount.toString(), + }, }); if (!tx) { await client.query('COMMIT'); @@ -209,11 +242,17 @@ async function creditDeposit( await ledgerRepository.creditUsingClient( client, account.id, - amount, + opts.ledgerAmount, 'deposit', 'transaction', tx.id ); + await networkInventoryRepository.creditUsingClient( + client, + opts.userId, + opts.network, + opts.ledgerAmount + ); await client.query('COMMIT'); } catch (e) { await client.query('ROLLBACK'); @@ -225,18 +264,30 @@ async function creditDeposit( if (!tx) return; await referralService.processFirstDepositReferralCommissions({ - userId, + userId: opts.userId, depositTransactionId: tx.id, - depositAmount: amount, - walletTypeId, + depositAmount: opts.ledgerAmount, + walletTypeId: opts.ledgerWalletTypeId, }); await auditLogRepository.create({ - userId, + userId: opts.userId, action: 'deposit_confirmed', resourceType: 'transaction', resourceId: tx.id, - metadata: { amount: amount.toString(), blockchainTxId }, + metadata: { + amount: opts.ledgerAmount.toString(), + chainAmount: opts.chainAmount.toString(), + network: opts.network, + sourceWalletType: opts.sourceWalletCode, + blockchainTxId: opts.blockchainTxId, + }, }); - await enqueueSweepAfterDeposit(userId, walletTypeId, amount, tx.id); - queueUserAdminStatsRefresh(userId); + // Sweep uses custody type + on-chain amount + await enqueueSweepAfterDeposit( + opts.userId, + opts.custodyWalletTypeId, + opts.chainAmount, + tx.id + ); + queueUserAdminStatsRefresh(opts.userId); } diff --git a/backend/src/services/hotLiquidityService.ts b/backend/src/services/hotLiquidityService.ts new file mode 100644 index 00000000..6b82c491 --- /dev/null +++ b/backend/src/services/hotLiquidityService.ts @@ -0,0 +1,125 @@ +/** + * Pre-flight checks: platform hot wallet has enough USDT + native gas + * to pay a withdrawal on the chosen rail (cross-network float model). + */ + +import { config } from '../config'; +import * as tronService from './blockchain/tronService'; +import * as bscService from './blockchain/bscService'; +import { + BEP20_USDT_DECIMALS, + scaleLedgerToChain, +} from '../utils/usdtUnits'; + +/** ~3 TRX — enough for a typical TRC20 transfer under energy rental / burned TRX. */ +export const MIN_TRX_SUN_FOR_WITHDRAWAL = 3_000_000n; +/** ~0.001 BNB — buffer above a simple ERC-20 transfer on BSC. */ +export const MIN_BNB_WEI_FOR_WITHDRAWAL = 1_000_000_000_000_000n; + +export type HotLiquidityVerdict = + | { ok: true } + | { ok: false; reason: 'usdt' | 'gas'; needed: string; available: string }; + +/** + * Pure comparison of hot balances vs required payout (ledger amount is always 6-dec micro-USDT). + */ +export function evaluateHotLiquidity(input: { + network: 'TRON' | 'BSC'; + usdtBalanceRaw: bigint; + nativeBalanceRaw: bigint; + ledgerAmountRaw: bigint; +}): HotLiquidityVerdict { + const { network, usdtBalanceRaw, nativeBalanceRaw, ledgerAmountRaw } = input; + if (ledgerAmountRaw <= 0n) { + return { ok: true }; + } + + if (network === 'TRON') { + if (usdtBalanceRaw < ledgerAmountRaw) { + return { + ok: false, + reason: 'usdt', + needed: ledgerAmountRaw.toString(), + available: usdtBalanceRaw.toString(), + }; + } + if (nativeBalanceRaw < MIN_TRX_SUN_FOR_WITHDRAWAL) { + return { + ok: false, + reason: 'gas', + needed: MIN_TRX_SUN_FOR_WITHDRAWAL.toString(), + available: nativeBalanceRaw.toString(), + }; + } + return { ok: true }; + } + + const chainUsdt = scaleLedgerToChain(ledgerAmountRaw, BEP20_USDT_DECIMALS); + if (usdtBalanceRaw < chainUsdt) { + return { + ok: false, + reason: 'usdt', + needed: chainUsdt.toString(), + available: usdtBalanceRaw.toString(), + }; + } + if (nativeBalanceRaw < MIN_BNB_WEI_FOR_WITHDRAWAL) { + return { + ok: false, + reason: 'gas', + needed: MIN_BNB_WEI_FOR_WITHDRAWAL.toString(), + available: nativeBalanceRaw.toString(), + }; + } + return { ok: true }; +} + +function liquidityError(message: string): Error & { code: string } { + const err = new Error(message) as Error & { code: string }; + err.code = 'HOT_WALLET_INSUFFICIENT_LIQUIDITY'; + return err; +} + +/** + * Reads on-chain hot balances and throws if the platform cannot pay `ledgerAmountRaw` on `network`. + */ +export async function assertHotWalletCanPay(params: { + network: 'TRON' | 'BSC'; + hotAddress: string; + ledgerAmountRaw: bigint; + usdtContract: string; +}): Promise { + const { network, hotAddress, ledgerAmountRaw, usdtContract } = params; + + let usdtBalanceRaw: bigint; + let nativeBalanceRaw: bigint; + + if (network === 'TRON') { + const contract = config.blockchain.tron.usdtTrc20Contract || usdtContract; + if (!contract) throw new Error('USDT TRC20 contract not configured'); + usdtBalanceRaw = await tronService.getTrc20BalanceRaw(hotAddress, contract); + nativeBalanceRaw = await tronService.getTrxBalanceSun(hotAddress); + } else { + const contract = bscService.resolveUsdtContract(usdtContract); + usdtBalanceRaw = await bscService.getUsdtBalanceRaw(hotAddress, contract); + nativeBalanceRaw = await bscService.getNativeBalanceWei(hotAddress); + } + + const verdict = evaluateHotLiquidity({ + network, + usdtBalanceRaw, + nativeBalanceRaw, + ledgerAmountRaw, + }); + + if (verdict.ok) return; + + if (verdict.reason === 'usdt') { + throw liquidityError( + `Platform hot wallet has insufficient USDT on ${network} to complete this withdrawal. Try again later or choose another network.` + ); + } + throw liquidityError( + `Platform hot wallet has insufficient ${network === 'TRON' ? 'TRX' : 'BNB'} for gas on ${network}. Try again later or choose another network.` + ); +} diff --git a/backend/src/services/walletService.ts b/backend/src/services/walletService.ts index 8cdf61b5..683080e2 100644 --- a/backend/src/services/walletService.ts +++ b/backend/src/services/walletService.ts @@ -1,6 +1,8 @@ /** * User wallet and deposit address service. * Derives TRON (TRC20) and BSC (BEP20) deposit addresses for USDT. + * Spendable ledger is always USDT_TRC20 (6 decimals). Inventory is deposit-sourced + * ops telemetry per network; withdrawals are capped by ledger + hot float, not inventory. */ import * as bip39 from 'bip39'; @@ -8,9 +10,11 @@ import { deriveEvmFromMnemonic, deriveTronFromMnemonic } from './hdWallet'; import { query } from '../db/connection'; import * as walletRepository from '../repositories/walletRepository'; import * as transactionRepository from '../repositories/transactionRepository'; +import * as networkInventoryRepository from '../repositories/networkInventoryRepository'; import { Transaction } from '../models'; import { assertUsdtWalletType, + enrichWalletType, enrichWalletTypeAsync, USDT_BEP20_CODE, USDT_TRC20_CODE, @@ -33,7 +37,7 @@ function getMnemonic(): string { } /** - * Gets or creates a USDT deposit address for a user (TRC20 or BEP20). + * Gets or creates a USDT deposit address for a user (TRC20 or BEP20 custody rail). */ export async function getOrCreateDepositAddress( userId: string, @@ -84,45 +88,89 @@ export async function getWalletTypes(): Promise { const types = await walletRepository.getWalletTypes(); 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< - Array<{ +export type NetworkBalanceInfo = { + code: string; + network: string; + depositEnabled: boolean; + withdrawEnabled: boolean; + /** Cumulative deposits credited on this network (ops / reporting; not a withdrawal cap). */ + inventory: string; + /** Max withdrawable on this rail when enabled = full spendable available (ledger units). */ + withdrawable: string; +}; + +export type UserBalancesResponse = { + /** Unified spendable USDT ledger (USDT_TRC20, 6 decimals). */ + spendable: { walletType: WalletTypeCapabilities; available: string; locked: string; bonusAvailable: string; testAvailable: string; - }> -> { - const types = await walletRepository.getWalletTypes(); + }; + inventory: { TRON: string; BSC: string }; + networks: NetworkBalanceInfo[]; + /** + * @deprecated Prefer `spendable` + `networks`. Kept for older clients: + * single spendable row only (no separate BEP20 ledger balance). + */ + balances: Array<{ + walletType: WalletTypeCapabilities; + available: string; + locked: string; + bonusAvailable: string; + testAvailable: string; + }>; +}; + +export async function getUserBalances(userId: string): Promise { 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; - locked: string; - bonusAvailable: string; - testAvailable: string; - }> = []; + + const ledgerType = await walletRepository.getWalletTypeByCode(USDT_TRC20_CODE); + if (!ledgerType) throw new Error('USDT_TRC20 wallet type not configured'); + + const account = await getOrCreateAccount(userId, ledgerType.id, 'main'); + const bonus = await getAccount(userId, ledgerType.id, 'bonus'); + const test = await getAccount(userId, ledgerType.id, 'test'); + const available = BigInt(account.available_balance); + const inv = await networkInventoryRepository.getAllForUser(userId); + + const spendable = { + walletType: enrichWalletType(ledgerType, settings), + available: account.available_balance, + locked: account.locked_balance, + bonusAvailable: bonus?.available_balance ?? '0', + testAvailable: test?.available_balance ?? '0', + }; + + const types = await walletRepository.getWalletTypes(); + const networks: NetworkBalanceInfo[] = []; 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, settings), - available: account.available_balance, - locked: account.locked_balance, - bonusAvailable: bonus?.available_balance ?? '0', - testAvailable: test?.available_balance ?? '0', + const caps = enrichWalletType(wt, settings); + const networkInv = wt.network === 'BSC' ? inv.BSC : inv.TRON; + const withdrawable = caps.withdrawEnabled ? available : 0n; + networks.push({ + code: wt.code, + network: wt.network, + depositEnabled: caps.depositEnabled, + withdrawEnabled: caps.withdrawEnabled, + inventory: networkInv.toString(), + withdrawable: withdrawable.toString(), }); } - return result; + + return { + spendable, + inventory: { TRON: inv.TRON.toString(), BSC: inv.BSC.toString() }, + networks, + balances: [spendable], + }; } export async function listUserTransactions( diff --git a/backend/src/services/withdrawalService.ts b/backend/src/services/withdrawalService.ts index 4d5499f8..a7e81c1c 100644 --- a/backend/src/services/withdrawalService.ts +++ b/backend/src/services/withdrawalService.ts @@ -1,6 +1,8 @@ /** * On-chain withdrawal service. - * Locks ledger balance, broadcasts via hot wallet, finalizes ledger atomically after broadcast. + * Debits unified USDT ledger (USDT_TRC20, 6 decimals); pays from the chosen + * rail hot wallet (TRC20 or BEP20). Network need not match deposit history — + * liquidity is gated by hot float (USDT + gas), not user inventory. */ import { config } from '../config'; @@ -27,17 +29,28 @@ 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'; +import { + enrichWalletType, + isSupportedUsdtCode, + USDT_TRC20_CODE, +} from './walletCapabilities'; +import { + BEP20_USDT_DECIMALS, + LEDGER_USDT_DECIMALS, + networkForWalletCode, + scaleLedgerToChain, +} from '../utils/usdtUnits'; +import { assertHotWalletCanPay } from './hotLiquidityService'; async function assertWithdrawalWithinLimits( userId: string, - walletType: WalletType, + railWalletType: WalletType, amountRaw: bigint, feeRaw: bigint, settings: SystemSettings ): Promise { - const amountUsd = rawAmountToUsdApprox(walletType.code, amountRaw, walletType.decimals); - const feeUsd = rawAmountToUsdApprox(walletType.code, feeRaw, walletType.decimals); + const amountUsd = rawAmountToUsdApprox(USDT_TRC20_CODE, amountRaw, LEDGER_USDT_DECIMALS); + const feeUsd = rawAmountToUsdApprox(USDT_TRC20_CODE, feeRaw, LEDGER_USDT_DECIMALS); const totalUsd = amountUsd + feeUsd; const startOfUtcDay = new Date(); @@ -64,7 +77,7 @@ async function assertWithdrawalWithinLimits( metadata: { amountUsd, thresholdUsd: settings.large_withdrawal_threshold_usd, - walletType: walletType.code, + walletType: railWalletType.code, amount: amountRaw.toString(), }, }); @@ -77,7 +90,7 @@ async function assertWithdrawalWithinLimits( metadata: { amountUsd, thresholdUsd: settings.large_withdrawal_threshold_usd, - walletType: walletType.code, + walletType: railWalletType.code, }, }).catch((e) => console.error('[withdrawal] large withdrawal alert failed:', e)); } @@ -92,8 +105,9 @@ export type WithdrawalResult = { }; /** - * Submits a withdrawal: locks funds (amount + network fee), sends amount on-chain from hot wallet. - * If on-chain succeeds but ledger finalization fails, funds stay locked and security is alerted. + * Submits a withdrawal: locks unified ledger, verifies hot float, pays from rail hot wallet. + * `walletTypeCode` selects the payout rail (USDT_TRC20 or USDT_BEP20). + * `amountRaw` is always in ledger micro-USDT (6 decimals). */ export async function requestWithdrawal( userId: string, @@ -110,25 +124,31 @@ export async function requestWithdrawal( await authService.assertWithdrawalSecondFactor(userId, totpCode); await assertUserCanWithdraw(userId); - const walletType = await walletRepository.getWalletTypeByCode(walletTypeCode); - if (!walletType) throw new Error('Unknown wallet type'); + const railWalletType = await walletRepository.getWalletTypeByCode(walletTypeCode); + if (!railWalletType) throw new Error('Unknown wallet type'); if (!isSupportedUsdtCode(walletTypeCode)) { throw new Error(`Withdrawals are only supported for USDT networks`); } - const caps = enrichWalletType(walletType, settings); + const network = networkForWalletCode(walletTypeCode); + if (!network) throw new Error('Unsupported withdrawal network'); + + const caps = enrichWalletType(railWalletType, 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 ledgerWalletType = await walletRepository.getWalletTypeByCode(USDT_TRC20_CODE); + if (!ledgerWalletType) throw new Error('USDT ledger wallet type not configured'); + + const feeRaw = getWithdrawalNetworkFeeRaw(settings, LEDGER_USDT_DECIMALS); const totalDebit = amountRaw + feeRaw; - await assertWithdrawalWithinLimits(userId, walletType, amountRaw, feeRaw, settings); + await assertWithdrawalWithinLimits(userId, railWalletType, amountRaw, feeRaw, settings); - const account = await ledgerRepository.getOrCreateAccount(userId, walletType.id); + const account = await ledgerRepository.getOrCreateAccount(userId, ledgerWalletType.id); const available = BigInt(account.available_balance); - const locked = await withdrawalLockRepository.getLockedAmount(userId, walletType.id); + const locked = await withdrawalLockRepository.getLockedAmount(userId, ledgerWalletType.id); if (available < totalDebit + locked) { throw new Error( feeRaw > 0n @@ -137,28 +157,44 @@ export async function requestWithdrawal( ); } + const hotWallet = await hotWalletRepository.getActiveHotWallet(railWalletType.id); + if (!hotWallet) throw new Error('Withdrawal temporarily unavailable'); + + if (network === 'TRON' || network === 'BSC') { + await assertHotWalletCanPay({ + network, + hotAddress: hotWallet.address, + ledgerAmountRaw: amountRaw, + usdtContract: railWalletType.contract_address || '', + }); + } + await ledgerRepository.lockBalance(account.id, totalDebit); queueUserAdminStatsRefresh(userId); const tx = await transactionRepository.create({ userId, - walletTypeId: walletType.id, + walletTypeId: ledgerWalletType.id, type: 'withdrawal', amount: amountRaw, fee: feeRaw, status: 'pending', toAddress, requiredConfirmations: - walletType.network === 'TRON' + railWalletType.network === 'TRON' ? config.blockchain.tron.confirmations - : walletType.network === 'BSC' + : railWalletType.network === 'BSC' ? config.blockchain.bsc.confirmations : config.blockchain.polygon.confirmations, + metadata: { + rail_wallet_type: walletTypeCode, + network, + }, }); await withdrawalLockRepository.create({ userId, - walletTypeId: walletType.id, + walletTypeId: ledgerWalletType.id, transactionId: tx.id, amount: totalDebit, }); @@ -173,33 +209,27 @@ export async function requestWithdrawal( fee: feeRaw.toString(), toAddress, walletType: walletTypeCode, + network, }, }); let blockchainTxId: string | null = null; try { - const hotWallet = await hotWalletRepository.getActiveHotWallet(walletType.id); - if (!hotWallet) throw new Error('Withdrawal temporarily unavailable'); - const privateKey = decryptPrivateKey(hotWallet.encrypted_private_key); await transactionRepository.updateStatus(tx.id, 'broadcasting'); - if (walletType.network === 'TRON') { + if (railWalletType.network === 'TRON') { const trc20Contract = - walletType.code === 'USDT_TRC20' && config.blockchain.tron.usdtTrc20Contract - ? config.blockchain.tron.usdtTrc20Contract - : walletType.contract_address; - if (trc20Contract) { - blockchainTxId = await tronService.sendTrc20(privateKey, trc20Contract, toAddress, amountRaw); - } 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') { + config.blockchain.tron.usdtTrc20Contract || railWalletType.contract_address; + if (!trc20Contract) throw new Error('USDT TRC20 contract not configured'); + blockchainTxId = await tronService.sendTrc20(privateKey, trc20Contract, toAddress, amountRaw); + } else if (railWalletType.network === 'BSC') { + const contract = bscService.resolveUsdtContract(railWalletType.contract_address); + const chainAmount = scaleLedgerToChain(amountRaw, BEP20_USDT_DECIMALS); + blockchainTxId = await bscService.sendUsdt(privateKey, contract, toAddress, chainAmount); + } else if (railWalletType.network === 'POLYGON') { blockchainTxId = await polygonService.sendUsdc(privateKey, toAddress, amountRaw); } else { throw new Error('Unsupported network'); @@ -243,6 +273,7 @@ export async function requestWithdrawal( totalDebited: totalDebit.toString(), toAddress, blockchainTxId, + network, }, }); queueUserAdminStatsRefresh(userId); @@ -252,7 +283,7 @@ export async function requestWithdrawal( userId, withdrawalTransactionId: tx.id, withdrawalAmount: amountRaw, - walletTypeId: walletType.id, + walletTypeId: ledgerWalletType.id, }); } catch (referralErr) { console.error('[referral] Withdrawal commission processing failed:', referralErr); diff --git a/backend/src/tests/hotLiquidity.test.ts b/backend/src/tests/hotLiquidity.test.ts new file mode 100644 index 00000000..bc2b9f5f --- /dev/null +++ b/backend/src/tests/hotLiquidity.test.ts @@ -0,0 +1,73 @@ +import { describe, test } from 'node:test'; +import assert from 'node:assert/strict'; +import { + evaluateHotLiquidity, + MIN_BNB_WEI_FOR_WITHDRAWAL, + MIN_TRX_SUN_FOR_WITHDRAWAL, +} from '../services/hotLiquidityService'; + +describe('evaluateHotLiquidity', () => { + test('TRON: allows when USDT + TRX sufficient (cross-network, no inventory)', () => { + const v = evaluateHotLiquidity({ + network: 'TRON', + usdtBalanceRaw: 1_000_000_000n, // 1000 USDT + nativeBalanceRaw: MIN_TRX_SUN_FOR_WITHDRAWAL, + ledgerAmountRaw: 1_000_000_000n, + }); + assert.equal(v.ok, true); + }); + + test('TRON: rejects when hot USDT below payout', () => { + const v = evaluateHotLiquidity({ + network: 'TRON', + usdtBalanceRaw: 999_999_999n, + nativeBalanceRaw: MIN_TRX_SUN_FOR_WITHDRAWAL, + ledgerAmountRaw: 1_000_000_000n, + }); + assert.equal(v.ok, false); + if (!v.ok) assert.equal(v.reason, 'usdt'); + }); + + test('TRON: rejects when TRX below gas floor', () => { + const v = evaluateHotLiquidity({ + network: 'TRON', + usdtBalanceRaw: 1_000_000_000n, + nativeBalanceRaw: MIN_TRX_SUN_FOR_WITHDRAWAL - 1n, + ledgerAmountRaw: 1n, + }); + assert.equal(v.ok, false); + if (!v.ok) assert.equal(v.reason, 'gas'); + }); + + test('BSC: scales ledger 6-dec to 18-dec USDT requirement', () => { + const ledger = 5_000_000n; // 5 USDT + const chainNeeded = ledger * 10n ** 12n; + const ok = evaluateHotLiquidity({ + network: 'BSC', + usdtBalanceRaw: chainNeeded, + nativeBalanceRaw: MIN_BNB_WEI_FOR_WITHDRAWAL, + ledgerAmountRaw: ledger, + }); + assert.equal(ok.ok, true); + + const short = evaluateHotLiquidity({ + network: 'BSC', + usdtBalanceRaw: chainNeeded - 1n, + nativeBalanceRaw: MIN_BNB_WEI_FOR_WITHDRAWAL, + ledgerAmountRaw: ledger, + }); + assert.equal(short.ok, false); + if (!short.ok) assert.equal(short.reason, 'usdt'); + }); + + test('BSC: rejects when BNB below gas floor', () => { + const v = evaluateHotLiquidity({ + network: 'BSC', + usdtBalanceRaw: 10n ** 18n, + nativeBalanceRaw: MIN_BNB_WEI_FOR_WITHDRAWAL - 1n, + ledgerAmountRaw: 1_000_000n, + }); + assert.equal(v.ok, false); + if (!v.ok) assert.equal(v.reason, 'gas'); + }); +}); diff --git a/backend/src/tests/usdtUnits.test.ts b/backend/src/tests/usdtUnits.test.ts new file mode 100644 index 00000000..7f19b91f --- /dev/null +++ b/backend/src/tests/usdtUnits.test.ts @@ -0,0 +1,30 @@ +import { describe, test } from 'node:test'; +import assert from 'node:assert/strict'; +import { + BEP20_USDT_DECIMALS, + LEDGER_USDT_DECIMALS, + scaleChainToLedger, + scaleLedgerToChain, +} from '../utils/usdtUnits'; + +describe('usdtUnits', () => { + test('scales 100 USDT BEP20 (18) down to ledger (6)', () => { + const chain = 100n * 10n ** 18n; + assert.equal(scaleChainToLedger(chain, BEP20_USDT_DECIMALS), 100n * 10n ** 6n); + }); + + test('truncates dust below 6 decimals', () => { + // 1 wei of BEP20 USDT + assert.equal(scaleChainToLedger(1n, BEP20_USDT_DECIMALS), 0n); + }); + + test('scales ledger amount up for BEP20 send', () => { + const ledger = 5n * 10n ** 6n; // 5 USDT + assert.equal(scaleLedgerToChain(ledger, BEP20_USDT_DECIMALS), 5n * 10n ** 18n); + }); + + test('identity when decimals match', () => { + assert.equal(scaleChainToLedger(123n, LEDGER_USDT_DECIMALS), 123n); + assert.equal(scaleLedgerToChain(123n, LEDGER_USDT_DECIMALS), 123n); + }); +}); diff --git a/backend/src/utils/usdtUnits.ts b/backend/src/utils/usdtUnits.ts new file mode 100644 index 00000000..5028482f --- /dev/null +++ b/backend/src/utils/usdtUnits.ts @@ -0,0 +1,34 @@ +/** + * USDT unit helpers: platform ledger uses 6 decimals; BEP20 chain uses 18. + */ + +export const LEDGER_USDT_DECIMALS = 6; +export const BEP20_USDT_DECIMALS = 18; + +export type CustodyNetwork = 'TRON' | 'BSC'; + +/** Truncate chain (18) amount down to ledger micro-USDT (6). */ +export function scaleChainToLedger(amount: bigint, fromDecimals: number, toDecimals = LEDGER_USDT_DECIMALS): bigint { + if (amount < 0n) return 0n; + if (fromDecimals === toDecimals) return amount; + if (fromDecimals > toDecimals) { + return amount / 10n ** BigInt(fromDecimals - toDecimals); + } + return amount * 10n ** BigInt(toDecimals - fromDecimals); +} + +/** Scale ledger micro-USDT (6) up to chain units (e.g. BEP20 18). */ +export function scaleLedgerToChain(amount: bigint, toDecimals: number, fromDecimals = LEDGER_USDT_DECIMALS): bigint { + if (amount < 0n) return 0n; + if (fromDecimals === toDecimals) return amount; + if (toDecimals > fromDecimals) { + return amount * 10n ** BigInt(toDecimals - fromDecimals); + } + return amount / 10n ** BigInt(fromDecimals - toDecimals); +} + +export function networkForWalletCode(code: string): CustodyNetwork | null { + if (code === 'USDT_TRC20') return 'TRON'; + if (code === 'USDT_BEP20') return 'BSC'; + return null; +} diff --git a/docs/DEPLOY-VPS.md b/docs/DEPLOY-VPS.md index f0f7a4d3..36bd7c4a 100644 --- a/docs/DEPLOY-VPS.md +++ b/docs/DEPLOY-VPS.md @@ -143,8 +143,9 @@ npm run seed-hot-wallets 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. +- Hot **TRON** : financer en **TRX** (gas) + USDT TRC20 — float plateforme pour **tous** les retraits TRC20 (même si le user a déposé en BEP20). +- Hot **BSC** : financer en **BNB** (gas) + USDT BEP20 — float pour **tous** les retraits BEP20. +- Dimensionnez les deux hots comme **trésorerie de payout** (gains inclus), pas seulement comme miroir des dépôts du même réseau. #### Rotation des adresses de dépôt (après changement de `PLATFORM_MNEMONIC`) @@ -397,12 +398,14 @@ Cette section regroupe les commandes lorsque PostgreSQL est **vide** (base cré ### 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). +2. Financer le hot BSC avec **BNB** + USDT BEP20 (float retraits). Pour les retraits cross-réseau TRC20, financer aussi le hot TRON (TRX + USDT). 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. +5. Attendre confirmations → **solde USDT unifié** crédité (Candle Predict utilise ce solde). +6. Micro-retrait : activer kill-switch global + flag withdraw BEP20 → retirer vers une adresse BSC (plafond = solde ledger ; le hot doit avoir assez d’USDT + BNB). +7. (Optionnel) activer withdraw TRC20 → même solde retirable en TRC20 si le hot TRON a assez d’USDT + TRX (indépendant du réseau de dépôt). + +> **Ledger unifié + float hot :** dépôts TRC20 et BEP20 alimentent le même solde jouable (`USDT_TRC20` en DB, 6 décimales). Le réseau de retrait n’a **pas** à correspondre au dépôt ; l’API refuse un retrait si le hot du rail choisi n’a pas assez d’USDT ou de gas (`HOT_WALLET_INSUFFICIENT_LIQUIDITY`). L’inventaire par réseau reste un compteur ops (dépôts), pas un plafond joueur. ### Prérequis communs diff --git a/prediqo_mobile/lib/data/repositories/wallet_repository_impl.dart b/prediqo_mobile/lib/data/repositories/wallet_repository_impl.dart index 9da3c8ac..1bdfd3be 100644 --- a/prediqo_mobile/lib/data/repositories/wallet_repository_impl.dart +++ b/prediqo_mobile/lib/data/repositories/wallet_repository_impl.dart @@ -23,12 +23,28 @@ class WalletRepositoryImpl { .toList(); } - /// Returns the authenticated user's balances across all wallet types. + /// Returns the authenticated user's balances (unified ledger payload). Future> getBalances() async { - final res = await _api.dio.get>('/api/v1/balances'); - return (res.data ?? []) - .map((e) => BalanceModel.fromJson(e as Map)) - .toList(); + final res = await _api.dio.get('/api/v1/balances'); + final data = res.data; + if (data is List) { + return data + .map((e) => BalanceModel.fromJson(e as Map)) + .toList(); + } + if (data is Map) { + final list = data['balances']; + if (list is List) { + return list + .map((e) => BalanceModel.fromJson(e as Map)) + .toList(); + } + final spendable = data['spendable']; + if (spendable is Map) { + return [BalanceModel.fromJson(spendable)]; + } + } + return []; } /// Retrieves a blockchain deposit address for the given [walletType] code. 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 5f455ab5..d7c41a73 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 @@ -75,7 +75,7 @@ class _DepositAssetSelectScreenState extends State { ), const SizedBox(height: 8), Text( - 'Select USDT on TRON (TRC20) or BSC (BEP20). You will then see the matching deposit address and QR code.', + 'Select a deposit network (TRON TRC20 or BSC BEP20). Credits go to your single USDT balance for predictions.', style: Theme.of(context).textTheme.bodyMedium?.copyWith( color: Theme.of(context).colorScheme.onSurfaceVariant, ), diff --git a/prediqo_web/src/features/wallet/WalletPage.tsx b/prediqo_web/src/features/wallet/WalletPage.tsx index 41150e71..fd38c103 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 on TRC20 and/or BEP20 (separate ledgers). + * Player wallet page — unified USDT ledger + per-network deposit/withdraw flags. */ import { Alert, @@ -33,8 +33,8 @@ import { TransactionList } from './components/TransactionList'; import { DEFAULT_TX_PAGE_SIZE, useBalances, useTransactions } from './hooks/useWalletData'; import type { WalletActivityCategory } from './types'; import { networkLabel } from './utils/coinDisplay'; -import { USDT_WALLET_CODE, isSupportedUsdtCode } from './utils/walletCapabilities'; -import { rawToHuman, shortSymbol } from './utils/walletFormat'; +import { USDT_WALLET_CODE } from './utils/walletCapabilities'; +import { rawToHuman } from './utils/walletFormat'; type DialogKind = 'receive' | 'transfer' | 'withdraw' | null; @@ -60,36 +60,14 @@ export function WalletPage() { }, }); - const balances = balancesQ.data ?? []; - const usdtBalances = useMemo( - () => balances.filter((b) => isSupportedUsdtCode(b.walletType.code)), - [balances] - ); - const depositableBalances = useMemo( - () => usdtBalances.filter((b) => b.walletType.depositEnabled === true), - [usdtBalances] - ); - const withdrawableBalances = useMemo( - () => usdtBalances.filter((b) => b.walletType.withdrawEnabled === true), - [usdtBalances] - ); + const spendable = balancesQ.data?.spendable ?? null; + const networks = balancesQ.data?.networks ?? []; + const transferBalances = balancesQ.data?.balances ?? []; const transactions = txQ.data?.items ?? []; const txTotal = txQ.data?.total ?? 0; - const primaryBalance = - usdtBalances.find((b) => b.walletType.code === USDT_WALLET_CODE) ?? usdtBalances[0]; - const portfolioSummary = useMemo(() => { - 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), - hasLocked: BigInt(b.locked || '0') > 0n, - network: networkLabel(b.walletType.code), - depositEnabled: b.walletType.depositEnabled === true, - })); - return { lines }; - }, [usdtBalances]); + const depositable = useMemo(() => networks.filter((n) => n.depositEnabled), [networks]); + const withdrawable = useMemo(() => networks.filter((n) => n.withdrawEnabled), [networks]); const refreshAll = async () => { await Promise.all([balancesQ.refetch(), txQ.refetch(), healthQ.refetch()]); @@ -98,24 +76,22 @@ export function WalletPage() { const openDialog = (kind: DialogKind, asset?: string) => { if (kind === 'receive') { - if (depositableBalances.length === 0) { + if (depositable.length === 0) { setToast(t('wallet.receiveDialog.noNetworks')); return; } - const ok = - !asset || depositableBalances.some((b) => b.walletType.code === asset); - setDialogAsset(ok ? asset ?? null : depositableBalances[0]?.walletType.code ?? null); + const ok = !asset || depositable.some((n) => n.code === asset); + setDialogAsset(ok ? asset ?? null : depositable[0]?.code ?? null); setDialog('receive'); return; } if (kind === 'withdraw') { - if (withdrawableBalances.length === 0) { + if (withdrawable.length === 0) { setToast(t('wallet.withdrawDialog.noNetworks')); return; } - const ok = - !asset || withdrawableBalances.some((b) => b.walletType.code === asset); - setDialogAsset(ok ? asset ?? null : withdrawableBalances[0]?.walletType.code ?? null); + const ok = !asset || withdrawable.some((n) => n.code === asset); + setDialogAsset(ok ? asset ?? null : withdrawable[0]?.code ?? null); setDialog('withdraw'); return; } @@ -163,21 +139,34 @@ export function WalletPage() { {loading ? ( - ) : portfolioSummary ? ( + ) : spendable ? ( - {portfolioSummary.lines.map((line) => ( - - - {line.human} {shortSymbol(line.code)} + + {rawToHuman(spendable.available, spendable.walletType.decimals)} USDT + + {BigInt(spendable.locked || '0') > 0n && ( + + )} + + {networks.map((n) => ( + + {networkLabel(n.code)} —{' '} + {n.depositEnabled + ? t('wallet.mainCard.depositsOn') + : t('wallet.mainCard.depositsOff')} + {' · '} + {n.withdrawEnabled + ? t('wallet.mainCard.withdrawalsOn') + : t('wallet.mainCard.withdrawalsOff')} - - {line.network} - - {line.hasLocked && ( - - )} - - ))} + ))} + ) : ( {t('wallet.noBalance')} @@ -188,7 +177,7 @@ export function WalletPage() { variant="contained" startIcon={} onClick={() => openDialog('receive')} - disabled={depositableBalances.length === 0} + disabled={depositable.length === 0} sx={{ flex: 1 }} > {t('wallet.receiveUsdt')} @@ -206,7 +195,7 @@ export function WalletPage() { color="warning" startIcon={} onClick={() => openDialog('withdraw')} - disabled={withdrawableBalances.length === 0 || !(healthQ.data?.withdrawalsEnabled ?? false)} + disabled={withdrawable.length === 0 || !(healthQ.data?.withdrawalsEnabled ?? false)} sx={{ flex: 1 }} > {t('wallet.withdraw')} @@ -241,32 +230,18 @@ export function WalletPage() { - ) : ( + ) : spendable ? ( <> - {usdtBalances.map((b) => ( - openDialog('receive', b.walletType.code)} - onSend={() => openDialog('transfer', b.walletType.code)} - /> - ))} - {primaryBalance ? ( - <> - - - - ) : null} + openDialog('receive')} + onSend={() => openDialog('transfer', USDT_WALLET_CODE)} + /> + + - )} + ) : null} )} @@ -290,7 +265,7 @@ export function WalletPage() { setDialog(null)} onSuccess={setToast} onError={setToast} @@ -320,10 +295,11 @@ export function WalletPage() { setDialog(null)} onSuccess={setToast} onError={setToast} diff --git a/prediqo_web/src/features/wallet/components/MainAssetCard.tsx b/prediqo_web/src/features/wallet/components/MainAssetCard.tsx index 5d171057..d4ea5b52 100644 --- a/prediqo_web/src/features/wallet/components/MainAssetCard.tsx +++ b/prediqo_web/src/features/wallet/components/MainAssetCard.tsx @@ -1,5 +1,5 @@ /** - * Main USDT wallet card (one network / ledger). + * Unified USDT spendable ledger card. */ import { Box, @@ -13,26 +13,26 @@ import { } from '@mui/material'; import QrCode2RoundedIcon from '@mui/icons-material/QrCode2Rounded'; import { useTranslation } from 'react-i18next'; -import type { BalanceEntry } from '../types'; +import type { BalanceEntry, NetworkBalanceInfo } from '../types'; import { coinColors, coinSymbol, networkLabel } from '../utils/coinDisplay'; -import { formatBalance } from '../utils/walletFormat'; +import { formatBalance, rawToHuman } from '../utils/walletFormat'; type MainAssetCardProps = { balance: BalanceEntry; + networks: NetworkBalanceInfo[]; onReceive: () => void; onSend: () => void; }; -export function MainAssetCard({ balance, onReceive, onSend }: MainAssetCardProps) { +export function MainAssetCard({ balance, networks, onReceive, onSend }: MainAssetCardProps) { const { t } = useTranslation(); const code = balance.walletType.code; const [c1, c2] = coinColors(code); const hasLocked = BigInt(balance.locked || '0') > 0n; - const depositEnabled = balance.walletType.depositEnabled === true; - const withdrawEnabled = balance.walletType.withdrawEnabled === true; + const anyDeposit = networks.some((n) => n.depositEnabled); return ( - + - {balance.walletType.name} + {t('wallet.mainCard.title')} - {networkLabel(code)} + {t('wallet.mainCard.unifiedSubtitle')} - - - - {balance.walletType.predictionEnabled ? ( - - ) : null} - + - {depositEnabled ? ( + {anyDeposit ? ( @@ -99,24 +73,33 @@ export function MainAssetCard({ balance, onReceive, onSend }: MainAssetCardProps {t('wallet.mainCard.availableBalance')} - {formatBalance(balance.available, balance.walletType.decimals, code)} + {formatBalance(balance.available, balance.walletType.decimals, 'USDT')} {hasLocked && ( {t('wallet.mainCard.locked')}{' '} - {formatBalance(balance.locked, balance.walletType.decimals, code)} + {formatBalance(balance.locked, balance.walletType.decimals, 'USDT')} )} - {!depositEnabled && ( - - {t('wallet.mainCard.depositsDisabledHint')} - - )} + + {networks.map((n) => ( + + {networkLabel(n.code)}:{' '} + {n.depositEnabled + ? t('wallet.mainCard.depositsOn') + : t('wallet.mainCard.depositsOff')} + {' · '} + {n.withdrawEnabled + ? t('wallet.mainCard.withdrawalsOn') + : t('wallet.mainCard.withdrawalsOff')} + + ))} + -