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

add test coverage to web3-core #7091

Merged
merged 9 commits into from
Jun 11, 2024
Merged
Show file tree
Hide file tree
Changes from 3 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
1 change: 0 additions & 1 deletion packages/web3-core/src/formatters.ts
Original file line number Diff line number Diff line change
Expand Up @@ -302,7 +302,6 @@ export const inputLogFormatter = (filter: Filter) => {
const val: Mutable<Filter> = isNullish(filter)
? {}
: mergeDeep({}, filter as Record<string, unknown>);

// If options !== undefined, don't blow out existing data
if (isNullish(val.fromBlock)) {
val.fromBlock = BlockTags.LATEST;
Expand Down
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)) &&
Copy link
Contributor Author

@luu-alex luu-alex Jun 7, 2024

Choose a reason for hiding this comment

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

removed, This conditional can never happen as we check jsonRpc.isResponseWithError(response) and jsonRpc.isResponseWithResult(response) seperately

!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) {
Copy link
Contributor Author

@luu-alex luu-alex Jun 7, 2024

Choose a reason for hiding this comment

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

removed, in the constructor
only one of requestManager or subscriptionManager must be defined

throw new SubscriptionError(
'Only requestManager or subscriptionManager should be provided at Subscription constructor',
);
}
if (!requestManager && !subscriptionManager) {
Copy link
Contributor Author

Choose a reason for hiding this comment

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

removed, in the constructor
either requestManager or subscriptionManager must be defined

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
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
/*
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();
}
}
120 changes: 119 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,123 @@ 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
Loading