From 912bc2f8de9af87a0b66c4d48ae36c97448dc787 Mon Sep 17 00:00:00 2001 From: Matthew Little Date: Thu, 10 Jun 2021 09:29:36 -0600 Subject: [PATCH] chore: allow odd-length hex strings that certain libs output --- packages/transactions/src/clarity/types/intCV.ts | 8 ++++++-- packages/transactions/tests/clarity.test.ts | 2 ++ 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/packages/transactions/src/clarity/types/intCV.ts b/packages/transactions/src/clarity/types/intCV.ts index bdda9ff71..4a4125f53 100644 --- a/packages/transactions/src/clarity/types/intCV.ts +++ b/packages/transactions/src/clarity/types/intCV.ts @@ -20,9 +20,13 @@ function valueToBN(value: unknown, signed: boolean): BigNum { return new BigNum(value); } if (typeof value === 'string') { + // If hex string then convert to buffer then fall through to the buffer condition if (value.toLowerCase().startsWith('0x')) { - // Convert to buffer then fall through to the buffer condition - value = Buffer.from(value.slice(2), 'hex'); + // Trim '0x' hex-prefix + let hex = value.slice(2); + // Allow odd-length strings like `0xf` -- some libs output these, or even just `0x${num.toString(16)}` + hex = hex.padStart(hex.length + (hex.length % 2), '0'); + value = Buffer.from(hex, 'hex'); } else { return new BigNum(value); } diff --git a/packages/transactions/tests/clarity.test.ts b/packages/transactions/tests/clarity.test.ts index 13346c2a9..aadc24db3 100644 --- a/packages/transactions/tests/clarity.test.ts +++ b/packages/transactions/tests/clarity.test.ts @@ -236,6 +236,8 @@ describe('Clarity Types', () => { ['10', '10', '0x0000000000000000000000000000000a'], ['0x0a', '10', '0x0000000000000000000000000000000a'], ['0x000a', '10', '0x0000000000000000000000000000000a'], + ['0xa', '10', '0x0000000000000000000000000000000a'], // hex string with odd padding + ['0x00a', '10', '0x0000000000000000000000000000000a'], // hex string with odd padding [new BN(10), '10', '0x0000000000000000000000000000000a'], [Buffer.from([0x0a]), '10', '0x0000000000000000000000000000000a'], [Buffer.from([0x00, 0x0a]), '10', '0x0000000000000000000000000000000a'],