702 lines
29 KiB
JavaScript
702 lines
29 KiB
JavaScript
"use strict";
|
|
/**
|
|
* Treasury overview and cold ↔ hot funding workflow.
|
|
*/
|
|
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.getTreasuryOverview = getTreasuryOverview;
|
|
exports.setColdWallet = setColdWallet;
|
|
exports.listColdWallets = listColdWallets;
|
|
exports.listSweeps = listSweeps;
|
|
exports.previewHotToColdGas = previewHotToColdGas;
|
|
exports.executeHotToColdGas = executeHotToColdGas;
|
|
exports.previewHotToColdUsdt = previewHotToColdUsdt;
|
|
exports.executeHotToColdUsdt = executeHotToColdUsdt;
|
|
exports.requestColdToHotGasFunding = requestColdToHotGasFunding;
|
|
exports.requestColdToHotFunding = requestColdToHotFunding;
|
|
exports.confirmColdToHotFunding = confirmColdToHotFunding;
|
|
exports.listFunding = listFunding;
|
|
exports.cancelFunding = cancelFunding;
|
|
exports.listStuckDeposits = listStuckDeposits;
|
|
exports.scanStuckDeposits = scanStuckDeposits;
|
|
const config_1 = require("../config");
|
|
const crypto_1 = require("../utils/crypto");
|
|
const walletRepository = __importStar(require("../repositories/walletRepository"));
|
|
const coldWalletRepository = __importStar(require("../repositories/coldWalletRepository"));
|
|
const hotWalletRepository = __importStar(require("../repositories/hotWalletRepository"));
|
|
const depositSweepRepository = __importStar(require("../repositories/depositSweepRepository"));
|
|
const exchangeFundingRepository = __importStar(require("../repositories/exchangeFundingRepository"));
|
|
const settingsRepository = __importStar(require("../repositories/settingsRepository"));
|
|
const tronService = __importStar(require("./blockchain/tronService"));
|
|
const bscService = __importStar(require("./blockchain/bscService"));
|
|
const walletCapabilities_1 = require("./walletCapabilities");
|
|
const gasReserve_1 = require("../utils/gasReserve");
|
|
const depositHdSnapshotRepository = __importStar(require("../repositories/depositHdSnapshotRepository"));
|
|
const hdWallet_1 = require("./hdWallet");
|
|
const ethers_1 = require("ethers");
|
|
/** Extra native reserved so the hot→cold gas tx itself can pay fees. */
|
|
const BSC_NATIVE_TX_BUFFER_WEI = 100000000000000n; // 0.0001 BNB
|
|
const TRON_NATIVE_TX_BUFFER_SUN = 1000000n; // 1 TRX
|
|
/** Human amount for admin messages, e.g. 1100000000000000n wei -> "0.0011". */
|
|
function formatNative(raw, decimals) {
|
|
return ethers_1.ethers.formatUnits(raw, decimals).replace(/\.0$/, '');
|
|
}
|
|
async function readTronTokenBalance(address, contract) {
|
|
try {
|
|
return (await tronService.getTrc20BalanceRaw(address, contract)).toString();
|
|
}
|
|
catch {
|
|
return null;
|
|
}
|
|
}
|
|
async function readTronNativeSun(address) {
|
|
try {
|
|
return (await tronService.getTrxBalanceSun(address)).toString();
|
|
}
|
|
catch {
|
|
return null;
|
|
}
|
|
}
|
|
async function readBscUsdtBalance(address, dbContract) {
|
|
try {
|
|
const contract = bscService.resolveUsdtContract(dbContract);
|
|
return (await bscService.getUsdtBalanceRaw(address, contract)).toString();
|
|
}
|
|
catch {
|
|
return null;
|
|
}
|
|
}
|
|
async function readBscNativeWei(address) {
|
|
try {
|
|
return (await bscService.getNativeBalanceWei(address)).toString();
|
|
}
|
|
catch {
|
|
return null;
|
|
}
|
|
}
|
|
async function getTreasuryOverview() {
|
|
const types = await walletRepository.getWalletTypes();
|
|
const coldWallets = await coldWalletRepository.listColdWallets();
|
|
const hotWallets = await hotWalletRepository.listActiveHotWallets();
|
|
const pendingSweeps = await depositSweepRepository.listSweeps({ status: 'pending', limit: 5 });
|
|
const failedSweeps = await depositSweepRepository.listSweeps({ status: 'failed', limit: 5 });
|
|
const pendingFunding = await exchangeFundingRepository.listFunding({ status: 'pending', limit: 10 });
|
|
const inProgressSweeps = await depositSweepRepository.summarizeInProgressSweeps();
|
|
const settings = await settingsRepository.getSettings();
|
|
const assets = await Promise.all(types.map(async (wt) => {
|
|
const cold = coldWallets.find((c) => c.wallet_type_id === wt.id && c.is_active);
|
|
const hot = hotWallets.find((h) => h.wallet_type_id === wt.id);
|
|
let hotOnChainBalance = null;
|
|
let coldOnChainBalance = null;
|
|
let hotNativeBalance = null;
|
|
let coldNativeBalance = null;
|
|
let nativeSymbol = null;
|
|
let nativeDecimals = null;
|
|
let minNativeForWithdraw = null;
|
|
if (wt.code === walletCapabilities_1.USDT_TRC20_CODE || wt.network === 'TRON') {
|
|
nativeSymbol = 'TRX';
|
|
nativeDecimals = 6;
|
|
minNativeForWithdraw = (0, gasReserve_1.gasReserveRaw)('TRON', settings).toString();
|
|
const contract = config_1.config.blockchain.tron.usdtTrc20Contract || wt.contract_address || '';
|
|
if (hot?.address) {
|
|
if (contract)
|
|
hotOnChainBalance = await readTronTokenBalance(hot.address, contract);
|
|
hotNativeBalance = await readTronNativeSun(hot.address);
|
|
}
|
|
if (cold?.address) {
|
|
if (contract)
|
|
coldOnChainBalance = await readTronTokenBalance(cold.address, contract);
|
|
coldNativeBalance = await readTronNativeSun(cold.address);
|
|
}
|
|
}
|
|
else if (wt.code === walletCapabilities_1.USDT_BEP20_CODE || wt.network === 'BSC') {
|
|
nativeSymbol = 'BNB';
|
|
nativeDecimals = 18;
|
|
minNativeForWithdraw = (0, gasReserve_1.gasReserveRaw)('BSC', settings).toString();
|
|
if (hot?.address) {
|
|
hotOnChainBalance = await readBscUsdtBalance(hot.address, wt.contract_address);
|
|
hotNativeBalance = await readBscNativeWei(hot.address);
|
|
}
|
|
if (cold?.address) {
|
|
coldOnChainBalance = await readBscUsdtBalance(cold.address, wt.contract_address);
|
|
coldNativeBalance = await readBscNativeWei(cold.address);
|
|
}
|
|
}
|
|
const hotNativeOk = hotNativeBalance != null && minNativeForWithdraw != null
|
|
? BigInt(hotNativeBalance) >= BigInt(minNativeForWithdraw)
|
|
: null;
|
|
return {
|
|
walletType: wt,
|
|
coldWallet: cold
|
|
? { id: cold.id, address: cold.address, label: cold.label, isActive: cold.is_active }
|
|
: null,
|
|
hotWallet: hot ? { id: hot.id, address: hot.address, isActive: hot.is_active } : null,
|
|
hotOnChainBalance,
|
|
coldOnChainBalance,
|
|
hotNativeBalance,
|
|
coldNativeBalance,
|
|
nativeSymbol,
|
|
nativeDecimals,
|
|
minNativeForWithdraw,
|
|
hotNativeOk,
|
|
};
|
|
}));
|
|
let stuckDepositAddresses = 0;
|
|
try {
|
|
stuckDepositAddresses = await depositHdSnapshotRepository.countPositive();
|
|
}
|
|
catch (e) {
|
|
console.warn('[treasury] stuck deposit count failed:', e instanceof Error ? e.message : e);
|
|
}
|
|
return {
|
|
sweepEnabled: config_1.config.treasury.sweepEnabled,
|
|
withdrawalsEnabled: settings.allow_withdrawals,
|
|
assets,
|
|
recentPendingSweeps: pendingSweeps.items.length,
|
|
recentFailedSweeps: failedSweeps.items.length,
|
|
inProgressSweeps: {
|
|
count: inProgressSweeps.count,
|
|
totalAmountRaw: inProgressSweeps.totalAmountRaw,
|
|
},
|
|
pendingColdToHotFunding: pendingFunding.items.map((f) => ({
|
|
id: f.id,
|
|
walletTypeId: f.wallet_type_id,
|
|
direction: f.direction,
|
|
amount: f.amount,
|
|
fromAddress: f.from_address,
|
|
toAddress: f.to_address,
|
|
status: f.status,
|
|
createdAt: f.created_at,
|
|
})),
|
|
stuckDepositAddresses,
|
|
};
|
|
}
|
|
async function setColdWallet(input) {
|
|
if (!input.address?.trim())
|
|
throw new Error('address is required');
|
|
const row = await coldWalletRepository.upsertActiveColdWallet({
|
|
walletTypeId: input.walletTypeId,
|
|
address: input.address,
|
|
label: input.label,
|
|
});
|
|
return {
|
|
id: row.id,
|
|
walletTypeId: row.wallet_type_id,
|
|
address: row.address,
|
|
label: row.label,
|
|
isActive: row.is_active,
|
|
};
|
|
}
|
|
async function listColdWallets() {
|
|
const rows = await coldWalletRepository.listColdWallets();
|
|
return rows.map((r) => ({
|
|
id: r.id,
|
|
walletTypeId: r.wallet_type_id,
|
|
address: r.address,
|
|
label: r.label,
|
|
isActive: r.is_active,
|
|
createdAt: r.created_at,
|
|
}));
|
|
}
|
|
async function listSweeps(opts) {
|
|
const result = await depositSweepRepository.listSweeps(opts);
|
|
return {
|
|
items: result.items.map((s) => ({
|
|
id: s.id,
|
|
userId: s.user_id,
|
|
walletTypeId: s.wallet_type_id,
|
|
fromAddress: s.from_address,
|
|
toColdAddress: s.to_cold_address,
|
|
amount: s.amount,
|
|
status: s.status,
|
|
blockchainTxId: s.blockchain_tx_id,
|
|
depositTransactionId: s.deposit_transaction_id,
|
|
errorMessage: s.error_message_encrypted
|
|
? (0, crypto_1.decryptSensitive)(s.error_message_encrypted)
|
|
: null,
|
|
createdAt: s.created_at,
|
|
})),
|
|
total: result.total,
|
|
};
|
|
}
|
|
function assertValidNativeRecipient(network, address) {
|
|
const a = address.trim();
|
|
if (network === 'BSC' || network === 'ETH') {
|
|
try {
|
|
ethers_1.ethers.getAddress(a);
|
|
}
|
|
catch {
|
|
throw new Error('Invalid EVM cold wallet address');
|
|
}
|
|
return;
|
|
}
|
|
if (network === 'TRON') {
|
|
if (!/^T[1-9A-HJ-NP-Za-km-z]{33}$/.test(a)) {
|
|
throw new Error('Invalid TRON cold wallet address');
|
|
}
|
|
return;
|
|
}
|
|
throw new Error(`Unsupported network for gas transfer: ${network}`);
|
|
}
|
|
async function previewHotToColdGas(walletTypeId) {
|
|
const wt = await walletRepository.getWalletTypeById(walletTypeId);
|
|
if (!wt)
|
|
throw new Error('Unknown wallet type');
|
|
const cold = await coldWalletRepository.getActiveColdWallet(walletTypeId);
|
|
const hot = await hotWalletRepository.getActiveHotWallet(walletTypeId);
|
|
if (!cold)
|
|
throw new Error('No active cold wallet for this network');
|
|
if (!hot)
|
|
throw new Error('No active hot wallet for this network');
|
|
assertValidNativeRecipient(wt.network, cold.address);
|
|
let hotNative = 0n;
|
|
let coldNative = 0n;
|
|
const settings = await settingsRepository.getSettings();
|
|
let symbol = 'BNB';
|
|
let decimals = 18;
|
|
let minReserve = (0, gasReserve_1.gasReserveRaw)('BSC', settings);
|
|
let txBuffer = BSC_NATIVE_TX_BUFFER_WEI;
|
|
if (wt.network === 'BSC' || wt.code === walletCapabilities_1.USDT_BEP20_CODE) {
|
|
hotNative = await bscService.getNativeBalanceWei(hot.address);
|
|
coldNative = await bscService.getNativeBalanceWei(cold.address);
|
|
}
|
|
else if (wt.network === 'TRON' || wt.code === walletCapabilities_1.USDT_TRC20_CODE) {
|
|
hotNative = await tronService.getTrxBalanceSun(hot.address);
|
|
coldNative = await tronService.getTrxBalanceSun(cold.address);
|
|
symbol = 'TRX';
|
|
decimals = 6;
|
|
minReserve = (0, gasReserve_1.gasReserveRaw)('TRON', settings);
|
|
txBuffer = TRON_NATIVE_TX_BUFFER_SUN;
|
|
}
|
|
else {
|
|
throw new Error('Gas transfer is only supported for BEP20 (BNB) and TRC20 (TRX)');
|
|
}
|
|
const maxSendable = hotNative > minReserve + txBuffer ? hotNative - minReserve - txBuffer : 0n;
|
|
return {
|
|
walletTypeId,
|
|
network: wt.network,
|
|
symbol,
|
|
decimals,
|
|
fromHot: hot.address,
|
|
toCold: cold.address,
|
|
hotNative: hotNative.toString(),
|
|
coldNative: coldNative.toString(),
|
|
minReserve: minReserve.toString(),
|
|
txBuffer: txBuffer.toString(),
|
|
maxSendable: maxSendable.toString(),
|
|
};
|
|
}
|
|
async function executeHotToColdGas(input) {
|
|
if (input.amountRaw <= 0n)
|
|
throw new Error('Invalid gas amount');
|
|
const preview = await previewHotToColdGas(input.walletTypeId);
|
|
if (input.amountRaw > BigInt(preview.maxSendable)) {
|
|
throw new Error(`Amount leaves the hot wallet below the gas reserve (${preview.symbol}). Max: ${formatNative(BigInt(preview.maxSendable), preview.decimals)} ${preview.symbol}`);
|
|
}
|
|
const hot = await hotWalletRepository.getActiveHotWallet(input.walletTypeId);
|
|
if (!hot)
|
|
throw new Error('No active hot wallet');
|
|
const privateKey = (0, hdWallet_1.decryptPrivateKey)(hot.encrypted_private_key);
|
|
const row = await exchangeFundingRepository.createFunding({
|
|
walletTypeId: input.walletTypeId,
|
|
direction: 'hot_to_cold_gas',
|
|
amount: input.amountRaw,
|
|
fromAddress: preview.fromHot,
|
|
toAddress: preview.toCold,
|
|
notes: input.notes,
|
|
requestedBy: input.requestedBy,
|
|
approvedBy: input.approvedBy,
|
|
});
|
|
let txId;
|
|
try {
|
|
if (preview.symbol === 'BNB') {
|
|
txId = await bscService.sendBnb(privateKey, preview.toCold, input.amountRaw);
|
|
}
|
|
else {
|
|
txId = await tronService.sendTrx(privateKey, preview.toCold, input.amountRaw);
|
|
}
|
|
}
|
|
catch (e) {
|
|
await exchangeFundingRepository.cancelFunding(row.id);
|
|
throw e;
|
|
}
|
|
await exchangeFundingRepository.completeFundingBroadcast(row.id, txId, input.approvedBy);
|
|
return {
|
|
fundingId: row.id,
|
|
blockchainTxId: txId,
|
|
from: preview.fromHot,
|
|
to: preview.toCold,
|
|
amount: input.amountRaw.toString(),
|
|
symbol: preview.symbol,
|
|
message: `Sent ${preview.symbol} from hot to cold`,
|
|
};
|
|
}
|
|
function hotUsdtMinReserveRaw() {
|
|
try {
|
|
return BigInt(config_1.config.treasury.hotUsdtMinReserveRaw || '0');
|
|
}
|
|
catch {
|
|
return 0n;
|
|
}
|
|
}
|
|
/** Preview USDT (or network token) Hot → Cold: balances, gas, maxSendable after reserve. */
|
|
async function previewHotToColdUsdt(walletTypeId) {
|
|
const wt = await walletRepository.getWalletTypeById(walletTypeId);
|
|
if (!wt)
|
|
throw new Error('Unknown wallet type');
|
|
const cold = await coldWalletRepository.getActiveColdWallet(walletTypeId);
|
|
const hot = await hotWalletRepository.getActiveHotWallet(walletTypeId);
|
|
if (!cold)
|
|
throw new Error('No active cold wallet for this network');
|
|
if (!hot)
|
|
throw new Error('No active hot wallet for this network');
|
|
assertValidNativeRecipient(wt.network, cold.address);
|
|
let hotUsdt = 0n;
|
|
let hotNative = 0n;
|
|
let coldUsdt = 0n;
|
|
const settings = await settingsRepository.getSettings();
|
|
let nativeSymbol = 'BNB';
|
|
let nativeDecimals = 18;
|
|
let minNative = (0, gasReserve_1.gasReserveRaw)('BSC', settings);
|
|
let txBuffer = BSC_NATIVE_TX_BUFFER_WEI;
|
|
let tokenContract = '';
|
|
if (wt.network === 'BSC' || wt.code === walletCapabilities_1.USDT_BEP20_CODE) {
|
|
tokenContract = bscService.resolveUsdtContract(wt.contract_address);
|
|
hotUsdt = await bscService.getUsdtBalanceRaw(hot.address, tokenContract);
|
|
coldUsdt = await bscService.getUsdtBalanceRaw(cold.address, tokenContract);
|
|
hotNative = await bscService.getNativeBalanceWei(hot.address);
|
|
}
|
|
else if (wt.network === 'TRON' || wt.code === walletCapabilities_1.USDT_TRC20_CODE) {
|
|
tokenContract =
|
|
config_1.config.blockchain.tron.usdtTrc20Contract || wt.contract_address || '';
|
|
if (!tokenContract)
|
|
throw new Error('USDT TRC20 contract not configured');
|
|
hotUsdt = await tronService.getTrc20BalanceRaw(hot.address, tokenContract);
|
|
coldUsdt = await tronService.getTrc20BalanceRaw(cold.address, tokenContract);
|
|
hotNative = await tronService.getTrxBalanceSun(hot.address);
|
|
nativeSymbol = 'TRX';
|
|
nativeDecimals = 6;
|
|
minNative = (0, gasReserve_1.gasReserveRaw)('TRON', settings);
|
|
txBuffer = TRON_NATIVE_TX_BUFFER_SUN;
|
|
}
|
|
else {
|
|
throw new Error('Hot→Cold USDT is only supported for BEP20 and TRC20');
|
|
}
|
|
const minUsdtReserve = hotUsdtMinReserveRaw();
|
|
const maxSendable = hotUsdt > minUsdtReserve ? hotUsdt - minUsdtReserve : 0n;
|
|
const gasOk = hotNative >= minNative + txBuffer;
|
|
return {
|
|
walletTypeId,
|
|
network: wt.network,
|
|
walletCode: wt.code,
|
|
tokenSymbol: 'USDT',
|
|
tokenDecimals: wt.decimals,
|
|
tokenContract,
|
|
fromHot: hot.address,
|
|
toCold: cold.address,
|
|
hotUsdt: hotUsdt.toString(),
|
|
coldUsdt: coldUsdt.toString(),
|
|
hotNative: hotNative.toString(),
|
|
nativeSymbol,
|
|
nativeDecimals,
|
|
minNativeForWithdraw: minNative.toString(),
|
|
txFeeBuffer: txBuffer.toString(),
|
|
minUsdtReserve: minUsdtReserve.toString(),
|
|
maxSendable: maxSendable.toString(),
|
|
gasOk,
|
|
gasHint: gasOk
|
|
? null
|
|
: `Hot wallet needs ≥ ${formatNative(minNative + txBuffer, nativeDecimals)} ${nativeSymbol} ` +
|
|
`(withdraw reserve ${formatNative(minNative, nativeDecimals)} + fee buffer ${formatNative(txBuffer, nativeDecimals)}) ` +
|
|
`to broadcast — current balance ${formatNative(hotNative, nativeDecimals)} ${nativeSymbol}.`,
|
|
};
|
|
}
|
|
/** Platform-signed USDT Hot → Cold after Super Admin approval. */
|
|
async function executeHotToColdUsdt(input) {
|
|
if (input.amountRaw <= 0n)
|
|
throw new Error('Invalid USDT amount');
|
|
const preview = await previewHotToColdUsdt(input.walletTypeId);
|
|
if (!preview.gasOk) {
|
|
throw new Error(preview.gasHint || 'Hot wallet has insufficient native gas');
|
|
}
|
|
if (input.amountRaw > BigInt(preview.maxSendable)) {
|
|
throw new Error(`Amount exceeds max sendable after USDT reserve. Max: ${preview.maxSendable}`);
|
|
}
|
|
const hot = await hotWalletRepository.getActiveHotWallet(input.walletTypeId);
|
|
if (!hot)
|
|
throw new Error('No active hot wallet');
|
|
const privateKey = (0, hdWallet_1.decryptPrivateKey)(hot.encrypted_private_key);
|
|
const row = await exchangeFundingRepository.createFunding({
|
|
walletTypeId: input.walletTypeId,
|
|
direction: 'hot_to_cold',
|
|
amount: input.amountRaw,
|
|
fromAddress: preview.fromHot,
|
|
toAddress: preview.toCold,
|
|
notes: input.notes,
|
|
requestedBy: input.requestedBy,
|
|
approvedBy: input.approvedBy,
|
|
});
|
|
let txId;
|
|
try {
|
|
if (preview.network === 'BSC' || preview.walletCode === walletCapabilities_1.USDT_BEP20_CODE) {
|
|
txId = await bscService.sendUsdt(privateKey, preview.tokenContract, preview.toCold, input.amountRaw);
|
|
}
|
|
else {
|
|
txId = await tronService.sendTrc20(privateKey, preview.tokenContract, preview.toCold, input.amountRaw);
|
|
}
|
|
}
|
|
catch (e) {
|
|
await exchangeFundingRepository.cancelFunding(row.id);
|
|
throw e;
|
|
}
|
|
await exchangeFundingRepository.completeFundingBroadcast(row.id, txId, input.approvedBy);
|
|
return {
|
|
fundingId: row.id,
|
|
blockchainTxId: txId,
|
|
from: preview.fromHot,
|
|
to: preview.toCold,
|
|
amount: input.amountRaw.toString(),
|
|
symbol: 'USDT',
|
|
network: preview.network,
|
|
message: 'Sent USDT from hot to cold',
|
|
};
|
|
}
|
|
async function requestColdToHotGasFunding(requestedBy, input) {
|
|
const preview = await previewHotToColdGas(input.walletTypeId);
|
|
if (input.amountRaw <= 0n)
|
|
throw new Error('Invalid amount');
|
|
const row = await exchangeFundingRepository.createFunding({
|
|
walletTypeId: input.walletTypeId,
|
|
direction: 'cold_to_hot_gas',
|
|
amount: input.amountRaw,
|
|
fromAddress: preview.toCold,
|
|
toAddress: preview.fromHot,
|
|
notes: input.notes,
|
|
requestedBy,
|
|
approvedBy: input.approvedBy,
|
|
});
|
|
return {
|
|
id: row.id,
|
|
status: row.status,
|
|
fromAddress: row.from_address,
|
|
toAddress: row.to_address,
|
|
amount: row.amount,
|
|
symbol: preview.symbol,
|
|
message: 'Funding request created. Transfer native gas manually from cold (MetaMask) to hot, then confirm with the blockchain transaction ID.',
|
|
};
|
|
}
|
|
async function requestColdToHotFunding(requestedBy, input) {
|
|
const cold = await coldWalletRepository.getActiveColdWallet(input.walletTypeId);
|
|
const hot = await hotWalletRepository.getActiveHotWallet(input.walletTypeId);
|
|
if (!cold)
|
|
throw new Error('No active cold wallet for this asset');
|
|
if (!hot)
|
|
throw new Error('No active hot wallet for this asset');
|
|
if (input.amountRaw <= 0n)
|
|
throw new Error('Invalid amount');
|
|
const row = await exchangeFundingRepository.createFunding({
|
|
walletTypeId: input.walletTypeId,
|
|
direction: 'cold_to_hot',
|
|
amount: input.amountRaw,
|
|
fromAddress: cold.address,
|
|
toAddress: hot.address,
|
|
notes: input.notes,
|
|
requestedBy,
|
|
approvedBy: input.approvedBy,
|
|
});
|
|
return {
|
|
id: row.id,
|
|
status: row.status,
|
|
fromAddress: row.from_address,
|
|
toAddress: row.to_address,
|
|
amount: row.amount,
|
|
message: 'Funding request created. Transfer manually from cold wallet, then confirm with blockchain transaction ID.',
|
|
};
|
|
}
|
|
async function confirmColdToHotFunding(adminUserId, fundingId, blockchainTxId) {
|
|
const txId = blockchainTxId?.trim();
|
|
if (!txId)
|
|
throw new Error('blockchainTxId is required');
|
|
const funding = await exchangeFundingRepository.findFundingById(fundingId);
|
|
if (!funding || funding.status !== 'pending') {
|
|
throw new Error('Funding request not found or not pending');
|
|
}
|
|
await assertFundingTxMatchesRequest(funding, txId);
|
|
const row = await exchangeFundingRepository.confirmFunding(fundingId, txId, adminUserId);
|
|
if (!row)
|
|
throw new Error('Funding request not found or not pending');
|
|
return {
|
|
id: row.id,
|
|
status: row.status,
|
|
blockchainTxId: row.blockchain_tx_id,
|
|
};
|
|
}
|
|
function addrEq(a, b) {
|
|
if (!a || !b)
|
|
return false;
|
|
const na = a.trim();
|
|
const nb = b.trim();
|
|
if (na.startsWith('0x') || nb.startsWith('0x'))
|
|
return na.toLowerCase() === nb.toLowerCase();
|
|
return na === nb;
|
|
}
|
|
/**
|
|
* Reject Confirm when the pasted tx does not match the pending funding row
|
|
* (wrong amount / addresses / asset) so history stays consistent with chain.
|
|
*/
|
|
async function assertFundingTxMatchesRequest(funding, txId) {
|
|
const walletType = await walletRepository.getWalletTypeById(funding.wallet_type_id);
|
|
if (!walletType)
|
|
throw new Error('Unknown wallet type for funding request');
|
|
const expectedAmount = BigInt(funding.amount);
|
|
const isGas = funding.direction === 'cold_to_hot_gas' || funding.direction === 'hot_to_cold_gas';
|
|
if (walletType.network === 'BSC' || walletType.code === walletCapabilities_1.USDT_BEP20_CODE) {
|
|
if (!/^0x[0-9a-fA-F]{64}$/.test(txId)) {
|
|
throw new Error('Invalid BSC transaction hash (expected 0x + 64 hex chars)');
|
|
}
|
|
const receipt = await bscService.getTransactionReceipt(txId);
|
|
if (!receipt)
|
|
throw new Error('Transaction not found on BSC (wait for confirmation, then retry)');
|
|
if (receipt.status !== 1)
|
|
throw new Error('Transaction failed on-chain');
|
|
if (isGas) {
|
|
const native = await bscService.getNativeTransfer(txId);
|
|
if (!native)
|
|
throw new Error('Transaction not found on BSC (wait for confirmation, then retry)');
|
|
if (native.status !== 1)
|
|
throw new Error('Transaction failed on-chain');
|
|
if (!addrEq(native.from, funding.from_address)) {
|
|
throw new Error(`Tx from ${native.from} does not match funding from ${funding.from_address}`);
|
|
}
|
|
if (!addrEq(native.to, funding.to_address)) {
|
|
throw new Error(`Tx to ${native.to} does not match funding to ${funding.to_address}`);
|
|
}
|
|
if (native.value !== expectedAmount) {
|
|
throw new Error(`On-chain amount ${native.value.toString()} wei does not match funding request ${expectedAmount.toString()} wei. Cancel and recreate the request with the real amount, or send exactly the requested amount.`);
|
|
}
|
|
return;
|
|
}
|
|
const contract = bscService.resolveUsdtContract(walletType.contract_address).toLowerCase();
|
|
const match = receipt.transfers.find((t) => t.contract.toLowerCase() === contract &&
|
|
addrEq(t.from, funding.from_address) &&
|
|
addrEq(t.to, funding.to_address) &&
|
|
t.value === expectedAmount);
|
|
if (!match) {
|
|
const usdtToHot = receipt.transfers.filter((t) => t.contract.toLowerCase() === contract &&
|
|
addrEq(t.to, funding.to_address));
|
|
if (usdtToHot.length === 0) {
|
|
throw new Error('No USDT BEP20 Transfer to the hot wallet found in this tx. Check the hash and destination.');
|
|
}
|
|
const got = usdtToHot.map((t) => t.value.toString()).join(', ');
|
|
throw new Error(`On-chain USDT amount(s) [${got}] do not match funding request ${expectedAmount.toString()} (raw). ` +
|
|
`Send exactly the requested amount, or Cancel this request and create a new one for the amount you actually sent.`);
|
|
}
|
|
return;
|
|
}
|
|
if (walletType.network === 'TRON') {
|
|
// TRON receipt verification is limited here; still require a plausible tx id length.
|
|
if (!/^[0-9a-fA-F]{64}$/.test(txId)) {
|
|
throw new Error('Invalid TRON transaction id (expected 64 hex characters)');
|
|
}
|
|
console.warn(`[treasury] confirm ${funding.id}: TRON tx ${txId} accepted without full amount verify yet`);
|
|
return;
|
|
}
|
|
throw new Error(`Unsupported network for funding confirm: ${walletType.network}`);
|
|
}
|
|
async function listFunding(opts) {
|
|
const result = await exchangeFundingRepository.listFunding(opts);
|
|
return {
|
|
items: result.items.map((f) => ({
|
|
id: f.id,
|
|
walletTypeId: f.wallet_type_id,
|
|
direction: f.direction,
|
|
amount: f.amount,
|
|
status: f.status,
|
|
blockchainTxId: f.blockchain_tx_id,
|
|
fromAddress: f.from_address,
|
|
toAddress: f.to_address,
|
|
notes: f.notes_encrypted ? (0, crypto_1.decryptSensitive)(f.notes_encrypted) : null,
|
|
approvedBy: f.approved_by,
|
|
createdAt: f.created_at,
|
|
})),
|
|
total: result.total,
|
|
};
|
|
}
|
|
async function cancelFunding(fundingId) {
|
|
await exchangeFundingRepository.cancelFunding(fundingId);
|
|
}
|
|
function issueFor(row) {
|
|
if (!row.credited)
|
|
return 'uncredited';
|
|
if (row.sweep_failed)
|
|
return 'sweep_failed';
|
|
if (row.sweep_pending)
|
|
return 'awaiting_sweep_approval';
|
|
return 'credited_still_on_hd';
|
|
}
|
|
async function listStuckDeposits() {
|
|
const rows = await depositHdSnapshotRepository.listPositiveSnapshots();
|
|
return {
|
|
checkedAt: new Date().toISOString(),
|
|
count: rows.length,
|
|
items: rows.map((r) => ({
|
|
userId: r.user_id,
|
|
userLabel: [r.first_name, r.last_name].filter(Boolean).join(' ') || r.user_id.slice(0, 8),
|
|
walletTypeId: r.wallet_type_id,
|
|
walletCode: r.wallet_code,
|
|
walletName: r.wallet_name,
|
|
network: r.network,
|
|
decimals: r.decimals,
|
|
address: r.address,
|
|
onChainAmount: r.on_chain_amount,
|
|
lastCheckedAt: r.last_checked_at,
|
|
issue: issueFor(r),
|
|
})),
|
|
};
|
|
}
|
|
async function scanStuckDeposits() {
|
|
const { processAllDeposits } = await Promise.resolve().then(() => __importStar(require('./depositMonitorService')));
|
|
const { enqueueSweepsForCreditedHdBalances } = await Promise.resolve().then(() => __importStar(require('./sweepService')));
|
|
await processAllDeposits();
|
|
const sweep = await enqueueSweepsForCreditedHdBalances();
|
|
const list = await listStuckDeposits();
|
|
return {
|
|
...list,
|
|
sweepEnabled: sweep.sweepEnabled,
|
|
sweepsEnqueued: sweep.enqueued,
|
|
sweepsAlreadyQueued: sweep.alreadyQueued,
|
|
};
|
|
}
|
|
//# sourceMappingURL=treasuryService.js.map
|