744 lines
25 KiB
TypeScript
744 lines
25 KiB
TypeScript
/**
|
|
* Treasury overview and cold ↔ hot funding workflow.
|
|
*/
|
|
|
|
import { config } from '../config';
|
|
import { decryptSensitive } from '../utils/crypto';
|
|
import * as walletRepository from '../repositories/walletRepository';
|
|
import * as coldWalletRepository from '../repositories/coldWalletRepository';
|
|
import * as hotWalletRepository from '../repositories/hotWalletRepository';
|
|
import * as depositSweepRepository from '../repositories/depositSweepRepository';
|
|
import * as exchangeFundingRepository from '../repositories/exchangeFundingRepository';
|
|
import * as settingsRepository from '../repositories/settingsRepository';
|
|
import * as tronService from './blockchain/tronService';
|
|
import * as bscService from './blockchain/bscService';
|
|
import { USDT_BEP20_CODE, USDT_TRC20_CODE } from './walletCapabilities';
|
|
import { MIN_BNB_WEI_FOR_WITHDRAWAL, MIN_TRX_SUN_FOR_WITHDRAWAL } from './hotLiquidityService';
|
|
import * as depositHdSnapshotRepository from '../repositories/depositHdSnapshotRepository';
|
|
import { decryptPrivateKey } from './hdWallet';
|
|
import { ethers } from 'ethers';
|
|
|
|
/** Extra native reserved so the hot→cold gas tx itself can pay fees. */
|
|
const BSC_NATIVE_TX_BUFFER_WEI = 100_000_000_000_000n; // 0.0001 BNB
|
|
const TRON_NATIVE_TX_BUFFER_SUN = 1_000_000n; // 1 TRX
|
|
|
|
async function readTronTokenBalance(address: string, contract: string): Promise<string | null> {
|
|
try {
|
|
return (await tronService.getTrc20BalanceRaw(address, contract)).toString();
|
|
} catch {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
async function readTronNativeSun(address: string): Promise<string | null> {
|
|
try {
|
|
return (await tronService.getTrxBalanceSun(address)).toString();
|
|
} catch {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
async function readBscUsdtBalance(address: string, dbContract: string | null): Promise<string | null> {
|
|
try {
|
|
const contract = bscService.resolveUsdtContract(dbContract);
|
|
return (await bscService.getUsdtBalanceRaw(address, contract)).toString();
|
|
} catch {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
async function readBscNativeWei(address: string): Promise<string | null> {
|
|
try {
|
|
return (await bscService.getNativeBalanceWei(address)).toString();
|
|
} catch {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
export 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 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: string | null = null;
|
|
let coldOnChainBalance: string | null = null;
|
|
let hotNativeBalance: string | null = null;
|
|
let coldNativeBalance: string | null = null;
|
|
let nativeSymbol: string | null = null;
|
|
let nativeDecimals: number | null = null;
|
|
let minNativeForWithdraw: string | null = null;
|
|
|
|
if (wt.code === USDT_TRC20_CODE || wt.network === 'TRON') {
|
|
nativeSymbol = 'TRX';
|
|
nativeDecimals = 6;
|
|
minNativeForWithdraw = MIN_TRX_SUN_FOR_WITHDRAWAL.toString();
|
|
const contract =
|
|
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 === USDT_BEP20_CODE || wt.network === 'BSC') {
|
|
nativeSymbol = 'BNB';
|
|
nativeDecimals = 18;
|
|
minNativeForWithdraw = MIN_BNB_WEI_FOR_WITHDRAWAL.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,
|
|
};
|
|
})
|
|
);
|
|
|
|
const settings = await settingsRepository.getSettings();
|
|
|
|
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.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,
|
|
};
|
|
}
|
|
|
|
export async function setColdWallet(input: {
|
|
walletTypeId: number;
|
|
address: string;
|
|
label?: string;
|
|
}) {
|
|
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,
|
|
};
|
|
}
|
|
|
|
export 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,
|
|
}));
|
|
}
|
|
|
|
export async function listSweeps(opts: { status?: string; limit?: number; offset?: number }) {
|
|
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
|
|
? decryptSensitive(s.error_message_encrypted)
|
|
: null,
|
|
createdAt: s.created_at,
|
|
})),
|
|
total: result.total,
|
|
};
|
|
}
|
|
|
|
function assertValidNativeRecipient(network: string, address: string): void {
|
|
const a = address.trim();
|
|
if (network === 'BSC' || network === 'ETH') {
|
|
try {
|
|
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}`);
|
|
}
|
|
|
|
export async function previewHotToColdGas(walletTypeId: number) {
|
|
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;
|
|
let symbol = 'BNB';
|
|
let decimals = 18;
|
|
let minReserve = MIN_BNB_WEI_FOR_WITHDRAWAL;
|
|
let txBuffer = BSC_NATIVE_TX_BUFFER_WEI;
|
|
if (wt.network === 'BSC' || wt.code === USDT_BEP20_CODE) {
|
|
hotNative = await bscService.getNativeBalanceWei(hot.address);
|
|
coldNative = await bscService.getNativeBalanceWei(cold.address);
|
|
} else if (wt.network === 'TRON' || wt.code === USDT_TRC20_CODE) {
|
|
hotNative = await tronService.getTrxBalanceSun(hot.address);
|
|
coldNative = await tronService.getTrxBalanceSun(cold.address);
|
|
symbol = 'TRX';
|
|
decimals = 6;
|
|
minReserve = MIN_TRX_SUN_FOR_WITHDRAWAL;
|
|
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(),
|
|
};
|
|
}
|
|
|
|
export async function executeHotToColdGas(input: {
|
|
walletTypeId: number;
|
|
amountRaw: bigint;
|
|
notes?: string;
|
|
requestedBy: string;
|
|
approvedBy: string;
|
|
}) {
|
|
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: ${preview.maxSendable}`
|
|
);
|
|
}
|
|
|
|
const hot = await hotWalletRepository.getActiveHotWallet(input.walletTypeId);
|
|
if (!hot) throw new Error('No active hot wallet');
|
|
const privateKey = 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: string;
|
|
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(): bigint {
|
|
try {
|
|
return BigInt(config.treasury.hotUsdtMinReserveRaw || '0');
|
|
} catch {
|
|
return 0n;
|
|
}
|
|
}
|
|
|
|
/** Preview USDT (or network token) Hot → Cold: balances, gas, maxSendable after reserve. */
|
|
export async function previewHotToColdUsdt(walletTypeId: number) {
|
|
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;
|
|
let nativeSymbol = 'BNB';
|
|
let nativeDecimals = 18;
|
|
let minNative = MIN_BNB_WEI_FOR_WITHDRAWAL;
|
|
let txBuffer = BSC_NATIVE_TX_BUFFER_WEI;
|
|
let tokenContract = '';
|
|
|
|
if (wt.network === 'BSC' || wt.code === 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 === USDT_TRC20_CODE) {
|
|
tokenContract =
|
|
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 = MIN_TRX_SUN_FOR_WITHDRAWAL;
|
|
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 ≥ ${(minNative + txBuffer).toString()} ${nativeSymbol} (withdraw reserve + fee buffer) to broadcast`,
|
|
};
|
|
}
|
|
|
|
/** Platform-signed USDT Hot → Cold after Super Admin approval. */
|
|
export async function executeHotToColdUsdt(input: {
|
|
walletTypeId: number;
|
|
amountRaw: bigint;
|
|
notes?: string;
|
|
requestedBy: string;
|
|
approvedBy: string;
|
|
}) {
|
|
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 = 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: string;
|
|
try {
|
|
if (preview.network === 'BSC' || preview.walletCode === 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',
|
|
};
|
|
}
|
|
|
|
export async function requestColdToHotGasFunding(
|
|
requestedBy: string,
|
|
input: {
|
|
walletTypeId: number;
|
|
amountRaw: bigint;
|
|
notes?: string;
|
|
approvedBy?: string;
|
|
}
|
|
) {
|
|
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.',
|
|
};
|
|
}
|
|
|
|
export async function requestColdToHotFunding(
|
|
requestedBy: string,
|
|
input: {
|
|
walletTypeId: number;
|
|
amountRaw: bigint;
|
|
notes?: string;
|
|
approvedBy?: string;
|
|
}
|
|
) {
|
|
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.',
|
|
};
|
|
}
|
|
|
|
export async function confirmColdToHotFunding(
|
|
adminUserId: string,
|
|
fundingId: string,
|
|
blockchainTxId: string
|
|
) {
|
|
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: string | null | undefined, b: string | null | undefined): boolean {
|
|
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: exchangeFundingRepository.ExchangeFundingRow,
|
|
txId: string
|
|
): Promise<void> {
|
|
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 === 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}`);
|
|
}
|
|
|
|
export async function listFunding(opts: { status?: string; limit?: number; offset?: number }) {
|
|
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 ? decryptSensitive(f.notes_encrypted) : null,
|
|
approvedBy: f.approved_by,
|
|
createdAt: f.created_at,
|
|
})),
|
|
total: result.total,
|
|
};
|
|
}
|
|
|
|
export async function cancelFunding(fundingId: string) {
|
|
await exchangeFundingRepository.cancelFunding(fundingId);
|
|
}
|
|
|
|
export type StuckDepositIssue =
|
|
| 'uncredited'
|
|
| 'awaiting_sweep_approval'
|
|
| 'sweep_failed'
|
|
| 'credited_still_on_hd';
|
|
|
|
function issueFor(row: {
|
|
credited: boolean;
|
|
sweep_pending: boolean;
|
|
sweep_failed: boolean;
|
|
}): StuckDepositIssue {
|
|
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';
|
|
}
|
|
|
|
export 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),
|
|
})),
|
|
};
|
|
}
|
|
|
|
export async function scanStuckDeposits() {
|
|
const { processAllDeposits } = await import('./depositMonitorService');
|
|
const { enqueueSweepsForCreditedHdBalances } = await import('./sweepService');
|
|
await processAllDeposits();
|
|
const sweep = await enqueueSweepsForCreditedHdBalances();
|
|
const list = await listStuckDeposits();
|
|
return {
|
|
...list,
|
|
sweepEnabled: sweep.sweepEnabled,
|
|
sweepsEnqueued: sweep.enqueued,
|
|
sweepsAlreadyQueued: sweep.alreadyQueued,
|
|
};
|
|
}
|