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/is-hex-string-empty-body.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@agentcommercekit/keys": patch
---

`isHexString` now returns `true` for a bare `0x` prefix with an empty body, matching its documented behavior. The check required at least one hex digit after the prefix, so `isHexString("0x")` returned `false` even though the JSDoc example states it returns `true`. A bare empty string with no prefix (`""`) continues to return `false`.
8 changes: 8 additions & 0 deletions packages/keys/src/encoding/hex.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,14 @@ describe("isHexString", () => {
expect(isHexString("1234567890abcdef")).toBe(true)
})

test("returns true for a bare 0x prefix with an empty body", () => {
expect(isHexString("0x")).toBe(true)
})

test("returns false for an empty string with no prefix", () => {
expect(isHexString("")).toBe(false)
})

test("returns false for invalid hex strings", () => {
expect(isHexString("0x1234567890abcdefg")).toBe(false)
expect(isHexString("not hex")).toBe(false)
Expand Down
10 changes: 9 additions & 1 deletion packages/keys/src/encoding/hex.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,14 @@ export function isHexString(value: unknown): value is string {
return false
}

const hexWithoutPrefix = value.startsWith("0x") ? value.slice(2) : value
const hasPrefix = value.startsWith("0x")
const hexWithoutPrefix = hasPrefix ? value.slice(2) : value

// A bare "0x" prefix has an empty body and is a valid (zero-length) hex
// string, as documented above. An empty string with no prefix is not.
if (hexWithoutPrefix.length === 0) {
return hasPrefix
}

return /^[0-9A-Fa-f]+$/.test(hexWithoutPrefix)
}