From 239df4cc7e37c655b2502c29853396c6faa37f90 Mon Sep 17 00:00:00 2001 From: janniks Date: Wed, 5 Jul 2023 22:01:38 +0200 Subject: [PATCH] fix: throw error if the number type used in the bigint constructor is not a safe integer value --- packages/common/src/utils.ts | 5 +++++ packages/transactions/tests/clarity.test.ts | 7 ++++++- 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/packages/common/src/utils.ts b/packages/common/src/utils.ts index ee36a6830..9c23b9924 100644 --- a/packages/common/src/utils.ts +++ b/packages/common/src/utils.ts @@ -328,6 +328,11 @@ export function intToBigInt(value: IntegerType, signed: boolean): bigint { if (!Number.isInteger(parsedValue)) { throw new RangeError(`Invalid value. Values of type 'number' must be an integer.`); } + if (parsedValue > Number.MAX_SAFE_INTEGER) { + throw new RangeError( + `Invalid value. Values of type 'number' must be a MAX_SAFE_INTEGER. Try using a BigInt instead.` + ); + } return BigInt(parsedValue); } if (typeof parsedValue === 'string') { diff --git a/packages/transactions/tests/clarity.test.ts b/packages/transactions/tests/clarity.test.ts index 4ee5ae075..636625eee 100644 --- a/packages/transactions/tests/clarity.test.ts +++ b/packages/transactions/tests/clarity.test.ts @@ -218,8 +218,9 @@ describe('Clarity Types', () => { expect(() => intCV(NaN)).toThrowError(RangeError); expect(() => intCV(Infinity)).toThrowError(RangeError); - expect(() => intCV(3.1415)).toThrowError(RangeError); expect(() => intCV('3.1415')).toThrowError(RangeError); + expect(() => intCV(3.1415)).toThrowError(RangeError); + expect(() => intCV(10000000000000000000000000000000)).toThrowError(RangeError); }); test.each([ @@ -281,6 +282,7 @@ describe('Clarity Types', () => { // Out of bounds, too large expect(() => intCV(2n ** 127n)).toThrow(RangeError); + expect(() => intCV(Number.MAX_SAFE_INTEGER + 1)).toThrowError(RangeError); // Out of bounds, too small expect(() => intCV((-2n) ** 127n - 1n)).toThrow(RangeError); @@ -298,6 +300,8 @@ describe('Clarity Types', () => { const serialized2 = serializeCV(uint2); expect('0x' + bytesToHex(serialized2.slice(1))).toBe('0x0000000000000000000000000000000a'); expect(cvToString(serializeDeserialize(uint2))).toBe(cvToString(uint)); + + expect(() => uintCV(10000000000000000000000000000000)).toThrowError(RangeError); }); test('UIntCV - bounds', () => { @@ -319,6 +323,7 @@ describe('Clarity Types', () => { // Out of bounds, too large expect(() => uintCV(2n ** 128n)).toThrow(RangeError); + expect(() => uintCV(Number.MAX_SAFE_INTEGER + 1)).toThrowError(RangeError); // Out of bounds, too small expect(() => uintCV(-1)).toThrow(RangeError);