games_app/backend/dist/services/treasuryService.js
2026-07-02 09:21:05 +02:00

229 lines
9.2 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.requestColdToHotFunding = requestColdToHotFunding;
exports.confirmColdToHotFunding = confirmColdToHotFunding;
exports.listFunding = listFunding;
exports.cancelFunding = cancelFunding;
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"));
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;
try {
if (hot?.address && wt.network === 'TRON') {
const contract = config_1.config.blockchain.tron.usdtTrc20Contract || wt.contract_address || '';
if (contract) {
hotOnChainBalance = (await tronService.getTrc20BalanceRaw(hot.address, contract)).toString();
}
}
if (cold?.address && wt.network === 'TRON') {
const contract = config_1.config.blockchain.tron.usdtTrc20Contract || wt.contract_address || '';
if (contract) {
coldOnChainBalance = (await tronService.getTrc20BalanceRaw(cold.address, contract)).toString();
}
}
}
catch {
// RPC errors — balances stay 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,
};
}));
const settings = await settingsRepository.getSettings();
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,
})),
};
}
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,
};
}
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);
}
//# sourceMappingURL=treasuryService.js.map