Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add check for 0x in hex string #172

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
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/sixty-ravens-swim.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"micro-stacks": patch
---

Add check for `0x` in hex string
1 change: 1 addition & 0 deletions packages/core/src/common/encoding-hex.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ for (let n = 0; n <= 0xff; ++n) {
export function hexToBytes(hex: string): Uint8Array {
if (typeof hex !== 'string')
throw new TypeError('hexToBytes: expected string, got ' + typeof hex);
if (hex.startsWith('0x')) hex = cleanHex(hex);
if (hex.length % 2)
throw new Error(`hexToBytes: received invalid unpadded hex, got: ${hex.length}`);
const array = new Uint8Array(hex.length / 2);
Comment on lines 10 to 16
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@whoabuddy Perhaps something along these lines would be a little closer to the micro-stacks coding style:

Suggested change
export function hexToBytes(hex: string): Uint8Array {
if (typeof hex !== 'string')
throw new TypeError('hexToBytes: expected string, got ' + typeof hex);
if (hex.startsWith('0x')) hex = cleanHex(hex);
if (hex.length % 2)
throw new Error(`hexToBytes: received invalid unpadded hex, got: ${hex.length}`);
const array = new Uint8Array(hex.length / 2);
export function hexToBytes(hex: string): Uint8Array {
if (typeof hex !== 'string')
throw new TypeError('hexToBytes: expected string, got ' + typeof hex);
const cleanedHex = cleanHex(hex); // already tolerant of both prefixed and non-prefixed args
if (cleanedHex.length % 2)
throw new Error(`hexToBytes: received invalid unpadded hex, got: ${cleanedHex.length}`);
const array = new Uint8Array(cleanedHex.length / 2);

And of course use cleanedHex in remainder of fn as well. Just my two cents.

Expand Down