200 lines
6.8 KiB
TypeScript
200 lines
6.8 KiB
TypeScript
/**
|
|
* On-chain withdrawal service.
|
|
* Locks ledger balance, broadcasts via hot wallet, finalizes ledger atomically after broadcast.
|
|
*/
|
|
|
|
import { config } from '../config';
|
|
import { decryptPrivateKey } from './hdWallet';
|
|
import * as ledgerRepository from '../repositories/ledgerRepository';
|
|
import * as transactionRepository from '../repositories/transactionRepository';
|
|
import * as withdrawalLockRepository from '../repositories/withdrawalLockRepository';
|
|
import * as hotWalletRepository from '../repositories/hotWalletRepository';
|
|
import * as auditLogRepository from '../repositories/auditLogRepository';
|
|
import * as walletRepository from '../repositories/walletRepository';
|
|
import * as settingsRepository from '../repositories/settingsRepository';
|
|
import * as tronService from './blockchain/tronService';
|
|
import * as polygonService from './blockchain/polygonService';
|
|
import { getWithdrawalNetworkFeeRaw } from '../utils/withdrawalFee';
|
|
import {
|
|
assertUserCanWithdraw,
|
|
raiseAlert,
|
|
SecurityBlockedError,
|
|
} from './securityService';
|
|
import { queueUserAdminStatsRefresh } from './userAdminStatsService';
|
|
import * as referralService from './referralService';
|
|
|
|
export type WithdrawalResult = {
|
|
transactionId: string;
|
|
status: string;
|
|
amount: string;
|
|
fee: string;
|
|
totalDebited: string;
|
|
};
|
|
|
|
/**
|
|
* 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.
|
|
*/
|
|
export async function requestWithdrawal(
|
|
userId: string,
|
|
walletTypeCode: string,
|
|
toAddress: string,
|
|
amountRaw: bigint,
|
|
_totpCode?: string
|
|
): Promise<WithdrawalResult> {
|
|
const settings = await settingsRepository.getSettings();
|
|
if (!settings.allow_withdrawals) {
|
|
throw new Error('Withdrawals are disabled by server configuration (enable in Admin → Settings).');
|
|
}
|
|
|
|
await assertUserCanWithdraw(userId);
|
|
|
|
const walletType = await walletRepository.getWalletTypeByCode(walletTypeCode);
|
|
if (!walletType) throw new Error('Unknown wallet type');
|
|
if (amountRaw <= 0n) throw new Error('Invalid amount');
|
|
|
|
const feeRaw = getWithdrawalNetworkFeeRaw(settings);
|
|
const totalDebit = amountRaw + feeRaw;
|
|
|
|
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);
|
|
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.blockchain.tron.confirmations
|
|
: config.blockchain.polygon.confirmations,
|
|
});
|
|
|
|
await withdrawalLockRepository.create({
|
|
userId,
|
|
walletTypeId: walletType.id,
|
|
transactionId: tx.id,
|
|
amount: totalDebit,
|
|
});
|
|
|
|
let blockchainTxId: string | null = null;
|
|
|
|
try {
|
|
const hotWallet = await hotWalletRepository.getActiveHotWallet(walletType.id);
|
|
if (!hotWallet) throw new Error('Withdrawal temporarily unavailable');
|
|
|
|
const privateKey = decryptPrivateKey(hotWallet.encrypted_private_key);
|
|
|
|
await transactionRepository.updateStatus(tx.id, 'broadcasting');
|
|
|
|
if (walletType.network === 'TRON') {
|
|
const trc20Contract =
|
|
walletType.code === 'USDT_TRC20' && config.blockchain.tron.usdtTrc20Contract
|
|
? 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 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,
|
|
},
|
|
});
|
|
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) },
|
|
});
|
|
queueUserAdminStatsRefresh(userId);
|
|
}
|
|
if (err instanceof SecurityBlockedError) throw err;
|
|
throw err;
|
|
}
|
|
}
|
|
|
|
export { SecurityBlockedError };
|