fix: throw error if the number type used in the bigint constructor is not a safe integer value

This commit is contained in:
janniks
2023-07-05 22:01:38 +02:00
committed by janniks
parent ee4df4877c
commit d6a6fcc30e
2 changed files with 11 additions and 1 deletions

View File

@@ -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 less than or equal to ${Number.MAX_SAFE_INTEGER}. For larger values, try using a BigInt instead.`
);
}
return BigInt(parsedValue);
}
if (typeof parsedValue === 'string') {

View File

@@ -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);