From 0b4fb7f384e133365ca1b67e8e31f63f985a5156 Mon Sep 17 00:00:00 2001 From: Your Name Date: Fri, 28 Aug 2026 15:41:51 +0200 Subject: [PATCH] After trying to recuparate money from cold wallet5 --- backend/src/controllers/treasuryController.ts | 63 ++++ backend/src/db/schema.sql | 11 +- .../repositories/exchangeFundingRepository.ts | 17 +- .../fundOperationRequestRepository.ts | 4 +- backend/src/routes/index.ts | 3 + backend/src/services/fundApprovalService.ts | 27 ++ backend/src/services/treasuryService.ts | 158 +++++++++ backend/src/validation/adminSchemas.ts | 9 + .../src/features/approvals/ApprovalsPage.tsx | 2 + .../features/treasury/TreasuryAdminPage.tsx | 317 +++++++++++++++++- prediqo_web/src/shared/i18n/locales/en.ts | 28 ++ prediqo_web/src/shared/i18n/locales/fr.ts | 28 ++ 12 files changed, 653 insertions(+), 14 deletions(-) diff --git a/backend/src/controllers/treasuryController.ts b/backend/src/controllers/treasuryController.ts index 4420ff70..c3bf8f9d 100644 --- a/backend/src/controllers/treasuryController.ts +++ b/backend/src/controllers/treasuryController.ts @@ -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 { + 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 { + 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' }); + } +} diff --git a/backend/src/db/schema.sql b/backend/src/db/schema.sql index 5e05877c..c07852c4 100644 --- a/backend/src/db/schema.sql +++ b/backend/src/db/schema.sql @@ -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(), diff --git a/backend/src/repositories/exchangeFundingRepository.ts b/backend/src/repositories/exchangeFundingRepository.ts index 00387745..48cae90d 100644 --- a/backend/src/repositories/exchangeFundingRepository.ts +++ b/backend/src/repositories/exchangeFundingRepository.ts @@ -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 { + const rows = await query( + `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 { await query( `UPDATE exchange_funding SET status = 'cancelled', updated_at = NOW() WHERE id = $1 AND status = 'pending'`, diff --git a/backend/src/repositories/fundOperationRequestRepository.ts b/backend/src/repositories/fundOperationRequestRepository.ts index 2db11364..ef2e34d6 100644 --- a/backend/src/repositories/fundOperationRequestRepository.ts +++ b/backend/src/repositories/fundOperationRequestRepository.ts @@ -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' diff --git a/backend/src/routes/index.ts b/backend/src/routes/index.ts index 075a80a6..a4be0dfa 100644 --- a/backend/src/routes/index.ts +++ b/backend/src/routes/index.ts @@ -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); diff --git a/backend/src/services/fundApprovalService.ts b/backend/src/services/fundApprovalService.ts index 9a200847..44a85b6a 100644 --- a/backend/src/services/fundApprovalService.ts +++ b/backend/src/services/fundApprovalService.ts @@ -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}`); } diff --git a/backend/src/services/treasuryService.ts b/backend/src/services/treasuryService.ts index 366ddfca..3787bda2 100644 --- a/backend/src/services/treasuryService.ts +++ b/backend/src/services/treasuryService.ts @@ -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 { 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: { diff --git a/backend/src/validation/adminSchemas.ts b/backend/src/validation/adminSchemas.ts index bb2087ff..fe15eefb 100644 --- a/backend/src/validation/adminSchemas.ts +++ b/backend/src/validation/adminSchemas.ts @@ -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(), }); diff --git a/prediqo_web/src/features/approvals/ApprovalsPage.tsx b/prediqo_web/src/features/approvals/ApprovalsPage.tsx index 9236594d..9f31501b 100644 --- a/prediqo_web/src/features/approvals/ApprovalsPage.tsx +++ b/prediqo_web/src/features/approvals/ApprovalsPage.tsx @@ -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() { diff --git a/prediqo_web/src/features/treasury/TreasuryAdminPage.tsx b/prediqo_web/src/features/treasury/TreasuryAdminPage.tsx index 1d38fd89..84b32059 100644 --- a/prediqo_web/src/features/treasury/TreasuryAdminPage.tsx +++ b/prediqo_web/src/features/treasury/TreasuryAdminPage.tsx @@ -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(null); const [fundingError, setFundingError] = useState(null); const [copyToast, setCopyToast] = useState(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('/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 ( } @@ -644,6 +736,172 @@ export function TreasuryAdminPage() { })} + {/* Native gas Hot ↔ Cold */} + + + + + + {t('admin.treasury.gasTransferTitle')} + + + + {t('admin.treasury.gasTransferSubtitle')} + + + {gasForm.direction === 'hot_to_cold' + ? t('admin.treasury.gasTransferStepsHot') + : t('admin.treasury.gasTransferStepsCold')} + + + + + {t('admin.treasury.network')} + + + + {t('admin.treasury.gasDirection')} + + + setGasForm((f) => ({ ...f, amount: e.target.value }))} + placeholder="0.002" + InputProps={{ + endAdornment: ( + + {gasPreview?.symbol ?? 'BNB'} + + ), + }} + 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 && ( + + )} + + + + + setGasForm((f) => ({ ...f, notes: e.target.value }))} + placeholder={t('admin.treasury.notesOptional')} + sx={{ maxWidth: 360, width: '100%' }} + /> + {gasPreviewQ.isError && ( + {t('admin.treasury.gasPreviewError')} + )} + {gasPreview && ( + + + {t('admin.treasury.gasHotBalance', { + amount: rawToHuman(gasPreview.hotNative, gasPreview.decimals), + symbol: gasPreview.symbol, + })} + + + {t('admin.treasury.gasColdBalance', { + amount: rawToHuman(gasPreview.coldNative, gasPreview.decimals), + symbol: gasPreview.symbol, + })} + + + + + )} + + + + {/* Cold → Hot */} @@ -773,23 +1031,58 @@ export function TreasuryAdminPage() { {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 ( - {wt ? networkLabel(wt.network) : f.walletTypeId} + + + {wt ? networkLabel(wt.network) : f.walletTypeId} + + + - {rawToHuman(f.amount, dec)} USDT + {rawToHuman(f.amount, dec)} {symbol} {shortAddress(f.fromAddress)} → {shortAddress(f.toAddress)} - + + {needsConfirm && ( + + )} + + + + ); @@ -1032,7 +1325,9 @@ export function TreasuryAdminPage() { {t('admin.treasury.confirmDialogTitle')} - {t('admin.treasury.confirmDialogHint')} + {confirmFunding?.isGas + ? t('admin.treasury.confirmDialogHintGas') + : t('admin.treasury.confirmDialogHint')}