After trying to recuparate money from cold wallet5
This commit is contained in:
parent
3dae5f5fd5
commit
0b4fb7f384
@ -154,3 +154,66 @@ export async function scanStuckDeposits(_req: AuthRequest, res: Response): Promi
|
||||
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' });
|
||||
}
|
||||
}
|
||||
|
||||
@ -130,7 +130,8 @@ CREATE TABLE IF NOT EXISTS fund_operation_requests (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
operation_type VARCHAR(64) NOT NULL
|
||||
CHECK (operation_type IN (
|
||||
'ledger_credit', 'treasury_cold_to_hot', 'bonus_pool_fund', 'sweep_manual', 'sweep_batch'
|
||||
'ledger_credit', 'treasury_cold_to_hot', 'bonus_pool_fund', 'sweep_manual', 'sweep_batch',
|
||||
'treasury_hot_to_cold_gas', 'treasury_cold_to_hot_gas'
|
||||
)),
|
||||
status VARCHAR(32) NOT NULL DEFAULT 'pending_approval'
|
||||
CHECK (status IN (
|
||||
@ -150,6 +151,14 @@ CREATE INDEX IF NOT EXISTS idx_fund_operation_requests_status ON fund_operation_
|
||||
CREATE INDEX IF NOT EXISTS idx_fund_operation_requests_type ON fund_operation_requests(operation_type);
|
||||
CREATE INDEX IF NOT EXISTS idx_fund_operation_requests_requested ON fund_operation_requests(requested_by);
|
||||
|
||||
ALTER TABLE fund_operation_requests DROP CONSTRAINT IF EXISTS fund_operation_requests_operation_type_check;
|
||||
ALTER TABLE fund_operation_requests
|
||||
ADD CONSTRAINT fund_operation_requests_operation_type_check
|
||||
CHECK (operation_type IN (
|
||||
'ledger_credit', 'treasury_cold_to_hot', 'bonus_pool_fund', 'sweep_manual', 'sweep_batch',
|
||||
'treasury_hot_to_cold_gas', 'treasury_cold_to_hot_gas'
|
||||
));
|
||||
|
||||
-- Batched automatic deposit sweeps awaiting approval
|
||||
CREATE TABLE IF NOT EXISTS deposit_sweep_batches (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
|
||||
@ -19,7 +19,7 @@ export type ExchangeFundingRow = {
|
||||
|
||||
export async function createFunding(input: {
|
||||
walletTypeId: number;
|
||||
direction: 'cold_to_hot' | 'hot_to_cold';
|
||||
direction: 'cold_to_hot' | 'hot_to_cold' | 'hot_to_cold_gas' | 'cold_to_hot_gas';
|
||||
amount: bigint;
|
||||
fromAddress?: string;
|
||||
toAddress?: string;
|
||||
@ -93,6 +93,21 @@ export async function confirmFunding(
|
||||
return rows[0] ?? null;
|
||||
}
|
||||
|
||||
export async function completeFundingBroadcast(
|
||||
id: string,
|
||||
blockchainTxId: string,
|
||||
approvedBy: string
|
||||
): Promise<ExchangeFundingRow | null> {
|
||||
const rows = await query<ExchangeFundingRow[]>(
|
||||
`UPDATE exchange_funding
|
||||
SET status = 'completed', blockchain_tx_id = $2, approved_by = $3, updated_at = NOW()
|
||||
WHERE id = $1
|
||||
RETURNING *, amount::text`,
|
||||
[id, blockchainTxId, approvedBy]
|
||||
);
|
||||
return rows[0] ?? null;
|
||||
}
|
||||
|
||||
export async function cancelFunding(id: string): Promise<void> {
|
||||
await query(
|
||||
`UPDATE exchange_funding SET status = 'cancelled', updated_at = NOW() WHERE id = $1 AND status = 'pending'`,
|
||||
|
||||
@ -9,7 +9,9 @@ export type FundOperationType =
|
||||
| 'treasury_cold_to_hot'
|
||||
| 'bonus_pool_fund'
|
||||
| 'sweep_manual'
|
||||
| 'sweep_batch';
|
||||
| 'sweep_batch'
|
||||
| 'treasury_hot_to_cold_gas'
|
||||
| 'treasury_cold_to_hot_gas';
|
||||
|
||||
export type FundOperationStatus =
|
||||
| 'pending_approval'
|
||||
|
||||
@ -54,6 +54,7 @@ import {
|
||||
treasuryColdWalletBodySchema,
|
||||
treasuryFundingBodySchema,
|
||||
treasuryFundingConfirmBodySchema,
|
||||
treasuryGasTransferBodySchema,
|
||||
countryRegistrationBodySchema,
|
||||
reportsBulkActionBodySchema,
|
||||
adminUsersExportBodySchema,
|
||||
@ -477,6 +478,8 @@ router.patch('/admin/treasury/funding/:fundingId/confirm', requireRoles('admin')
|
||||
router.delete('/admin/treasury/funding/:fundingId', requireRoles('admin'), requirePermissions('treasury.view'), treasuryController.cancelFunding);
|
||||
router.get('/admin/treasury/stuck-deposits', requireRoles('admin'), requirePermissions('treasury.view'), treasuryController.listStuckDeposits);
|
||||
router.post('/admin/treasury/stuck-deposits/scan', requireRoles('admin'), requirePermissions('treasury.view'), treasuryController.scanStuckDeposits);
|
||||
router.get('/admin/treasury/gas-transfer/preview', requireRoles('admin'), requirePermissions('treasury.view'), treasuryController.previewGasTransfer);
|
||||
router.post('/admin/treasury/gas-transfer', requireRoles('admin'), requirePermissions('treasury.view'), validateBody(treasuryGasTransferBodySchema), treasuryController.requestGasTransfer);
|
||||
|
||||
router.get('/admin/overview', requireRoles('admin'), requirePermissions('reports.admin'), overviewController.getAdminOverview);
|
||||
router.get('/admin/analytics/dashboard', requireRoles('admin'), requirePermissions('reports.admin'), analyticsController.getDashboardAnalytics);
|
||||
|
||||
@ -147,6 +147,33 @@ async function executeApprovedRequest(
|
||||
const processed = await sweepService.executeApprovedBatch(batchId);
|
||||
return { batchId, processed };
|
||||
}
|
||||
case 'treasury_hot_to_cold_gas': {
|
||||
const { walletTypeId, amountRaw, notes } = request.payload as {
|
||||
walletTypeId: number;
|
||||
amountRaw: string;
|
||||
notes?: string;
|
||||
};
|
||||
return treasuryService.executeHotToColdGas({
|
||||
walletTypeId,
|
||||
amountRaw: BigInt(amountRaw),
|
||||
notes,
|
||||
requestedBy: request.requested_by,
|
||||
approvedBy,
|
||||
});
|
||||
}
|
||||
case 'treasury_cold_to_hot_gas': {
|
||||
const { walletTypeId, amountRaw, notes } = request.payload as {
|
||||
walletTypeId: number;
|
||||
amountRaw: string;
|
||||
notes?: string;
|
||||
};
|
||||
return treasuryService.requestColdToHotGasFunding(request.requested_by, {
|
||||
walletTypeId,
|
||||
amountRaw: BigInt(amountRaw),
|
||||
notes,
|
||||
approvedBy,
|
||||
});
|
||||
}
|
||||
default:
|
||||
throw new FundApprovalError(`Unknown operation type: ${request.operation_type}`);
|
||||
}
|
||||
|
||||
@ -15,6 +15,12 @@ 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';
|
||||
import * as depositHdSnapshotRepository from '../repositories/depositHdSnapshotRepository';
|
||||
import { decryptPrivateKey } from './hdWallet';
|
||||
import { ethers } from 'ethers';
|
||||
|
||||
/** Extra native reserved so the hot→cold gas tx itself can pay fees. */
|
||||
const BSC_NATIVE_TX_BUFFER_WEI = 100_000_000_000_000n; // 0.0001 BNB
|
||||
const TRON_NATIVE_TX_BUFFER_SUN = 1_000_000n; // 1 TRX
|
||||
|
||||
async function readTronTokenBalance(address: string, contract: string): Promise<string | null> {
|
||||
try {
|
||||
@ -209,6 +215,158 @@ export async function listSweeps(opts: { status?: string; limit?: number; offset
|
||||
};
|
||||
}
|
||||
|
||||
function assertValidNativeRecipient(network: string, address: string): void {
|
||||
const a = address.trim();
|
||||
if (network === 'BSC' || network === 'ETH') {
|
||||
try {
|
||||
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}`);
|
||||
}
|
||||
|
||||
export async function previewHotToColdGas(walletTypeId: number) {
|
||||
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 = MIN_BNB_WEI_FOR_WITHDRAWAL;
|
||||
let txBuffer = BSC_NATIVE_TX_BUFFER_WEI;
|
||||
if (wt.network === 'BSC' || wt.code === USDT_BEP20_CODE) {
|
||||
hotNative = await bscService.getNativeBalanceWei(hot.address);
|
||||
coldNative = await bscService.getNativeBalanceWei(cold.address);
|
||||
} else if (wt.network === 'TRON' || wt.code === USDT_TRC20_CODE) {
|
||||
hotNative = await tronService.getTrxBalanceSun(hot.address);
|
||||
coldNative = await tronService.getTrxBalanceSun(cold.address);
|
||||
symbol = 'TRX';
|
||||
decimals = 6;
|
||||
minReserve = 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(),
|
||||
};
|
||||
}
|
||||
|
||||
export async function executeHotToColdGas(input: {
|
||||
walletTypeId: number;
|
||||
amountRaw: bigint;
|
||||
notes?: string;
|
||||
requestedBy: string;
|
||||
approvedBy: string;
|
||||
}) {
|
||||
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 = 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: string;
|
||||
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`,
|
||||
};
|
||||
}
|
||||
|
||||
export async function requestColdToHotGasFunding(
|
||||
requestedBy: string,
|
||||
input: {
|
||||
walletTypeId: number;
|
||||
amountRaw: bigint;
|
||||
notes?: string;
|
||||
approvedBy?: string;
|
||||
}
|
||||
) {
|
||||
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.',
|
||||
};
|
||||
}
|
||||
|
||||
export async function requestColdToHotFunding(
|
||||
requestedBy: string,
|
||||
input: {
|
||||
|
||||
@ -97,6 +97,8 @@ export const fundRequestCreateBodySchema = z.object({
|
||||
'bonus_pool_fund',
|
||||
'sweep_manual',
|
||||
'sweep_batch',
|
||||
'treasury_hot_to_cold_gas',
|
||||
'treasury_cold_to_hot_gas',
|
||||
]),
|
||||
payload: z.record(z.string(), z.unknown()),
|
||||
});
|
||||
@ -230,6 +232,13 @@ export const treasuryFundingConfirmBodySchema = z.object({
|
||||
blockchainTxId: z.string().trim().min(1).max(255),
|
||||
});
|
||||
|
||||
export const treasuryGasTransferBodySchema = z.object({
|
||||
walletTypeId: z.number().int().positive(),
|
||||
direction: z.enum(['hot_to_cold', 'cold_to_hot']),
|
||||
amount: z.string().regex(/^\d+$/),
|
||||
notes: z.string().trim().max(2000).optional(),
|
||||
});
|
||||
|
||||
export const countryRegistrationBodySchema = z.object({
|
||||
registrationAllowed: z.boolean(),
|
||||
});
|
||||
|
||||
@ -45,6 +45,8 @@ const OP_TYPE_KEYS = [
|
||||
'bonus_pool_fund',
|
||||
'sweep_manual',
|
||||
'sweep_batch',
|
||||
'treasury_hot_to_cold_gas',
|
||||
'treasury_cold_to_hot_gas',
|
||||
] as const;
|
||||
|
||||
export function ApprovalsPage() {
|
||||
|
||||
@ -38,6 +38,7 @@ import {
|
||||
import AccountBalanceWalletRoundedIcon from '@mui/icons-material/AccountBalanceWalletRounded';
|
||||
import ExpandMoreRoundedIcon from '@mui/icons-material/ExpandMoreRounded';
|
||||
import NorthEastRoundedIcon from '@mui/icons-material/NorthEastRounded';
|
||||
import LocalGasStationRoundedIcon from '@mui/icons-material/LocalGasStationRounded';
|
||||
import ContentCopyRoundedIcon from '@mui/icons-material/ContentCopyRounded';
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
@ -88,6 +89,7 @@ type TreasuryOverview = {
|
||||
fromAddress: string | null;
|
||||
toAddress: string | null;
|
||||
status: string;
|
||||
direction?: string;
|
||||
}>;
|
||||
stuckDepositAddresses?: number;
|
||||
};
|
||||
@ -118,6 +120,20 @@ type StuckDepositRow = {
|
||||
issue: 'uncredited' | 'awaiting_sweep_approval' | 'sweep_failed' | 'credited_still_on_hd';
|
||||
};
|
||||
|
||||
type GasPreview = {
|
||||
walletTypeId: number;
|
||||
network: string;
|
||||
symbol: string;
|
||||
decimals: number;
|
||||
fromHot: string;
|
||||
toCold: string;
|
||||
hotNative: string;
|
||||
coldNative: string;
|
||||
minReserve: string;
|
||||
txBuffer: string;
|
||||
maxSendable: string;
|
||||
};
|
||||
|
||||
/** Precise human → raw (avoids float errors on 18-decimal BEP20). */
|
||||
function humanAmountToRaw(human: string, decimals: number): string {
|
||||
const cleaned = human.replace(/,/g, '').replace(/\s/g, '').trim();
|
||||
@ -250,7 +266,17 @@ export function TreasuryAdminPage() {
|
||||
amountUsdt: '',
|
||||
notes: '',
|
||||
});
|
||||
const [confirmFunding, setConfirmFunding] = useState<{ id: string; txId: string } | null>(null);
|
||||
const [gasForm, setGasForm] = useState({
|
||||
walletTypeId: 0,
|
||||
direction: 'hot_to_cold' as 'hot_to_cold' | 'cold_to_hot',
|
||||
amount: '',
|
||||
notes: '',
|
||||
});
|
||||
const [confirmFunding, setConfirmFunding] = useState<{
|
||||
id: string;
|
||||
txId: string;
|
||||
isGas?: boolean;
|
||||
} | null>(null);
|
||||
const [pendingMsg, setPendingMsg] = useState<string | null>(null);
|
||||
const [fundingError, setFundingError] = useState<string | null>(null);
|
||||
const [copyToast, setCopyToast] = useState<string | null>(null);
|
||||
@ -316,6 +342,7 @@ export function TreasuryAdminPage() {
|
||||
assets[0];
|
||||
if (preferred) {
|
||||
setFundingForm((f) => ({ ...f, walletTypeId: preferred.walletType.id }));
|
||||
setGasForm((f) => (f.walletTypeId ? f : { ...f, walletTypeId: preferred.walletType.id }));
|
||||
}
|
||||
}, [assets, fundingForm.walletTypeId]);
|
||||
|
||||
@ -325,6 +352,19 @@ export function TreasuryAdminPage() {
|
||||
? humanAmountToRaw(fundingForm.amountUsdt, fundingDecimals)
|
||||
: '0';
|
||||
|
||||
const gasPreviewQ = useQuery({
|
||||
queryKey: ['admin-treasury-gas-preview', gasForm.walletTypeId],
|
||||
queryFn: async () => {
|
||||
const res = await api.get<GasPreview>('/api/v1/admin/treasury/gas-transfer/preview', {
|
||||
params: { walletTypeId: gasForm.walletTypeId },
|
||||
});
|
||||
return res.data;
|
||||
},
|
||||
enabled: gasForm.walletTypeId > 0,
|
||||
retry: false,
|
||||
});
|
||||
const gasPreview = gasPreviewQ.data;
|
||||
|
||||
const setColdMut = useMutation({
|
||||
mutationFn: (body: { walletTypeId: number; address: string; label?: string }) =>
|
||||
api.post('/api/v1/admin/treasury/cold-wallets', body),
|
||||
@ -353,6 +393,22 @@ export function TreasuryAdminPage() {
|
||||
},
|
||||
});
|
||||
|
||||
const requestGasMut = useMutation({
|
||||
mutationFn: (body: {
|
||||
walletTypeId: number;
|
||||
direction: 'hot_to_cold' | 'cold_to_hot';
|
||||
amount: string;
|
||||
notes?: string;
|
||||
}) => api.post<{ message?: string }>('/api/v1/admin/treasury/gas-transfer', body),
|
||||
onSuccess: (res) => {
|
||||
setPendingMsg(res.data.message ?? t('admin.treasury.gasPending'));
|
||||
void qc.invalidateQueries({ queryKey: ['admin-treasury-overview'] });
|
||||
void qc.invalidateQueries({ queryKey: ['admin-treasury-gas-preview'] });
|
||||
setGasForm((f) => ({ ...f, amount: '', notes: '' }));
|
||||
setFundingError(null);
|
||||
},
|
||||
});
|
||||
|
||||
const confirmFundingMut = useMutation({
|
||||
mutationFn: ({ id, blockchainTxId }: { id: string; blockchainTxId: string }) =>
|
||||
api.patch(`/api/v1/admin/treasury/funding/${id}/confirm`, { blockchainTxId }),
|
||||
@ -362,6 +418,14 @@ export function TreasuryAdminPage() {
|
||||
},
|
||||
});
|
||||
|
||||
const cancelFundingMut = useMutation({
|
||||
mutationFn: (id: string) => api.delete(`/api/v1/admin/treasury/funding/${id}`),
|
||||
onSuccess: () => {
|
||||
setPendingMsg(t('admin.treasury.fundingCancelled'));
|
||||
void qc.invalidateQueries({ queryKey: ['admin-treasury-overview'] });
|
||||
},
|
||||
});
|
||||
|
||||
const submitFunding = () => {
|
||||
setFundingError(null);
|
||||
if (!fundingForm.walletTypeId) {
|
||||
@ -380,6 +444,33 @@ export function TreasuryAdminPage() {
|
||||
});
|
||||
};
|
||||
|
||||
const submitGasTransfer = () => {
|
||||
setFundingError(null);
|
||||
if (!gasForm.walletTypeId) {
|
||||
setFundingError(t('admin.treasury.fundingSelectNetwork'));
|
||||
return;
|
||||
}
|
||||
if (!gasPreview) {
|
||||
setFundingError(t('admin.treasury.gasPreviewError'));
|
||||
return;
|
||||
}
|
||||
const raw = humanAmountToRaw(gasForm.amount, gasPreview.decimals);
|
||||
if (raw === '0') {
|
||||
setFundingError(t('admin.treasury.invalidGasAmount'));
|
||||
return;
|
||||
}
|
||||
if (gasForm.direction === 'hot_to_cold' && BigInt(raw) > BigInt(gasPreview.maxSendable)) {
|
||||
setFundingError(t('admin.treasury.gasExceedsReserve'));
|
||||
return;
|
||||
}
|
||||
void requestGasMut.mutateAsync({
|
||||
walletTypeId: gasForm.walletTypeId,
|
||||
direction: gasForm.direction,
|
||||
amount: raw,
|
||||
notes: gasForm.notes || undefined,
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<Box sx={{ minWidth: 0 }}>
|
||||
<PageHeader
|
||||
@ -392,6 +483,7 @@ export function TreasuryAdminPage() {
|
||||
void overviewQ.refetch();
|
||||
void sweepsQ.refetch();
|
||||
void stuckQ.refetch();
|
||||
void gasPreviewQ.refetch();
|
||||
}}
|
||||
/>
|
||||
}
|
||||
@ -644,6 +736,172 @@ export function TreasuryAdminPage() {
|
||||
})}
|
||||
</Box>
|
||||
|
||||
{/* Native gas Hot ↔ Cold */}
|
||||
<Card variant="outlined" sx={{ borderRadius: 2.5 }}>
|
||||
<CardContent sx={{ p: { xs: 2, sm: 2.5 } }}>
|
||||
<Stack direction="row" spacing={1} alignItems="center" sx={{ mb: 0.5 }}>
|
||||
<LocalGasStationRoundedIcon color="primary" />
|
||||
<Typography variant="h6" sx={{ fontWeight: 800 }}>
|
||||
{t('admin.treasury.gasTransferTitle')}
|
||||
</Typography>
|
||||
</Stack>
|
||||
<Typography variant="body2" sx={{ opacity: 0.72, mb: 2, maxWidth: 720 }}>
|
||||
{t('admin.treasury.gasTransferSubtitle')}
|
||||
</Typography>
|
||||
<Typography variant="caption" sx={{ opacity: 0.6, display: 'block', mb: 1.5 }}>
|
||||
{gasForm.direction === 'hot_to_cold'
|
||||
? t('admin.treasury.gasTransferStepsHot')
|
||||
: t('admin.treasury.gasTransferStepsCold')}
|
||||
</Typography>
|
||||
<Stack spacing={1.25}>
|
||||
<Stack
|
||||
direction={{ xs: 'column', sm: 'row' }}
|
||||
spacing={1.25}
|
||||
useFlexGap
|
||||
sx={{ flexWrap: 'wrap' }}
|
||||
>
|
||||
<FormControl size="small" sx={{ minWidth: { xs: '100%', sm: 220 } }}>
|
||||
<InputLabel id="treasury-gas-network">{t('admin.treasury.network')}</InputLabel>
|
||||
<Select
|
||||
labelId="treasury-gas-network"
|
||||
label={t('admin.treasury.network')}
|
||||
value={gasForm.walletTypeId || ''}
|
||||
onChange={(e) =>
|
||||
setGasForm((f) => ({ ...f, walletTypeId: Number(e.target.value) }))
|
||||
}
|
||||
>
|
||||
{assets.map((a) => (
|
||||
<MenuItem key={a.walletType.id} value={a.walletType.id}>
|
||||
{a.walletType.name} ({networkLabel(a.walletType.network)})
|
||||
</MenuItem>
|
||||
))}
|
||||
</Select>
|
||||
</FormControl>
|
||||
<FormControl size="small" sx={{ minWidth: { xs: '100%', sm: 280 } }}>
|
||||
<InputLabel id="treasury-gas-dir">{t('admin.treasury.gasDirection')}</InputLabel>
|
||||
<Select
|
||||
labelId="treasury-gas-dir"
|
||||
label={t('admin.treasury.gasDirection')}
|
||||
value={gasForm.direction}
|
||||
onChange={(e) =>
|
||||
setGasForm((f) => ({
|
||||
...f,
|
||||
direction: e.target.value as 'hot_to_cold' | 'cold_to_hot',
|
||||
}))
|
||||
}
|
||||
>
|
||||
<MenuItem value="hot_to_cold">{t('admin.treasury.gasDirHotToCold')}</MenuItem>
|
||||
<MenuItem value="cold_to_hot">{t('admin.treasury.gasDirColdToHot')}</MenuItem>
|
||||
</Select>
|
||||
</FormControl>
|
||||
<TextField
|
||||
size="small"
|
||||
label={t('admin.treasury.gasAmount')}
|
||||
value={gasForm.amount}
|
||||
onChange={(e) => setGasForm((f) => ({ ...f, amount: e.target.value }))}
|
||||
placeholder="0.002"
|
||||
InputProps={{
|
||||
endAdornment: (
|
||||
<InputAdornment position="end">
|
||||
{gasPreview?.symbol ?? 'BNB'}
|
||||
</InputAdornment>
|
||||
),
|
||||
}}
|
||||
helperText={
|
||||
gasPreview
|
||||
? t('admin.treasury.gasMaxSendable', {
|
||||
amount: rawToHuman(gasPreview.maxSendable, gasPreview.decimals),
|
||||
symbol: gasPreview.symbol,
|
||||
})
|
||||
: t('admin.treasury.gasAmountHint')
|
||||
}
|
||||
sx={{ width: { xs: '100%', sm: 180 } }}
|
||||
/>
|
||||
{gasForm.direction === 'hot_to_cold' && gasPreview && BigInt(gasPreview.maxSendable) > 0n && (
|
||||
<Button
|
||||
size="small"
|
||||
onClick={() =>
|
||||
setGasForm((f) => ({
|
||||
...f,
|
||||
amount: rawToHuman(gasPreview.maxSendable, gasPreview.decimals),
|
||||
}))
|
||||
}
|
||||
sx={{ alignSelf: { xs: 'stretch', sm: 'flex-start' }, mt: { sm: 0.25 } }}
|
||||
>
|
||||
{t('admin.treasury.gasUseMax')}
|
||||
</Button>
|
||||
)}
|
||||
<PermissionGate permission="admin.treasury.manage">
|
||||
<Button
|
||||
variant="contained"
|
||||
disabled={requestGasMut.isPending || !gasForm.amount.trim()}
|
||||
onClick={submitGasTransfer}
|
||||
sx={{
|
||||
whiteSpace: 'nowrap',
|
||||
alignSelf: { xs: 'stretch', sm: 'flex-start' },
|
||||
mt: { sm: 0.25 },
|
||||
minHeight: 40,
|
||||
}}
|
||||
>
|
||||
{t('admin.treasury.requestGasTransfer')}
|
||||
</Button>
|
||||
</PermissionGate>
|
||||
</Stack>
|
||||
<TextField
|
||||
size="small"
|
||||
label={t('admin.treasury.notes')}
|
||||
value={gasForm.notes}
|
||||
onChange={(e) => setGasForm((f) => ({ ...f, notes: e.target.value }))}
|
||||
placeholder={t('admin.treasury.notesOptional')}
|
||||
sx={{ maxWidth: 360, width: '100%' }}
|
||||
/>
|
||||
{gasPreviewQ.isError && (
|
||||
<Alert severity="warning">{t('admin.treasury.gasPreviewError')}</Alert>
|
||||
)}
|
||||
{gasPreview && (
|
||||
<Stack spacing={0.5}>
|
||||
<Typography variant="body2" sx={{ opacity: 0.75 }}>
|
||||
{t('admin.treasury.gasHotBalance', {
|
||||
amount: rawToHuman(gasPreview.hotNative, gasPreview.decimals),
|
||||
symbol: gasPreview.symbol,
|
||||
})}
|
||||
</Typography>
|
||||
<Typography variant="body2" sx={{ opacity: 0.75 }}>
|
||||
{t('admin.treasury.gasColdBalance', {
|
||||
amount: rawToHuman(gasPreview.coldNative, gasPreview.decimals),
|
||||
symbol: gasPreview.symbol,
|
||||
})}
|
||||
</Typography>
|
||||
<AddressField
|
||||
label={
|
||||
gasForm.direction === 'hot_to_cold'
|
||||
? t('admin.treasury.hotWallet')
|
||||
: t('admin.treasury.coldWallet')
|
||||
}
|
||||
address={
|
||||
gasForm.direction === 'hot_to_cold' ? gasPreview.fromHot : gasPreview.toCold
|
||||
}
|
||||
network={gasPreview.network}
|
||||
onCopied={notifyCopy}
|
||||
/>
|
||||
<AddressField
|
||||
label={
|
||||
gasForm.direction === 'hot_to_cold'
|
||||
? t('admin.treasury.coldWallet')
|
||||
: t('admin.treasury.hotWallet')
|
||||
}
|
||||
address={
|
||||
gasForm.direction === 'hot_to_cold' ? gasPreview.toCold : gasPreview.fromHot
|
||||
}
|
||||
network={gasPreview.network}
|
||||
onCopied={notifyCopy}
|
||||
/>
|
||||
</Stack>
|
||||
)}
|
||||
</Stack>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Cold → Hot */}
|
||||
<Card variant="outlined" sx={{ borderRadius: 2.5 }}>
|
||||
<CardContent sx={{ p: { xs: 2, sm: 2.5 } }}>
|
||||
@ -773,23 +1031,58 @@ export function TreasuryAdminPage() {
|
||||
<TableBody>
|
||||
{overview.pendingColdToHotFunding.map((f) => {
|
||||
const wt = walletById.get(f.walletTypeId);
|
||||
const dec = wt?.decimals ?? 18;
|
||||
const asset = assets.find((a) => a.walletType.id === f.walletTypeId);
|
||||
const isGas = (f.direction ?? '').includes('_gas');
|
||||
const dec = isGas
|
||||
? (asset?.nativeDecimals ?? (wt?.network === 'TRON' ? 6 : 18))
|
||||
: (wt?.decimals ?? 18);
|
||||
const symbol = isGas ? (asset?.nativeSymbol ?? 'BNB') : 'USDT';
|
||||
const needsConfirm =
|
||||
!isGas || f.direction === 'cold_to_hot_gas';
|
||||
return (
|
||||
<TableRow key={f.id}>
|
||||
<TableCell>{wt ? networkLabel(wt.network) : f.walletTypeId}</TableCell>
|
||||
<TableCell>
|
||||
<Stack direction="row" spacing={0.5} alignItems="center">
|
||||
<span>{wt ? networkLabel(wt.network) : f.walletTypeId}</span>
|
||||
<Chip
|
||||
size="small"
|
||||
label={
|
||||
isGas
|
||||
? t('admin.treasury.fundingKindGas')
|
||||
: t('admin.treasury.fundingKindUsdt')
|
||||
}
|
||||
/>
|
||||
</Stack>
|
||||
</TableCell>
|
||||
<TableCell sx={{ fontWeight: 700 }}>
|
||||
{rawToHuman(f.amount, dec)} USDT
|
||||
{rawToHuman(f.amount, dec)} {symbol}
|
||||
</TableCell>
|
||||
<TableCell sx={{ fontFamily: 'ui-monospace, monospace', fontSize: 12 }}>
|
||||
{shortAddress(f.fromAddress)} → {shortAddress(f.toAddress)}
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<Button
|
||||
size="small"
|
||||
onClick={() => setConfirmFunding({ id: f.id, txId: '' })}
|
||||
>
|
||||
{t('admin.treasury.confirmTx')}
|
||||
</Button>
|
||||
<Stack direction="row" spacing={0.5}>
|
||||
{needsConfirm && (
|
||||
<Button
|
||||
size="small"
|
||||
onClick={() =>
|
||||
setConfirmFunding({ id: f.id, txId: '', isGas })
|
||||
}
|
||||
>
|
||||
{t('admin.treasury.confirmTx')}
|
||||
</Button>
|
||||
)}
|
||||
<PermissionGate permission="admin.treasury.manage">
|
||||
<Button
|
||||
size="small"
|
||||
color="inherit"
|
||||
disabled={cancelFundingMut.isPending}
|
||||
onClick={() => void cancelFundingMut.mutateAsync(f.id)}
|
||||
>
|
||||
{t('common.cancel')}
|
||||
</Button>
|
||||
</PermissionGate>
|
||||
</Stack>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
);
|
||||
@ -1032,7 +1325,9 @@ export function TreasuryAdminPage() {
|
||||
<DialogTitle>{t('admin.treasury.confirmDialogTitle')}</DialogTitle>
|
||||
<DialogContent>
|
||||
<Typography variant="body2" sx={{ opacity: 0.7, mb: 1.5 }}>
|
||||
{t('admin.treasury.confirmDialogHint')}
|
||||
{confirmFunding?.isGas
|
||||
? t('admin.treasury.confirmDialogHintGas')
|
||||
: t('admin.treasury.confirmDialogHint')}
|
||||
</Typography>
|
||||
<TextField
|
||||
fullWidth
|
||||
|
||||
@ -1140,6 +1140,8 @@ export const en = {
|
||||
bonus_pool_fund: 'Bonus pool fund',
|
||||
sweep_manual: 'Manual sweeps',
|
||||
sweep_batch: 'Auto sweep batch',
|
||||
treasury_hot_to_cold_gas: 'Hot → Cold gas (BNB / TRX)',
|
||||
treasury_cold_to_hot_gas: 'Cold → Hot gas (BNB / TRX)',
|
||||
},
|
||||
},
|
||||
users: {
|
||||
@ -1548,6 +1550,31 @@ export const en = {
|
||||
gasLow: 'below min {{min}} {{symbol}} — top up before withdrawals',
|
||||
gasHint:
|
||||
'Native gas (BNB / TRX) is not a platform ledger balance. It stays on the hot wallet on-chain and is checked live before each withdrawal. History: use the explorer link.',
|
||||
gasTransferTitle: 'Move gas between Hot and Cold',
|
||||
gasTransferSubtitle:
|
||||
'Top up the cold wallet with BNB or TRX from the hot wallet (or the reverse) without going through an exchange. Hot → Cold is signed by the platform after approval. Cold → Hot is sent from MetaMask, then confirmed here.',
|
||||
gasTransferStepsHot:
|
||||
'1) Request · 2) Approve · 3) Platform broadcasts from hot to cold',
|
||||
gasTransferStepsCold:
|
||||
'1) Request · 2) Approve · 3) Send from cold (MetaMask) · 4) Confirm tx',
|
||||
gasDirection: 'Route',
|
||||
gasDirHotToCold: 'Hot → Cold (platform sends)',
|
||||
gasDirColdToHot: 'Cold → Hot (manual from MetaMask)',
|
||||
gasAmount: 'Amount',
|
||||
gasAmountHint: 'Enter a human amount, e.g. 0.002',
|
||||
gasMaxSendable: 'Max from hot without starving withdrawals: {{amount}} {{symbol}}',
|
||||
gasHotBalance: 'Hot: {{amount}} {{symbol}}',
|
||||
gasColdBalance: 'Cold: {{amount}} {{symbol}}',
|
||||
gasUseMax: 'Max',
|
||||
requestGasTransfer: 'Request gas transfer',
|
||||
gasPending: 'Gas transfer submitted — pending super-admin approval',
|
||||
invalidGasAmount: 'Enter a valid native amount greater than zero',
|
||||
gasExceedsReserve: 'This amount would leave the hot wallet below the withdrawal gas reserve',
|
||||
gasPreviewError: 'Could not load gas balances for this network',
|
||||
fundingKindUsdt: 'USDT',
|
||||
fundingKindGas: 'Gas',
|
||||
confirmDialogHintGas:
|
||||
'Paste the blockchain transaction hash after you sent BNB or TRX from cold to hot.',
|
||||
viewOnExplorer: 'Explorer',
|
||||
configureCold: 'Configure cold address',
|
||||
coldAddress: 'Cold wallet address',
|
||||
@ -1590,6 +1617,7 @@ export const en = {
|
||||
sweepPending:
|
||||
'Sweep batch(es) submitted — approve under Approvals to broadcast USDT to cold.',
|
||||
fundingPending: 'Funding request submitted — pending super-admin approval',
|
||||
fundingCancelled: 'Funding request cancelled.',
|
||||
stuckTitle: 'USDT still on user deposit addresses',
|
||||
stuckSubtitle:
|
||||
'On-chain USDT that has not reached cold storage yet — missed credits, pending sweeps, or failed sweeps. Updated automatically by the deposit monitor.',
|
||||
|
||||
@ -1156,6 +1156,8 @@ export const fr = {
|
||||
bonus_pool_fund: 'Alimentation pool bonus',
|
||||
sweep_manual: 'Sweeps manuels',
|
||||
sweep_batch: 'Lot de sweeps auto',
|
||||
treasury_hot_to_cold_gas: 'Gas Hot → Cold (BNB / TRX)',
|
||||
treasury_cold_to_hot_gas: 'Gas Cold → Hot (BNB / TRX)',
|
||||
},
|
||||
},
|
||||
users: {
|
||||
@ -1564,6 +1566,31 @@ export const fr = {
|
||||
gasLow: 'sous le minimum {{min}} {{symbol}} — rechargez avant les retraits',
|
||||
gasHint:
|
||||
'Le gas natif (BNB / TRX) n’est pas un solde ledger Prediqo. Il reste on-chain sur le hot wallet et est vérifié en direct avant chaque retrait. Historique : lien explorateur.',
|
||||
gasTransferTitle: 'Déplacer le gas entre Hot et Cold',
|
||||
gasTransferSubtitle:
|
||||
'Alimentez le cold en BNB ou TRX depuis le hot (ou l’inverse) sans passer par un exchange. Hot → Cold est signé par la plateforme après approbation. Cold → Hot est envoyé depuis MetaMask, puis confirmé ici.',
|
||||
gasTransferStepsHot:
|
||||
'1) Demande · 2) Approbation · 3) La plateforme diffuse du hot vers le cold',
|
||||
gasTransferStepsCold:
|
||||
'1) Demande · 2) Approbation · 3) Envoi depuis le cold (MetaMask) · 4) Confirmer la tx',
|
||||
gasDirection: 'Parcours',
|
||||
gasDirHotToCold: 'Hot → Cold (envoi plateforme)',
|
||||
gasDirColdToHot: 'Cold → Hot (manuel depuis MetaMask)',
|
||||
gasAmount: 'Montant',
|
||||
gasAmountHint: 'Saisissez un montant lisible, ex. 0.002',
|
||||
gasMaxSendable: 'Max depuis le hot sans affamer les retraits : {{amount}} {{symbol}}',
|
||||
gasHotBalance: 'Hot : {{amount}} {{symbol}}',
|
||||
gasColdBalance: 'Cold : {{amount}} {{symbol}}',
|
||||
gasUseMax: 'Max',
|
||||
requestGasTransfer: 'Demander le transfert de gas',
|
||||
gasPending: 'Transfert de gas soumis — en attente d’approbation super-admin',
|
||||
invalidGasAmount: 'Saisissez un montant natif valide supérieur à zéro',
|
||||
gasExceedsReserve: 'Ce montant laisserait le hot wallet sous la réserve de gas des retraits',
|
||||
gasPreviewError: 'Impossible de charger les soldes de gas pour ce réseau',
|
||||
fundingKindUsdt: 'USDT',
|
||||
fundingKindGas: 'Gas',
|
||||
confirmDialogHintGas:
|
||||
'Collez le hash de transaction après avoir envoyé du BNB ou TRX du cold vers le hot.',
|
||||
viewOnExplorer: 'Explorateur',
|
||||
configureCold: 'Configurer l’adresse cold',
|
||||
coldAddress: 'Adresse cold wallet',
|
||||
@ -1607,6 +1634,7 @@ export const fr = {
|
||||
sweepPending:
|
||||
'Lot(s) de sweep soumis — approuvez sous Approvals pour diffuser l’USDT vers le cold.',
|
||||
fundingPending: 'Demande de financement soumise — en attente d’approbation super-admin',
|
||||
fundingCancelled: 'Demande de financement annulée.',
|
||||
stuckTitle: 'USDT encore sur les adresses de dépôt',
|
||||
stuckSubtitle:
|
||||
'USDT on-chain qui n’est pas encore en cold — crédits manqués, sweeps en attente ou échoués. Mis à jour par le monitor de dépôts.',
|
||||
|
||||
Loading…
Reference in New Issue
Block a user