diff --git a/.env.example b/.env.example index 294b9a8c..4b6ba7e9 100644 --- a/.env.example +++ b/.env.example @@ -70,6 +70,8 @@ BSC_CONFIRMATIONS=15 # Leave empty to use official USDT BEP20 from DB (0x55d3…7955) USDT_BEP20_CONTRACT= BSC_GETLOGS_BLOCK_RANGE=2000 +# Optional: Etherscan V2 key helps auto-credit if public BSC eth_getLogs is empty +# BSCSCAN_API_KEY= POLYGON_RPC_URL=https://rpc-amoy.polygon.technology POLYGON_CONFIRMATIONS=8 USDC_POLYGON_CONTRACT= diff --git a/backend/src/config/index.ts b/backend/src/config/index.ts index b91ce0bf..241afb13 100644 --- a/backend/src/config/index.ts +++ b/backend/src/config/index.ts @@ -118,6 +118,14 @@ export const config = { process.env.BSC_DEPOSIT_OVERLAP_LOOKBACK_BLOCKS || '5000', 10 ), + /** + * When HD still holds USDT (missed credit), rescan only this many recent blocks + * via getLogs — not the full 7-day window (public RPCs time out). + */ + unpaidLookbackBlocks: parseInt(process.env.BSC_UNPAID_LOOKBACK_BLOCKS || '30000', 10), + /** Optional Etherscan V2 / BscScan key for unpaid deposit fallback. */ + explorerApiKey: process.env.BSCSCAN_API_KEY || process.env.ETHERSCAN_API_KEY || '', + explorerApiUrl: process.env.BSC_EXPLORER_API_URL || 'https://bsc.blockscout.com/api', /** Native BNB top-up for sweeps (wei); default 0.001 BNB */ gasTopUpWei: process.env.SWEEP_BSC_GAS_TOPUP_WEI || '1000000000000000', }, diff --git a/backend/src/controllers/treasuryController.ts b/backend/src/controllers/treasuryController.ts index 37b25f8b..4420ff70 100644 --- a/backend/src/controllers/treasuryController.ts +++ b/backend/src/controllers/treasuryController.ts @@ -138,3 +138,19 @@ export async function cancelFunding(req: AuthRequest, res: Response): Promise { + try { + res.json(await treasuryService.listStuckDeposits()); + } catch (e) { + res.status(500).json({ error: e instanceof Error ? e.message : 'Failed to list stuck deposits' }); + } +} + +export async function scanStuckDeposits(_req: AuthRequest, res: Response): Promise { + try { + res.json(await treasuryService.scanStuckDeposits()); + } catch (e) { + res.status(500).json({ error: e instanceof Error ? e.message : 'Stuck-deposit scan failed' }); + } +} diff --git a/backend/src/db/schema.sql b/backend/src/db/schema.sql index 3633ddcf..5e05877c 100644 --- a/backend/src/db/schema.sql +++ b/backend/src/db/schema.sql @@ -207,6 +207,19 @@ 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); +-- On-chain USDT still sitting on user HD deposit addresses (ops visibility). +CREATE TABLE IF NOT EXISTS deposit_hd_snapshots ( + user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, + wallet_type_id INTEGER NOT NULL REFERENCES wallet_types(id), + address VARCHAR(255) NOT NULL, + on_chain_amount NUMERIC(78, 0) NOT NULL DEFAULT 0, + last_checked_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + PRIMARY KEY (user_id, wallet_type_id) +); + +CREATE INDEX IF NOT EXISTS idx_deposit_hd_snapshots_amount ON deposit_hd_snapshots(on_chain_amount) + WHERE on_chain_amount > 0; + -- 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, diff --git a/backend/src/repositories/depositHdSnapshotRepository.ts b/backend/src/repositories/depositHdSnapshotRepository.ts new file mode 100644 index 00000000..9760f499 --- /dev/null +++ b/backend/src/repositories/depositHdSnapshotRepository.ts @@ -0,0 +1,85 @@ +/** + * Snapshots of USDT still on user HD deposit addresses (ops / treasury). + */ + +import { query } from '../db/connection'; + +export type HdSnapshotRow = { + user_id: string; + wallet_type_id: number; + address: string; + on_chain_amount: string; + last_checked_at: Date; + network: string; + wallet_code: string; + wallet_name: string; + decimals: number; + first_name: string | null; + last_name: string | null; + credited: boolean; + sweep_pending: boolean; + sweep_failed: boolean; +}; + +export async function upsertSnapshot(input: { + userId: string; + walletTypeId: number; + address: string; + onChainAmount: bigint; +}): Promise { + await query( + `INSERT INTO deposit_hd_snapshots (user_id, wallet_type_id, address, on_chain_amount, last_checked_at) + VALUES ($1, $2, $3, $4::numeric, NOW()) + ON CONFLICT (user_id, wallet_type_id) DO UPDATE SET + address = EXCLUDED.address, + on_chain_amount = EXCLUDED.on_chain_amount, + last_checked_at = NOW()`, + [input.userId, input.walletTypeId, input.address, input.onChainAmount.toString()] + ); +} + +export async function listPositiveSnapshots(): Promise { + return query( + `SELECT + s.user_id, + s.wallet_type_id, + s.address, + s.on_chain_amount::text AS on_chain_amount, + s.last_checked_at, + wt.network, + wt.code AS wallet_code, + wt.name AS wallet_name, + wt.decimals, + u.first_name, + u.last_name, + EXISTS ( + SELECT 1 FROM transactions t + WHERE t.type = 'deposit' + AND t.status = 'completed' + AND lower(t.to_address) = lower(s.address) + ) AS credited, + EXISTS ( + SELECT 1 FROM deposit_sweeps ds + WHERE ds.status IN ('pending', 'gas_funding', 'broadcasting') + AND lower(ds.from_address) = lower(s.address) + ) AS sweep_pending, + EXISTS ( + SELECT 1 FROM deposit_sweeps ds + WHERE ds.status = 'failed' + AND lower(ds.from_address) = lower(s.address) + ) AS sweep_failed + FROM deposit_hd_snapshots s + JOIN wallet_types wt ON wt.id = s.wallet_type_id + JOIN users u ON u.id = s.user_id + WHERE s.on_chain_amount > 0 + AND u.deleted_at IS NULL + ORDER BY s.on_chain_amount DESC, s.last_checked_at DESC` + ); +} + +export async function countPositive(): Promise { + const rows = await query<{ c: string }[]>( + `SELECT COUNT(*)::text AS c FROM deposit_hd_snapshots WHERE on_chain_amount > 0` + ); + return parseInt(rows[0]?.c ?? '0', 10); +} diff --git a/backend/src/routes/index.ts b/backend/src/routes/index.ts index 0216a3ac..075a80a6 100644 --- a/backend/src/routes/index.ts +++ b/backend/src/routes/index.ts @@ -475,6 +475,8 @@ router.get('/admin/treasury/funding', requireRoles('admin'), requirePermissions( router.post('/admin/treasury/funding', requireRoles('admin'), requirePermissions('treasury.view'), validateBody(treasuryFundingBodySchema), treasuryController.requestFunding); router.patch('/admin/treasury/funding/:fundingId/confirm', requireRoles('admin'), requirePermissions('treasury.view'), validateBody(treasuryFundingConfirmBodySchema), treasuryController.confirmFunding); router.delete('/admin/treasury/funding/:fundingId', requireRoles('admin'), requirePermissions('treasury.view'), treasuryController.cancelFunding); +router.get('/admin/treasury/stuck-deposits', requireRoles('admin'), requirePermissions('treasury.view'), treasuryController.listStuckDeposits); +router.post('/admin/treasury/stuck-deposits/scan', requireRoles('admin'), requirePermissions('treasury.view'), treasuryController.scanStuckDeposits); router.get('/admin/overview', requireRoles('admin'), requirePermissions('reports.admin'), overviewController.getAdminOverview); router.get('/admin/analytics/dashboard', requireRoles('admin'), requirePermissions('reports.admin'), analyticsController.getDashboardAnalytics); diff --git a/backend/src/services/blockchain/bscService.ts b/backend/src/services/blockchain/bscService.ts index 8fbbf186..d6e8f9b6 100644 --- a/backend/src/services/blockchain/bscService.ts +++ b/backend/src/services/blockchain/bscService.ts @@ -5,6 +5,7 @@ import { ethers } from 'ethers'; import { config } from '../../config'; +import { parseExplorerTokenTxResult } from '../../utils/bscExplorerTokentx'; const ERC20_ABI = [ 'function transfer(address to, uint256 amount) returns (bool)', @@ -134,6 +135,12 @@ export async function getUsdtTransfersToAddress( chunk = Math.max(MIN_GETLOGS_BLOCK_RANGE, Math.floor(chunk / 2)); continue; } + const msg = err instanceof Error ? err.message : String(err); + if (/timeout|429|rate limit|too many requests|busy|503/i.test(msg) && chunk > MIN_GETLOGS_BLOCK_RANGE) { + chunk = Math.max(MIN_GETLOGS_BLOCK_RANGE, Math.floor(chunk / 2)); + await new Promise((r) => setTimeout(r, 400)); + continue; + } throw err; } } @@ -141,6 +148,78 @@ export async function getUsdtTransfersToAddress( return out; } +type ExplorerTokentxRow = { + hash?: string; + from?: string; + to?: string; + contractAddress?: string; +}; + +function explorerUsdtHashes(payload: unknown, usdtContract: string, toAddress: string): string[] { + const wantTo = toAddress.toLowerCase(); + return parseExplorerTokenTxResult(payload, usdtContract) + .filter((row) => !row.to || row.to.toLowerCase() === wantTo) + .map((row) => row.hash); +} + +async function fetchExplorerTokentx(url: string): Promise { + const res = await fetch(url, { signal: AbortSignal.timeout(20_000) }); + if (!res.ok) throw new Error(`explorer HTTP ${res.status}`); + return res.json(); +} + +/** + * Incoming USDT tx hashes for an address (Etherscan-compatible explorer). + * Used when eth_getLogs is empty/rate-limited but the HD still holds USDT. + */ +export async function listIncomingUsdtTxHashesViaExplorer( + toAddress: string, + contractAddress: string +): Promise { + const usdt = resolveUsdtContract(contractAddress); + const to = ethers.getAddress(toAddress); + const key = config.blockchain.bsc.explorerApiKey.trim(); + const urls: string[] = []; + + if (key) { + const q = new URLSearchParams({ + chainid: '56', + module: 'account', + action: 'tokentx', + contractaddress: usdt, + address: to, + page: '1', + offset: '25', + sort: 'desc', + apikey: key, + }); + urls.push(`https://api.etherscan.io/v2/api?${q.toString()}`); + } + + const base = config.blockchain.bsc.explorerApiUrl.replace(/\/$/, ''); + const q2 = new URLSearchParams({ + module: 'account', + action: 'tokentx', + contractaddress: usdt, + address: to, + page: '1', + offset: '25', + sort: 'desc', + }); + urls.push(`${base}?${q2.toString()}`); + + for (const url of urls) { + try { + const json = await fetchExplorerTokentx(url); + const hashes = explorerUsdtHashes(json, usdt, to); + if (hashes.length > 0) return hashes; + } catch (e) { + console.warn('[bsc] explorer tokentx failed:', e instanceof Error ? e.message : e); + } + } + return []; +} + export async function sendUsdt( fromPrivateKeyHex: string, contractAddress: string, diff --git a/backend/src/services/depositMonitorService.ts b/backend/src/services/depositMonitorService.ts index d7660402..3a5ecb81 100644 --- a/backend/src/services/depositMonitorService.ts +++ b/backend/src/services/depositMonitorService.ts @@ -19,6 +19,7 @@ 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 * as depositHdSnapshotRepository from '../repositories/depositHdSnapshotRepository'; import { BEP20_USDT_DECIMALS, LEDGER_USDT_DECIMALS, @@ -126,6 +127,20 @@ export async function processTronDeposits(): Promise { } } + for (const { address, user_id } of userWallets) { + try { + const bal = await tronService.getTrc20BalanceRaw(address, trc20Contract); + await depositHdSnapshotRepository.upsertSnapshot({ + userId: user_id, + walletTypeId: custodyType.id, + address, + onChainAmount: bal, + }); + } catch (e) { + console.error(`[deposit] USDT_TRC20: balance snapshot failed for ${address}:`, e); + } + } + await depositScannerRepository.updateState(custodyType.id, BigInt(currentBlock)); } @@ -171,62 +186,113 @@ export async function processBscDeposits(): Promise { const contract = bscService.resolveUsdtContract(custodyType.contract_address); - // Catch-up: any address still holding USDT likely missed a credit — deepen lookback. - for (const { address } of userWallets) { + const unpaidAddresses = new Set(); + for (const { address, user_id } of userWallets) { try { const bal = await bscService.getUsdtBalanceRaw(address, contract); - if (bal > 0n) { - const deepFrom = Math.max(0, currentBlock - initialLookback); - if (deepFrom < fromBlock) { - console.warn( - `[deposit] USDT_BEP20: unpaid on-chain balance on ${address} — deep rescan from ${deepFrom}` - ); - fromBlock = deepFrom; - } - break; - } + await depositHdSnapshotRepository.upsertSnapshot({ + userId: user_id, + walletTypeId: custodyType.id, + address, + onChainAmount: bal, + }); + if (bal > 0n) unpaidAddresses.add(address.toLowerCase()); } catch (e) { console.error(`[deposit] USDT_BEP20: balance check failed for ${address}:`, e); } } + if (unpaidAddresses.size > 0) { + console.warn( + `[deposit] USDT_BEP20: ${unpaidAddresses.size} HD address(es) still hold USDT — will recover via logs + explorer` + ); + } + console.log( `[deposit] USDT_BEP20 (id=${custodyType.id}): ${userWallets.length} wallets, fromBlock=${fromBlock}, tip=${currentBlock}` ); for (const { address, user_id } of userWallets) { - const transfers = await bscService.getUsdtTransfersToAddress( - address, - contract, - fromBlock, - currentBlock - ); - if (transfers.length > 0) { - console.log(`[deposit] USDT_BEP20 ${address}: ${transfers.length} transfer(s) in window`); - } - 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({ - 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, - requiredConfirmations: BSC_CONFIRMATIONS, - }); - } catch (e) { - console.error(`[deposit] BEP20 credit failed tx=${t.txHash}:`, e); + try { + const transfers = await bscService.getUsdtTransfersToAddress( + address, + contract, + fromBlock, + currentBlock + ); + if (transfers.length > 0) { + console.log(`[deposit] USDT_BEP20 ${address}: ${transfers.length} transfer(s) in window`); } + 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({ + 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, + requiredConfirmations: BSC_CONFIRMATIONS, + }); + } catch (e) { + console.error(`[deposit] BEP20 credit failed tx=${t.txHash}:`, e); + } + } + } catch (e) { + console.error(`[deposit] USDT_BEP20 getLogs failed for ${address}:`, e); + } + } + + // Receipt-based catch-up (same path as creditBscDepositByTx): public eth_getLogs + // often times out on a 7-day window, so unpaid HDs never get credited without this. + const unpaidLookback = config.blockchain.bsc.unpaidLookbackBlocks; + for (const { address } of userWallets) { + if (!unpaidAddresses.has(address.toLowerCase())) continue; + try { + const still = await bscService.getUsdtBalanceRaw(address, contract); + if (still <= 0n) continue; + + const hashes = new Set(); + try { + const recentFrom = Math.max(0, currentBlock - unpaidLookback); + const recent = await bscService.getUsdtTransfersToAddress( + address, + contract, + recentFrom, + currentBlock + ); + for (const t of recent) hashes.add(t.txHash); + } catch (e) { + console.warn( + `[deposit] USDT_BEP20 unpaid getLogs failed for ${address}:`, + e instanceof Error ? e.message : e + ); + } + + if (hashes.size === 0) { + const viaExplorer = await bscService.listIncomingUsdtTxHashesViaExplorer(address, contract); + for (const h of viaExplorer) hashes.add(h); + } + + for (const txHash of hashes) { + const result = await creditBscDepositByTxHash(txHash); + if (result.credited) { + console.log(`[deposit] USDT_BEP20 recovered unpaid via tx=${txHash} user=${result.userId}`); + } else if (result.reason && !/already|idempotent/i.test(result.reason)) { + console.warn(`[deposit] USDT_BEP20 unpaid recover skipped tx=${txHash}: ${result.reason}`); + } + } + } catch (e) { + console.error(`[deposit] USDT_BEP20 unpaid recover failed for ${address}:`, e); } } diff --git a/backend/src/services/treasuryService.ts b/backend/src/services/treasuryService.ts index efc1fe4e..2fc96b38 100644 --- a/backend/src/services/treasuryService.ts +++ b/backend/src/services/treasuryService.ts @@ -14,6 +14,7 @@ import * as tronService from './blockchain/tronService'; import * as bscService from './blockchain/bscService'; import { USDT_BEP20_CODE, USDT_TRC20_CODE } from './walletCapabilities'; import { MIN_BNB_WEI_FOR_WITHDRAWAL, MIN_TRX_SUN_FOR_WITHDRAWAL } from './hotLiquidityService'; +import * as depositHdSnapshotRepository from '../repositories/depositHdSnapshotRepository'; async function readTronTokenBalance(address: string, contract: string): Promise { try { @@ -143,6 +144,7 @@ export async function getTreasuryOverview() { status: f.status, createdAt: f.created_at, })), + stuckDepositAddresses: await depositHdSnapshotRepository.countPositive(), }; } @@ -279,3 +281,47 @@ export async function listFunding(opts: { status?: string; limit?: number; offse export async function cancelFunding(fundingId: string) { await exchangeFundingRepository.cancelFunding(fundingId); } + +export type StuckDepositIssue = + | 'uncredited' + | 'awaiting_sweep_approval' + | 'sweep_failed' + | 'credited_still_on_hd'; + +function issueFor(row: { + credited: boolean; + sweep_pending: boolean; + sweep_failed: boolean; +}): StuckDepositIssue { + if (!row.credited) return 'uncredited'; + if (row.sweep_failed) return 'sweep_failed'; + if (row.sweep_pending) return 'awaiting_sweep_approval'; + return 'credited_still_on_hd'; +} + +export async function listStuckDeposits() { + const rows = await depositHdSnapshotRepository.listPositiveSnapshots(); + return { + checkedAt: new Date().toISOString(), + count: rows.length, + items: rows.map((r) => ({ + userId: r.user_id, + userLabel: [r.first_name, r.last_name].filter(Boolean).join(' ') || r.user_id.slice(0, 8), + walletTypeId: r.wallet_type_id, + walletCode: r.wallet_code, + walletName: r.wallet_name, + network: r.network, + decimals: r.decimals, + address: r.address, + onChainAmount: r.on_chain_amount, + lastCheckedAt: r.last_checked_at, + issue: issueFor(r), + })), + }; +} + +export async function scanStuckDeposits() { + const { processAllDeposits } = await import('./depositMonitorService'); + await processAllDeposits(); + return listStuckDeposits(); +} diff --git a/backend/src/tests/bscExplorerTokentx.test.ts b/backend/src/tests/bscExplorerTokentx.test.ts new file mode 100644 index 00000000..8ec648ac --- /dev/null +++ b/backend/src/tests/bscExplorerTokentx.test.ts @@ -0,0 +1,37 @@ +import { describe, test } from 'node:test'; +import assert from 'node:assert/strict'; +import { parseExplorerTokenTxResult } from '../utils/bscExplorerTokentx'; + +const USDT = '0x55d398326f99059fF775485246999027B3197955'; + +describe('parseExplorerTokenTxResult', () => { + test('extracts USDT hashes and ignores other contracts', () => { + const rows = parseExplorerTokenTxResult( + { + status: '1', + result: [ + { + hash: '0x1111111111111111111111111111111111111111111111111111111111111111', + from: '0xaaaa', + to: '0xbbbb', + contractAddress: USDT, + }, + { + hash: '0x2222222222222222222222222222222222222222222222222222222222222222', + from: '0xaaaa', + to: '0xbbbb', + contractAddress: '0x0000000000000000000000000000000000000000', + }, + ], + }, + USDT + ); + assert.equal(rows.length, 1); + assert.equal(rows[0].hash, '0x1111111111111111111111111111111111111111111111111111111111111111'); + }); + + test('returns empty on malformed payloads', () => { + assert.deepEqual(parseExplorerTokenTxResult(null, USDT), []); + assert.deepEqual(parseExplorerTokenTxResult({ result: 'NOTOK' }, USDT), []); + }); +}); diff --git a/backend/src/utils/bscExplorerTokentx.ts b/backend/src/utils/bscExplorerTokentx.ts new file mode 100644 index 00000000..cf39fd4b --- /dev/null +++ b/backend/src/utils/bscExplorerTokentx.ts @@ -0,0 +1,30 @@ +/** + * Parsers for Etherscan-compatible account/tokentx explorer APIs (Blockscout, BscScan). + */ + +export type ExplorerTokenTx = { + hash: string; + from: string; + to: string; + contractAddress: string; +}; + +export function parseExplorerTokenTxResult(payload: unknown, usdtContract: string): ExplorerTokenTx[] { + if (!payload || typeof payload !== 'object') return []; + const result = (payload as { result?: unknown }).result; + if (!Array.isArray(result)) return []; + const want = usdtContract.toLowerCase(); + const out: ExplorerTokenTx[] = []; + for (const row of result) { + if (!row || typeof row !== 'object') continue; + const r = row as Record; + const hash = typeof r.hash === 'string' ? r.hash : ''; + const from = typeof r.from === 'string' ? r.from : ''; + const to = typeof r.to === 'string' ? r.to : ''; + const contractAddress = typeof r.contractAddress === 'string' ? r.contractAddress : ''; + if (!/^0x[0-9a-fA-F]{64}$/.test(hash)) continue; + if (contractAddress && contractAddress.toLowerCase() !== want) continue; + out.push({ hash, from, to, contractAddress }); + } + return out; +} diff --git a/docker-compose.yml b/docker-compose.yml index aab1a475..9d270797 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -44,6 +44,10 @@ x-backend-common: &backend-common BSC_CONFIRMATIONS: ${BSC_CONFIRMATIONS:-15} USDT_BEP20_CONTRACT: ${USDT_BEP20_CONTRACT:-} BSC_GETLOGS_BLOCK_RANGE: ${BSC_GETLOGS_BLOCK_RANGE:-2000} + BSC_UNPAID_LOOKBACK_BLOCKS: ${BSC_UNPAID_LOOKBACK_BLOCKS:-30000} + BSCSCAN_API_KEY: ${BSCSCAN_API_KEY:-} + ETHERSCAN_API_KEY: ${ETHERSCAN_API_KEY:-} + BSC_EXPLORER_API_URL: ${BSC_EXPLORER_API_URL:-https://bsc.blockscout.com/api} 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 099f47f7..17de2e53 100644 --- a/docs/DEPLOY-VPS.md +++ b/docs/DEPLOY-VPS.md @@ -74,6 +74,8 @@ nano .env # ou vim | `BSC_CONFIRMATIONS` | Ex. `15` | | `BSC_DEPOSIT_INITIAL_LOOKBACK_BLOCKS` | Lookback 1er scan / catch-up balance (défaut `200000` ≈ 7 j) | | `BSC_DEPOSIT_OVERLAP_LOOKBACK_BLOCKS` | Re-scan chevauchant chaque poll (défaut `5000`) | +| `BSC_UNPAID_LOOKBACK_BLOCKS` | Rattrapage si l’HD a encore de l’USDT (défaut `30000` ≈ 1 j) | +| `BSCSCAN_API_KEY` / `ETHERSCAN_API_KEY` | Optionnel — fallback explorateur si `eth_getLogs` est vide | | `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) | | `SWEEP_ENABLED` | `false` jusqu’au test cold/sweep ; passer à `true` + cold wallet (voir section trésorerie) | @@ -414,7 +416,7 @@ Cette section regroupe les commandes lorsque PostgreSQL est **vide** (base cré 1. Vérifier sur BscScan que l’USDT est bien sur l’adresse Receive BEP20 du user (contrat `0x55d39832…7955`). 2. Admin → Settings → dépôt **BEP20** activé. -3. Après déploiement du fix scanner : le monitor détecte un solde unpaid et re-scanne (~7 j). Sinon crédit manuel : +3. Après déploiement : le monitor crédite tout seul (logs + receipt si l’HD a encore de l’USDT). Le script n’est qu’un rattrapage exceptionnel : ```bash sudo docker compose run --rm --no-deps --build backend \ diff --git a/prediqo_web/src/features/treasury/TreasuryAdminPage.tsx b/prediqo_web/src/features/treasury/TreasuryAdminPage.tsx index 3afe0ad6..1d38fd89 100644 --- a/prediqo_web/src/features/treasury/TreasuryAdminPage.tsx +++ b/prediqo_web/src/features/treasury/TreasuryAdminPage.tsx @@ -89,6 +89,7 @@ type TreasuryOverview = { toAddress: string | null; status: string; }>; + stuckDepositAddresses?: number; }; type SweepRow = { @@ -103,6 +104,20 @@ type SweepRow = { createdAt: string; }; +type StuckDepositRow = { + userId: string; + userLabel: string; + walletTypeId: number; + walletCode: string; + walletName: string; + network: string; + decimals: number; + address: string; + onChainAmount: string; + lastCheckedAt: string; + issue: 'uncredited' | 'awaiting_sweep_approval' | 'sweep_failed' | 'credited_still_on_hd'; +}; + /** Precise human → raw (avoids float errors on 18-decimal BEP20). */ function humanAmountToRaw(human: string, decimals: number): string { const cleaned = human.replace(/,/g, '').replace(/\s/g, '').trim(); @@ -262,6 +277,29 @@ export function TreasuryAdminPage() { }, }); + const stuckQ = useQuery({ + queryKey: ['admin-treasury-stuck-deposits'], + queryFn: async () => { + const res = await api.get<{ count: number; items: StuckDepositRow[] }>( + '/api/v1/admin/treasury/stuck-deposits' + ); + return res.data; + }, + }); + + const scanStuckMut = useMutation({ + mutationFn: () => + api.post<{ count: number; items: StuckDepositRow[] }>('/api/v1/admin/treasury/stuck-deposits/scan'), + onSuccess: (res) => { + setPendingMsg( + t('admin.treasury.stuckScanDone', { count: res.data.count }) + ); + void qc.invalidateQueries({ queryKey: ['admin-treasury-stuck-deposits'] }); + void qc.invalidateQueries({ queryKey: ['admin-treasury-overview'] }); + void qc.invalidateQueries({ queryKey: ['admin-treasury-sweeps'] }); + }, + }); + const overview = overviewQ.data; const assets = overview?.assets ?? []; const walletById = useMemo(() => { @@ -353,6 +391,7 @@ export function TreasuryAdminPage() { onClick={() => { void overviewQ.refetch(); void sweepsQ.refetch(); + void stuckQ.refetch(); }} /> } @@ -397,6 +436,14 @@ export function TreasuryAdminPage() { color="error" /> )} + {(overview.stuckDepositAddresses ?? stuckQ.data?.count ?? 0) > 0 && ( + + )} {!overview.sweepEnabled && ( @@ -758,6 +805,89 @@ export function TreasuryAdminPage() { + {/* USDT still on user HD deposit addresses */} + + + + + + {t('admin.treasury.stuckTitle')} + + + {t('admin.treasury.stuckSubtitle')} + + + + + + + + + + + {t('admin.treasury.stuckIssue')} + {t('admin.treasury.user')} + {t('admin.treasury.network')} + {t('admin.treasury.amount')} + {t('admin.treasury.address')} + + + + {(stuckQ.data?.items ?? []).length === 0 ? ( + + + + {t('admin.treasury.stuckEmpty')} + + + + ) : ( + (stuckQ.data?.items ?? []).map((row) => ( + + + + + {row.userLabel} + {networkLabel(row.network)} + + {rawToHuman(row.onChainAmount, row.decimals)} USDT + + + + + + )) + )} + +
+
+
+
+ {/* Sweeps */} diff --git a/prediqo_web/src/shared/i18n/locales/en.ts b/prediqo_web/src/shared/i18n/locales/en.ts index 0f850765..29da9d49 100644 --- a/prediqo_web/src/shared/i18n/locales/en.ts +++ b/prediqo_web/src/shared/i18n/locales/en.ts @@ -1590,6 +1590,19 @@ export const en = { sweepPending: 'Sweep batch(es) submitted — approve under Approvals to broadcast USDT to cold.', fundingPending: 'Funding request submitted — pending super-admin approval', + stuckTitle: 'USDT still on user deposit addresses', + stuckSubtitle: + 'On-chain USDT that has not reached cold storage yet — missed credits, pending sweeps, or failed sweeps. Updated automatically by the deposit monitor.', + stuckScan: 'Scan & credit now', + stuckScanDone: 'Scan finished — {{count}} address(es) still holding USDT.', + stuckEmpty: 'No USDT sitting on user deposit addresses.', + stuckChip: '{{count}} deposit address(es) still holding USDT', + stuckIssue: 'Issue', + user: 'User', + stuckIssue_uncredited: 'Not credited to user', + stuckIssue_awaiting_sweep_approval: 'Credited — awaiting sweep approval', + stuckIssue_sweep_failed: 'Sweep failed', + stuckIssue_credited_still_on_hd: 'Credited — still on HD (enqueue/sweep)', // legacy keys kept for safety coldOnChain: 'Cold: {{address}} · USDT {{balance}}', hotOnChain: 'Hot: {{address}} · USDT {{balance}}', diff --git a/prediqo_web/src/shared/i18n/locales/fr.ts b/prediqo_web/src/shared/i18n/locales/fr.ts index f7bcb99f..1d4eef41 100644 --- a/prediqo_web/src/shared/i18n/locales/fr.ts +++ b/prediqo_web/src/shared/i18n/locales/fr.ts @@ -1607,6 +1607,19 @@ export const fr = { sweepPending: 'Lot(s) de sweep soumis — approuvez sous Approvals pour diffuser l’USDT vers le cold.', fundingPending: 'Demande de financement soumise — en attente d’approbation super-admin', + stuckTitle: 'USDT encore sur les adresses de dépôt', + stuckSubtitle: + 'USDT on-chain qui n’est pas encore en cold — crédits manqués, sweeps en attente ou échoués. Mis à jour par le monitor de dépôts.', + stuckScan: 'Scanner et créditer maintenant', + stuckScanDone: 'Scan terminé — {{count}} adresse(s) détiennent encore de l’USDT.', + stuckEmpty: 'Aucun USDT restant sur les adresses de dépôt utilisateur.', + stuckChip: '{{count}} adresse(s) de dépôt avec USDT', + stuckIssue: 'Problème', + user: 'Utilisateur', + stuckIssue_uncredited: 'Non crédité au compte', + stuckIssue_awaiting_sweep_approval: 'Crédité — sweep en attente d’approbation', + stuckIssue_sweep_failed: 'Sweep échoué', + stuckIssue_credited_still_on_hd: 'Crédité — encore sur l’HD (enqueue/sweep)', coldOnChain: 'Cold : {{address}} · USDT {{balance}}', hotOnChain: 'Hot : {{address}} · USDT {{balance}}', coldGasOnChain: 'Gas cold ({{symbol}}) : {{balance}}',