fix: validate amount with isFinite and fix float precision in USDC conversion - #30
fix: validate amount with isFinite and fix float precision in USDC conversion#30memosr wants to merge 2 commits into
Conversation
| @@ -58,6 +58,14 @@ export async function POST(req: NextRequest) { | |||
| // Convert amount to bigint (amount should be in USDC, multiply by 1_000_000) | |||
| const parsedAmount = parseFloat(amount); | |||
There was a problem hiding this comment.
amount comes directly from req.json(), so this still accepts malformed money input before the finite check:
parseFloat("1abc") === 1
Number.isFinite(parseFloat("1abc")) === trueThat means amount: "1abc" passes validation on this deposit endpoint and is treated as 1 USDC. parsedAmount.toFixed(6) also silently rounds over-precision input (0.1234567 -> 0.123457) instead of rejecting it.
The new BigInt conversion fixes the old Math.floor(parsedAmount * 1_000_000) precision path, but the raw input needs a strict decimal gate before parseFloat:
if (typeof amount !== "string" || !/^\d+(?:\.\d{1,6})?$/.test(amount)) {
return NextResponse.json(
{ error: "Amount must be a valid USDC amount" },
{ status: 400 }
);
}Then keep the existing parsedAmount <= 0 check. The same pattern exists in app/api/gateway/transfer/route.ts, so the guard should be applied there too.
|
Thanks. Both issues addressed in dbb9acb: Added strict regex validation Now |
|
Nice, this addresses the issue cleanly. I re-checked the update on I also checked representative cases ( No further concerns from my earlier review. |
Problem
Two related bugs in
deposit/route.tsandtransfer/route.ts:1. NaN bypasses validation and crashes BigInt
2. Float precision loss in financial math
IEEE 754 float multiplication causes precision loss for USDC amounts.
Fix
toFixed(6)produces a stable string like"1.100000"which we split and recombine as integer arithmetic — no float multiplication, no precision loss.Impact
0.1 USDC → 100000not99999)