Skip to content

Commit

Permalink
add test coverage to web3-core (#7091)
Browse files Browse the repository at this point in the history
* add test coverage to web3-core

* make types compitable

* update

* update

* update types

* update types

* update

* update tests
  • Loading branch information
Alex authored Jun 11, 2024
1 parent 9547643 commit 7a51c33
Show file tree
Hide file tree
Showing 12 changed files with 611 additions and 31 deletions.
10 changes: 0 additions & 10 deletions packages/web3-core/src/web3_request_manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -429,7 +429,6 @@ export class Web3RequestManager<
) {
return this._buildResponse(payload, response, error);
}

if (jsonRpc.isBatchRequest(payload) && !Array.isArray(response)) {
throw new ResponseError(response, 'Got normal response for a batch request.');
}
Expand All @@ -438,15 +437,6 @@ export class Web3RequestManager<
throw new ResponseError(response, 'Got batch response for a normal request.');
}

if (
(jsonRpc.isResponseWithError(response) || jsonRpc.isResponseWithResult(response)) &&
!jsonRpc.isBatchRequest(payload)
) {
if (response.id && payload.id !== response.id) {
throw new InvalidResponseError<ErrorType>(response);
}
}

throw new ResponseError(response, 'Invalid response');
}

Expand Down
11 changes: 0 additions & 11 deletions packages/web3-core/src/web3_subscriptions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@ import {
Web3APISpec,
} from 'web3-types';
import { jsonRpc } from 'web3-utils';
import { SubscriptionError } from 'web3-errors';

// eslint-disable-next-line import/no-cycle
import { Web3SubscriptionManager } from './web3_subscription_manager.js';
Expand Down Expand Up @@ -82,16 +81,6 @@ export abstract class Web3Subscription<
super();
const { requestManager } = options as { requestManager: Web3RequestManager<API> };
const { subscriptionManager } = options as { subscriptionManager: Web3SubscriptionManager };
if (requestManager && subscriptionManager) {
throw new SubscriptionError(
'Only requestManager or subscriptionManager should be provided at Subscription constructor',
);
}
if (!requestManager && !subscriptionManager) {
throw new SubscriptionError(
'Either requestManager or subscriptionManager should be provided at Subscription constructor',
);
}
if (requestManager) {
// eslint-disable-next-line deprecation/deprecation
this._subscriptionManager = new Web3SubscriptionManager(requestManager, {}, true);
Expand Down
73 changes: 73 additions & 0 deletions packages/web3-core/test/unit/fixtures/custom_transaction_type.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
/*
This file is part of web3.js.
web3.js is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
web3.js is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with web3.js. If not, see <http://www.gnu.org/licenses/>.
*/

import {
BaseTransaction,
TxValuesArray,
AccessListEIP2930ValuesArray,
FeeMarketEIP1559ValuesArray,
JsonTx,
} from 'web3-eth-accounts';

export class CustomTransactionType extends BaseTransaction<unknown> {
// eslint-disable-next-line class-methods-use-this
public getUpfrontCost(): bigint {
throw new Error('Method not implemented.');
}
// eslint-disable-next-line class-methods-use-this
public raw(): TxValuesArray | AccessListEIP2930ValuesArray | FeeMarketEIP1559ValuesArray {
throw new Error('Method not implemented.');
}
// eslint-disable-next-line class-methods-use-this
public serialize(): Uint8Array {
throw new Error('Method not implemented.');
}
public getMessageToSign(hashMessage: false): Uint8Array | Uint8Array[];
public getMessageToSign(hashMessage?: true | undefined): Uint8Array;
// eslint-disable-next-line class-methods-use-this
public getMessageToSign(): Uint8Array | Uint8Array[] {
throw new Error('Method not implemented.');
}
// eslint-disable-next-line class-methods-use-this
public hash(): Uint8Array {
throw new Error('Method not implemented.');
}
// eslint-disable-next-line class-methods-use-this
public getMessageToVerifySignature(): Uint8Array {
throw new Error('Method not implemented.');
}
// eslint-disable-next-line class-methods-use-this
public getSenderPublicKey(): Uint8Array {
throw new Error('Method not implemented.');
}
// eslint-disable-next-line class-methods-use-this
public toJSON(): JsonTx {
throw new Error('Method not implemented.');
}
// eslint-disable-next-line class-methods-use-this
protected _processSignature(): unknown {
throw new Error('Method not implemented.');
}
// eslint-disable-next-line @typescript-eslint/explicit-member-accessibility, class-methods-use-this
public errorStr(): string {
throw new Error('Method not implemented.');
}
// eslint-disable-next-line class-methods-use-this
protected _errorMsg(): string {
throw new Error('Method not implemented.');
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with web3.js. If not, see <http://www.gnu.org/licenses/>.
*/

import { DataFormat } from 'web3-types';
import { Web3Subscription } from '../../../src';

export class ExampleSubscription extends Web3Subscription<
Expand All @@ -26,4 +26,7 @@ export class ExampleSubscription extends Web3Subscription<
protected _buildSubscriptionParams() {
return ['newHeads'];
}
public getReturnFormat(): DataFormat {
return this.returnFormat;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
/*
This file is part of web3.js.
web3.js is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
web3.js is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with web3.js. If not, see <http://www.gnu.org/licenses/>.
*/
import { Web3Subscription } from '../../../src';

// subscription class that exposes buildSubscriptionParams
export class BuildSubscription extends Web3Subscription<
{ data: string },
{ param1: string },
{ eth_subscribe: (newHeads: string) => void }
> {
public buildSubscriptionParams() {
this._buildSubscriptionParams();
}
}
118 changes: 117 additions & 1 deletion packages/web3-core/test/unit/formatters.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,9 @@ along with web3.js. If not, see <http://www.gnu.org/licenses/>.
*/

import * as utils from 'web3-utils';
import { BlockTags } from 'web3-types';
import { BlockTags, TransactionInput, Filter } from 'web3-types';
import { Iban } from 'web3-eth-iban';
import { FormatterError } from 'web3-errors';
import {
inputAddressFormatter,
inputBlockNumberFormatter,
Expand Down Expand Up @@ -268,6 +269,121 @@ describe('formatters', () => {
);
});

describe('inputCallFormatter', () => {
let txInput: any;

beforeEach(() => {
jest.spyOn(utils, 'isAddress').mockReturnValue(true);
txInput = {
to: '0xabcd',
};
});

it('should format "to" address if provided', () => {
expect(formatters.inputCallFormatter({ ...txInput, to: '0xABCD' })).toEqual(
expect.objectContaining({ to: '0xabcd' }),
);
});

it('should format "from" if defaultAddress is provided', () => {
expect(formatters.inputCallFormatter({ ...txInput, to: '0xABCD' }, '0xABCDE')).toEqual(
expect.objectContaining({ from: '0xabcde', to: '0xabcd' }),
);
});
});

describe('inputTransactionFormatter', () => {
let txInput: any;

beforeEach(() => {
jest.spyOn(utils, 'isAddress').mockReturnValue(true);
txInput = {
to: '0xabcd',
};
});
it('should format and populate "from"', () => {
expect(
formatters.inputTransactionFormatter({ ...txInput, to: '0xabcd', from: '0xABCDE' }),
).toEqual(expect.objectContaining({ from: '0xabcde', to: '0xabcd' }));
});

it('should throw an error when from is undefined', () => {
expect(() => formatters.inputTransactionFormatter({ ...txInput })).toThrow(
new FormatterError('The send transactions "from" field must be defined!'),
);
});
});

describe('outputTransactionFormatter', () => {
it('should correctly format blockNumber from hex to number', () => {
const txInput: TransactionInput = {
to: '0x1234567890abcdef',
from: '0xabcdef1234567890',
gas: '0x123456',
gasPrice: '0x987654321',
nonce: '0x1',
value: '0x9876543210',
blockNumber: '0x123',
transactionIndex: '0x1',
maxFeePerGas: '0x87654321',
maxPriorityFeePerGas: '0x7654321',
type: '0x1',
};

const formattedTxOutput = formatters.outputTransactionFormatter(txInput);
// should return the mocked values;
expect(formattedTxOutput.blockNumber).toBe(123);
expect(formattedTxOutput.to).toBe('toChecksumAddress');
expect(formattedTxOutput.from).toBe('toChecksumAddress');
expect(formattedTxOutput.gas).toBe(123);
expect(formattedTxOutput.nonce).toBe(123);
expect(formattedTxOutput.transactionIndex).toBe(123);
expect(formattedTxOutput.value).toBe(12345);
expect(formattedTxOutput.maxFeePerGas).toBe(12345);
expect(formattedTxOutput.maxPriorityFeePerGas).toBe(12345);
expect(formattedTxOutput.type).toBe(123);
});

it('should make "to" property undefined', () => {
const txInput = { gas: '0x', nonce: '1', value: '0x' };
const formattedTxOutput = formatters.outputTransactionFormatter(txInput);

expect(formattedTxOutput.to).toBeUndefined();
});
});

describe('inputLogFormatter', () => {
beforeAll(() => {
const actualUtils = jest.requireActual('web3-utils');
jest.spyOn(utils, 'mergeDeep').mockImplementation(actualUtils.mergeDeep);
});
it('should correctly format a filter with all fields provided', () => {
const filter: Filter = {
fromBlock: '0x1',
toBlock: '0x2',
address: '0x1234567890abcdef1234567890abcdef12345678',
topics: ['0x123', ['0x456', '0x789']],
};

const formattedFilter = formatters.inputLogFormatter(filter);

expect(formattedFilter.fromBlock).toBe('0x1');
expect(formattedFilter.toBlock).toBe('0x2');
expect(formattedFilter.address).toBe('0x1234567890abcdef1234567890abcdef12345678');
expect(formattedFilter.topics).toEqual(['0x123', ['0x456', '0x789']]);
});
it('should correctly format a filter with no fromBlock', () => {
const filter: Filter = {
address: ['0x123', '0x222'],
};

const formattedFilter = formatters.inputLogFormatter(filter);

expect(formattedFilter.fromBlock).toBe('latest');
expect(formattedFilter.address).toEqual(['0x123', '0x222']);
});
});

describe('outputLogFormatter', () => {
it('should set log id from "blockHash", "transactionHash" and "logIndex"', () => {
const result = outputLogFormatter({
Expand Down
Loading

1 comment on commit 7a51c33

@github-actions
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Benchmark

Benchmark suite Current: 7a51c33 Previous: 9547643 Ratio
processingTx 8886 ops/sec (±4.14%) 9360 ops/sec (±3.81%) 1.05
processingContractDeploy 36289 ops/sec (±7.97%) 41290 ops/sec (±6.77%) 1.14
processingContractMethodSend 19089 ops/sec (±6.68%) 19873 ops/sec (±7.29%) 1.04
processingContractMethodCall 37879 ops/sec (±3.96%) 40597 ops/sec (±6.38%) 1.07
abiEncode 41900 ops/sec (±6.51%) 45937 ops/sec (±6.53%) 1.10
abiDecode 29048 ops/sec (±10.00%) 30402 ops/sec (±7.52%) 1.05
sign 1535 ops/sec (±3.67%) 1575 ops/sec (±3.03%) 1.03
verify 371 ops/sec (±0.63%) 382 ops/sec (±0.52%) 1.03

This comment was automatically generated by workflow using github-action-benchmark.

Please sign in to comment.