From fec413a94b695dc0d0b622e603f578c724d69c2c Mon Sep 17 00:00:00 2001 From: Your Name Date: Sat, 29 Aug 2026 18:36:41 +0200 Subject: [PATCH] After trying to recuparate money from cold wallet20 --- backend/src/bootstrap/appBootstrap.ts | 1 + .../depositSweepBatchRepository.ts | 42 +++++++++++-- backend/src/services/sweepBatchService.ts | 62 ++++++++++++++++++- 3 files changed, 98 insertions(+), 7 deletions(-) diff --git a/backend/src/bootstrap/appBootstrap.ts b/backend/src/bootstrap/appBootstrap.ts index d085015f..99e82e7f 100644 --- a/backend/src/bootstrap/appBootstrap.ts +++ b/backend/src/bootstrap/appBootstrap.ts @@ -109,6 +109,7 @@ function startSweepBatchMonitor(): void { console.log(`[sweep] auto-executed ${nAuto} sweep(s)`); } } + // Creates Approvals only when needed; also cancels orphan batches already auto-swept. const n = await createSweepBatchApprovalRequests(); if (n > 0) { console.log(`[sweep-batch] Enqueued ${n} batch approval request(s)`); diff --git a/backend/src/repositories/depositSweepBatchRepository.ts b/backend/src/repositories/depositSweepBatchRepository.ts index e6813b30..d5ab2142 100644 --- a/backend/src/repositories/depositSweepBatchRepository.ts +++ b/backend/src/repositories/depositSweepBatchRepository.ts @@ -80,18 +80,50 @@ export async function listSweepIdsInBatch(batchId: string): Promise { return rows.map((r) => r.id); } -export async function countPendingUnbatchedSweeps(): Promise { +export async function countPendingSweepsInBatch(batchId: string): Promise { const rows = await query<{ count: string }[]>( - `SELECT COUNT(*)::text AS count FROM deposit_sweeps WHERE batch_id IS NULL AND status = 'pending'` + `SELECT COUNT(*)::text AS count FROM deposit_sweeps + WHERE batch_id = $1 AND status IN ('pending', 'gas_funding', 'broadcasting')`, + [batchId] ); return parseInt(rows[0]?.count ?? '0', 10); } +/** Batches still open that have at least one unfinished sweep (for Approvals). */ export async function queryOpenBatchesReadyForApproval(): Promise { return query( - `SELECT * FROM deposit_sweep_batches - WHERE status = 'pending_batch' AND sweep_count > 0 AND fund_request_id IS NULL - ORDER BY created_at ASC` + `SELECT b.* + FROM deposit_sweep_batches b + WHERE b.status = 'pending_batch' + AND b.fund_request_id IS NULL + AND EXISTS ( + SELECT 1 FROM deposit_sweeps s + WHERE s.batch_id = b.id + AND s.status IN ('pending', 'gas_funding', 'broadcasting') + ) + ORDER BY b.created_at ASC` + ); +} + +/** + * Batches whose sweeps are all done (or empty) but still look "open" / awaiting approval. + * Used to clear orphan Approvals after SWEEP_AUTO_EXECUTE. + */ +export async function queryBatchesFullySettledNeedingCleanup(): Promise { + return query( + `SELECT b.* + FROM deposit_sweep_batches b + WHERE b.status IN ('pending_batch', 'pending_approval') + AND NOT EXISTS ( + SELECT 1 FROM deposit_sweeps s + WHERE s.batch_id = b.id + AND s.status IN ('pending', 'gas_funding', 'broadcasting') + ) + AND ( + b.sweep_count > 0 + OR EXISTS (SELECT 1 FROM deposit_sweeps s2 WHERE s2.batch_id = b.id) + ) + ORDER BY b.created_at ASC` ); } diff --git a/backend/src/services/sweepBatchService.ts b/backend/src/services/sweepBatchService.ts index 29faae78..5c1cdb93 100644 --- a/backend/src/services/sweepBatchService.ts +++ b/backend/src/services/sweepBatchService.ts @@ -2,8 +2,10 @@ * Periodic batching of auto-enqueued deposit sweeps for super-admin approval. */ +import { config } from '../config'; import { query } from '../db/connection'; import * as depositSweepBatchRepository from '../repositories/depositSweepBatchRepository'; +import * as fundOperationRequestRepository from '../repositories/fundOperationRequestRepository'; import * as fundApprovalService from './fundApprovalService'; export const SWEEP_BATCH_INTERVAL_MS = 15 * 60 * 1000; @@ -29,17 +31,73 @@ async function getAutomatedRequesterId(): Promise { throw new Error('No administrator available for automated sweep batch request'); } +/** + * After SWEEP_AUTO_EXECUTE finishes the on-chain sweeps, mark batches completed and + * cancel orphan Approvals so the UI does not ask to approve an already-done move. + */ +export async function reconcileSettledSweepBatches(): Promise { + const batches = await depositSweepBatchRepository.queryBatchesFullySettledNeedingCleanup(); + let cleaned = 0; + + for (const batch of batches) { + if (batch.fund_request_id) { + const req = await fundOperationRequestRepository.findById(batch.fund_request_id); + if (req && req.status === 'pending_approval') { + await fundOperationRequestRepository.markCancelled(batch.fund_request_id); + console.log( + `[sweep-batch] cancelled orphan approval ${batch.fund_request_id} (batch ${batch.id} already swept)` + ); + } + } + await depositSweepBatchRepository.markBatchStatus(batch.id, 'completed'); + cleaned += 1; + } + + return cleaned; +} + export async function createSweepBatchApprovalRequests(): Promise { + // When every pending sweep is auto-eligible, do not open Approvals at all. + if (config.treasury.sweepEnabled && config.treasury.sweepAutoExecute) { + const maxRaw = config.treasury.sweepAutoMaxAmountRaw; + if (!maxRaw) { + // No cap → everything auto; only clean up settled batches. + await reconcileSettledSweepBatches(); + return 0; + } + } + + await reconcileSettledSweepBatches(); + const batches = await depositSweepBatchRepository.queryOpenBatchesReadyForApproval(); let created = 0; for (const batch of batches) { - if (batch.sweep_count <= 0) continue; + const pending = await depositSweepBatchRepository.countPendingSweepsInBatch(batch.id); + if (pending <= 0) { + await depositSweepBatchRepository.markBatchStatus(batch.id, 'completed'); + continue; + } + + // With auto-execute + max: only send Approvals if some pending sweeps exceed the cap. + if (config.treasury.sweepAutoExecute && config.treasury.sweepAutoMaxAmountRaw) { + const overMax = await query<{ n: string }[]>( + `SELECT COUNT(*)::text AS n FROM deposit_sweeps + WHERE batch_id = $1 + AND status IN ('pending', 'gas_funding', 'broadcasting') + AND amount::numeric > $2::numeric`, + [batch.id, config.treasury.sweepAutoMaxAmountRaw] + ); + if (parseInt(overMax[0]?.n ?? '0', 10) === 0) { + // Still pending only because auto job has not run yet — do not create Approvals. + continue; + } + } const requesterId = await getAutomatedRequesterId(); const request = await fundApprovalService.createFundRequest({ operationType: 'sweep_batch', - payload: { batchId: batch.id, sweepCount: batch.sweep_count, automated: true }, + payload: { batchId: batch.id, sweepCount: pending, automated: true }, requestedBy: requesterId, });