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 19a6628
Show file tree
Hide file tree
Showing 4 changed files with 36 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`.
14 changes: 14 additions & 0 deletions src/errors/unit.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { BaseError } from './base.js'

export type ScientificNotationUnsupportedErrorType =
ScientificNotationUnsupportedError & {
name: 'ScientificNotationUnsupportedError'
}
export class ScientificNotationUnsupportedError extends BaseError {
constructor({ value }: { value: string }) {
super(
`Scientific notation is not supported for unit parsing (value: \`${value}\`). Please provide a decimal number.`,
{ name: 'ScientificNotationUnsupportedError' },
)
}
}
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(`
[ScientificNotationUnsupportedError: Scientific notation is not supported for unit parsing (value: \`1.234e5\`). Please provide a decimal number.
Version: viem@x.y.z]
`)
expect(() => parseUnits('1.234e-5', 3)).toThrowErrorMatchingInlineSnapshot(`
[ScientificNotationUnsupportedError: Scientific notation is not supported for unit parsing (value: \`1.234e-5\`). 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 { ScientificNotationUnsupportedError } 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 (value.includes('e'))
throw new ScientificNotationUnsupportedError({ value })

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

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

0 comments on commit 19a6628

Please sign in to comment.