"use strict"; /** * On-chain withdrawal service (state machine v2). * * A valid request is always recorded as `pending` with `amount + fee` reserved on the user's * unified USDT ledger (USDT_TRC20, 6 decimals), even when the platform hot wallet cannot pay * right now. Payout runs separately: pending -> processing -> completed once the transaction * is confirmed on-chain. Platform liquidity problems never surface to the user — the request * simply stays pending until an admin (or the automatic attempt) processes it. */ 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.broadcastApprovedWithdrawal = void 0; exports.requestWithdrawal = requestWithdrawal; exports.processWithdrawal = processWithdrawal; exports.processApprovedWithdrawal = processApprovedWithdrawal; exports.verifyBroadcastWithdrawal = verifyBroadcastWithdrawal; exports.runWithdrawalAutoRetryCycle = runWithdrawalAutoRetryCycle; exports.runWithdrawalMonitorCycle = runWithdrawalMonitorCycle; exports.rejectWithdrawal = rejectWithdrawal; exports.cancelWithdrawal = cancelWithdrawal; exports.cancelWithdrawalFromApproval = cancelWithdrawalFromApproval; exports.requeueWithdrawal = requeueWithdrawal; const config_1 = require("../config"); const connection_1 = require("../db/connection"); const hdWallet_1 = require("./hdWallet"); const transactionRepository = __importStar(require("../repositories/transactionRepository")); const hotWalletRepository = __importStar(require("../repositories/hotWalletRepository")); const auditLogRepository = __importStar(require("../repositories/auditLogRepository")); const walletRepository = __importStar(require("../repositories/walletRepository")); const settingsRepository = __importStar(require("../repositories/settingsRepository")); const withdrawalRepository = __importStar(require("../repositories/withdrawalRepository")); const fundOperationRequestRepository = __importStar(require("../repositories/fundOperationRequestRepository")); const withdrawalFee_1 = require("../utils/withdrawalFee"); const securityService_1 = require("./securityService"); const authService = __importStar(require("./authService")); const userAdminStatsService_1 = require("./userAdminStatsService"); const referralService = __importStar(require("./referralService")); const withdrawalLimits_1 = require("../utils/withdrawalLimits"); const walletCapabilities_1 = require("./walletCapabilities"); const usdtUnits_1 = require("../utils/usdtUnits"); const hotLiquidityService_1 = require("./hotLiquidityService"); const walletNotificationService = __importStar(require("./walletNotificationService")); const withdrawalStateMachine_1 = require("./withdrawals/withdrawalStateMachine"); const withdrawalPayoutService_1 = require("./withdrawals/withdrawalPayoutService"); const SYSTEM_ACTOR = { actorType: 'system' }; /** Claimed rows with no signed payout after this long are considered interrupted. */ const STALE_CLAIM_MINUTES = 10; function assertPayoutAddress(network, toAddress) { const a = toAddress.trim(); if (network === 'BSC') { if (!/^0x[a-fA-F0-9]{40}$/.test(a)) { throw new Error('Invalid BEP20 address. Use a 0x… address on BNB Smart Chain.'); } return; } if (!/^T[1-9A-HJ-NP-Za-km-z]{33}$/.test(a)) { throw new Error('Invalid TRC20 address. Use a T… address on TRON.'); } } async function assertWithdrawalWithinLimits(userId, amountRaw, feeRaw, settings, client) { const amountUsd = (0, withdrawalLimits_1.rawAmountToUsdApprox)(walletCapabilities_1.USDT_TRC20_CODE, amountRaw, usdtUnits_1.LEDGER_USDT_DECIMALS); const feeUsd = (0, withdrawalLimits_1.rawAmountToUsdApprox)(walletCapabilities_1.USDT_TRC20_CODE, feeRaw, usdtUnits_1.LEDGER_USDT_DECIMALS); const totalUsd = amountUsd + feeUsd; const startOfUtcDay = new Date(); startOfUtcDay.setUTCHours(0, 0, 0, 0); const rows = await transactionRepository.listWithdrawalsSince(userId, startOfUtcDay, client); let usedUsd = 0; for (const row of rows) { usedUsd += (0, withdrawalLimits_1.rawAmountToUsdApprox)(row.code, BigInt(row.amount), row.decimals); usedUsd += (0, withdrawalLimits_1.rawAmountToUsdApprox)(row.code, BigInt(row.fee || '0'), row.decimals); } if (usedUsd + totalUsd > settings.daily_withdrawal_limit_usd) { const err = new Error(`Daily withdrawal limit exceeded ($${settings.daily_withdrawal_limit_usd} USD per UTC day).`); err.code = 'DAILY_WITHDRAWAL_LIMIT_EXCEEDED'; throw err; } } async function flagLargeWithdrawal(userId, railWalletType, amountRaw, amountUsd, settings) { await auditLogRepository.create({ userId, action: 'large_withdrawal_requested', metadata: { amountUsd, thresholdUsd: settings.large_withdrawal_threshold_usd, walletType: railWalletType.code, amount: amountRaw.toString(), }, }); void (0, securityService_1.raiseAlert)({ userId, severity: 'medium', alertType: 'large_withdrawal_requested', title: 'Large withdrawal requested', details: `User requested $${amountUsd.toFixed(2)} withdrawal (threshold $${settings.large_withdrawal_threshold_usd}).`, metadata: { amountUsd, thresholdUsd: settings.large_withdrawal_threshold_usd, walletType: railWalletType.code, }, }).catch((e) => console.error('[withdrawal] large withdrawal alert failed:', e)); } function toResult(row, extra = {}) { const total = BigInt(row.amount) + BigInt(row.fee || '0'); return { transactionId: row.id, status: row.status, amount: row.amount, fee: row.fee, totalDebited: total.toString(), blockchainTxId: row.status === 'completed' ? row.blockchain_tx_id : null, ...extra, }; } function rowNetwork(row) { const n = String(row.metadata?.network ?? ''); return n === 'TRON' || n === 'BSC' ? n : null; } function rowRailCode(row) { return String(row.metadata?.rail_wallet_type ?? ''); } /** * Records a withdrawal request: validates, reserves funds and returns status `pending`. * Never fails because of platform hot-wallet liquidity. */ async function requestWithdrawal(userId, walletTypeCode, toAddress, amountRaw, totpCode, options = {}) { const settings = await settingsRepository.getSettings(); if (!settings.allow_withdrawals) { const err = new Error('Withdrawals are disabled by server configuration (enable in Admin → Settings).'); err.code = 'WITHDRAWALS_DISABLED'; throw err; } await authService.assertWithdrawalSecondFactor(userId, totpCode); await (0, securityService_1.assertUserCanWithdraw)(userId); const railWalletType = await walletRepository.getWalletTypeByCode(walletTypeCode); if (!railWalletType) throw new Error('Unknown wallet type'); if (!(0, walletCapabilities_1.isSupportedUsdtCode)(walletTypeCode)) { throw new Error(`Withdrawals are only supported for USDT networks`); } const network = (0, usdtUnits_1.networkForWalletCode)(walletTypeCode); if (!network) throw new Error('Unsupported withdrawal network'); const caps = (0, walletCapabilities_1.enrichWalletType)(railWalletType, settings); if (!caps.withdrawEnabled) { const err = new Error(`Withdrawals are disabled for ${walletTypeCode}`); err.code = 'WITHDRAWAL_NETWORK_DISABLED'; throw err; } if (amountRaw <= 0n) throw new Error('Invalid amount'); const destination = toAddress.trim(); assertPayoutAddress(network, destination); const ledgerWalletType = await walletRepository.getWalletTypeByCode(walletCapabilities_1.USDT_TRC20_CODE); if (!ledgerWalletType) throw new Error('USDT ledger wallet type not configured'); const feeRaw = (0, withdrawalFee_1.getWithdrawalNetworkFeeRaw)(settings, usdtUnits_1.LEDGER_USDT_DECIMALS); const amountUsd = (0, withdrawalLimits_1.rawAmountToUsdApprox)(walletCapabilities_1.USDT_TRC20_CODE, amountRaw, usdtUnits_1.LEDGER_USDT_DECIMALS); const requiresApproval = amountUsd >= settings.large_withdrawal_threshold_usd; const { row, duplicate } = await withdrawalRepository.createWithdrawalRequest({ userId, walletTypeId: ledgerWalletType.id, amountRaw, feeRaw, toAddress: destination, requiredConfirmations: network === 'TRON' ? config_1.config.blockchain.tron.confirmations : config_1.config.blockchain.bsc.confirmations, metadata: { rail_wallet_type: walletTypeCode, network }, pendingReason: requiresApproval ? 'awaiting_approval' : 'queued', idempotencyKey: options.idempotencyKey?.trim() || null, insufficientMessage: feeRaw > 0n ? 'Insufficient balance (withdrawal amount + network fee)' : 'Insufficient balance', beforeReserve: (client) => assertWithdrawalWithinLimits(userId, amountRaw, feeRaw, settings, client), }); if (duplicate) return toResult(row, { duplicate: true }); await auditLogRepository.create({ userId, action: 'withdrawal_requested', resourceType: 'transaction', resourceId: row.id, metadata: { amount: amountRaw.toString(), fee: feeRaw.toString(), toAddress: destination, walletType: walletTypeCode, network, requiresApproval, }, }); (0, userAdminStatsService_1.queueUserAdminStatsRefresh)(userId); void walletNotificationService.notifyWithdrawalSubmitted(userId, { amountRaw, feeRaw, toAddress: destination, network, transactionId: row.id, pendingApproval: requiresApproval, }); let fundRequestId; if (requiresApproval) { await flagLargeWithdrawal(userId, railWalletType, amountRaw, amountUsd, settings); const hotWallet = await hotWalletRepository.getActiveHotWallet(railWalletType.id); try { const { createFundRequest } = await Promise.resolve().then(() => __importStar(require('./fundApprovalService'))); const fundReq = await createFundRequest({ operationType: 'user_withdrawal', payload: { transactionId: row.id, userId, amountRaw: amountRaw.toString(), feeRaw: feeRaw.toString(), walletTypeId: railWalletType.id, walletCode: walletTypeCode, assetCode: walletTypeCode, network, fromAddress: hotWallet?.address ?? null, toAddress: destination, }, requestedBy: userId, skipRequestPermission: true, }); fundRequestId = fundReq.id; await withdrawalRepository.patchPendingDetails(row.id, { metadata: { fund_request_id: fundReq.id }, }); } catch (e) { // The request stays pending (awaiting approval) and remains visible to admins. console.error('[withdrawal] approval request creation failed:', e); await auditLogRepository.create({ userId, action: 'withdrawal_approval_request_failed', resourceType: 'transaction', resourceId: row.id, metadata: { error: e instanceof Error ? e.message : String(e) }, }); } } else if (options.autoProcess !== false) { scheduleProcessing(row.id); } const fresh = (await withdrawalRepository.findWithdrawal(row.id)) ?? row; return toResult(fresh, fundRequestId ? { fundRequestId } : {}); } /** Starts an automatic payout attempt without blocking the HTTP response. */ function scheduleProcessing(transactionId) { setImmediate(() => { processWithdrawal(transactionId, SYSTEM_ACTOR).catch((e) => { if (e instanceof withdrawalStateMachine_1.WithdrawalStateError) return; console.error('[withdrawal] automatic processing error:', e); }); }); } const PAYOUT_LOCK_NS = 872364302; /** Serializes sign + broadcast per network (nonce safety, in-flight liquidity accounting). */ async function withPayoutLock(network, fn) { const client = await (0, connection_1.getClient)(); try { await client.query('SELECT pg_advisory_lock($1, $2)', [PAYOUT_LOCK_NS, network === 'TRON' ? 1 : 2]); try { return await fn(); } finally { await client .query('SELECT pg_advisory_unlock($1, $2)', [PAYOUT_LOCK_NS, network === 'TRON' ? 1 : 2]) .catch(() => undefined); } } finally { client.release(); } } function stateErrorMessage(code, status) { switch (code) { case 'WITHDRAWAL_NOT_FOUND': return 'Withdrawal not found'; case 'WITHDRAWAL_AWAITING_APPROVAL': return 'This withdrawal is waiting for the large-withdrawal approval quorum (see Approvals).'; case 'WITHDRAWAL_ALREADY_BROADCAST': return 'A payout transaction already exists for this withdrawal; it is being verified on-chain.'; case 'WITHDRAWAL_LEGACY_READ_ONLY': return 'Legacy withdrawal record: manual review required.'; default: return `Withdrawal cannot be changed from its current status (${status ?? 'unknown'}).`; } } function throwStateError(res) { throw new withdrawalStateMachine_1.WithdrawalStateError(res.code, stateErrorMessage(res.code, res.status)); } async function moveToPending(row, reason, actor, detail, discardUnsentHash = false) { const res = await withdrawalRepository.releaseToPending(row.id, { reason, lastError: detail ?? null, actor, discardUnsentHash, }); if (res.ok) { await auditLogRepository.create({ userId: actor.actorUserId ?? null, action: 'withdrawal_returned_to_pending', resourceType: 'transaction', resourceId: row.id, metadata: { reason, detail: detail ?? null }, }); } return { transactionId: row.id, status: 'pending', pendingReason: reason, message: detail }; } async function moveToFailed(row, error, actor) { const res = await withdrawalRepository.failProcessing(row.id, { error, actor }); if (res.ok) { await auditLogRepository.create({ userId: actor.actorUserId ?? null, action: 'withdrawal_failed', resourceType: 'transaction', resourceId: row.id, metadata: { error }, }); void walletNotificationService.notifyWithdrawalFailed(row.user_id, { amountRaw: BigInt(row.amount), feeRaw: BigInt(row.fee || '0'), toAddress: row.to_address ?? undefined, transactionId: row.id, }); (0, userAdminStatsService_1.queueUserAdminStatsRefresh)(row.user_id); } return { transactionId: row.id, status: 'failed', message: error }; } /** * Attempts the payout of a pending/failed request: pending|failed -> processing, then either * broadcast (stays processing until confirmed), back to pending (liquidity), or failed. * Throws WithdrawalStateError only when the request cannot be processed from its status. */ async function processWithdrawal(transactionId, actor, opts = {}) { const claim = await withdrawalRepository.claimForProcessing(transactionId, actor, opts); if (!claim.ok) throwStateError(claim); const row = claim.row; await auditLogRepository.create({ userId: actor.actorUserId ?? null, action: 'withdrawal_processing_started', resourceType: 'transaction', resourceId: row.id, metadata: { attempt: row.processing_attempts, from: claim.fromStatus, actor: actor.actorType }, }); if (claim.fromStatus === 'failed' || row.processing_attempts === 1) { void walletNotificationService.notifyWithdrawalProcessing(row.user_id, { transactionId: row.id }); } try { try { await (0, securityService_1.assertUserCanWithdraw)(row.user_id); } catch (e) { if (e instanceof securityService_1.SecurityBlockedError) { return moveToPending(row, 'account_on_hold', actor, e.message); } throw e; } const network = rowNetwork(row); const railWalletType = await walletRepository.getWalletTypeByCode(rowRailCode(row)); if (!network || !railWalletType) { return moveToFailed(row, 'Unknown withdrawal network', actor); } const hotWallet = await hotWalletRepository.getActiveHotWallet(railWalletType.id); if (!hotWallet) { return moveToPending(row, 'hot_wallet_unavailable', actor, `No active hot wallet for ${network}`); } return await withPayoutLock(network, () => executePayout(row, actor, network, railWalletType, hotWallet)); } catch (e) { const msg = e instanceof Error ? e.message : String(e); const current = await withdrawalRepository.findWithdrawal(row.id); if (current?.status === 'processing' && current.blockchain_tx_id) { // A signed payout may be on the network: never fail blindly, the monitor verifies it. console.error(`[withdrawal] ${row.id} error after signing, left for on-chain verification:`, msg); return { transactionId: row.id, status: 'processing', message: msg }; } if (current?.status === 'processing') return moveToFailed(current, msg, actor); return { transactionId: row.id, status: current?.status ?? 'unknown', message: msg }; } } async function executePayout(row, actor, network, railWalletType, hotWallet) { const amountRaw = BigInt(row.amount); const usdtContract = railWalletType.contract_address || ''; const inFlightRaw = await withdrawalRepository.sumInFlightPayouts(network, row.id); const balances = await (0, hotLiquidityService_1.readHotBalances)({ network, hotAddress: hotWallet.address, usdtContract }); const settings = await settingsRepository.getSettings(); const verdict = (0, hotLiquidityService_1.evaluateHotLiquidity)({ network, usdtBalanceRaw: balances.usdtBalanceRaw, nativeBalanceRaw: balances.nativeBalanceRaw, ledgerAmountRaw: amountRaw + inFlightRaw, minNativeRaw: (0, hotLiquidityService_1.gasReserveRaw)(network, settings), }); if (!verdict.ok) { const detail = `Hot wallet ${verdict.reason === 'usdt' ? 'USDT' : 'gas'} insufficient on ${network} (needed ${verdict.needed}, available ${verdict.available}, in-flight ${inFlightRaw})`; return moveToPending(row, verdict.reason === 'usdt' ? 'awaiting_liquidity' : 'awaiting_gas', actor, detail); } let signed; try { signed = await (0, withdrawalPayoutService_1.signPayout)({ network, privateKey: (0, hdWallet_1.decryptPrivateKey)(hotWallet.encrypted_private_key), usdtContract, toAddress: row.to_address || '', ledgerAmountRaw: amountRaw, }); } catch (e) { if (e instanceof withdrawalPayoutService_1.PayoutError && (e.kind === 'liquidity_usdt' || e.kind === 'liquidity_gas')) { return moveToPending(row, e.kind === 'liquidity_usdt' ? 'awaiting_liquidity' : 'awaiting_gas', actor, e.message); } return moveToFailed(row, `Could not prepare payout: ${e instanceof Error ? e.message : String(e)}`, actor); } const recorded = await withdrawalRepository.recordSignedPayout(row.id, { txHash: signed.txHash, signedPayload: signed.payload, expiresAt: signed.expiresAt, fromAddress: signed.fromAddress, }); if (!recorded) { return moveToFailed(row, 'Withdrawal state changed before broadcast', actor); } const outcome = await (0, withdrawalPayoutService_1.broadcastPayout)(signed); if (outcome.kind === 'accepted') { await withdrawalRepository.markBroadcast(row.id, { stage: 'broadcast' }); await auditLogRepository.create({ userId: actor.actorUserId ?? null, action: 'withdrawal_broadcast', resourceType: 'transaction', resourceId: row.id, metadata: { txHash: signed.txHash, network }, }); return { transactionId: row.id, status: 'processing', blockchainTxId: signed.txHash }; } if (outcome.kind === 'uncertain') { await withdrawalRepository.markBroadcast(row.id, { stage: 'broadcast_uncertain', lastError: outcome.message, }); return { transactionId: row.id, status: 'processing', blockchainTxId: signed.txHash, message: 'Broadcast response lost; the payout is being verified on-chain.', }; } if (outcome.failure === 'liquidity_usdt' || outcome.failure === 'liquidity_gas') { return moveToPending(row, outcome.failure === 'liquidity_usdt' ? 'awaiting_liquidity' : 'awaiting_gas', actor, outcome.message, true); } return moveToFailed(row, `Network refused payout: ${outcome.message}`, actor); } /** Called by the approval workflow once the large-withdrawal quorum is reached. */ async function processApprovedWithdrawal(transactionId, approvedBy) { const result = await processWithdrawal(transactionId, { actorType: 'admin', actorUserId: approvedBy }, { approvalGranted: true }); return { ...result }; } /** @deprecated name kept for the approval workflow; payout is now asynchronous. */ exports.broadcastApprovedWithdrawal = processApprovedWithdrawal; async function onCompleted(row) { const network = rowNetwork(row); await auditLogRepository.create({ userId: row.user_id, action: 'withdrawal_completed', resourceType: 'transaction', resourceId: row.id, metadata: { amount: row.amount, fee: row.fee, toAddress: row.to_address, blockchainTxId: row.blockchain_tx_id, network, confirmations: row.confirmations, }, }); (0, userAdminStatsService_1.queueUserAdminStatsRefresh)(row.user_id); void walletNotificationService.notifyWithdrawalCompleted(row.user_id, { amountRaw: BigInt(row.amount), feeRaw: BigInt(row.fee || '0'), toAddress: row.to_address || '', network: network ?? undefined, transactionId: row.id, blockchainTxId: row.blockchain_tx_id, }); try { await referralService.processWithdrawalReferralCommissions({ userId: row.user_id, withdrawalTransactionId: row.id, withdrawalAmount: BigInt(row.amount), walletTypeId: row.wallet_type_id, }); } catch (referralErr) { console.error('[referral] Withdrawal commission processing failed:', referralErr); } } /** Verifies one broadcast payout on-chain and advances its status when the result is known. */ async function verifyBroadcastWithdrawal(row, nowMs = Date.now()) { const network = rowNetwork(row); const hash = row.blockchain_tx_id; if (!network || !hash) return 'skipped'; const status = await (0, withdrawalPayoutService_1.getPayoutStatus)(network, hash); if (status.kind === 'mined') { if (!status.success) { await moveToFailed(row, `Payout transaction failed on-chain${status.message ? `: ${status.message}` : ''}`, SYSTEM_ACTOR); void (0, securityService_1.raiseAlert)({ userId: row.user_id, severity: 'high', alertType: 'withdrawal_payout_reverted', title: 'Withdrawal payout reverted on-chain', details: `transaction=${row.id}, hash=${hash}, network=${network}`, metadata: { transactionId: row.id, txHash: hash, network }, }).catch(() => undefined); return 'failed'; } const required = row.required_confirmations ?? 1; if (status.confirmations >= required) { const done = await withdrawalRepository.finalizeCompleted(row.id, { confirmations: status.confirmations, }); if (done.ok) await onCompleted(done.row); return done.ok ? 'completed' : 'skipped'; } await withdrawalRepository.updateConfirmations(row.id, status.confirmations); return 'confirming'; } if (status.kind === 'pending') return 'pending'; const nonceConsumed = network === 'BSC' && row.signed_payload && row.from_address ? await (0, withdrawalPayoutService_1.isBscNonceConsumed)(row.from_address, row.signed_payload) : undefined; const decision = (0, withdrawalPayoutService_1.decideMissingPayout)({ network, nowMs, broadcastAtMs: row.broadcast_at ? new Date(row.broadcast_at).getTime() : null, expiresAtMs: row.signed_expires_at ? new Date(row.signed_expires_at).getTime() : null, nonceConsumed, }); if (decision === 'dropped') { await moveToFailed(row, 'Payout was never included on-chain and has expired', SYSTEM_ACTOR); return 'failed'; } if (decision === 'rebroadcast' && row.signed_payload) { try { await (0, withdrawalPayoutService_1.rebroadcastPayout)(network, row.signed_payload); await withdrawalRepository.markBroadcast(row.id, { stage: 'broadcast' }); } catch (e) { console.warn(`[withdrawal] rebroadcast ${row.id} failed:`, e instanceof Error ? e.message : e); } return 'rebroadcast'; } return 'waiting'; } /** Pending reasons that clear on their own once the hot wallet is replenished. */ const AUTO_RETRY_REASONS = [ 'awaiting_liquidity', 'awaiting_gas', 'hot_wallet_unavailable', ]; const AUTO_RETRY_BATCH = 20; /** * Automatic retry pass (only when enabled in settings). A request is claimed only when the * hot wallet can pay it right now (USDT + gas, minus payouts already in flight), so an * unfunded wallet produces no status churn. */ async function runWithdrawalAutoRetryCycle() { const settings = await settingsRepository.getSettings(); if (!settings.withdrawal_auto_retry_enabled || !settings.allow_withdrawals) { return { attempted: 0, skipped: 0 }; } const rows = await withdrawalRepository.listAutoRetryCandidates(AUTO_RETRY_REASONS, AUTO_RETRY_BATCH); const balancesByNetwork = new Map(); let attempted = 0; let skipped = 0; for (const row of rows) { const network = rowNetwork(row); const railWalletType = await walletRepository.getWalletTypeByCode(rowRailCode(row)); const hotWallet = railWalletType ? await hotWalletRepository.getActiveHotWallet(railWalletType.id) : null; if (!network || !railWalletType || !hotWallet) { skipped++; continue; } if (!balancesByNetwork.has(network)) { const balances = await (0, hotLiquidityService_1.readHotBalances)({ network, hotAddress: hotWallet.address, usdtContract: railWalletType.contract_address || '', }).catch((e) => { console.warn(`[withdrawal] auto-retry balance read failed (${network}):`, e instanceof Error ? e.message : e); return null; }); balancesByNetwork.set(network, balances); } const balances = balancesByNetwork.get(network); if (!balances) { skipped++; continue; } const inFlightRaw = await withdrawalRepository.sumInFlightPayouts(network, row.id); const verdict = (0, hotLiquidityService_1.evaluateHotLiquidity)({ network, usdtBalanceRaw: balances.usdtBalanceRaw, nativeBalanceRaw: balances.nativeBalanceRaw, ledgerAmountRaw: BigInt(row.amount) + inFlightRaw, minNativeRaw: (0, hotLiquidityService_1.gasReserveRaw)(network, settings), }); if (!verdict.ok) { skipped++; continue; } try { attempted++; await processWithdrawal(row.id, SYSTEM_ACTOR); } catch (e) { if (!(e instanceof withdrawalStateMachine_1.WithdrawalStateError)) { console.error(`[withdrawal] auto-retry ${row.id} failed:`, e); } } } return { attempted, skipped }; } let lastAutoRetryAtMs = 0; async function maybeRunAutoRetry(nowMs) { const settings = await settingsRepository.getSettings(); if (!settings.withdrawal_auto_retry_enabled) return; const intervalMs = Math.max(1, settings.withdrawal_auto_retry_interval_minutes || 10) * 60000; if (nowMs - lastAutoRetryAtMs < intervalMs) return; lastAutoRetryAtMs = nowMs; const r = await runWithdrawalAutoRetryCycle(); if (r.attempted > 0) console.log(`[withdrawal] auto-retry started ${r.attempted} payout(s)`); } /** One pass of the confirmation monitor (also recovers interrupted claims and auto-retries). */ async function runWithdrawalMonitorCycle() { let completed = 0; const rows = await withdrawalRepository.listAwaitingChainResult(50); for (const row of rows) { try { const outcome = await verifyBroadcastWithdrawal(row); if (outcome === 'completed') completed++; } catch (e) { console.warn(`[withdrawal] verify ${row.id} failed:`, e instanceof Error ? e.message : e); } } const stale = await withdrawalRepository.listStaleClaims(STALE_CLAIM_MINUTES); for (const row of stale) { await moveToPending(row, 'processing_interrupted', SYSTEM_ACTOR, 'Processing was interrupted before signing'); } try { await maybeRunAutoRetry(Date.now()); } catch (e) { console.error('[withdrawal] auto-retry pass failed:', e); } return { checked: rows.length, completed }; } async function resolveLinkedFundRequest(row) { const fromMeta = row.metadata?.fund_request_id; if (typeof fromMeta === 'string' && fromMeta) return fromMeta; return withdrawalRepository.findFundRequestIdForWithdrawal(row.id); } /** * Closes the approval request of a large withdrawal before it is refunded. * Refuses when the quorum was already reached (the payout is underway). */ async function closeApprovalRequest(row, mode) { if (row.pending_reason !== 'awaiting_approval') return; const fundRequestId = await resolveLinkedFundRequest(row); if (!fundRequestId) return; const closed = mode.kind === 'reject' ? await fundOperationRequestRepository.markRejected(fundRequestId, mode.actorId, mode.reason) : await fundOperationRequestRepository.markCancelled(fundRequestId); if (closed) return; const fund = await fundOperationRequestRepository.findById(fundRequestId); if (fund && (fund.status === 'approved' || fund.status === 'processing')) { throw new withdrawalStateMachine_1.WithdrawalStateError('WITHDRAWAL_INVALID_TRANSITION', 'The approval quorum was already reached; the withdrawal is being processed.'); } } /** Admin refusal (pending|failed -> rejected) with a full, single refund. */ async function rejectWithdrawal(transactionId, input) { const reason = input.reason.trim(); if (!reason) throw new Error('Rejection reason is required'); const row = await withdrawalRepository.findWithdrawal(transactionId); if (!row) throw new withdrawalStateMachine_1.WithdrawalStateError('WITHDRAWAL_NOT_FOUND', 'Withdrawal not found'); if (input.source !== 'approval') { await closeApprovalRequest(row, { kind: 'reject', actorId: input.actorId, reason }); } const res = await withdrawalRepository.refundWithdrawal(transactionId, { toStatus: 'rejected', actor: { actorType: 'admin', actorUserId: input.actorId }, reason, }); if (!res.ok) throwStateError(res); await auditLogRepository.create({ userId: input.actorId, action: 'withdrawal_rejected', resourceType: 'transaction', resourceId: transactionId, metadata: { reason, source: input.source ?? 'admin', refundedAmount: (BigInt(res.row.amount) + BigInt(res.row.fee || '0')).toString(), ownerUserId: res.row.user_id, }, }); (0, userAdminStatsService_1.queueUserAdminStatsRefresh)(res.row.user_id); void walletNotificationService.notifyWithdrawalRejected(res.row.user_id, { amountRaw: BigInt(res.row.amount), feeRaw: BigInt(res.row.fee || '0'), transactionId, }); return res.row; } /** User cancellation of a request that is still pending (pending -> cancelled, refunded). */ async function cancelWithdrawal(transactionId, input) { const row = await withdrawalRepository.findWithdrawal(transactionId); if (!row || row.user_id !== input.userId) { throw new withdrawalStateMachine_1.WithdrawalStateError('WITHDRAWAL_NOT_FOUND', 'Withdrawal not found'); } if (row.status !== 'pending') { throw new withdrawalStateMachine_1.WithdrawalStateError('WITHDRAWAL_INVALID_TRANSITION', 'Only a withdrawal that has not started processing can be cancelled.'); } if (input.source !== 'approval') await closeApprovalRequest(row, { kind: 'cancel' }); const actorType = input.actorType ?? 'user'; const res = await withdrawalRepository.refundWithdrawal(transactionId, { toStatus: 'cancelled', actor: { actorType, actorUserId: input.actorId ?? input.userId }, reason: actorType === 'user' ? 'cancelled_by_user' : 'cancelled', ownerUserId: input.userId, }); if (!res.ok) throwStateError(res); await auditLogRepository.create({ userId: input.actorId ?? input.userId, action: 'withdrawal_cancelled', resourceType: 'transaction', resourceId: transactionId, metadata: { refundedAmount: (BigInt(res.row.amount) + BigInt(res.row.fee || '0')).toString(), source: input.source ?? 'user', }, }); (0, userAdminStatsService_1.queueUserAdminStatsRefresh)(res.row.user_id); void walletNotificationService.notifyWithdrawalCancelled(res.row.user_id, { amountRaw: BigInt(res.row.amount), feeRaw: BigInt(res.row.fee || '0'), transactionId, }); return res.row; } /** Approval workflow cancelled by the requester / super admin. */ async function cancelWithdrawalFromApproval(transactionId, actorId) { const row = await withdrawalRepository.findWithdrawal(transactionId); if (!row || row.status !== 'pending') return; await cancelWithdrawal(transactionId, { userId: row.user_id, actorType: actorId === row.user_id ? 'user' : 'admin', actorId, source: 'approval', }); } /** Admin: failed -> pending (e.g. before a later retry). */ async function requeueWithdrawal(transactionId, actorId) { const row = await withdrawalRepository.findWithdrawal(transactionId); if (!row) throw new withdrawalStateMachine_1.WithdrawalStateError('WITHDRAWAL_NOT_FOUND', 'Withdrawal not found'); if (row.status !== 'failed') { throw new withdrawalStateMachine_1.WithdrawalStateError('WITHDRAWAL_INVALID_TRANSITION', 'Only a failed withdrawal can be put back in the queue.'); } const res = await withdrawalRepository.releaseToPending(transactionId, { reason: 'requeued_by_admin', actor: { actorType: 'admin', actorUserId: actorId }, }); if (!res.ok) throwStateError(res); await auditLogRepository.create({ userId: actorId, action: 'withdrawal_requeued', resourceType: 'transaction', resourceId: transactionId, }); return res.row; } //# sourceMappingURL=withdrawalService.js.map