diff --git a/backend/src/repositories/depositHdSnapshotRepository.ts b/backend/src/repositories/depositHdSnapshotRepository.ts index 35bb4c1a..5b50b585 100644 --- a/backend/src/repositories/depositHdSnapshotRepository.ts +++ b/backend/src/repositories/depositHdSnapshotRepository.ts @@ -130,3 +130,44 @@ export async function countPositive(): Promise { throw e; } } + +/** + * True when completed deposits to this HD (minus completed sweeps) already cover on-chain USDT. + * Used to skip expensive unpaid getLogs when funds only await cold sweep. + */ +export async function isAddressLedgerCaughtUp( + address: string, + onChainAmount: bigint, + custodyDecimals: number +): Promise { + if (onChainAmount <= 0n) return true; + const rows = await query>( + `SELECT ( + COALESCE(( + SELECT SUM( + COALESCE( + NULLIF(t.metadata->>'chain_amount', '')::numeric, + CASE + WHEN $2::int = 18 THEN t.amount::numeric * 1000000000000 + ELSE t.amount::numeric + END + ) + ) + FROM transactions t + WHERE t.type = 'deposit' + AND t.status = 'completed' + AND lower(t.to_address) = lower($1) + ), 0) + - + COALESCE(( + SELECT SUM(ds.amount::numeric) + FROM deposit_sweeps ds + WHERE ds.status = 'completed' + AND lower(ds.from_address) = lower($1) + ), 0) + )::text AS net`, + [address, custodyDecimals] + ); + const net = BigInt(rows[0]?.net?.split('.')[0] ?? '0'); + return net >= onChainAmount; +} diff --git a/backend/src/services/blockchain/bscService.ts b/backend/src/services/blockchain/bscService.ts index c8a0250a..9d2d5938 100644 --- a/backend/src/services/blockchain/bscService.ts +++ b/backend/src/services/blockchain/bscService.ts @@ -209,7 +209,7 @@ export async function getUsdtTransfersToAddress( const url = urls[i]!; try { const hits = await queryUsdtTransfersOnRpc(url, toAddress, contractAddress, fromBlock, endCap); - if (url !== config.blockchain.bsc.rpcUrl.trim()) { + if (url !== config.blockchain.bsc.rpcUrl.trim() && hits.length > 0) { console.warn( `[bsc] eth_getLogs ok via ${url} for ${toAddress} hits=${hits.length} blocks=${fromBlock}-${endCap}` ); diff --git a/backend/src/services/depositMonitorService.ts b/backend/src/services/depositMonitorService.ts index e712610b..cf8a7020 100644 --- a/backend/src/services/depositMonitorService.ts +++ b/backend/src/services/depositMonitorService.ts @@ -185,8 +185,12 @@ export async function processBscDeposits(): Promise { }); const contract = bscService.resolveUsdtContract(custodyType.contract_address); + const custodyDecimals = custodyType.decimals ?? BEP20_USDT_DECIMALS; - const unpaidAddresses = new Set(); + /** HD still holding USDT that is not yet covered by ledger deposits (needs credit recover). */ + const uncreditedHd = new Set(); + /** HD with any on-chain USDT (ops log / sweep path). */ + let hdHoldingCount = 0; for (const { address, user_id } of userWallets) { try { const bal = await bscService.getUsdtBalanceRaw(address, contract); @@ -196,15 +200,25 @@ export async function processBscDeposits(): Promise { address, onChainAmount: bal, }); - if (bal > 0n) unpaidAddresses.add(address.toLowerCase()); + if (bal <= 0n) continue; + hdHoldingCount += 1; + const caughtUp = await depositHdSnapshotRepository.isAddressLedgerCaughtUp( + address, + bal, + custodyDecimals + ); + if (!caughtUp) uncreditedHd.add(address.toLowerCase()); } catch (e) { console.error(`[deposit] USDT_BEP20: balance check failed for ${address}:`, e); } } - if (unpaidAddresses.size > 0) { + if (hdHoldingCount > 0) { console.warn( - `[deposit] USDT_BEP20: ${unpaidAddresses.size} HD address(es) still hold USDT — will recover via logs + explorer` + `[deposit] USDT_BEP20: ${hdHoldingCount} HD address(es) still hold USDT` + + (uncreditedHd.size > 0 + ? ` — ${uncreditedHd.size} not yet credited (recover)` + : ' — all already credited (awaiting sweep)') ); } @@ -260,7 +274,7 @@ export async function processBscDeposits(): Promise { config.blockchain.bsc.depositInitialLookbackBlocks ); for (const { address } of userWallets) { - if (!unpaidAddresses.has(address.toLowerCase())) continue; + if (!uncreditedHd.has(address.toLowerCase())) continue; try { const still = await bscService.getUsdtBalanceRaw(address, contract); if (still <= 0n) continue; @@ -311,6 +325,8 @@ export async function processBscDeposits(): Promise { const result = await creditBscDepositByTxHash(txHash); if (result.credited) { console.log(`[deposit] USDT_BEP20 recovered unpaid via tx=${txHash} user=${result.userId}`); + } else if (result.alreadyCredited) { + // idempotent — expected when re-scanning } else if (result.reason && !/already|idempotent/i.test(result.reason)) { console.warn(`[deposit] USDT_BEP20 unpaid recover skipped tx=${txHash}: ${result.reason}`); } @@ -330,6 +346,7 @@ export async function processBscDeposits(): Promise { */ export async function creditBscDepositByTxHash(txHash: string): Promise<{ credited: boolean; + alreadyCredited?: boolean; userId?: string; ledgerAmount?: string; reason?: string; @@ -388,7 +405,7 @@ export async function creditBscDepositByTxHash(txHash: string): Promise<{ const ledgerAmount = scaleChainToLedger(transfer.value, BEP20_USDT_DECIMALS, LEDGER_USDT_DECIMALS); if (ledgerAmount <= 0n) return { credited: false, reason: 'amount too small after scale' }; - await creditDeposit({ + const inserted = await creditDeposit({ userId: wallet.user_id, ledgerWalletTypeId: ledgerType.id, custodyWalletTypeId: custodyType.id, @@ -403,6 +420,16 @@ export async function creditBscDepositByTxHash(txHash: string): Promise<{ requiredConfirmations: BSC_CONFIRMATIONS, }); + if (!inserted) { + return { + credited: false, + alreadyCredited: true, + userId: wallet.user_id, + ledgerAmount: ledgerAmount.toString(), + reason: 'already credited (idempotent)', + }; + } + return { credited: true, userId: wallet.user_id, @@ -423,7 +450,7 @@ async function creditDeposit(opts: { toAddress: string; confirmations: number; requiredConfirmations: number; -}): Promise { +}): Promise { const account = await ledgerRepository.getOrCreateAccount( opts.userId, opts.ledgerWalletTypeId, @@ -451,7 +478,7 @@ async function creditDeposit(opts: { }); if (!tx) { await client.query('COMMIT'); - return; + return false; } await ledgerRepository.creditUsingClient( client, @@ -478,7 +505,7 @@ async function creditDeposit(opts: { client.release(); } - if (!tx) return; + if (!tx) return false; await referralService.processFirstDepositReferralCommissions({ userId: opts.userId, @@ -507,4 +534,5 @@ async function creditDeposit(opts: { tx.id ); queueUserAdminStatsRefresh(opts.userId); + return true; }