Skip to content
Open
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: 5 additions & 0 deletions .changeset/hex-tonumber-empty.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"ox": patch
---

Fixed `Hex.toNumber` (and `Bytes.toNumber`, which delegates to it) returning `NaN` for empty hex (`0x`) instead of throwing, consistent with `Hex.toBigInt`.
7 changes: 6 additions & 1 deletion src/core/Hex.ts
Original file line number Diff line number Diff line change
Expand Up @@ -665,7 +665,12 @@ export declare namespace toBytes {
*/
export function toNumber(hex: Hex, options: toNumber.Options = {}): number {
const { signed, size } = options
if (!signed && !size) return Number(hex)
if (!signed && !size) {
const number = Number(hex)
// `Number('0x')` is `NaN`; defer to `toBigInt` so empty hex throws
// instead of silently returning `NaN` (consistent with `Hex.toBigInt`).
if (!Number.isNaN(number)) return number
}
return Number(toBigInt(hex, options))
}

Expand Down
5 changes: 5 additions & 0 deletions src/core/_test/Hex.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -641,6 +641,11 @@ describe('toNumber', () => {
'[Hex.SizeOverflowError: Size cannot exceed `32` bytes. Given size: `64` bytes.]',
)
})

test('error: empty hex', () => {
// Consistent with `Hex.toBigInt('0x')`, which throws. Must not return `NaN`.
expect(() => Hex.toNumber('0x')).toThrow()
})
})

describe('toString', () => {
Expand Down