demobank-ui: remove wrong and dangerous usage of float

This commit is contained in:
Florian Dold 2023-02-26 19:16:42 +01:00
parent 3e8562456d
commit 93dc842e97
No known key found for this signature in database
GPG Key ID: D2E4F00F29D02A4B

View File

@ -46,21 +46,27 @@ export function WalletWithdrawForm({
const { i18n } = useTranslationContext();
const { createWithdrawal } = useAccessAPI();
const [amount, setAmount] = useState<string | undefined>("5.00");
const [amountStr, setAmountStr] = useState<string | undefined>("5.00");
const ref = useRef<HTMLInputElement>(null);
useEffect(() => {
if (focus) ref.current?.focus();
}, [focus]);
const amountFloat = amount ? parseFloat(amount) : undefined;
// Beware: We never ever want to treat the amount as a float!
const trimmedAmountStr = amountStr?.trim();
const parsedAmount = trimmedAmountStr
? Amounts.parse(`${currency}:${trimmedAmountStr}`)
: undefined;
const errors = undefinedIfEmpty({
amount: !amountFloat
? i18n.str`required`
: Number.isNaN(amountFloat)
? i18n.str`should be a number`
: amountFloat < 0
? i18n.str`should be positive`
: undefined,
amount:
trimmedAmountStr == null
? i18n.str`required`
: parsedAmount == null
? i18n.str`invalid`
: undefined,
});
return (
<form
@ -92,14 +98,14 @@ export function WalletWithdrawForm({
ref={ref}
id="withdraw-amount"
name="withdraw-amount"
value={amount ?? ""}
value={amountStr ?? ""}
onChange={(e): void => {
setAmount(e.currentTarget.value);
setAmountStr(e.currentTarget.value);
}}
/>
<ShowInputErrorLabel
message={errors?.amount}
isDirty={amount !== undefined}
isDirty={amountStr !== undefined}
/>
</div>
</p>
@ -113,14 +119,11 @@ export function WalletWithdrawForm({
value={i18n.str`Withdraw`}
onClick={async (e) => {
e.preventDefault();
if (!amountFloat) return;
if (!parsedAmount) return;
try {
const result = await createWithdrawal({
amount: Amounts.stringify(
Amounts.fromFloat(amountFloat, currency),
),
amount: Amounts.stringify(parsedAmount),
});
onSuccess(result.data);
} catch (error) {
if (error instanceof RequestError) {