games_app/backend/dist/services/treasuryService.js

487 lines
19 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.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 hotLiquidityService_1 = require("./hotLiquidityService");
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
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 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 = hotLiquidityService_1.MIN_TRX_SUN_FOR_WITHDRAWAL.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 = hotLiquidityService_1.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_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;
let symbol = 'BNB';
let decimals = 18;
let minReserve = hotLiquidityService_1.MIN_BNB_WEI_FOR_WITHDRAWAL;
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 = hotLiquidityService_1.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(),
};
}
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: ${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_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`,
};
}
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) {
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,
};
}
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