Skip to content

Commit

Permalink
chore: add error handling in parseUnits for scientific notation
Browse files Browse the repository at this point in the history
  • Loading branch information
jxom committed Sep 7, 2024
1 parent 615d39c commit 7c4f2a9
Show file tree
Hide file tree
Showing 4 changed files with 35 additions and 0 deletions.
5 changes: 5 additions & 0 deletions .changeset/real-turkeys-bathe.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"viem": patch
---

Added error handling if scientific notation is passed to `parseUnits`.
13 changes: 13 additions & 0 deletions src/errors/unit.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { BaseError } from './base.js'

export type InvalidDecimalNumberErrorType = InvalidDecimalNumberError & {
name: 'InvalidDecimalNumberError'
}
export class InvalidDecimalNumberError extends BaseError {
constructor({ value }: { value: string }) {
super(
`Number \`${value}\` is not supported for unit parsing. Please provide a decimal number.`,
{ name: 'InvalidDecimalNumberError' },
)
}
}
13 changes: 13 additions & 0 deletions src/utils/unit/parseUnits.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -100,3 +100,16 @@ test('decimals < fraction length', () => {
expect(parseUnits('69.59000000059', 9)).toMatchInlineSnapshot('69590000001n')
expect(parseUnits('69.59000002359', 9)).toMatchInlineSnapshot('69590000024n')
})

test('error: scientific notation', () => {
expect(() => parseUnits('1.234e5', 3)).toThrowErrorMatchingInlineSnapshot(`
[InvalidDecimalNumberError: Number \`1.234e5\` is not supported for unit parsing. Please provide a decimal number.
Version: viem@x.y.z]
`)
expect(() => parseUnits('1.234e-5', 3)).toThrowErrorMatchingInlineSnapshot(`
[InvalidDecimalNumberError: Number \`1.234e-5\` is not supported for unit parsing. Please provide a decimal number.
Version: viem@x.y.z]
`)
})
4 changes: 4 additions & 0 deletions src/utils/unit/parseUnits.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { InvalidDecimalNumberError } from '../../errors/unit.js'
import type { ErrorType } from '../../errors/utils.js'

export type ParseUnitsErrorType = ErrorType
Expand All @@ -14,6 +15,9 @@ export type ParseUnitsErrorType = ErrorType
* // 420000000000n
*/
export function parseUnits(value: string, decimals: number) {
if (!/^(-?)([0-9]*)\.?([0-9]*)$/.test(value))
throw new InvalidDecimalNumberError({ value })

let [integer, fraction = '0'] = value.split('.')

const negative = integer.startsWith('-')
Expand Down

0 comments on commit 7c4f2a9

Please sign in to comment.