Skip to content

Commit

Permalink
precalculate numbers limits to avoid **
Browse files Browse the repository at this point in the history
  • Loading branch information
Muhammad-Altabba committed Oct 12, 2023
1 parent 45f317d commit 59b9731
Show file tree
Hide file tree
Showing 2 changed files with 506 additions and 19 deletions.
20 changes: 1 addition & 19 deletions packages/web3-eth-abi/src/coders/base/number.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import { padLeft, toBigInt } from 'web3-utils';
import { utils } from 'web3-validator';
import { DecoderResult, EncoderResult } from '../types.js';
import { WORD_SIZE } from '../utils.js';
import { numberLimits } from './numbersLimits.js';

// eslint-disable-next-line no-bitwise
const mask = BigInt(1) << BigInt(256);
Expand All @@ -43,25 +44,6 @@ function uint8ArrayToBigInt(value: Uint8Array, max: bigint): bigint {
return result - mask;
}

const numberLimits = new Map<string, { min: bigint; max: bigint }>();

// precalculate all the limits
for (let i = 8; i <= 256; i += 8) {
numberLimits.set(`uint${i}`, {
min: BigInt(0),
max: BigInt(2) ** BigInt(i) - BigInt(1),
});
numberLimits.set(`int${i}`, {
min: -(BigInt(2) ** BigInt(i - 1)),
max: BigInt(2) ** BigInt(i - 1) - BigInt(1),
});
}

// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
numberLimits.set(`int`, numberLimits.get('int256')!);
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
numberLimits.set(`uint`, numberLimits.get('uint256')!);

export function encodeNumber(param: AbiParameter, input: unknown): EncoderResult {
let value;
try {
Expand Down
Loading

0 comments on commit 59b9731

Please sign in to comment.