Skip to content

fix: handle odd-length hex in signed hexToBigInt / hexToNumber - #4913

Open
Kropiunig wants to merge 1 commit into
wevm:mainfrom
Kropiunig:fix/signed-odd-length-hex
Open

fix: handle odd-length hex in signed hexToBigInt / hexToNumber#4913
Kropiunig wants to merge 1 commit into
wevm:mainfrom
Kropiunig:fix/signed-odd-length-hex

Conversation

@Kropiunig

Copy link
Copy Markdown
Contributor

Summary

hexToBigInt (and hexToNumber) with signed: true crash on any odd-length hex value:

import { hexToBigInt } from 'viem'

hexToBigInt('0x1a4', { signed: true })
// RangeError: The number 1.5 cannot be converted to a BigInt because it is not an integer

This is the function's own @example (src/utils/encoding/fromHex.ts:124 documents it returning 420n). It also hits minimal-encoded JSON-RPC quantities, which are odd-length whenever the leading nibble is dropped (0x0, 0xf, 0x1a4, ...).

Root cause

src/utils/encoding/fromHex.ts:140:

const size = (hex.length - 2) / 2

For odd-length hex the byte size is fractional ('0x1a4'1.5), and the subsequent BigInt(size) throws. The unsigned path is unaffected — size is only used to compute the signed two's-complement bound.

Fix

Round the byte size up:

const size = Math.ceil((hex.length - 2) / 2)

An odd-length value is interpreted at its minimal byte width (0x1a40x01a4, 2 bytes), so hexToBigInt('0x1a4', { signed: true }) now returns 420n as documented. Even-length inputs take the exact same path as before.

Test

Extended the args: signed tests in fromHex.test.ts with odd-length cases (0x0, 0xf, 0x1a4) for both hexToBigInt and hexToNumber. They fail on main with the RangeError above and pass with the fix.

@vercel

vercel Bot commented Jul 28, 2026

Copy link
Copy Markdown

@Kropiunig is attempting to deploy a commit to the Wevm Team on Vercel.

A member of the Team first needs to authorize it.

@changeset-bot

changeset-bot Bot commented Jul 28, 2026

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 7b8d935

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 1 package
Name Type
viem Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@pkg-pr-new

pkg-pr-new Bot commented Jul 28, 2026

Copy link
Copy Markdown

Open in StackBlitz

npm i https://pkg.pr.new/viem@4913

commit: 7b8d935

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant