Skip to content

Commit e1ead14

Browse files
committed
fix: throw on negative param cairo.uint256 and bnToUint256
1 parent 0f8b266 commit e1ead14

File tree

3 files changed

+26
-1
lines changed

3 files changed

+26
-1
lines changed

__tests__/utils/uint256.test.ts

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,29 @@
1+
import { cairo } from '../../src';
12
import { UINT_128_MAX, UINT_256_MAX, bnToUint256, uint256ToBN } from '../../src/utils/uint256';
23

34
describe('cairo uint256', () => {
5+
test('bnToUint256 should not convert -1 from BN to uint256 struct', () => {
6+
expect(() => {
7+
bnToUint256(-1n);
8+
}).toThrow('uint256 must be positive number');
9+
});
10+
11+
test('uint256 should not convert -1 to uint256 hex-string struct', () => {
12+
expect(() => {
13+
cairo.uint256(-1n);
14+
}).toThrow('uint256 must be positive number');
15+
});
16+
17+
test('uint256 should not convert -1 to uint256 dec struct', () => {
18+
const uint256 = cairo.uint256(1000n);
19+
expect(uint256).toMatchInlineSnapshot(`
20+
Object {
21+
"high": "0",
22+
"low": "1000",
23+
}
24+
`);
25+
});
26+
427
test('should convert 0 from BN to uint256 struct', () => {
528
const uint256 = bnToUint256(0n);
629
expect(uint256).toMatchInlineSnapshot(`

src/utils/calldata/cairo.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -100,6 +100,7 @@ export function getAbiContractVersion(abi: Abi): ContractVersion {
100100
*/
101101
export const uint256 = (it: BigNumberish): Uint256 => {
102102
const bn = BigInt(it);
103+
if (bn < 0) throw Error('uint256 must be positive number');
103104
if (!isUint256(bn)) throw new Error('Number is too large');
104105
return {
105106
// eslint-disable-next-line no-bitwise

src/utils/uint256.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,8 @@ export function isUint256(bn: BigNumberish): boolean {
2727
* Convert BigNumberish (string | number | bigint) to Uint256 (hex)
2828
*/
2929
export function bnToUint256(bn: BigNumberish): Uint256 {
30-
const bi = toBigInt(bn);
30+
const bi = BigInt(bn);
31+
if (bi < 0) throw Error('uint256 must be positive number');
3132
if (!isUint256(bi)) throw new Error('Number is too large');
3233
return {
3334
low: addHexPrefix((bi & UINT_128_MAX).toString(16)),

0 commit comments

Comments
 (0)