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

Fixed signed `hexToBigInt` and `hexToNumber` calls with odd-length hex values.
9 changes: 9 additions & 0 deletions src/utils/encoding/fromHex.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,10 @@ describe('converts hex to number', () => {
expect(hexToNumber('0x00027760a62ec2ac', { signed: true })).toBe(
694206942069420,
)

// odd-length hex
expect(hexToNumber('0x0', { signed: true })).toBe(0)
expect(hexToNumber('0x1a4', { signed: true })).toBe(420)
})

test('args: size', () => {
Expand Down Expand Up @@ -129,6 +133,11 @@ describe('converts hex to bigint', () => {
{ signed: true },
),
).toBe(-12312312312312312412n)

// odd-length hex
expect(hexToBigInt('0x0', { signed: true })).toBe(0n)
expect(hexToBigInt('0xf', { signed: true })).toBe(15n)
expect(hexToBigInt('0x1a4', { signed: true })).toBe(420n)
})

test('args: size', () => {
Expand Down
2 changes: 1 addition & 1 deletion src/utils/encoding/fromHex.ts
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,7 @@ export function hexToBigInt(hex: Hex, opts: HexToBigIntOpts = {}): bigint {
const value = BigInt(hex)
if (!signed) return value

const size = (hex.length - 2) / 2
const size = Math.ceil((hex.length - 2) / 2)
const max = (1n << (BigInt(size) * 8n - 1n)) - 1n
if (value <= max) return value

Expand Down
Loading