Skip to content

Commit

Permalink
feat: Allow 0x prefix in hexToBytes helper (#1690)
Browse files Browse the repository at this point in the history
Co-authored-by: janniks <[email protected]>
  • Loading branch information
janniks and janniks authored May 28, 2024
1 parent baeff07 commit 33ca645
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 2 deletions.
5 changes: 5 additions & 0 deletions packages/common/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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++) {
Expand Down
8 changes: 6 additions & 2 deletions packages/transactions/tests/contract-abi.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down

0 comments on commit 33ca645

Please sign in to comment.