"use strict"; /** * On-chain withdrawal service. * Debits unified USDT ledger (USDT_TRC20, 6 decimals); pays from the chosen * rail hot wallet (TRC20 or BEP20). Network need not match deposit history — * liquidity is gated by hot float (USDT + gas), not user inventory. */ 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.SecurityBlockedError = void 0; exports.requestWithdrawal = requestWithdrawal; const config_1 = require("../config"); const hdWallet_1 = require("./hdWallet"); const ledgerRepository = __importStar(require("../repositories/ledgerRepository")); const transactionRepository = __importStar(require("../repositories/transactionRepository")); const withdrawalLockRepository = __importStar(require("../repositories/withdrawalLockRepository")); 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 tronService = __importStar(require("./blockchain/tronService")); const polygonService = __importStar(require("./blockchain/polygonService")); const bscService = __importStar(require("./blockchain/bscService")); const withdrawalFee_1 = require("../utils/withdrawalFee"); const securityService_1 = require("./securityService"); Object.defineProperty(exports, "SecurityBlockedError", { enumerable: true, get: function () { return securityService_1.SecurityBlockedError; } }); 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"); 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, railWalletType, amountRaw, feeRaw, settings) { 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); 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; } if (amountUsd >= settings.large_withdrawal_threshold_usd) { 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)); } } /** * Submits a withdrawal: locks unified ledger, verifies hot float, pays from rail hot wallet. * `walletTypeCode` selects the payout rail (USDT_TRC20 or USDT_BEP20). * `amountRaw` is always in ledger micro-USDT (6 decimals). */ async function requestWithdrawal(userId, walletTypeCode, toAddress, amountRaw, totpCode) { 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'); assertPayoutAddress(network, toAddress); 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 totalDebit = amountRaw + feeRaw; await assertWithdrawalWithinLimits(userId, railWalletType, amountRaw, feeRaw, settings); const account = await ledgerRepository.getOrCreateAccount(userId, ledgerWalletType.id); const available = BigInt(account.available_balance); const locked = await withdrawalLockRepository.getLockedAmount(userId, ledgerWalletType.id); if (available < totalDebit + locked) { const err = new Error(feeRaw > 0n ? 'Insufficient balance (withdrawal amount + network fee)' : 'Insufficient balance'); err.code = 'INSUFFICIENT_BALANCE'; throw err; } const hotWallet = await hotWalletRepository.getActiveHotWallet(railWalletType.id); if (!hotWallet) throw new Error('Withdrawal temporarily unavailable'); if (network === 'TRON' || network === 'BSC') { await (0, hotLiquidityService_1.assertHotWalletCanPay)({ network, hotAddress: hotWallet.address, ledgerAmountRaw: amountRaw, usdtContract: railWalletType.contract_address || '', }); } await ledgerRepository.lockBalance(account.id, totalDebit); (0, userAdminStatsService_1.queueUserAdminStatsRefresh)(userId); const tx = await transactionRepository.create({ userId, walletTypeId: ledgerWalletType.id, type: 'withdrawal', amount: amountRaw, fee: feeRaw, status: 'pending', toAddress, requiredConfirmations: railWalletType.network === 'TRON' ? config_1.config.blockchain.tron.confirmations : railWalletType.network === 'BSC' ? config_1.config.blockchain.bsc.confirmations : config_1.config.blockchain.polygon.confirmations, metadata: { rail_wallet_type: walletTypeCode, network, }, }); await withdrawalLockRepository.create({ userId, walletTypeId: ledgerWalletType.id, transactionId: tx.id, amount: totalDebit, }); await auditLogRepository.create({ userId, action: 'withdrawal_requested', resourceType: 'transaction', resourceId: tx.id, metadata: { amount: amountRaw.toString(), fee: feeRaw.toString(), toAddress, walletType: walletTypeCode, network, }, }); let blockchainTxId = null; try { const privateKey = (0, hdWallet_1.decryptPrivateKey)(hotWallet.encrypted_private_key); await transactionRepository.updateStatus(tx.id, 'broadcasting'); if (railWalletType.network === 'TRON') { const trc20Contract = config_1.config.blockchain.tron.usdtTrc20Contract || railWalletType.contract_address; if (!trc20Contract) throw new Error('USDT TRC20 contract not configured'); blockchainTxId = await tronService.sendTrc20(privateKey, trc20Contract, toAddress, amountRaw); } else if (railWalletType.network === 'BSC') { const contract = bscService.resolveUsdtContract(railWalletType.contract_address); const chainAmount = (0, usdtUnits_1.scaleLedgerToChain)(amountRaw, usdtUnits_1.BEP20_USDT_DECIMALS); blockchainTxId = await bscService.sendUsdt(privateKey, contract, toAddress, chainAmount); } else if (railWalletType.network === 'POLYGON') { blockchainTxId = await polygonService.sendUsdc(privateKey, toAddress, amountRaw); } else { throw new Error('Unsupported network'); } await transactionRepository.updateStatus(tx.id, 'confirming', 0, blockchainTxId); try { await ledgerRepository.finalizeWithdrawalFromLocked(account.id, totalDebit, tx.id); await withdrawalLockRepository.deleteByTransactionId(tx.id); await transactionRepository.updateStatus(tx.id, 'completed', 1); } catch (ledgerErr) { await transactionRepository.updateStatus(tx.id, 'ledger_finalize_failed', 1, blockchainTxId); await (0, securityService_1.raiseAlert)({ userId, severity: 'critical', alertType: 'withdrawal_ledger_finalize_failed', title: 'Withdrawal broadcast succeeded but ledger finalization failed', details: `transaction=${tx.id}, blockchain_tx=${blockchainTxId}, amount=${amountRaw.toString()}, fee=${feeRaw.toString()}. ` + `Funds remain locked; manual reconciliation required.`, metadata: { transactionId: tx.id, blockchainTxId, amount: amountRaw.toString(), fee: feeRaw.toString(), }, suspendUser: true, }); throw ledgerErr; } await auditLogRepository.create({ userId, action: 'withdrawal_completed', resourceType: 'transaction', resourceId: tx.id, metadata: { amount: amountRaw.toString(), fee: feeRaw.toString(), totalDebited: totalDebit.toString(), toAddress, blockchainTxId, network, }, }); (0, userAdminStatsService_1.queueUserAdminStatsRefresh)(userId); try { await referralService.processWithdrawalReferralCommissions({ userId, withdrawalTransactionId: tx.id, withdrawalAmount: amountRaw, walletTypeId: ledgerWalletType.id, }); } catch (referralErr) { console.error('[referral] Withdrawal commission processing failed:', referralErr); } return { transactionId: tx.id, status: 'completed', amount: amountRaw.toString(), fee: feeRaw.toString(), totalDebited: totalDebit.toString(), }; } catch (err) { if (!blockchainTxId) { await ledgerRepository.unlockBalance(account.id, totalDebit); await withdrawalLockRepository.deleteByTransactionId(tx.id); await transactionRepository.updateStatus(tx.id, 'failed'); await auditLogRepository.create({ userId, action: 'withdrawal_failed', resourceType: 'transaction', resourceId: tx.id, metadata: { error: String(err) }, }); (0, userAdminStatsService_1.queueUserAdminStatsRefresh)(userId); } if (err instanceof securityService_1.SecurityBlockedError) throw err; throw err; } } //# sourceMappingURL=withdrawalService.js.map