games_app/prediqo_web/src/features/wallet/components/TransferDialog.tsx

206 lines
6.7 KiB
TypeScript

/**
* In-app transfer dialog for the wallet page.
* Sends funds to another Prediqo user by email with optional 2FA.
*/
import {
Alert,
Button,
Dialog,
DialogActions,
DialogContent,
DialogTitle,
FormControl,
InputLabel,
MenuItem,
Select,
Stack,
TextField,
Typography,
} from '@mui/material';
import { useEffect, useMemo, useState } from 'react';
import { useQueryClient } from '@tanstack/react-query';
import { Trans, useTranslation } from 'react-i18next';
import { api } from '../../../shared/services/api';
import type { BalanceEntry } from '../types';
import { networkLabel } from '../utils/coinDisplay';
import { formatBalance, humanToRaw, shortSymbol } from '../utils/walletFormat';
type TransferDialogProps = {
open: boolean;
balances: BalanceEntry[];
initialAsset?: string | null;
onClose: () => void;
onSuccess?: (message: string) => void;
onError?: (message: string) => void;
};
/**
* Modal to transfer crypto to another user by email address.
*/
export function TransferDialog({
open,
balances,
initialAsset,
onClose,
onSuccess,
onError,
}: TransferDialogProps) {
const { t } = useTranslation();
const qc = useQueryClient();
const [asset, setAsset] = useState('');
const [toEmail, setToEmail] = useState('');
const [amount, setAmount] = useState('');
const [totpCode, setTotpCode] = useState('');
const [confirmOpen, setConfirmOpen] = useState(false);
const [submitting, setSubmitting] = useState(false);
useEffect(() => {
if (open) {
setAsset(initialAsset ?? balances[0]?.walletType.code ?? '');
setToEmail('');
setAmount('');
setTotpCode('');
setConfirmOpen(false);
}
}, [open, initialAsset, balances]);
const selected = useMemo(
() => balances.find((b) => b.walletType.code === asset),
[balances, asset]
);
const submit = async () => {
if (!selected) return;
setSubmitting(true);
try {
await api.post('/api/v1/transfer', {
toEmail: toEmail.trim().toLowerCase(),
walletType: asset,
amount: humanToRaw(amount, selected.walletType.decimals),
totpCode: totpCode.trim() || undefined,
});
await qc.invalidateQueries({ queryKey: ['wallet-balances'] });
await qc.invalidateQueries({ queryKey: ['wallet-transactions'] });
onSuccess?.(t('wallet.transferDialog.success'));
onClose();
} catch (e: unknown) {
const err = e as { response?: { data?: { error?: string } }; message?: string };
onError?.(err?.response?.data?.error ?? err?.message ?? t('common.transferFailed'));
} finally {
setSubmitting(false);
setConfirmOpen(false);
}
};
const canProceed =
!!selected &&
toEmail.trim().length > 3 &&
Number(amount) > 0 &&
totpCode.trim().length === 6;
return (
<>
<Dialog open={open && !confirmOpen} onClose={onClose} maxWidth="sm" fullWidth>
<DialogTitle sx={{ fontWeight: 900 }}>{t('wallet.transferDialog.title')}</DialogTitle>
<DialogContent>
<Stack spacing={2} sx={{ pt: 0.5 }}>
<Typography variant="body2" sx={{ opacity: 0.75 }}>
{t('wallet.transferDialog.subtitle')}
</Typography>
<TextField
label={t('wallet.transferDialog.recipientEmail')}
type="email"
fullWidth
value={toEmail}
onChange={(e) => setToEmail(e.target.value)}
autoComplete="email"
/>
<FormControl fullWidth>
<InputLabel id="transfer-asset-label">{t('common.asset')}</InputLabel>
<Select
labelId="transfer-asset-label"
label={t('common.asset')}
value={asset}
onChange={(e) => setAsset(e.target.value)}
>
{balances.map((b) => (
<MenuItem key={b.walletType.code} value={b.walletType.code}>
{b.walletType.name} — {networkLabel(b.walletType.code)}
</MenuItem>
))}
</Select>
</FormControl>
<Alert severity="info" sx={{ borderRadius: 2 }}>
<Trans
i18nKey="wallet.transferDialog.networkAuto"
values={{ network: networkLabel(asset) }}
components={{ b: <b /> }}
/>
</Alert>
<TextField
label={t('common.amount')}
fullWidth
value={amount}
onChange={(e) => setAmount(e.target.value)}
inputMode="decimal"
helperText={
selected
? t('wallet.transferDialog.available', {
amount: formatBalance(selected.available, selected.walletType.decimals, asset),
})
: undefined
}
/>
<TextField
label={t('wallet.transferDialog.totpCode')}
fullWidth
value={totpCode}
onChange={(e) => setTotpCode(e.target.value.replace(/\D/g, '').slice(0, 6))}
inputMode="numeric"
placeholder={t('wallet.transferDialog.totpPlaceholder')}
helperText={t('wallet.transferDialog.totpRequired')}
/>
</Stack>
</DialogContent>
<DialogActions sx={{ px: 3, pb: 2 }}>
<Button onClick={onClose}>{t('common.cancel')}</Button>
<Button variant="contained" disabled={!canProceed} onClick={() => setConfirmOpen(true)}>
{t('wallet.transferDialog.review')}
</Button>
</DialogActions>
</Dialog>
<Dialog open={confirmOpen} onClose={() => setConfirmOpen(false)} maxWidth="xs" fullWidth>
<DialogTitle sx={{ fontWeight: 900 }}>{t('wallet.transferDialog.confirmTitle')}</DialogTitle>
<DialogContent>
<Stack spacing={1} sx={{ pt: 0.5 }}>
<Typography>
<Trans
i18nKey="wallet.transferDialog.confirmBody"
values={{ amount, asset: shortSymbol(asset), email: toEmail }}
components={{ b: <b /> }}
/>
</Typography>
<Typography variant="body2" sx={{ opacity: 0.7 }}>
{t('wallet.transferDialog.irreversible')}
</Typography>
</Stack>
</DialogContent>
<DialogActions sx={{ px: 3, pb: 2 }}>
<Button onClick={() => setConfirmOpen(false)} disabled={submitting}>
{t('common.back')}
</Button>
<Button variant="contained" onClick={submit} disabled={submitting}>
{submitting ? t('common.sending') : t('common.confirm')}
</Button>
</DialogActions>
</Dialog>
</>
);
}