Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use BigInt when decoding functions' and events' parameters returned from Smart Contracts calls and events #5435

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -733,3 +733,20 @@ should use 4.0.1-alpha.0 for testing.
- Dependency tree cannot be resolved by Yarn due to old deprecated packages picked by yarn - fixed (#5382)

## [Unreleased]

Muhammad-Altabba marked this conversation as resolved.
Show resolved Hide resolved
### Added

#### web3-error

- Add optional `innerError` property to the abstract class `Web3Error`.

### Fixed

#### web3-eth-contract

- According to the latest change in `web3-eth-abi`, the decoded values of the large numbers, returned from function calls or events, are now available as `BigInt`.

#### web3-eth-abi

- Return `BigInt` instead of `string` when decoding function parameters for large numbers, such as `uint256`.
- If an error happens when decoding a value, preserve that exception at `innerError` inside the `AbiError`.
6 changes: 6 additions & 0 deletions packages/web3-errors/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,3 +34,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- I've improved the security in XY (#1000)

-->

## [Unreleased]

### Added

- Add optional `innerError` property to the abstract class `Web3Error`.
11 changes: 9 additions & 2 deletions packages/web3-errors/src/web3_error_base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,11 @@ export abstract class Web3Error extends Error implements ErrorInterface {
public readonly name: string;
public abstract readonly code: number;
public stack: string | undefined;
public innerError: Error | undefined;
Muhammad-Altabba marked this conversation as resolved.
Show resolved Hide resolved

public constructor(msg?: string) {
public constructor(msg?: string, innerError?: Error) {
super(msg);
this.innerError = innerError;
this.name = this.constructor.name;

if (typeof Error.captureStackTrace === 'function') {
Expand All @@ -51,7 +53,12 @@ export abstract class Web3Error extends Error implements ErrorInterface {
}

public toJSON() {
return { name: this.name, code: this.code, message: this.message };
return {
name: this.name,
code: this.code,
message: this.message,
innerError: this.innerError,
};
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ Object {
"code": 504,
"errorCode": 10,
"errorReason": "reason",
"innerError": undefined,
"message": "CONNECTION ERROR: The connection got closed with the close code 10 and the following reason string reason",
"name": "ConnectionCloseError",
}
Expand All @@ -15,6 +16,7 @@ Object {
"code": 500,
"errorCode": 10,
"errorReason": "reason",
"innerError": undefined,
"message": "error message",
"name": "ConnectionError",
}
Expand All @@ -25,6 +27,7 @@ Object {
"code": 503,
"errorCode": 10,
"errorReason": "reason",
"innerError": undefined,
"message": "Connection not open",
"name": "ConnectionNotOpenError",
}
Expand All @@ -36,6 +39,7 @@ Object {
"duration": 5000,
"errorCode": undefined,
"errorReason": undefined,
"innerError": undefined,
"message": "CONNECTION TIMEOUT: timeout of 5000ms achieved",
"name": "ConnectionTimeoutError",
}
Expand All @@ -44,6 +48,7 @@ Object {
exports[`errors ContractCodeNotStoredError should have valid json structure 1`] = `
Object {
"code": 404,
"innerError": undefined,
"message": "The contract code couldn't be stored, please check your gas limit.",
"name": "ContractCodeNotStoredError",
"receipt": Object {
Expand All @@ -56,6 +61,7 @@ exports[`errors ContractEventDoesNotExistError should have valid json structure
Object {
"code": 304,
"eventName": "eventName",
"innerError": undefined,
"message": "Event \\"eventName\\" doesn't exist in this contract.",
"name": "ContractEventDoesNotExistError",
}
Expand All @@ -64,6 +70,7 @@ Object {
exports[`errors ContractMissingABIError should have valid json structure 1`] = `
Object {
"code": 302,
"innerError": undefined,
"message": "You must provide the json interface of the contract when instantiating a contract object.",
"name": "ContractMissingABIError",
}
Expand All @@ -72,6 +79,7 @@ Object {
exports[`errors ContractMissingDeployDataError should have valid json structure 1`] = `
Object {
"code": 306,
"innerError": undefined,
"message": "No \\"data\\" specified in neither the given options, nor the default options.",
"name": "ContractMissingDeployDataError",
}
Expand All @@ -80,6 +88,7 @@ Object {
exports[`errors ContractNoAddressDefinedError should have valid json structure 1`] = `
Object {
"code": 307,
"innerError": undefined,
"message": "This contract object doesn't have address set yet, please set an address first.",
"name": "ContractNoAddressDefinedError",
}
Expand All @@ -88,6 +97,7 @@ Object {
exports[`errors ContractNoFromAddressDefinedError should have valid json structure 1`] = `
Object {
"code": 308,
"innerError": undefined,
"message": "No \\"from\\" address specified in neither the given options, nor the default options.",
"name": "ContractNoFromAddressDefinedError",
}
Expand All @@ -96,6 +106,7 @@ Object {
exports[`errors ContractOnceRequiresCallbackError should have valid json structure 1`] = `
Object {
"code": 303,
"innerError": undefined,
"message": "Once requires a callback as the second parameter.",
"name": "ContractOnceRequiresCallbackError",
}
Expand All @@ -104,6 +115,7 @@ Object {
exports[`errors ContractReservedEventError should have valid json structure 1`] = `
Object {
"code": 305,
"innerError": undefined,
"message": "Event \\"type\\" doesn't exist in this contract.",
"name": "ContractReservedEventError",
"type": "type",
Expand All @@ -116,6 +128,7 @@ Object {
"errorCode": 10,
"errorReason": "reason",
"host": "my host",
"innerError": undefined,
"message": "CONNECTION ERROR: Couldn't connect to node my host.",
"name": "InvalidConnectionError",
}
Expand All @@ -126,6 +139,7 @@ Object {
"code": 200,
"expected": 20,
"got": 10,
"innerError": undefined,
"message": "Invalid number of parameters for \\"method\\". Got \\"10\\" expected \\"20\\"!",
"method": "method",
"name": "InvalidNumberOfParamsError",
Expand All @@ -135,6 +149,7 @@ Object {
exports[`errors InvalidProviderError should have valid json structure 1`] = `
Object {
"code": 601,
"innerError": undefined,
"message": "Provider with url \\"my url\\" is not set or invalid",
"name": "InvalidProviderError",
}
Expand All @@ -147,6 +162,7 @@ Object {
"a": "10",
"b": "20",
},
"innerError": undefined,
"message": "Returned error: error message",
"name": "InvalidResponseError",
}
Expand All @@ -157,6 +173,7 @@ Object {
"code": 505,
"errorCode": undefined,
"errorReason": undefined,
"innerError": undefined,
"message": "Maximum number of reconnect attempts reached!",
"name": "MaxAttemptsReachedOnReconnectingError",
}
Expand All @@ -165,6 +182,7 @@ Object {
exports[`errors NoContractAddressFoundError should have valid json structure 1`] = `
Object {
"code": 403,
"innerError": undefined,
"message": "The transaction receipt didn't contain a contract address.",
"name": "NoContractAddressFoundError",
"receipt": Object {
Expand All @@ -178,6 +196,7 @@ Object {
"code": 506,
"errorCode": undefined,
"errorReason": undefined,
"innerError": undefined,
"message": "CONNECTION ERROR: Provider started to reconnect before the response got received!",
"name": "PendingRequestsOnReconnectingError",
}
Expand All @@ -187,6 +206,7 @@ exports[`errors ResolverMethodMissingError should have valid json structure 1`]
Object {
"address": "address",
"code": 301,
"innerError": undefined,
"message": "The resolver at address does not implement requested method: \\"name\\".",
"name": "name",
}
Expand All @@ -199,6 +219,7 @@ Object {
"a": "10",
"b": "20",
},
"innerError": undefined,
"message": "Returned error: error message",
"name": "ResponseError",
}
Expand All @@ -208,6 +229,7 @@ exports[`errors ResponseError should have valid json structure without data 1`]
Object {
"code": 100,
"data": undefined,
"innerError": undefined,
"message": "Returned error: error message",
"name": "ResponseError",
}
Expand All @@ -216,6 +238,7 @@ Object {
exports[`errors RevertInstructionError should have valid json structure 1`] = `
Object {
"code": 401,
"innerError": undefined,
"message": "Your request got reverted with the following reason string: message",
"name": "RevertInstructionError",
"reason": "message",
Expand All @@ -226,6 +249,7 @@ Object {
exports[`errors TransactionError should have valid json structure 1`] = `
Object {
"code": 400,
"innerError": undefined,
"message": "message",
"name": "TransactionError",
"receipt": Object {
Expand All @@ -237,6 +261,7 @@ Object {
exports[`errors TransactionOutOfGasError should have valid json structure 1`] = `
Object {
"code": 406,
"innerError": undefined,
"message": "Transaction ran out of gas. Please provide more gas:
{
\\"attr1\\": \\"attr1\\"
Expand All @@ -251,6 +276,7 @@ Object {
exports[`errors TransactionRevertError should have valid json structure 1`] = `
Object {
"code": 402,
"innerError": undefined,
"message": "Transaction has been reverted by the EVM:
{
\\"attr1\\": \\"attr1\\"
Expand All @@ -267,6 +293,7 @@ Object {
exports[`errors TransactionRevertedWithoutReasonError should have valid json structure 1`] = `
Object {
"code": 405,
"innerError": undefined,
"message": "Transaction has been reverted by the EVM:
{
\\"attr1\\": \\"attr1\\"
Expand Down
9 changes: 9 additions & 0 deletions packages/web3-eth-abi/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,3 +34,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- I've improved the security in XY (#1000)

-->

## [Unreleased]

### Fixed

#### web3-eth-abi

- Return `BigInt` instead of `string` when decoding function parameters for large numbers, such as `uint256`.
- If an error happens when decoding a value, preserve that exception at `innerError` inside the `AbiError`.
2 changes: 1 addition & 1 deletion packages/web3-eth-abi/src/api/parameters_api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ export const encodeParameters = (abi: ReadonlyArray<AbiInput>, params: unknown[]
modifiedParams,
);
} catch (err) {
throw new AbiError(`Parameter encoding error: ${(err as Error).message}`);
throw new AbiError(`Parameter encoding error`, err as Error);
}
};

Expand Down
15 changes: 5 additions & 10 deletions packages/web3-eth-abi/src/ethers_abi_coder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,16 +17,11 @@ along with web3.js. If not, see <http://www.gnu.org/licenses/>.

import { AbiCoder } from '@ethersproject/abi';

const ethersAbiCoder = new AbiCoder((type, value) => {
if (
/^u?int/.exec(type) &&
!Array.isArray(value) &&
// eslint-disable-next-line @typescript-eslint/ban-types
(!(!!value && typeof value === 'object') || (value as Function).constructor.name !== 'BN')
) {
// Because of tye type def from @ethersproject/abi
// eslint-disable-next-line @typescript-eslint/no-unsafe-return, @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-call
return value.toString();
const ethersAbiCoder = new AbiCoder((_, value) => {
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument, @typescript-eslint/no-unsafe-member-access
if (['BigNumber', 'BN'].includes(value?.constructor?.name)) {
// eslint-disable-next-line @typescript-eslint/ban-types, @typescript-eslint/no-unsafe-argument
return BigInt(value);
}

// Because of tye type def from @ethersproject/abi
Expand Down
9 changes: 9 additions & 0 deletions packages/web3-eth-abi/test/fixtures/data.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,15 @@ along with web3.js. If not, see <http://www.gnu.org/licenses/>.

import { encodeParameters, decodeParameters } from '../../src/api/parameters_api';

// Because Jest does not support BigInt (https://github.com/facebook/jest/issues/12827)
// The BigInt values in this file is in a string format.
// And the following override is to convert BigInt to a string inside the Unit Tests that uses this file,
// i.e when serialization is needed there (because the values in this file is in a string format).
(BigInt.prototype as any).toJSON = function () {
// eslint-disable-next-line @typescript-eslint/no-unsafe-return, @typescript-eslint/no-unsafe-call
return this.toString();
};

export const jsonInterfaceValidData: [any, string][] = [
[
{
Expand Down
3 changes: 2 additions & 1 deletion packages/web3-eth-abi/test/unit/api/logs_api.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,8 @@ describe('logs_api', () => {
it.each(validDecodeLogsData)(
'should pass for valid values: %j',
({ input: { abi, data, topics }, output }) => {
expect(decodeLog(abi, data, topics)).toEqual(output);
const expected = decodeLog(abi, data, topics);
expect(JSON.parse(JSON.stringify(expected))).toEqual(output);
},
);
});
Expand Down
14 changes: 8 additions & 6 deletions packages/web3-eth-abi/test/unit/api/parameters_api.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,14 +32,15 @@ describe('parameters_api', () => {
it.each(validEncodeParametersData)(
'%#: should pass for valid values: %j',
({ input: [abi, params], output }) => {
expect(encodeParameters(abi, params)).toEqual(output);
const expected = encodeParameters(abi, params);
expect(JSON.parse(JSON.stringify(expected))).toEqual(output);
},
);
});

describe('invalid data', () => {
it.each(inValidEncodeParametersData)(
'%#: should pass for valid values: %j',
'%#: should not pass for invalid values: %j',
({ input: [abi, params], output }) => {
expect(() => encodeParameters(abi, params)).toThrow(output);
},
Expand All @@ -52,7 +53,8 @@ describe('parameters_api', () => {
it.each(validEncodeDoesNotMutateData)(
'%#: should pass for valid values: %j',
({ input: [abi, params], output, expectedInput }) => {
expect(encodeParameters(abi, params)).toEqual(output);
const expected = encodeParameters(abi, params);
expect(JSON.parse(JSON.stringify(expected))).toEqual(output);
// check that params has not been mutated
expect(JSON.parse(JSON.stringify(params))).toEqual(
JSON.parse(JSON.stringify(expectedInput)),
Expand Down Expand Up @@ -90,7 +92,7 @@ describe('parameters_api', () => {

describe('invalid data', () => {
it.each(inValidDecodeParametersData)(
'%#: should pass for valid values: %j',
'%#: should not pass for invalid values: %j',
({ input: [abi, bytes], output }) => {
expect(() => decodeParameters(abi, bytes)).toThrow(output);
},
Expand All @@ -105,9 +107,9 @@ describe('parameters_api', () => {
({ input: [abi, params], output, outputResult }) => {
const rwAbi = abi as AbiInput[];
const encodedBytes = encodeParameters(abi, params);
expect(encodedBytes).toEqual(output);
expect(JSON.parse(JSON.stringify(encodedBytes))).toEqual(output);
const decodedBytes = decodeParameters(rwAbi, encodedBytes);
expect(decodedBytes).toEqual(outputResult);
expect(JSON.parse(JSON.stringify(decodedBytes))).toEqual(outputResult);
},
);
});
Expand Down
Loading