Skip to content

Commit

Permalink
fix: throw error if the number type used in the bigint constructor is…
Browse files Browse the repository at this point in the history
… not a safe integer value
  • Loading branch information
janniks committed Jul 5, 2023
1 parent ee4df48 commit 239df4c
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 1 deletion.
5 changes: 5 additions & 0 deletions packages/common/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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') {
Expand Down
7 changes: 6 additions & 1 deletion packages/transactions/tests/clarity.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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([
Expand Down Expand Up @@ -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);
Expand All @@ -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', () => {
Expand All @@ -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);
Expand Down

0 comments on commit 239df4c

Please sign in to comment.