games_app/backend/src/controllers/treasuryController.ts

280 lines
10 KiB
TypeScript

import { Response } from 'express';
import { AuthRequest } from '../middleware/auth';
import * as treasuryService from '../services/treasuryService';
import * as fundApprovalService from '../services/fundApprovalService';
import { createSweepBatchApprovalRequests } from '../services/sweepBatchService';
export async function getOverview(_req: AuthRequest, res: Response): Promise<void> {
try {
const overview = await treasuryService.getTreasuryOverview();
res.json(overview);
} catch (e) {
res.status(500).json({ error: e instanceof Error ? e.message : 'Failed to load treasury' });
}
}
export async function listColdWallets(_req: AuthRequest, res: Response): Promise<void> {
try {
res.json({ items: await treasuryService.listColdWallets() });
} catch (e) {
res.status(500).json({ error: e instanceof Error ? e.message : 'Failed to list cold wallets' });
}
}
export async function setColdWallet(req: AuthRequest, res: Response): Promise<void> {
try {
const { walletTypeId, address, label } = req.body as {
walletTypeId?: number;
address?: string;
label?: string;
};
if (typeof walletTypeId !== 'number' || !address) {
res.status(400).json({ error: 'walletTypeId and address are required' });
return;
}
const row = await treasuryService.setColdWallet({ walletTypeId, address, label });
res.json(row);
} catch (e) {
res.status(400).json({ error: e instanceof Error ? e.message : 'Failed to set cold wallet' });
}
}
export async function listSweeps(req: AuthRequest, res: Response): Promise<void> {
try {
const status = (req.query.status as string) || undefined;
const limit = parseInt((req.query.limit as string) || '50', 10);
const offset = parseInt((req.query.offset as string) || '0', 10);
const result = await treasuryService.listSweeps({ status, limit, offset });
res.json(result);
} catch (e) {
res.status(500).json({ error: e instanceof Error ? e.message : 'Failed to list sweeps' });
}
}
export async function runSweeps(_req: AuthRequest, res: Response): Promise<void> {
try {
// Close open batches → Approvals (sweep_batch) → on-chain execute after super-admin approve.
// (Legacy sweep_manual + unbatchedOnly never saw deposits, which are always batched.)
const batchesSubmitted = await createSweepBatchApprovalRequests();
res.status(202).json({
batchesSubmitted,
message:
batchesSubmitted > 0
? `${batchesSubmitted} sweep batch(es) submitted — approve under Approvals to broadcast to cold`
: 'No open sweep batches ready. Need SWEEP_ENABLED=true, an active cold wallet, and a credited deposit that enqueued a sweep.',
});
} catch (e) {
res.status(400).json({ error: e instanceof Error ? e.message : 'Sweep request failed' });
}
}
export async function requestFunding(req: AuthRequest, res: Response): Promise<void> {
try {
const { walletTypeId, amount, notes } = req.body as {
walletTypeId?: number;
amount?: string | number;
notes?: string;
};
if (typeof walletTypeId !== 'number' || amount == null) {
res.status(400).json({ error: 'walletTypeId and amount are required' });
return;
}
const result = await fundApprovalService.createFundRequest({
operationType: 'treasury_cold_to_hot',
payload: {
walletTypeId,
amountRaw: BigInt(amount).toString(),
notes,
},
requestedBy: req.user!.userId,
});
res.status(202).json({
requestId: result.id,
status: result.status,
message: 'Funding request submitted — pending super-admin approval',
});
} catch (e) {
res.status(400).json({ error: e instanceof Error ? e.message : 'Funding request failed' });
}
}
export async function confirmFunding(req: AuthRequest, res: Response): Promise<void> {
try {
const fundingId = req.params.fundingId;
const { blockchainTxId } = req.body as { blockchainTxId?: string };
if (!blockchainTxId) {
res.status(400).json({ error: 'blockchainTxId is required' });
return;
}
const result = await treasuryService.confirmColdToHotFunding(
req.user!.userId,
fundingId,
blockchainTxId
);
res.json(result);
} catch (e) {
const msg = e instanceof Error ? e.message : 'Confirm failed';
res.status(msg.includes('not found') ? 404 : 400).json({ error: msg });
}
}
export async function listFunding(req: AuthRequest, res: Response): Promise<void> {
try {
const status = (req.query.status as string) || undefined;
const limit = parseInt((req.query.limit as string) || '50', 10);
const offset = parseInt((req.query.offset as string) || '0', 10);
const result = await treasuryService.listFunding({ status, limit, offset });
res.json(result);
} catch (e) {
res.status(500).json({ error: e instanceof Error ? e.message : 'Failed to list funding' });
}
}
export async function cancelFunding(req: AuthRequest, res: Response): Promise<void> {
try {
await treasuryService.cancelFunding(req.params.fundingId);
res.json({ message: 'Cancelled' });
} catch (e) {
res.status(400).json({ error: e instanceof Error ? e.message : 'Cancel failed' });
}
}
export async function previewHotToColdUsdt(req: AuthRequest, res: Response): Promise<void> {
try {
const walletTypeId = parseInt(String(req.query.walletTypeId ?? ''), 10);
if (!Number.isFinite(walletTypeId) || walletTypeId <= 0) {
res.status(400).json({ error: 'walletTypeId is required' });
return;
}
res.json(await treasuryService.previewHotToColdUsdt(walletTypeId));
} catch (e) {
res.status(400).json({ error: e instanceof Error ? e.message : 'Hot→Cold preview failed' });
}
}
export async function requestHotToColdUsdt(req: AuthRequest, res: Response): Promise<void> {
try {
const { walletTypeId, amount, notes } = req.body as {
walletTypeId?: number;
amount?: string | number;
notes?: string;
};
if (typeof walletTypeId !== 'number' || amount == null) {
res.status(400).json({ error: 'walletTypeId and amount are required' });
return;
}
const preview = await treasuryService.previewHotToColdUsdt(walletTypeId);
const amountRaw = BigInt(amount);
if (amountRaw <= 0n) {
res.status(400).json({ error: 'amount must be greater than zero' });
return;
}
if (!preview.gasOk) {
res.status(400).json({ error: preview.gasHint || 'Hot wallet has insufficient native gas' });
return;
}
if (amountRaw > BigInt(preview.maxSendable)) {
res.status(400).json({
error: `Amount exceeds max sendable after USDT reserve. Max: ${preview.maxSendable}`,
});
return;
}
const result = await fundApprovalService.createFundRequest({
operationType: 'treasury_hot_to_cold',
payload: {
walletTypeId,
amountRaw: amountRaw.toString(),
notes,
},
requestedBy: req.user!.userId,
});
res.status(202).json({
requestId: result.id,
status: result.status,
message:
'Hot→Cold USDT submitted — approve under Approvals; the platform will send from hot to cold',
});
} catch (e) {
res.status(400).json({ error: e instanceof Error ? e.message : 'Hot→Cold request failed' });
}
}
export async function listStuckDeposits(_req: AuthRequest, res: Response): Promise<void> {
try {
res.json(await treasuryService.listStuckDeposits());
} catch (e) {
res.status(500).json({ error: e instanceof Error ? e.message : 'Failed to list stuck deposits' });
}
}
export async function scanStuckDeposits(_req: AuthRequest, res: Response): Promise<void> {
try {
res.json(await treasuryService.scanStuckDeposits());
} catch (e) {
res.status(500).json({ error: e instanceof Error ? e.message : 'Stuck-deposit scan failed' });
}
}
export async function previewGasTransfer(req: AuthRequest, res: Response): Promise<void> {
try {
const walletTypeId = parseInt(String(req.query.walletTypeId ?? ''), 10);
if (!Number.isFinite(walletTypeId) || walletTypeId <= 0) {
res.status(400).json({ error: 'walletTypeId is required' });
return;
}
res.json(await treasuryService.previewHotToColdGas(walletTypeId));
} catch (e) {
res.status(400).json({ error: e instanceof Error ? e.message : 'Gas preview failed' });
}
}
export async function requestGasTransfer(req: AuthRequest, res: Response): Promise<void> {
try {
const { walletTypeId, direction, amount, notes } = req.body as {
walletTypeId?: number;
direction?: string;
amount?: string;
notes?: string;
};
if (typeof walletTypeId !== 'number' || !amount || !direction) {
res.status(400).json({ error: 'walletTypeId, direction and amount are required' });
return;
}
if (direction !== 'hot_to_cold' && direction !== 'cold_to_hot') {
res.status(400).json({ error: 'direction must be hot_to_cold or cold_to_hot' });
return;
}
const preview = await treasuryService.previewHotToColdGas(walletTypeId);
const amountRaw = BigInt(amount);
if (amountRaw <= 0n) {
res.status(400).json({ error: 'amount must be greater than zero' });
return;
}
if (direction === 'hot_to_cold' && amountRaw > BigInt(preview.maxSendable)) {
res.status(400).json({
error: `Amount would leave the hot wallet below the gas reserve. Max: ${preview.maxSendable}`,
});
return;
}
const result = await fundApprovalService.createFundRequest({
operationType: direction === 'hot_to_cold' ? 'treasury_hot_to_cold_gas' : 'treasury_cold_to_hot_gas',
payload: {
walletTypeId,
amountRaw: amountRaw.toString(),
notes,
},
requestedBy: req.user!.userId,
});
res.status(202).json({
requestId: result.id,
status: result.status,
message:
direction === 'hot_to_cold'
? 'Gas transfer submitted — approve under Approvals to send native gas from hot to cold'
: 'Gas transfer submitted — after approval, send from MetaMask (cold) to hot, then Confirm tx',
});
} catch (e) {
res.status(400).json({ error: e instanceof Error ? e.message : 'Gas transfer request failed' });
}
}