After trying to recuparate money from cold wallet3
This commit is contained in:
parent
38d0bab26d
commit
a0f84e46fc
@ -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=
|
||||
|
||||
@ -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',
|
||||
},
|
||||
|
||||
@ -138,3 +138,19 @@ export async function cancelFunding(req: AuthRequest, res: Response): Promise<vo
|
||||
res.status(400).json({ error: e instanceof Error ? e.message : 'Cancel failed' });
|
||||
}
|
||||
}
|
||||
|
||||
export async function listStuckDeposits(_req: AuthRequest, res: Response): Promise<void> {
|
||||
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<void> {
|
||||
try {
|
||||
res.json(await treasuryService.scanStuckDeposits());
|
||||
} catch (e) {
|
||||
res.status(500).json({ error: e instanceof Error ? e.message : 'Stuck-deposit scan failed' });
|
||||
}
|
||||
}
|
||||
|
||||
@ -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,
|
||||
|
||||
85
backend/src/repositories/depositHdSnapshotRepository.ts
Normal file
85
backend/src/repositories/depositHdSnapshotRepository.ts
Normal file
@ -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<void> {
|
||||
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<HdSnapshotRow[]> {
|
||||
return query<HdSnapshotRow[]>(
|
||||
`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<number> {
|
||||
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);
|
||||
}
|
||||
@ -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);
|
||||
|
||||
@ -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<unknown> {
|
||||
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<string[]> {
|
||||
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,
|
||||
|
||||
@ -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<void> {
|
||||
}
|
||||
}
|
||||
|
||||
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<void> {
|
||||
|
||||
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<string>();
|
||||
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<string>();
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@ -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<string | null> {
|
||||
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();
|
||||
}
|
||||
|
||||
37
backend/src/tests/bscExplorerTokentx.test.ts
Normal file
37
backend/src/tests/bscExplorerTokentx.test.ts
Normal file
@ -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), []);
|
||||
});
|
||||
});
|
||||
30
backend/src/utils/bscExplorerTokentx.ts
Normal file
30
backend/src/utils/bscExplorerTokentx.ts
Normal file
@ -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<string, unknown>;
|
||||
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;
|
||||
}
|
||||
@ -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:-}
|
||||
|
||||
@ -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 \
|
||||
|
||||
@ -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 && (
|
||||
<Chip
|
||||
label={t('admin.treasury.stuckChip', {
|
||||
count: overview.stuckDepositAddresses ?? stuckQ.data?.count ?? 0,
|
||||
})}
|
||||
color="warning"
|
||||
/>
|
||||
)}
|
||||
</Stack>
|
||||
|
||||
{!overview.sweepEnabled && (
|
||||
@ -758,6 +805,89 @@ export function TreasuryAdminPage() {
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* USDT still on user HD deposit addresses */}
|
||||
<Card variant="outlined" sx={{ borderRadius: 2.5 }}>
|
||||
<CardContent sx={{ p: { xs: 2, sm: 2.5 } }}>
|
||||
<Stack
|
||||
direction={{ xs: 'column', sm: 'row' }}
|
||||
spacing={1}
|
||||
sx={{ alignItems: { sm: 'center' }, mb: 2 }}
|
||||
>
|
||||
<Box sx={{ flex: 1 }}>
|
||||
<Typography variant="h6" sx={{ fontWeight: 800 }}>
|
||||
{t('admin.treasury.stuckTitle')}
|
||||
</Typography>
|
||||
<Typography variant="body2" sx={{ opacity: 0.65 }}>
|
||||
{t('admin.treasury.stuckSubtitle')}
|
||||
</Typography>
|
||||
</Box>
|
||||
<PermissionGate permission="admin.treasury.manage">
|
||||
<Button
|
||||
size="small"
|
||||
variant="contained"
|
||||
disabled={scanStuckMut.isPending}
|
||||
onClick={() => void scanStuckMut.mutateAsync()}
|
||||
>
|
||||
{t('admin.treasury.stuckScan')}
|
||||
</Button>
|
||||
</PermissionGate>
|
||||
</Stack>
|
||||
<ScrollableTable>
|
||||
<Table size="small">
|
||||
<TableHead>
|
||||
<TableRow>
|
||||
<TableCell>{t('admin.treasury.stuckIssue')}</TableCell>
|
||||
<TableCell>{t('admin.treasury.user')}</TableCell>
|
||||
<TableCell>{t('admin.treasury.network')}</TableCell>
|
||||
<TableCell>{t('admin.treasury.amount')}</TableCell>
|
||||
<TableCell>{t('admin.treasury.address')}</TableCell>
|
||||
</TableRow>
|
||||
</TableHead>
|
||||
<TableBody>
|
||||
{(stuckQ.data?.items ?? []).length === 0 ? (
|
||||
<TableRow>
|
||||
<TableCell colSpan={5}>
|
||||
<Typography variant="body2" sx={{ opacity: 0.55 }}>
|
||||
{t('admin.treasury.stuckEmpty')}
|
||||
</Typography>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
) : (
|
||||
(stuckQ.data?.items ?? []).map((row) => (
|
||||
<TableRow key={`${row.userId}-${row.walletTypeId}`}>
|
||||
<TableCell>
|
||||
<Chip
|
||||
size="small"
|
||||
color={
|
||||
row.issue === 'uncredited' || row.issue === 'sweep_failed'
|
||||
? 'error'
|
||||
: 'warning'
|
||||
}
|
||||
label={t(`admin.treasury.stuckIssue_${row.issue}`)}
|
||||
/>
|
||||
</TableCell>
|
||||
<TableCell>{row.userLabel}</TableCell>
|
||||
<TableCell>{networkLabel(row.network)}</TableCell>
|
||||
<TableCell sx={{ fontWeight: 700 }}>
|
||||
{rawToHuman(row.onChainAmount, row.decimals)} USDT
|
||||
</TableCell>
|
||||
<TableCell sx={{ minWidth: 220 }}>
|
||||
<AddressField
|
||||
label=""
|
||||
address={row.address}
|
||||
network={row.network}
|
||||
onCopied={notifyCopy}
|
||||
/>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))
|
||||
)}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</ScrollableTable>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Sweeps */}
|
||||
<Card variant="outlined" sx={{ borderRadius: 2.5 }}>
|
||||
<CardContent sx={{ p: { xs: 2, sm: 2.5 } }}>
|
||||
|
||||
@ -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}}',
|
||||
|
||||
@ -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}}',
|
||||
|
||||
Loading…
Reference in New Issue
Block a user