262 lines
12 KiB
JavaScript
262 lines
12 KiB
JavaScript
"use strict";
|
|
/**
|
|
* On-chain withdrawal service.
|
|
* Locks ledger balance, broadcasts via hot wallet, finalizes ledger atomically after broadcast.
|
|
*/
|
|
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 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");
|
|
async function assertWithdrawalWithinLimits(userId, walletType, amountRaw, feeRaw, settings) {
|
|
const amountUsd = (0, withdrawalLimits_1.rawAmountToUsdApprox)(walletType.code, amountRaw, walletType.decimals);
|
|
const feeUsd = (0, withdrawalLimits_1.rawAmountToUsdApprox)(walletType.code, feeRaw, walletType.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: walletType.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: walletType.code,
|
|
},
|
|
}).catch((e) => console.error('[withdrawal] large withdrawal alert failed:', e));
|
|
}
|
|
}
|
|
/**
|
|
* Submits a withdrawal: locks funds (amount + network fee), sends amount on-chain from hot wallet.
|
|
* If on-chain succeeds but ledger finalization fails, funds stay locked and security is alerted.
|
|
*/
|
|
async function requestWithdrawal(userId, walletTypeCode, toAddress, amountRaw, totpCode) {
|
|
const settings = await settingsRepository.getSettings();
|
|
if (!settings.allow_withdrawals) {
|
|
throw new Error('Withdrawals are disabled by server configuration (enable in Admin → Settings).');
|
|
}
|
|
await authService.assertWithdrawalSecondFactor(userId, totpCode);
|
|
await (0, securityService_1.assertUserCanWithdraw)(userId);
|
|
const feeRaw = (0, withdrawalFee_1.getWithdrawalNetworkFeeRaw)(settings);
|
|
const totalDebit = amountRaw + feeRaw;
|
|
const walletType = await walletRepository.getWalletTypeByCode(walletTypeCode);
|
|
if (!walletType)
|
|
throw new Error('Unknown wallet type');
|
|
if (amountRaw <= 0n)
|
|
throw new Error('Invalid amount');
|
|
await assertWithdrawalWithinLimits(userId, walletType, amountRaw, feeRaw, settings);
|
|
const account = await ledgerRepository.getOrCreateAccount(userId, walletType.id);
|
|
const available = BigInt(account.available_balance);
|
|
const locked = await withdrawalLockRepository.getLockedAmount(userId, walletType.id);
|
|
if (available < totalDebit + locked) {
|
|
throw new Error(feeRaw > 0n
|
|
? 'Insufficient balance (withdrawal amount + network fee)'
|
|
: 'Insufficient balance');
|
|
}
|
|
await ledgerRepository.lockBalance(account.id, totalDebit);
|
|
(0, userAdminStatsService_1.queueUserAdminStatsRefresh)(userId);
|
|
const tx = await transactionRepository.create({
|
|
userId,
|
|
walletTypeId: walletType.id,
|
|
type: 'withdrawal',
|
|
amount: amountRaw,
|
|
fee: feeRaw,
|
|
status: 'pending',
|
|
toAddress,
|
|
requiredConfirmations: walletType.network === 'TRON'
|
|
? config_1.config.blockchain.tron.confirmations
|
|
: config_1.config.blockchain.polygon.confirmations,
|
|
});
|
|
await withdrawalLockRepository.create({
|
|
userId,
|
|
walletTypeId: walletType.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,
|
|
},
|
|
});
|
|
let blockchainTxId = null;
|
|
try {
|
|
const hotWallet = await hotWalletRepository.getActiveHotWallet(walletType.id);
|
|
if (!hotWallet)
|
|
throw new Error('Withdrawal temporarily unavailable');
|
|
const privateKey = (0, hdWallet_1.decryptPrivateKey)(hotWallet.encrypted_private_key);
|
|
await transactionRepository.updateStatus(tx.id, 'broadcasting');
|
|
if (walletType.network === 'TRON') {
|
|
const trc20Contract = walletType.code === 'USDT_TRC20' && config_1.config.blockchain.tron.usdtTrc20Contract
|
|
? config_1.config.blockchain.tron.usdtTrc20Contract
|
|
: walletType.contract_address;
|
|
if (trc20Contract) {
|
|
blockchainTxId = await tronService.sendTrc20(privateKey, trc20Contract, toAddress, amountRaw);
|
|
}
|
|
else {
|
|
blockchainTxId = await tronService.sendTrx(privateKey, toAddress, amountRaw);
|
|
}
|
|
}
|
|
else if (walletType.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,
|
|
},
|
|
});
|
|
(0, userAdminStatsService_1.queueUserAdminStatsRefresh)(userId);
|
|
try {
|
|
await referralService.processWithdrawalReferralCommissions({
|
|
userId,
|
|
withdrawalTransactionId: tx.id,
|
|
withdrawalAmount: amountRaw,
|
|
walletTypeId: walletType.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
|