From e1ead1466984f26ff91d7fe6174fc87be8c3aede Mon Sep 17 00:00:00 2001 From: Toni Tabak Date: Fri, 26 Jan 2024 09:28:04 +0100 Subject: [PATCH] fix: throw on negative param cairo.uint256 and bnToUint256 --- __tests__/utils/uint256.test.ts | 23 +++++++++++++++++++++++ src/utils/calldata/cairo.ts | 1 + src/utils/uint256.ts | 3 ++- 3 files changed, 26 insertions(+), 1 deletion(-) diff --git a/__tests__/utils/uint256.test.ts b/__tests__/utils/uint256.test.ts index 1c72f9f42..3fbd8a60f 100644 --- a/__tests__/utils/uint256.test.ts +++ b/__tests__/utils/uint256.test.ts @@ -1,6 +1,29 @@ +import { cairo } from '../../src'; import { UINT_128_MAX, UINT_256_MAX, bnToUint256, uint256ToBN } from '../../src/utils/uint256'; describe('cairo uint256', () => { + test('bnToUint256 should not convert -1 from BN to uint256 struct', () => { + expect(() => { + bnToUint256(-1n); + }).toThrow('uint256 must be positive number'); + }); + + test('uint256 should not convert -1 to uint256 hex-string struct', () => { + expect(() => { + cairo.uint256(-1n); + }).toThrow('uint256 must be positive number'); + }); + + test('uint256 should not convert -1 to uint256 dec struct', () => { + const uint256 = cairo.uint256(1000n); + expect(uint256).toMatchInlineSnapshot(` + Object { + "high": "0", + "low": "1000", + } + `); + }); + test('should convert 0 from BN to uint256 struct', () => { const uint256 = bnToUint256(0n); expect(uint256).toMatchInlineSnapshot(` diff --git a/src/utils/calldata/cairo.ts b/src/utils/calldata/cairo.ts index 712c54e03..8cfda439e 100644 --- a/src/utils/calldata/cairo.ts +++ b/src/utils/calldata/cairo.ts @@ -100,6 +100,7 @@ export function getAbiContractVersion(abi: Abi): ContractVersion { */ export const uint256 = (it: BigNumberish): Uint256 => { const bn = BigInt(it); + if (bn < 0) throw Error('uint256 must be positive number'); if (!isUint256(bn)) throw new Error('Number is too large'); return { // eslint-disable-next-line no-bitwise diff --git a/src/utils/uint256.ts b/src/utils/uint256.ts index ced7e4308..d542620f1 100644 --- a/src/utils/uint256.ts +++ b/src/utils/uint256.ts @@ -27,7 +27,8 @@ export function isUint256(bn: BigNumberish): boolean { * Convert BigNumberish (string | number | bigint) to Uint256 (hex) */ export function bnToUint256(bn: BigNumberish): Uint256 { - const bi = toBigInt(bn); + const bi = BigInt(bn); + if (bi < 0) throw Error('uint256 must be positive number'); if (!isUint256(bi)) throw new Error('Number is too large'); return { low: addHexPrefix((bi & UINT_128_MAX).toString(16)),