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

225 lines
7.2 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';
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;
try {
if (hot?.address && wt.network === 'TRON') {
const contract =
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.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.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);
}