diff --git a/packages/common/src/utils.ts b/packages/common/src/utils.ts index 6b5caf15d..4d9afc446 100644 --- a/packages/common/src/utils.ts +++ b/packages/common/src/utils.ts @@ -506,12 +506,17 @@ export function bytesToHex(uint8a: Uint8Array): string { * @example * ``` * hexToBytes('deadbeef') // Uint8Array(4) [ 222, 173, 190, 239 ] + * hexToBytes('0xdeadbeef') // Uint8Array(4) [ 222, 173, 190, 239 ] * ``` */ export function hexToBytes(hex: string): Uint8Array { if (typeof hex !== 'string') { throw new TypeError(`hexToBytes: expected string, got ${typeof hex}`); } + + // todo: add use `without0x` from current `next` to replace duplicate trimming code + hex = hex.startsWith('0x') || hex.startsWith('0X') ? hex.slice(2) : hex; // remove 0x prefix + const paddedHex = hex.length % 2 ? `0${hex}` : hex; // left pad with a zero if odd length const array = new Uint8Array(paddedHex.length / 2); for (let i = 0; i < array.length; i++) { diff --git a/packages/transactions/tests/contract-abi.test.ts b/packages/transactions/tests/contract-abi.test.ts index 859bf4e20..0dde9580d 100644 --- a/packages/transactions/tests/contract-abi.test.ts +++ b/packages/transactions/tests/contract-abi.test.ts @@ -61,8 +61,12 @@ test.each(TEST_CASES)(encodeClarityValue.name, ({ type, value, expected }) => { test(encodeAbiClarityValue.name, () => { // buffer is expected to be hex - const result = encodeAbiClarityValue('beef', { buffer: { length: 10 } }); - expect(result).toEqual(Cl.bufferFromHex('beef')); + + const resultA = encodeAbiClarityValue('beef', { buffer: { length: 10 } }); + expect(resultA).toEqual(Cl.bufferFromHex('beef')); + + const resultB = encodeAbiClarityValue('0xbeef', { buffer: { length: 10 } }); + expect(resultB).toEqual(Cl.bufferFromHex('beef')); TEST_CASES.filter((tc: any) => !tc.type.buffer).forEach(({ type, value, expected }) => { const result = encodeAbiClarityValue(value, type);