diff --git a/components/AssetInput/WhaleInput.tsx b/components/AssetInput/WhaleInput.tsx index 345a4f55..6f708ed6 100644 --- a/components/AssetInput/WhaleInput.tsx +++ b/components/AssetInput/WhaleInput.tsx @@ -126,7 +126,10 @@ ref) => { onChange={({ target }) => { onChange({ ...token, - amount: amountInputValidation(target.value), + amount: amountInputValidation( + target.value, + tokenInfo?.decimals + ), }); }} /> diff --git a/util/amountInputValidation.ts b/util/amountInputValidation.ts index fbefc56a..e8e0d875 100644 --- a/util/amountInputValidation.ts +++ b/util/amountInputValidation.ts @@ -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 }