diff --git a/packages/abi-coder/src/encoding/coders/BigNumberCoder.test.ts b/packages/abi-coder/src/encoding/coders/BigNumberCoder.test.ts index 35198060bf..dc43eaa6a1 100644 --- a/packages/abi-coder/src/encoding/coders/BigNumberCoder.test.ts +++ b/packages/abi-coder/src/encoding/coders/BigNumberCoder.test.ts @@ -33,10 +33,19 @@ describe('BigNumberCoder', () => { expect(data).toEqual(expected); }); + it('should throw an error when encoding [number more than max safe integer]', () => { + const coder = new BigNumberCoder('u64'); + const value: number = Number.MAX_SAFE_INTEGER + 1; + + expect(() => coder.encode(value)).toThrow( + new FuelError(ErrorCode.ENCODE_ERROR, 'Invalid u64 type - number value is too large.') + ); + }); + it('should encode a u64 [very big number - as string]', () => { const coder = new BigNumberCoder('u64'); - const value: string = (Number.MAX_SAFE_INTEGER + 1).toString(); - const expected = new Uint8Array([0, 32, 0, 0, 0, 0, 0, 0]); + const value: string = '76472027892439376'; + const expected = new Uint8Array([1, 15, 174, 231, 121, 200, 89, 80]); const data = coder.encode(value); @@ -45,7 +54,7 @@ describe('BigNumberCoder', () => { it('should throw an error when encoding [number more than max safe integer]', () => { const coder = new BigNumberCoder('u64'); - const value: number = Number.MAX_SAFE_INTEGER + 1; + const value: number = 76472027892439376; expect(() => coder.encode(value)).toThrow( new FuelError(ErrorCode.ENCODE_ERROR, 'Invalid u64 type - number value is too large.') diff --git a/packages/abi-coder/src/encoding/coders/BigNumberCoder.ts b/packages/abi-coder/src/encoding/coders/BigNumberCoder.ts index ff0162a872..e9a68d5e78 100644 --- a/packages/abi-coder/src/encoding/coders/BigNumberCoder.ts +++ b/packages/abi-coder/src/encoding/coders/BigNumberCoder.ts @@ -20,6 +20,9 @@ export class BigNumberCoder extends Coder { encode(value: BNInput): Uint8Array { let bytes; + // We throw an error if the value is a number and it's more than the max safe integer + // This is because we can experience some odd behavior with integers more than the max safe integer + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER#description if (typeof value === 'number' && value > Number.MAX_SAFE_INTEGER) { throw new FuelError( ErrorCode.ENCODE_ERROR,