From bedda74d897afa17a9c4e64fcf0dec2c33505207 Mon Sep 17 00:00:00 2001 From: Your Name Date: Fri, 28 Aug 2026 19:41:27 +0200 Subject: [PATCH] After trying to recuparate money from cold wallet9 --- .../src/repositories/transactionRepository.ts | 11 +++++ backend/src/services/sweepService.ts | 42 +++++++++++++++++++ backend/src/services/treasuryService.ts | 10 ++++- .../features/treasury/TreasuryAdminPage.tsx | 30 +++++++++++-- prediqo_web/src/shared/i18n/locales/en.ts | 12 +++++- prediqo_web/src/shared/i18n/locales/fr.ts | 12 +++++- 6 files changed, 110 insertions(+), 7 deletions(-) diff --git a/backend/src/repositories/transactionRepository.ts b/backend/src/repositories/transactionRepository.ts index 199220bf..22c91c0a 100644 --- a/backend/src/repositories/transactionRepository.ts +++ b/backend/src/repositories/transactionRepository.ts @@ -168,6 +168,17 @@ export async function findById(id: string): Promise { return rows[0] || null; } +export async function listCompletedDepositsToAddress(toAddress: string): Promise { + return query( + `SELECT id, user_id, wallet_type_id, type, amount::text, fee::text, status, blockchain_tx_id, + from_address, to_address, confirmations, required_confirmations, metadata, created_at, updated_at + FROM transactions + WHERE type = 'deposit' AND status = 'completed' AND lower(to_address) = lower($1) + ORDER BY created_at ASC`, + [toAddress] + ); +} + /** * Lists a user's transactions ordered by creation time (newest first). * @param userId - ID of the user whose transactions to fetch. diff --git a/backend/src/services/sweepService.ts b/backend/src/services/sweepService.ts index fd8a4a90..ee1e2b32 100644 --- a/backend/src/services/sweepService.ts +++ b/backend/src/services/sweepService.ts @@ -83,6 +83,48 @@ export async function enqueueSweepAfterDeposit( await depositSweepBatchRepository.incrementBatchCount(batch.id); } +export async function enqueueSweepsForCreditedHdBalances(): Promise<{ + sweepEnabled: boolean; + enqueued: number; + alreadyQueued: number; +}> { + if (!config.treasury.sweepEnabled) { + return { sweepEnabled: false, enqueued: 0, alreadyQueued: 0 }; + } + + const { listPositiveSnapshots } = await import('../repositories/depositHdSnapshotRepository'); + const { listCompletedDepositsToAddress } = await import('../repositories/transactionRepository'); + const snapshots = await listPositiveSnapshots(); + let enqueued = 0; + let alreadyQueued = 0; + + for (const s of snapshots) { + if (!s.credited) continue; + const deposits = await listCompletedDepositsToAddress(s.address); + for (const deposit of deposits) { + const existing = await depositSweepRepository.findByDepositTransactionId(deposit.id); + if (existing) { + alreadyQueued += 1; + continue; + } + const meta = (deposit.metadata ?? {}) as Record; + const chainRaw = + typeof meta.chain_amount === 'string' + ? meta.chain_amount + : typeof meta.chainAmount === 'string' + ? meta.chainAmount + : null; + const amount = chainRaw ? BigInt(chainRaw) : BigInt(deposit.amount); + if (amount <= 0n) continue; + await enqueueSweepAfterDeposit(deposit.user_id, s.wallet_type_id, amount, deposit.id); + const after = await depositSweepRepository.findByDepositTransactionId(deposit.id); + if (after) enqueued += 1; + } + } + + return { sweepEnabled: true, enqueued, alreadyQueued }; +} + async function ensureTronGasForTokenSweep(depositAddress: string, usdtWalletTypeId: number): Promise { const trxBalance = await tronService.getTrxBalanceSun(depositAddress); if (trxBalance >= MIN_TRX_FOR_TRC20_SWEEP) return; diff --git a/backend/src/services/treasuryService.ts b/backend/src/services/treasuryService.ts index 3787bda2..70bc0bd3 100644 --- a/backend/src/services/treasuryService.ts +++ b/backend/src/services/treasuryService.ts @@ -487,6 +487,14 @@ export async function listStuckDeposits() { export async function scanStuckDeposits() { const { processAllDeposits } = await import('./depositMonitorService'); + const { enqueueSweepsForCreditedHdBalances } = await import('./sweepService'); await processAllDeposits(); - return listStuckDeposits(); + const sweep = await enqueueSweepsForCreditedHdBalances(); + const list = await listStuckDeposits(); + return { + ...list, + sweepEnabled: sweep.sweepEnabled, + sweepsEnqueued: sweep.enqueued, + sweepsAlreadyQueued: sweep.alreadyQueued, + }; } diff --git a/prediqo_web/src/features/treasury/TreasuryAdminPage.tsx b/prediqo_web/src/features/treasury/TreasuryAdminPage.tsx index 332a4804..789ab367 100644 --- a/prediqo_web/src/features/treasury/TreasuryAdminPage.tsx +++ b/prediqo_web/src/features/treasury/TreasuryAdminPage.tsx @@ -325,15 +325,35 @@ export function TreasuryAdminPage() { const scanStuckMut = useMutation({ mutationFn: () => - api.post<{ count: number; items: StuckDepositRow[] }>('/api/v1/admin/treasury/stuck-deposits/scan'), + api.post<{ + count: number; + items: StuckDepositRow[]; + sweepEnabled?: boolean; + sweepsEnqueued?: number; + }>('/api/v1/admin/treasury/stuck-deposits/scan', {}, { timeout: 180000 }), onSuccess: (res) => { - setPendingMsg( - t('admin.treasury.stuckScanDone', { count: res.data.count }) + const creditedStillOnHd = (res.data.items ?? []).some( + (row) => row.issue === 'credited_still_on_hd' || row.issue === 'awaiting_sweep_approval' ); + const uncredited = (res.data.items ?? []).some((row) => row.issue === 'uncredited'); + if (uncredited) { + setPendingMsg(t('admin.treasury.stuckScanUncredited', { count: res.data.count })); + } else if (res.data.sweepsEnqueued && res.data.sweepsEnqueued > 0) { + setPendingMsg(t('admin.treasury.stuckScanEnqueued', { count: res.data.sweepsEnqueued })); + } else if (creditedStillOnHd && res.data.sweepEnabled === false) { + setPendingMsg(t('admin.treasury.stuckScanAlreadyCreditedSweepOff')); + } else if (creditedStillOnHd) { + setPendingMsg(t('admin.treasury.stuckScanAlreadyCredited')); + } else { + 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'] }); }, + onError: (err) => { + setPendingMsg(apiErrorMessage(err, t('admin.treasury.stuckScanFailed'))); + }, }); const overview = overviewQ.data; @@ -1157,7 +1177,9 @@ export function TreasuryAdminPage() { disabled={scanStuckMut.isPending} onClick={() => void scanStuckMut.mutateAsync()} > - {t('admin.treasury.stuckScan')} + {scanStuckMut.isPending + ? t('admin.treasury.stuckScanBusy') + : t('admin.treasury.stuckScan')} diff --git a/prediqo_web/src/shared/i18n/locales/en.ts b/prediqo_web/src/shared/i18n/locales/en.ts index 39062272..401e297b 100644 --- a/prediqo_web/src/shared/i18n/locales/en.ts +++ b/prediqo_web/src/shared/i18n/locales/en.ts @@ -1630,7 +1630,17 @@ export const en = { 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.', + stuckScanBusy: 'Scanning on-chain… (up to 1 min)', + stuckScanDone: 'Scan finished — {{count}} address(es) still holding USDT on-chain.', + stuckScanFailed: 'Scan failed. Check backend logs and try again.', + stuckScanAlreadyCredited: + 'This USDT is already credited to the user. The chip stays until you Submit sweeps for approval, then approve under Approvals.', + stuckScanAlreadyCreditedSweepOff: + 'Already credited to the user. Set SWEEP_ENABLED=true in .env (and docker-compose), recreate the backend, then Submit sweeps for approval.', + stuckScanEnqueued: + '{{count}} sweep(s) queued. Click Submit sweeps for approval, then approve under Approvals.', + stuckScanUncredited: + 'Scan finished — {{count}} address(es) still uncredited. Check deposit logs / BscScan.', stuckEmpty: 'No USDT sitting on user deposit addresses.', stuckChip: '{{count}} deposit address(es) still holding USDT', stuckIssue: 'Issue', diff --git a/prediqo_web/src/shared/i18n/locales/fr.ts b/prediqo_web/src/shared/i18n/locales/fr.ts index 38c75da8..927c54db 100644 --- a/prediqo_web/src/shared/i18n/locales/fr.ts +++ b/prediqo_web/src/shared/i18n/locales/fr.ts @@ -1647,7 +1647,17 @@ export const fr = { 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.', + stuckScanBusy: 'Scan on-chain… (jusqu’à 1 min)', + stuckScanDone: 'Scan terminé — {{count}} adresse(s) détiennent encore de l’USDT on-chain.', + stuckScanFailed: 'Le scan a échoué. Vérifiez les logs backend et réessayez.', + stuckScanAlreadyCredited: + 'Cet USDT est déjà crédité au compte utilisateur. Le bandeau reste jusqu’au sweep : Submit sweeps for approval, puis Approvals.', + stuckScanAlreadyCreditedSweepOff: + 'Déjà crédité au compte. Mettez SWEEP_ENABLED=true dans le .env (et docker-compose), recréez le backend, puis Submit sweeps for approval.', + stuckScanEnqueued: + '{{count}} sweep(s) en file. Cliquez Submit sweeps for approval, puis approuvez sous Approvals.', + stuckScanUncredited: + 'Scan terminé — {{count}} adresse(s) encore non créditées. Vérifiez les logs de dépôt / BscScan.', 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',