games_app/backend/dist-test-faq/services/sweepBatchService.js

126 lines
5.7 KiB
JavaScript

"use strict";
/**
* Periodic batching of auto-enqueued deposit sweeps for super-admin approval.
*/
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.SWEEP_BATCH_INTERVAL_MS = void 0;
exports.reconcileSettledSweepBatches = reconcileSettledSweepBatches;
exports.createSweepBatchApprovalRequests = createSweepBatchApprovalRequests;
const config_1 = require("../config");
const connection_1 = require("../db/connection");
const depositSweepBatchRepository = __importStar(require("../repositories/depositSweepBatchRepository"));
const fundOperationRequestRepository = __importStar(require("../repositories/fundOperationRequestRepository"));
const fundApprovalService = __importStar(require("./fundApprovalService"));
exports.SWEEP_BATCH_INTERVAL_MS = 15 * 60 * 1000;
async function getAutomatedRequesterId() {
const superRows = await (0, connection_1.query)(`SELECT ur.user_id
FROM user_roles ur
JOIN roles r ON r.id = ur.role_id
WHERE r.name = 'super_admin'
LIMIT 1`);
if (superRows[0])
return superRows[0].user_id;
const adminRows = await (0, connection_1.query)(`SELECT ur.user_id
FROM user_roles ur
JOIN roles r ON r.id = ur.role_id
WHERE r.name = 'admin'
LIMIT 1`);
if (adminRows[0])
return adminRows[0].user_id;
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.
*/
async function reconcileSettledSweepBatches() {
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;
}
async function createSweepBatchApprovalRequests() {
// When every pending sweep is auto-eligible, do not open Approvals at all.
if (config_1.config.treasury.sweepEnabled && config_1.config.treasury.sweepAutoExecute) {
const maxRaw = config_1.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) {
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_1.config.treasury.sweepAutoExecute && config_1.config.treasury.sweepAutoMaxAmountRaw) {
const overMax = await (0, connection_1.query)(`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_1.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: pending, automated: true },
requestedBy: requesterId,
});
await depositSweepBatchRepository.linkFundRequest(batch.id, request.id);
created++;
}
return created;
}
//# sourceMappingURL=sweepBatchService.js.map