Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Input validation #598

Merged
merged 4 commits into from
Nov 8, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion components/AssetInput/WhaleInput.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,10 @@ ref) => {
onChange={({ target }) => {
onChange({
...token,
amount: amountInputValidation(target.value),
amount: amountInputValidation(
target.value,
tokenInfo?.decimals
),
});
}}
/>
Expand Down
30 changes: 18 additions & 12 deletions util/amountInputValidation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,20 +2,26 @@
* General use validation function for when the user supplies a positive decimal value.
* For example it is used with token and slippage amounts.
* @param input The user supplied value
* @param decimals Optional number of decimals to respect
* @returns Validated string that has invalid patterns removed
*/
export const amountInputValidation = (input: string): string => {
const amount = input.
// Limiting the number of characters to be 32
export const amountInputValidation = (input: string, decimals?: number): string => {
let amount = input.
slice(0, 32).
// Disallowing leading decimal place and multiple zeros before decimal place
replace(/^(?:\.|0{2,}\.)/u, '0.').
// Eliminating multiple leading zeros before the numbers between 1-9
replace(/^0+(?=[0-9])/u, '').
// Remove excess zeros after decimal point
replace(/\.(\d+?)0{2,}$/u, '.$10')
// Ensuring multiple decimal points can't be used
return input.indexOf('.') !== amount.lastIndexOf('.') ?
amount.slice(0, amount.indexOf('.') + 1) + amount.slice(amount.indexOf('.')).replaceAll('.', '')
: amount;
replace(/^0+(?=[0-9])/u, '')

// Handle multiple decimal points
if (input.indexOf('.') !== amount.lastIndexOf('.')) {
amount = amount.slice(0, amount.indexOf('.') + 1) +
amount.slice(amount.indexOf('.')).replaceAll('.', '')
}

// If decimals is specified, just limit decimal places without padding
if (decimals !== undefined && amount.includes('.')) {
const [whole, fraction] = amount.split('.')
amount = `${whole}.${fraction.slice(0, decimals)}`
}

return amount
}
Loading