Skip to content

Commit

Permalink
fix: throw on negative param cairo.uint256 and bnToUint256
Browse files Browse the repository at this point in the history
  • Loading branch information
tabaktoni committed Jan 26, 2024
1 parent 0f8b266 commit e1ead14
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 1 deletion.
23 changes: 23 additions & 0 deletions __tests__/utils/uint256.test.ts
Original file line number Diff line number Diff line change
@@ -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(`
Expand Down
1 change: 1 addition & 0 deletions src/utils/calldata/cairo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
3 changes: 2 additions & 1 deletion src/utils/uint256.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)),
Expand Down

0 comments on commit e1ead14

Please sign in to comment.