282 lines
9.3 KiB
TypeScript
282 lines
9.3 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';
|
|
|
|
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();
|
|
|
|
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,
|
|
})),
|
|
};
|
|
}
|
|
|
|
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,
|
|
};
|
|
}
|
|
|
|
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
|
|
) {
|
|
if (!blockchainTxId?.trim()) throw new Error('blockchainTxId is required');
|
|
const row = await exchangeFundingRepository.confirmFunding(
|
|
fundingId,
|
|
blockchainTxId.trim(),
|
|
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,
|
|
};
|
|
}
|
|
|
|
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);
|
|
}
|