From 12615451c577112afafac264094f43e057efb9c3 Mon Sep 17 00:00:00 2001 From: Nazar Hussain Date: Mon, 13 Jun 2022 16:11:03 +0200 Subject: [PATCH 01/26] :art: Update the code for small fixes --- packages/web3-common/src/formatters.ts | 6 +- packages/web3-common/src/index.ts | 3 +- .../web3-common/src/web3_base_provider.ts | 21 ++ .../{promi_event.ts => web3_promi_event.ts} | 2 +- ...event.test.ts => web3_promi_event.test.ts} | 12 +- packages/web3-core/src/types.ts | 3 +- packages/web3-core/src/web3_context.ts | 7 +- .../web3-core/src/web3_request_manager.ts | 2 +- packages/web3-errors/src/web3_error_base.ts | 4 +- packages/web3-eth-contract/src/contract.ts | 4 +- packages/web3-eth-contract/src/types.ts | 6 +- .../test/integration/contract_deploy.test.ts | 24 +- packages/web3-eth-ens/src/registry.ts | 4 +- packages/web3-eth-iban/src/index.ts | 219 +---------------- packages/web3-eth-iban/src/web3_iban.ts | 232 ++++++++++++++++++ packages/web3-eth-iban/test/unit/iban.test.ts | 34 +-- .../web3-eth-personal/src/eth_personal.ts | 60 +++++ packages/web3-eth-personal/src/index.ts | 47 +--- packages/web3-eth/src/rpc_method_wrappers.ts | 10 +- .../watch_transaction_for_confirmations.ts | 31 ++- packages/web3-eth/test/integration/helper.ts | 4 +- .../integration/watch_transaction.test.ts | 24 +- .../send_signed_transaction.test.ts | 26 +- .../send_transaction.test.ts | 26 +- packages/web3-utils/package.json | 2 +- packages/web3/package.json | 1 + packages/web3/src/web3.ts | 34 ++- tsconfig.json | 2 +- yarn.lock | 66 +++-- 29 files changed, 515 insertions(+), 401 deletions(-) rename packages/web3-common/src/{promi_event.ts => web3_promi_event.ts} (96%) rename packages/web3-common/test/unit/{promi_event.test.ts => web3_promi_event.test.ts} (83%) create mode 100644 packages/web3-eth-iban/src/web3_iban.ts create mode 100644 packages/web3-eth-personal/src/eth_personal.ts diff --git a/packages/web3-common/src/formatters.ts b/packages/web3-common/src/formatters.ts index 41d6d811610..aefaf4051f7 100644 --- a/packages/web3-common/src/formatters.ts +++ b/packages/web3-common/src/formatters.ts @@ -16,7 +16,7 @@ along with web3.js. If not, see . */ import { FormatterError } from 'web3-errors'; -import { Iban } from 'web3-eth-iban'; +import { Web3Iban } from 'web3-eth-iban'; import { BlockTags, Filter, @@ -121,8 +121,8 @@ export const inputDefaultBlockNumberFormatter = ( }; export const inputAddressFormatter = (address: string): string | never => { - if (Iban.isValid(address) && Iban.isDirect(address)) { - const iban = new Iban(address); + if (Web3Iban.isValid(address) && Web3Iban.isDirect(address)) { + const iban = new Web3Iban(address); return iban.toAddress().toLowerCase(); } diff --git a/packages/web3-common/src/index.ts b/packages/web3-common/src/index.ts index 0fd4446207a..c4d263976a4 100644 --- a/packages/web3-common/src/index.ts +++ b/packages/web3-common/src/index.ts @@ -22,7 +22,8 @@ export * from './web3_base_wallet'; export * from './web3_event_emitter'; export * from './eth_execution_api'; export * from './deferred_promise'; -export * from './promi_event'; +export * from './web3_promi_event'; export * from './formatters'; +export * as formatters from './formatters'; export * from './formatter'; export * as jsonRpc from './json_rpc'; diff --git a/packages/web3-common/src/web3_base_provider.ts b/packages/web3-common/src/web3_base_provider.ts index 53555e4b93d..68de4428326 100644 --- a/packages/web3-common/src/web3_base_provider.ts +++ b/packages/web3-common/src/web3_base_provider.ts @@ -51,6 +51,27 @@ export abstract class Web3BaseProvider, ResponseType = Web3APIReturnType>( + payload: Web3APIPayload, + // Used "null" value to match the legacy version + // eslint-disable-next-line @typescript-eslint/ban-types + cb: (err?: Error | null, response?: JsonRpcResponse) => void, + ) { + this.request(payload) + .then(response => { + cb(undefined, response); + }) + .catch((err: Error) => { + cb(err); + }); + } + // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1193.md#request public abstract request< Method extends Web3APIMethod, diff --git a/packages/web3-common/src/promi_event.ts b/packages/web3-common/src/web3_promi_event.ts similarity index 96% rename from packages/web3-common/src/promi_event.ts rename to packages/web3-common/src/web3_promi_event.ts index 40f77465f2f..f516c408048 100644 --- a/packages/web3-common/src/promi_event.ts +++ b/packages/web3-common/src/web3_promi_event.ts @@ -22,7 +22,7 @@ export type PromiseExecutor = ( reject: (reason: unknown) => void, ) => void; -export class PromiEvent +export class Web3PromiEvent extends Web3EventEmitter implements Promise { diff --git a/packages/web3-common/test/unit/promi_event.test.ts b/packages/web3-common/test/unit/web3_promi_event.test.ts similarity index 83% rename from packages/web3-common/test/unit/promi_event.test.ts rename to packages/web3-common/test/unit/web3_promi_event.test.ts index b3614791308..13bf6892f56 100644 --- a/packages/web3-common/test/unit/promi_event.test.ts +++ b/packages/web3-common/test/unit/web3_promi_event.test.ts @@ -15,11 +15,11 @@ You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see . */ -import { PromiEvent } from '../../src/promi_event'; +import { Web3PromiEvent } from '../../src/web3_promi_event'; -describe('PromiEvent', () => { +describe('Web3PromiEvent', () => { it('should initialize and resolve promise', async () => { - const p = new PromiEvent(resolve => { + const p = new Web3PromiEvent(resolve => { resolve('Resolved Value'); }); @@ -27,7 +27,7 @@ describe('PromiEvent', () => { }); it('should initialize and reject promise', async () => { - const p = new PromiEvent((_, reject) => { + const p = new Web3PromiEvent((_, reject) => { reject(new Error('My Error')); }); @@ -36,7 +36,7 @@ describe('PromiEvent', () => { it('should initialize and emit event', async () => { return new Promise(done => { - const p = new PromiEvent(resolve => { + const p = new Web3PromiEvent(resolve => { resolve('resolved value'); }); @@ -56,7 +56,7 @@ describe('PromiEvent', () => { it('should initialize and emit later', async () => { return new Promise(done => { const func = () => { - const p = new PromiEvent(resolve => { + const p = new Web3PromiEvent(resolve => { resolve('resolved value'); }); diff --git a/packages/web3-core/src/types.ts b/packages/web3-core/src/types.ts index 711ce592aed..f5eeb1cdaa9 100644 --- a/packages/web3-core/src/types.ts +++ b/packages/web3-core/src/types.ts @@ -51,8 +51,7 @@ export type SupportedProviders = | Web3BaseProvider | LegacyRequestProvider | LegacySendProvider - | LegacySendAsyncProvider - | string; + | LegacySendAsyncProvider; export type Web3BaseProviderConstructor = new ( url: string, diff --git a/packages/web3-core/src/web3_context.ts b/packages/web3-core/src/web3_context.ts index 4fbfebcec48..15ef63eae5d 100644 --- a/packages/web3-core/src/web3_context.ts +++ b/packages/web3-core/src/web3_context.ts @@ -59,7 +59,7 @@ export type Web3ContextInitOptions< } = any, > = { config?: Partial; - provider: SupportedProviders; + provider: SupportedProviders | string; requestManager?: Web3RequestManager; subscriptionManager?: Web3SubscriptionManager | undefined; registeredSubscriptions?: RegisteredSubs; @@ -98,7 +98,10 @@ export class Web3Context< private _wallet?: Web3BaseWallet; public constructor( - providerOrContext: SupportedProviders | Web3ContextInitOptions, + providerOrContext?: + | SupportedProviders + | Web3ContextInitOptions + | string, ) { super(); if ( diff --git a/packages/web3-core/src/web3_request_manager.ts b/packages/web3-core/src/web3_request_manager.ts index a4efa3d7bf3..2a2a00e5d14 100644 --- a/packages/web3-core/src/web3_request_manager.ts +++ b/packages/web3-core/src/web3_request_manager.ts @@ -89,7 +89,7 @@ export class Web3RequestManager< return availableProviders; } - public setProvider(provider: SupportedProviders, net?: Socket) { + public setProvider(provider: SupportedProviders | string, net?: Socket) { let newProvider!: Web3BaseProvider; // autodetect provider diff --git a/packages/web3-errors/src/web3_error_base.ts b/packages/web3-errors/src/web3_error_base.ts index 51387aaa42c..6c4e546a40c 100644 --- a/packages/web3-errors/src/web3_error_base.ts +++ b/packages/web3-errors/src/web3_error_base.ts @@ -27,7 +27,7 @@ export abstract class Web3Error extends Error { this.name = this.constructor.name; if (typeof Error.captureStackTrace === 'function') { - Error.captureStackTrace(this, new.target.constructor); + Error.captureStackTrace(new.target.constructor); } else { this.stack = new Error().stack; } @@ -36,7 +36,7 @@ export abstract class Web3Error extends Error { public static convertToString(value: unknown, unquotValue = false) { // Using "null" value intentionally for validation // eslint-disable-next-line no-null/no-null - if (value === null || value === undefined ) return 'undefined'; + if (value === null || value === undefined) return 'undefined'; const result = JSON.stringify( value, diff --git a/packages/web3-eth-contract/src/contract.ts b/packages/web3-eth-contract/src/contract.ts index 99290c53ba0..893568b9f60 100644 --- a/packages/web3-eth-contract/src/contract.ts +++ b/packages/web3-eth-contract/src/contract.ts @@ -23,7 +23,7 @@ import { inputAddressFormatter, inputLogFormatter, LogsInput, - PromiEvent, + Web3PromiEvent, Web3EventEmitter, ReceiptInfo, } from 'web3-common'; @@ -368,7 +368,7 @@ export class Contract arguments: args, send: ( options?: PayableTxOptions, - ): PromiEvent, SendTransactionEvents> => { + ): Web3PromiEvent, SendTransactionEvents> => { const modifiedOptions = { ...options }; // Remove to address diff --git a/packages/web3-eth-contract/src/types.ts b/packages/web3-eth-contract/src/types.ts index 1450458ac5e..0d11f47167f 100644 --- a/packages/web3-eth-contract/src/types.ts +++ b/packages/web3-eth-contract/src/types.ts @@ -20,7 +20,7 @@ import { DEFAULT_RETURN_FORMAT, EthExecutionAPI, FormatType, - PromiEvent, + Web3PromiEvent, } from 'web3-common'; import { SupportedProviders } from 'web3-core'; import { ContractAbi } from 'web3-eth-abi'; @@ -91,7 +91,7 @@ export interface NonPayableMethodObject call(tx?: NonPayableCallOptions, block?: BlockNumberOrTag): Promise; send( tx?: NonPayableTxOptions, - ): PromiEvent, SendTransactionEvents>; + ): Web3PromiEvent, SendTransactionEvents>; estimateGas( options?: NonPayableCallOptions, returnFormat?: ReturnFormat, @@ -104,7 +104,7 @@ export interface PayableMethodObject { call(tx?: PayableCallOptions, block?: BlockNumberOrTag): Promise; send( tx?: PayableTxOptions, - ): PromiEvent, SendTransactionEvents>; + ): Web3PromiEvent, SendTransactionEvents>; estimateGas( options?: PayableCallOptions, returnFormat?: ReturnFormat, diff --git a/packages/web3-eth-contract/test/integration/contract_deploy.test.ts b/packages/web3-eth-contract/test/integration/contract_deploy.test.ts index fad447f63ba..d7eeaee0719 100644 --- a/packages/web3-eth-contract/test/integration/contract_deploy.test.ts +++ b/packages/web3-eth-contract/test/integration/contract_deploy.test.ts @@ -97,11 +97,11 @@ describe('contract', () => { it('should emit the "transactionHash" event', async () => { const handler = jest.fn(); - const promiEvent = contract.deploy(deployOptions).send(sendOptions); + const Web3PromiEvent = contract.deploy(deployOptions).send(sendOptions); - promiEvent.on('transactionHash', handler); + Web3PromiEvent.on('transactionHash', handler); // Deploy the contract - await promiEvent; + await Web3PromiEvent; expect(handler).toHaveBeenCalled(); }); @@ -109,11 +109,11 @@ describe('contract', () => { it('should emit the "sending" event', async () => { const handler = jest.fn(); - const promiEvent = contract.deploy(deployOptions).send(sendOptions); + const Web3PromiEvent = contract.deploy(deployOptions).send(sendOptions); - promiEvent.on('sending', handler); + Web3PromiEvent.on('sending', handler); // Deploy the contract - await promiEvent; + await Web3PromiEvent; expect(handler).toHaveBeenCalled(); }); @@ -121,11 +121,11 @@ describe('contract', () => { it('should emit the "sent" event', async () => { const handler = jest.fn(); - const promiEvent = contract.deploy(deployOptions).send(sendOptions); + const Web3PromiEvent = contract.deploy(deployOptions).send(sendOptions); - promiEvent.on('sent', handler); + Web3PromiEvent.on('sent', handler); // Deploy the contract - await promiEvent; + await Web3PromiEvent; expect(handler).toHaveBeenCalled(); }); @@ -133,11 +133,11 @@ describe('contract', () => { it('should emit the "receipt" event', async () => { const handler = jest.fn(); - const promiEvent = contract.deploy(deployOptions).send(sendOptions); + const Web3PromiEvent = contract.deploy(deployOptions).send(sendOptions); - promiEvent.on('receipt', handler); + Web3PromiEvent.on('receipt', handler); // Deploy the contract - await promiEvent; + await Web3PromiEvent; expect(handler).toHaveBeenCalled(); }); diff --git a/packages/web3-eth-ens/src/registry.ts b/packages/web3-eth-ens/src/registry.ts index c2780ec9795..334ca106a3e 100644 --- a/packages/web3-eth-ens/src/registry.ts +++ b/packages/web3-eth-ens/src/registry.ts @@ -69,9 +69,9 @@ export class Registry { txConfig: NonPayableCallOptions, // TODO: web3-eth txconfig should be replaced with sendTransaction type ) { try { - const promievent = this.contract.methods.setTTL(namehash(name), ttl).send(txConfig); + const Web3PromiEvent = this.contract.methods.setTTL(namehash(name), ttl).send(txConfig); - return promievent; + return Web3PromiEvent; } catch (error) { throw new Error(); // TODO: TransactionRevertError Needs to be added after web3-eth call method is implemented } diff --git a/packages/web3-eth-iban/src/index.ts b/packages/web3-eth-iban/src/index.ts index 2dee4210e3e..93b91ba658a 100644 --- a/packages/web3-eth-iban/src/index.ts +++ b/packages/web3-eth-iban/src/index.ts @@ -1,4 +1,4 @@ -/* +/* This file is part of web3.js. web3.js is free software: you can redistribute it and/or modify @@ -15,218 +15,9 @@ You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see . */ -import { toChecksumAddress, isAddress, leftPad, hexToNumber, HexString } from 'web3-utils'; -import { InvalidAddressError } from 'web3-errors'; -import { IbanOptions } from './types'; +import { Web3Iban } from './web3_iban'; -export class Iban { - private readonly _iban: string; +export * from './web3_iban'; +export * from './types'; - public static isDirect(iban: string): boolean { - return iban.length === 34 || iban.length === 35; - } - - public static isIndirect(iban: string): boolean { - return iban.length === 20; - } - - /** - * Construct a direct or indirect IBAN - * - * @param iban - */ - public constructor(iban: string) { - if (Iban.isIndirect(iban) || Iban.isDirect(iban)) { - this._iban = iban; - } else { - throw new Error('Invalid IBAN was provided'); - } - } - - /** - * Prepare an IBAN for mod 97 computation by moving the first 4 chars to the end and transforming the letters to - * numbers (A = 10, B = 11, ..., Z = 35), as specified in ISO13616. - * - * @param iban - */ - private static readonly _iso13616Prepare = (iban: string): string => { - const A = 'A'.charCodeAt(0); - const Z = 'Z'.charCodeAt(0); - - const upperIban = iban.toUpperCase(); - const modifiedIban = `${upperIban.slice(4)}${upperIban.slice(0, 4)}`; - - return modifiedIban - .split('') - .map(n => { - const code = n.charCodeAt(0); - if (code >= A && code <= Z) { - // A = 10, B = 11, ... Z = 35 - return code - A + 10; - } - return n; - }) - .join(''); - }; - - /** - * return the bigint of the given string with the specified base - * - * @param str - * @param base - */ - private static readonly _parseInt = (str: string, base: number): bigint => - [...str].reduce( - (acc, curr) => BigInt(parseInt(curr, base)) + BigInt(base) * acc, - BigInt(0), - ); - - /** - * Calculates the MOD 97 10 of the passed IBAN as specified in ISO7064. - * - * @param iban - */ - private static readonly _mod9710 = (iban: string): number => { - let remainder = iban; - let block; - - while (remainder.length > 2) { - block = remainder.slice(0, 9); - remainder = `${(parseInt(block, 10) % 97).toString()}${remainder.slice(block.length)}`; - } - - return parseInt(remainder, 10) % 97; - }; - - private static readonly _isValid = (iban: string): boolean => - /^XE[0-9]{2}(ETH[0-9A-Z]{13}|[0-9A-Z]{30,31})$/.test(iban) && - Iban._mod9710(Iban._iso13616Prepare(iban)) === 1; - - /** - * check if iban number is direct - */ - public isDirect(): boolean { - return Iban.isDirect(this._iban); - } - - /** - * Get the clients direct address from iban - */ - public toAddress = (): HexString => { - if (this.isDirect()) { - // check if Iban can be converted to an address - const base36 = this._iban.slice(4); - const parsedBigInt = Iban._parseInt(base36, 36); // convert the base36 string to a bigint - const paddedBigInt = leftPad(parsedBigInt, 40); - return toChecksumAddress(paddedBigInt); - } - throw new Error('Iban is indirect and cannot be converted. Must be length of 34 or 35'); - }; - /** - * This method should be used to create an ethereum address from a direct iban address - * - * @param iban - */ - public static toAddress = (iban: string): HexString => { - const ibanObject = new Iban(iban); - return ibanObject.toAddress(); - }; - - /** - * Convert the passed BBAN to an IBAN for this country specification. - * Please note that "generation of the IBAN shall be the exclusive responsibility of the bank/branch servicing the account". - * This method implements the preferred algorithm described in http://en.wikipedia.org/wiki/International_Bank_Account_Number#Generating_IBAN_check_digits - * - * @param bban - */ - public static fromBban(bban: string): Iban { - const countryCode = 'XE'; - - const remainder = this._mod9710(this._iso13616Prepare(`${countryCode}00${bban}`)); - const checkDigit = `0${(98 - remainder).toString()}`.slice(-2); - - return new Iban(`${countryCode}${checkDigit}${bban}`); - } - - /** - * This method should be used to create iban object from an ethereum address - * - * @param address - */ - public static fromAddress(address: HexString): Iban { - if (!isAddress(address)) { - throw new InvalidAddressError(address); - } - - const num = BigInt(hexToNumber(address)); - const base36 = num.toString(36); - const padded = leftPad(base36, 15); - return Iban.fromBban(padded.toUpperCase()); - } - - /** - * This method should be used to create iban address from an ethereum address - * - * @param address - */ - public static toIban(address: HexString): string { - return Iban.fromAddress(address).toString(); - } - - /** - * Should be used to create IBAN object for given institution and identifier - * - * @param options - */ - public static createIndirect(options: IbanOptions): Iban { - return Iban.fromBban(`ETH${options.institution}${options.identifier}`); - } - - /** - * Should be called to get client identifier within institution - */ - public client(): string { - return this.isIndirect() ? this._iban.slice(11) : ''; - } - - /** - * Returns the ibans checksum - */ - public checksum(): string { - return this._iban.slice(2, 4); - } - - /** - * Returns institution identifier from iban - */ - public institution(): string { - return this.isIndirect() ? this._iban.slice(7, 11) : ''; - } - - /** - * Should be called to check if iban is correct - */ - public isValid(): boolean { - return Iban._isValid(this._iban); - } - - /** - * This method should be used to check if given string is valid iban object - * - * @param iban - */ - public static isValid(iban: string) { - return Iban._isValid(iban); - } - - public toString(): string { - return this._iban; - } - - /** - * check if iban number if indirect - */ - public isIndirect(): boolean { - return Iban.isIndirect(this._iban); - } -} +export default Web3Iban; diff --git a/packages/web3-eth-iban/src/web3_iban.ts b/packages/web3-eth-iban/src/web3_iban.ts new file mode 100644 index 00000000000..1847f1bff6d --- /dev/null +++ b/packages/web3-eth-iban/src/web3_iban.ts @@ -0,0 +1,232 @@ +/* +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 . +*/ + +import { toChecksumAddress, isAddress, leftPad, hexToNumber, HexString } from 'web3-utils'; +import { InvalidAddressError } from 'web3-errors'; +import { IbanOptions } from './types'; + +export class Web3Iban { + private readonly _iban: string; + + public static isDirect(iban: string): boolean { + return iban.length === 34 || iban.length === 35; + } + + public static isIndirect(iban: string): boolean { + return iban.length === 20; + } + + /** + * Construct a direct or indirect IBAN + * + * @param iban + */ + public constructor(iban: string) { + if (Web3Iban.isIndirect(iban) || Web3Iban.isDirect(iban)) { + this._iban = iban; + } else { + throw new Error('Invalid IBAN was provided'); + } + } + + /** + * Prepare an IBAN for mod 97 computation by moving the first 4 chars to the end and transforming the letters to + * numbers (A = 10, B = 11, ..., Z = 35), as specified in ISO13616. + * + * @param iban + */ + private static readonly _iso13616Prepare = (iban: string): string => { + const A = 'A'.charCodeAt(0); + const Z = 'Z'.charCodeAt(0); + + const upperIban = iban.toUpperCase(); + const modifiedIban = `${upperIban.slice(4)}${upperIban.slice(0, 4)}`; + + return modifiedIban + .split('') + .map(n => { + const code = n.charCodeAt(0); + if (code >= A && code <= Z) { + // A = 10, B = 11, ... Z = 35 + return code - A + 10; + } + return n; + }) + .join(''); + }; + + /** + * return the bigint of the given string with the specified base + * + * @param str + * @param base + */ + private static readonly _parseInt = (str: string, base: number): bigint => + [...str].reduce( + (acc, curr) => BigInt(parseInt(curr, base)) + BigInt(base) * acc, + BigInt(0), + ); + + /** + * Calculates the MOD 97 10 of the passed IBAN as specified in ISO7064. + * + * @param iban + */ + private static readonly _mod9710 = (iban: string): number => { + let remainder = iban; + let block; + + while (remainder.length > 2) { + block = remainder.slice(0, 9); + remainder = `${(parseInt(block, 10) % 97).toString()}${remainder.slice(block.length)}`; + } + + return parseInt(remainder, 10) % 97; + }; + + private static readonly _isValid = (iban: string): boolean => + /^XE[0-9]{2}(ETH[0-9A-Z]{13}|[0-9A-Z]{30,31})$/.test(iban) && + Web3Iban._mod9710(Web3Iban._iso13616Prepare(iban)) === 1; + + /** + * check if iban number is direct + */ + public isDirect(): boolean { + return Web3Iban.isDirect(this._iban); + } + + /** + * Get the clients direct address from iban + */ + public toAddress = (): HexString => { + if (this.isDirect()) { + // check if Iban can be converted to an address + const base36 = this._iban.slice(4); + const parsedBigInt = Web3Iban._parseInt(base36, 36); // convert the base36 string to a bigint + const paddedBigInt = leftPad(parsedBigInt, 40); + return toChecksumAddress(paddedBigInt); + } + throw new Error('Iban is indirect and cannot be converted. Must be length of 34 or 35'); + }; + /** + * This method should be used to create an ethereum address from a direct iban address + * + * @param iban + */ + public static toAddress = (iban: string): HexString => { + const ibanObject = new Web3Iban(iban); + return ibanObject.toAddress(); + }; + + /** + * Convert the passed BBAN to an IBAN for this country specification. + * Please note that "generation of the IBAN shall be the exclusive responsibility of the bank/branch servicing the account". + * This method implements the preferred algorithm described in http://en.wikipedia.org/wiki/International_Bank_Account_Number#Generating_IBAN_check_digits + * + * @param bban + */ + public static fromBban(bban: string): Web3Iban { + const countryCode = 'XE'; + + const remainder = this._mod9710(this._iso13616Prepare(`${countryCode}00${bban}`)); + const checkDigit = `0${(98 - remainder).toString()}`.slice(-2); + + return new Web3Iban(`${countryCode}${checkDigit}${bban}`); + } + + /** + * This method should be used to create iban object from an ethereum address + * + * @param address + */ + public static fromAddress(address: HexString): Web3Iban { + if (!isAddress(address)) { + throw new InvalidAddressError(address); + } + + const num = BigInt(hexToNumber(address)); + const base36 = num.toString(36); + const padded = leftPad(base36, 15); + return Web3Iban.fromBban(padded.toUpperCase()); + } + + /** + * This method should be used to create iban address from an ethereum address + * + * @param address + */ + public static toIban(address: HexString): string { + return Web3Iban.fromAddress(address).toString(); + } + + /** + * Should be used to create IBAN object for given institution and identifier + * + * @param options + */ + public static createIndirect(options: IbanOptions): Web3Iban { + return Web3Iban.fromBban(`ETH${options.institution}${options.identifier}`); + } + + /** + * Should be called to get client identifier within institution + */ + public client(): string { + return this.isIndirect() ? this._iban.slice(11) : ''; + } + + /** + * Returns the ibans checksum + */ + public checksum(): string { + return this._iban.slice(2, 4); + } + + /** + * Returns institution identifier from iban + */ + public institution(): string { + return this.isIndirect() ? this._iban.slice(7, 11) : ''; + } + + /** + * Should be called to check if iban is correct + */ + public isValid(): boolean { + return Web3Iban._isValid(this._iban); + } + + /** + * This method should be used to check if given string is valid iban object + * + * @param iban + */ + public static isValid(iban: string) { + return Web3Iban._isValid(iban); + } + + public toString(): string { + return this._iban; + } + + /** + * check if iban number if indirect + */ + public isIndirect(): boolean { + return Web3Iban.isIndirect(this._iban); + } +} diff --git a/packages/web3-eth-iban/test/unit/iban.test.ts b/packages/web3-eth-iban/test/unit/iban.test.ts index 8bfd7311ad0..35ab1207190 100644 --- a/packages/web3-eth-iban/test/unit/iban.test.ts +++ b/packages/web3-eth-iban/test/unit/iban.test.ts @@ -15,7 +15,7 @@ You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see . */ -import { Iban } from '../../src/index'; +import { Web3Iban } from '../../src/web3_iban'; import { validIbanToAddressData, validFromBbanData, @@ -33,7 +33,7 @@ describe('iban', () => { describe('create', () => { describe('valid cases', () => { it.each(validIbanToAddressData)('%s', () => { - const iban = new Iban('XE7338O073KYGTWWZN0F2WZ0R8PX5ZPPZS'); + const iban = new Web3Iban('XE7338O073KYGTWWZN0F2WZ0R8PX5ZPPZS'); expect(typeof iban).toBe('object'); }); }); @@ -42,13 +42,13 @@ describe('iban', () => { describe('toAddress', () => { describe('valid cases', () => { it.each(validIbanToAddressData)('%s', (input, output) => { - const iban = new Iban(input); + const iban = new Web3Iban(input); expect(iban.toAddress()).toBe(output); }); }); describe('invalid cases', () => { it.each(invalidIbanToAddressData)('%s', (input, output) => { - const iban = new Iban(input); + const iban = new Web3Iban(input); expect(() => iban.toAddress()).toThrow(output); }); }); @@ -57,12 +57,12 @@ describe('iban', () => { describe('toAddress static method', () => { describe('valid cases', () => { it.each(validIbanToAddressData)('%s', (input, output) => { - expect(Iban.toAddress(input)).toBe(output); + expect(Web3Iban.toAddress(input)).toBe(output); }); }); describe('invalid cases', () => { it.each(invalidIbanToAddressData)('%s', (input, output) => { - expect(() => Iban.toAddress(input)).toThrow(output); + expect(() => Web3Iban.toAddress(input)).toThrow(output); }); }); }); @@ -70,7 +70,7 @@ describe('iban', () => { describe('toIban', () => { describe('valid cases', () => { it.each(validIbanToAddressData)('%s', (output, input) => { - expect(Iban.toIban(input)).toBe(output); + expect(Web3Iban.toIban(input)).toBe(output); }); }); }); @@ -78,7 +78,7 @@ describe('iban', () => { describe('fromAddress', () => { describe('valid cases', () => { it.each(validIbanToAddressData)('%s', (output, input) => { - expect(Iban.fromAddress(input).toString()).toBe(output); + expect(Web3Iban.fromAddress(input).toString()).toBe(output); }); }); }); @@ -86,7 +86,7 @@ describe('iban', () => { describe('fromBban', () => { describe('valid cases', () => { it.each(validFromBbanData)('%s', (input, output) => { - expect(Iban.fromBban(input).toString()).toBe(output); + expect(Web3Iban.fromBban(input).toString()).toBe(output); }); }); }); @@ -94,7 +94,7 @@ describe('iban', () => { describe('createIndirect', () => { describe('valid cases', () => { it.each(validCreateIndirectData)('%s', (input, output) => { - expect(Iban.createIndirect(input).toString()).toBe(output); + expect(Web3Iban.createIndirect(input).toString()).toBe(output); }); }); }); @@ -102,7 +102,7 @@ describe('iban', () => { describe('isValid', () => { describe('valid cases', () => { it.each(isValidData)('%s', (input, output) => { - const iban = new Iban(input); + const iban = new Web3Iban(input); expect(iban.isValid()).toBe(output); }); }); @@ -111,7 +111,7 @@ describe('iban', () => { describe('isValid static', () => { describe('valid cases', () => { it.each(isValidData)('%s', (input, output) => { - expect(Iban.isValid(input)).toBe(output); + expect(Web3Iban.isValid(input)).toBe(output); }); }); }); @@ -119,7 +119,7 @@ describe('iban', () => { describe('isDirect', () => { describe('valid cases', () => { it.each(validIsDirectData)('%s', (input, output) => { - expect(Iban.isValid(input)).toBe(output); + expect(Web3Iban.isValid(input)).toBe(output); }); }); }); @@ -127,7 +127,7 @@ describe('iban', () => { describe('isIndirect', () => { describe('valid cases', () => { it.each(validIsIndirectData)('%s', (input, output) => { - expect(Iban.isIndirect(input)).toBe(output); + expect(Web3Iban.isIndirect(input)).toBe(output); }); }); }); @@ -135,7 +135,7 @@ describe('iban', () => { describe('client', () => { describe('valid cases', () => { it.each(validClientData)('%s', (input, output) => { - const iban = new Iban(input); + const iban = new Web3Iban(input); expect(iban.client()).toBe(output); }); }); @@ -144,7 +144,7 @@ describe('iban', () => { describe('institution', () => { describe('valid cases', () => { it.each(validInstitutionData)('%s', (input, output) => { - const iban = new Iban(input); + const iban = new Web3Iban(input); expect(iban.institution()).toBe(output); }); }); @@ -153,7 +153,7 @@ describe('iban', () => { describe('checksum', () => { describe('valid cases', () => { it.each(validChecksumData)('%s', (input, output) => { - const iban = new Iban(input); + const iban = new Web3Iban(input); expect(iban.checksum()).toBe(output); }); }); diff --git a/packages/web3-eth-personal/src/eth_personal.ts b/packages/web3-eth-personal/src/eth_personal.ts new file mode 100644 index 00000000000..86c4d3df19f --- /dev/null +++ b/packages/web3-eth-personal/src/eth_personal.ts @@ -0,0 +1,60 @@ +/* +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 . +*/ + +import { Web3Context } from 'web3-core'; +import { Transaction } from 'web3-eth'; +import { Address, HexString } from 'web3-utils'; +import { EthPersonalAPI } from './eth_personal_api'; +import * as rpcWrappers from './rpc_method_wrappers'; + +export class EthPersonal extends Web3Context { + public async getAccounts() { + return rpcWrappers.getAccounts(this.requestManager); + } + + public async newAccount(password: string) { + return rpcWrappers.newAccount(this.requestManager, password); + } + + public async unlockAccount(address: Address, password: string, unlockDuration: number) { + return rpcWrappers.unlockAccount(this.requestManager, address, password, unlockDuration); + } + + public async lockAccount(address: Address) { + return rpcWrappers.lockAccount(this.requestManager, address); + } + + public async importRawKey(keyData: HexString, passphrase: string) { + return rpcWrappers.importRawKey(this.requestManager, keyData, passphrase); + } + + public async sendTransaction(tx: Transaction, passphrase: string) { + return rpcWrappers.sendTransaction(this.requestManager, tx, passphrase); + } + + public async signTransaction(tx: Transaction, passphrase: string) { + return rpcWrappers.signTransaction(this.requestManager, tx, passphrase); + } + + public async sign(data: HexString, address: Address, passphrase: string) { + return rpcWrappers.sign(this.requestManager, data, address, passphrase); + } + + public async ecRecover(signedData: HexString, signature: string) { + return rpcWrappers.ecRecover(this.requestManager, signedData, signature); + } +} diff --git a/packages/web3-eth-personal/src/index.ts b/packages/web3-eth-personal/src/index.ts index ad25dab76c0..6c52da72cdd 100644 --- a/packages/web3-eth-personal/src/index.ts +++ b/packages/web3-eth-personal/src/index.ts @@ -1,4 +1,4 @@ -/* +/* This file is part of web3.js. web3.js is free software: you can redistribute it and/or modify @@ -15,48 +15,9 @@ You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see . */ -import { Web3Context } from 'web3-core'; -import { Transaction } from 'web3-eth'; -import { Address, HexString } from 'web3-utils'; -import { EthPersonalAPI } from './eth_personal_api'; -import * as rpcWrappers from './rpc_method_wrappers'; +import { EthPersonal } from './eth_personal'; -export class EthPersonal extends Web3Context { - public async getAccounts() { - return rpcWrappers.getAccounts(this.requestManager); - } - - public async newAccount(password: string) { - return rpcWrappers.newAccount(this.requestManager, password); - } - - public async unlockAccount(address: Address, password: string, unlockDuration: number) { - return rpcWrappers.unlockAccount(this.requestManager, address, password, unlockDuration); - } - - public async lockAccount(address: Address) { - return rpcWrappers.lockAccount(this.requestManager, address); - } - - public async importRawKey(keyData: HexString, passphrase: string) { - return rpcWrappers.importRawKey(this.requestManager, keyData, passphrase); - } - - public async sendTransaction(tx: Transaction, passphrase: string) { - return rpcWrappers.sendTransaction(this.requestManager, tx, passphrase); - } - - public async signTransaction(tx: Transaction, passphrase: string) { - return rpcWrappers.signTransaction(this.requestManager, tx, passphrase); - } - - public async sign(data: HexString, address: Address, passphrase: string) { - return rpcWrappers.sign(this.requestManager, data, address, passphrase); - } - - public async ecRecover(signedData: HexString, signature: string) { - return rpcWrappers.ecRecover(this.requestManager, signedData, signature); - } -} +export * from './types'; +export * from './eth_personal'; export default EthPersonal; diff --git a/packages/web3-eth/src/rpc_method_wrappers.ts b/packages/web3-eth/src/rpc_method_wrappers.ts index 27ccf575339..9647b256cfe 100644 --- a/packages/web3-eth/src/rpc_method_wrappers.ts +++ b/packages/web3-eth/src/rpc_method_wrappers.ts @@ -21,7 +21,7 @@ import { DataFormat, EthExecutionAPI, format, - PromiEvent, + Web3PromiEvent, FMT_BYTES, FMT_NUMBER, DEFAULT_RETURN_FORMAT, @@ -483,7 +483,7 @@ export function sendTransaction< transaction: Transaction, returnFormat: ReturnFormat, options?: SendTransactionOptions, -): PromiEvent { +): Web3PromiEvent { const fromAddress = transaction.from ?? getTransactionFromAttr(web3Context); let transactionFormatted = formatTransaction( @@ -491,7 +491,7 @@ export function sendTransaction< DEFAULT_RETURN_FORMAT, ); - const promiEvent = new PromiEvent((resolve, reject) => { + const promiEvent = new Web3PromiEvent((resolve, reject) => { setImmediate(() => { (async () => { try { @@ -624,10 +624,10 @@ export function sendSignedTransaction( web3Context: Web3Context, signedTransaction: Bytes, returnFormat: ReturnFormat, -): PromiEvent { +): Web3PromiEvent { // TODO - Promise returned in function argument where a void return was expected // eslint-disable-next-line @typescript-eslint/no-misused-promises - const promiEvent = new PromiEvent(resolve => { + const promiEvent = new Web3PromiEvent(resolve => { setImmediate(() => { (async () => { // Formatting signedTransaction as per returnFormat to be returned to user diff --git a/packages/web3-eth/src/utils/watch_transaction_for_confirmations.ts b/packages/web3-eth/src/utils/watch_transaction_for_confirmations.ts index 40ec59e68f0..10c63c61d9a 100644 --- a/packages/web3-eth/src/utils/watch_transaction_for_confirmations.ts +++ b/packages/web3-eth/src/utils/watch_transaction_for_confirmations.ts @@ -19,7 +19,7 @@ import { DataFormat, EthExecutionAPI, format, - PromiEvent, + Web3PromiEvent, Web3BaseProvider, } from 'web3-common'; import { SubscriptionError } from 'web3-errors'; @@ -35,19 +35,19 @@ import { ReceiptInfo, SendSignedTransactionEvents, SendTransactionEvents } from import { getBlockByNumber } from '../rpc_methods'; import { NewHeadsSubscription } from '../web3_subscriptions'; -type PromiEventEventTypeBase = SendTransactionEvents | SendSignedTransactionEvents; +type Web3PromiEventEventTypeBase = SendTransactionEvents | SendSignedTransactionEvents; type ReturnFormatBase = DataFormat; type WaitProps = { web3Context: Web3Context; transactionReceipt: ReceiptInfo; - transactionPromiEvent: PromiEvent; + transactionWeb3PromiEvent: Web3PromiEvent; returnFormat: ReturnFormatBase; }; const watchByPolling = ({ web3Context, transactionReceipt, - transactionPromiEvent, + transactionWeb3PromiEvent, returnFormat, }: WaitProps) => { // Having a transactionReceipt means that the transaction has already been included @@ -66,7 +66,7 @@ const watchByPolling = ({ if (nextBlock?.hash) { confirmationNumber += 1; - transactionPromiEvent.emit('confirmation', { + transactionWeb3PromiEvent.emit('confirmation', { confirmationNumber: format({ eth: 'uint' }, confirmationNumber, returnFormat), receipt: transactionReceipt, latestBlockHash: format({ eth: 'bytes32' }, nextBlock.hash, returnFormat), @@ -79,7 +79,7 @@ const watchByPolling = ({ const watchBySubscription = ({ web3Context, transactionReceipt, - transactionPromiEvent, + transactionWeb3PromiEvent, returnFormat, }: WaitProps) => { setImmediate(() => { @@ -92,7 +92,7 @@ const watchBySubscription = ({ } const confirmationNumber = BigInt(data.number) - BigInt(transactionReceipt.blockNumber) + BigInt(1); - transactionPromiEvent.emit('confirmation', { + transactionWeb3PromiEvent.emit('confirmation', { confirmationNumber: format( { eth: 'uint' }, confirmationNumber, @@ -114,7 +114,7 @@ const watchBySubscription = ({ watchByPolling({ web3Context, transactionReceipt, - transactionPromiEvent, + transactionWeb3PromiEvent, returnFormat, }); }); @@ -132,18 +132,18 @@ const watchBySubscription = ({ /** * * @param web3Context - * @param transactionPromiEvent + * @param transactionWeb3PromiEvent * @param transactionReceipt * @param transactionHash * @param returnFormat */ export function watchTransactionForConfirmations< - PromiEventEventType extends PromiEventEventTypeBase, + Web3PromiEventEventType extends Web3PromiEventEventTypeBase, ReturnFormat extends DataFormat, ResolveType = ReceiptInfo, >( web3Context: Web3Context, - transactionPromiEvent: PromiEvent, + transactionWeb3PromiEvent: Web3PromiEvent, transactionReceipt: ReceiptInfo, transactionHash: Bytes, returnFormat: ReturnFormat, @@ -164,10 +164,15 @@ export function watchTransactionForConfirmations< watchBySubscription({ web3Context, transactionReceipt, - transactionPromiEvent, + transactionWeb3PromiEvent, returnFormat, }); } else { - watchByPolling({ web3Context, transactionReceipt, transactionPromiEvent, returnFormat }); + watchByPolling({ + web3Context, + transactionReceipt, + transactionWeb3PromiEvent, + returnFormat, + }); } } diff --git a/packages/web3-eth/test/integration/helper.ts b/packages/web3-eth/test/integration/helper.ts index fc5625ea672..eaaca342405 100644 --- a/packages/web3-eth/test/integration/helper.ts +++ b/packages/web3-eth/test/integration/helper.ts @@ -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 . */ -import { PromiEvent } from 'web3-common'; +import { Web3PromiEvent } from 'web3-common'; import { ReceiptInfo, SendTransactionEvents, Web3Eth } from '../../src'; type SendFewTxParams = { @@ -34,7 +34,7 @@ export const sendFewTxes = async ({ }: SendFewTxParams): Promise => { const res = []; for (let i = 0; i < times; i += 1) { - const tx: PromiEvent = web3Eth.sendTransaction({ + const tx: Web3PromiEvent = web3Eth.sendTransaction({ to, value, from, diff --git a/packages/web3-eth/test/integration/watch_transaction.test.ts b/packages/web3-eth/test/integration/watch_transaction.test.ts index 79cb57a7350..5abefcdeddd 100644 --- a/packages/web3-eth/test/integration/watch_transaction.test.ts +++ b/packages/web3-eth/test/integration/watch_transaction.test.ts @@ -15,7 +15,7 @@ You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see . */ import WebSocketProvider from 'web3-providers-ws'; -import { PromiEvent, Web3BaseProvider } from 'web3-common'; +import { Web3PromiEvent, Web3BaseProvider } from 'web3-common'; import { Web3Eth, SendTransactionEvents, ReceiptInfo } from '../../src'; import { sendFewTxes } from './helper'; @@ -60,11 +60,12 @@ describeIf(getSystemTestProvider().startsWith('ws'))('watch subscription transac const from = accounts[0]; const to = accounts[1]; const value = `0x1`; - const sentTx: PromiEvent = web3Eth.sendTransaction({ - to, - value, - from, - }); + const sentTx: Web3PromiEvent = + web3Eth.sendTransaction({ + to, + value, + from, + }); const receiptPromise = new Promise((resolve: Resolve) => { sentTx.on('receipt', (params: ReceiptInfo) => { @@ -108,11 +109,12 @@ describeIf(getSystemTestProvider().startsWith('http'))('watch polling transactio const to = accounts[1]; const value = `0x1`; - const sentTx: PromiEvent = web3Eth.sendTransaction({ - to, - value, - from, - }); + const sentTx: Web3PromiEvent = + web3Eth.sendTransaction({ + to, + value, + from, + }); let shouldBe = 2; const confirmationPromise = new Promise((resolve: Resolve) => { sentTx.on('confirmation', ({ confirmationNumber }) => { diff --git a/packages/web3-eth/test/unit/rpc_method_wrappers/send_signed_transaction.test.ts b/packages/web3-eth/test/unit/rpc_method_wrappers/send_signed_transaction.test.ts index fc6211b8b59..15c0e2c08ea 100644 --- a/packages/web3-eth/test/unit/rpc_method_wrappers/send_signed_transaction.test.ts +++ b/packages/web3-eth/test/unit/rpc_method_wrappers/send_signed_transaction.test.ts @@ -54,12 +54,12 @@ describe('sendTransaction', () => { inputSignedTransaction, DEFAULT_RETURN_FORMAT, ); - const promiEvent = sendSignedTransaction( + const Web3PromiEvent = sendSignedTransaction( web3Context, inputSignedTransaction, DEFAULT_RETURN_FORMAT, ); - promiEvent.on('sending', signedTransaction => { + Web3PromiEvent.on('sending', signedTransaction => { expect(signedTransaction).toStrictEqual(inputSignedTransactionFormatted); done(undefined); }); @@ -92,12 +92,12 @@ describe('sendTransaction', () => { inputSignedTransaction, DEFAULT_RETURN_FORMAT, ); - const promiEvent = sendSignedTransaction( + const Web3PromiEvent = sendSignedTransaction( web3Context, inputSignedTransaction, DEFAULT_RETURN_FORMAT, ); - promiEvent.on('sent', signedTransaction => { + Web3PromiEvent.on('sent', signedTransaction => { expect(signedTransaction).toStrictEqual(inputSignedTransactionFormatted); done(undefined); }); @@ -113,12 +113,12 @@ describe('sendTransaction', () => { expectedTransactionHash, ); - const promiEvent = sendSignedTransaction( + const Web3PromiEvent = sendSignedTransaction( web3Context, inputSignedTransaction, DEFAULT_RETURN_FORMAT, ); - promiEvent.on('transactionHash', transactionHash => { + Web3PromiEvent.on('transactionHash', transactionHash => { expect(transactionHash).toStrictEqual(expectedTransactionHash); done(undefined); }); @@ -182,12 +182,12 @@ describe('sendTransaction', () => { expectedReceiptInfo, ); - const promiEvent = sendSignedTransaction( + const Web3PromiEvent = sendSignedTransaction( web3Context, inputSignedTransaction, DEFAULT_RETURN_FORMAT, ); - promiEvent.on('receipt', receiptInfo => { + Web3PromiEvent.on('receipt', receiptInfo => { expect(receiptInfo).toStrictEqual(formattedReceiptInfo); done(undefined); }); @@ -196,7 +196,7 @@ describe('sendTransaction', () => { ); it.each(testData)( - `should resolve promiEvent with expectedReceiptInfo\n ${testMessage}`, + `should resolve Web3PromiEvent with expectedReceiptInfo\n ${testMessage}`, async (_, inputSignedTransaction) => { const formattedReceiptInfo = format( receiptInfoSchema, @@ -237,13 +237,13 @@ describe('sendTransaction', () => { expectedReceiptInfo, ); - const promiEvent = sendSignedTransaction( + const Web3PromiEvent = sendSignedTransaction( web3Context, inputTransaction, DEFAULT_RETURN_FORMAT, ); - promiEvent.on('confirmation', () => undefined); - await promiEvent; + Web3PromiEvent.on('confirmation', () => undefined); + await Web3PromiEvent; expect(rpcMethods.getTransactionReceipt).toHaveBeenCalledWith( web3Context.requestManager, @@ -251,7 +251,7 @@ describe('sendTransaction', () => { ); expect(watchTransactionForConfirmationsSpy).toHaveBeenCalledWith( web3Context, - promiEvent, + Web3PromiEvent, formattedReceiptInfo, expectedTransactionHash, DEFAULT_RETURN_FORMAT, diff --git a/packages/web3-eth/test/unit/rpc_method_wrappers/send_transaction.test.ts b/packages/web3-eth/test/unit/rpc_method_wrappers/send_transaction.test.ts index 6e7556341b0..9350f8e6115 100644 --- a/packages/web3-eth/test/unit/rpc_method_wrappers/send_transaction.test.ts +++ b/packages/web3-eth/test/unit/rpc_method_wrappers/send_transaction.test.ts @@ -87,13 +87,13 @@ describe('sendTransaction', () => { (rpcMethods.getTransactionReceipt as jest.Mock).mockResolvedValue( expectedReceiptInfo, ); - const promiEvent = sendTransaction( + const Web3PromiEvent = sendTransaction( web3Context, inputTransaction, DEFAULT_RETURN_FORMAT, sendTransactionOptions, ); - promiEvent.on('sending', transaction => { + Web3PromiEvent.on('sending', transaction => { expect(transaction).toStrictEqual(formattedTransaction); done(undefined); }); @@ -130,13 +130,13 @@ describe('sendTransaction', () => { (rpcMethods.getTransactionReceipt as jest.Mock).mockResolvedValue( expectedReceiptInfo, ); - const promiEvent = sendTransaction( + const Web3PromiEvent = sendTransaction( web3Context, inputTransaction, DEFAULT_RETURN_FORMAT, sendTransactionOptions, ); - promiEvent.on('sent', transaction => { + Web3PromiEvent.on('sent', transaction => { expect(transaction).toStrictEqual(formattedTransaction); done(undefined); }); @@ -155,13 +155,13 @@ describe('sendTransaction', () => { expectedReceiptInfo, ); - const promiEvent = sendTransaction( + const Web3PromiEvent = sendTransaction( web3Context, inputTransaction, DEFAULT_RETURN_FORMAT, sendTransactionOptions, ); - promiEvent.on('transactionHash', transactionHash => { + Web3PromiEvent.on('transactionHash', transactionHash => { expect(transactionHash).toStrictEqual(expectedTransactionHash); done(undefined); }); @@ -235,13 +235,13 @@ describe('sendTransaction', () => { (rpcMethods.getTransactionReceipt as jest.Mock).mockResolvedValueOnce( formattedReceiptInfo, ); - const promiEvent = sendTransaction( + const Web3PromiEvent = sendTransaction( web3Context, inputTransaction, DEFAULT_RETURN_FORMAT, sendTransactionOptions, ); - promiEvent.on('receipt', receiptInfo => { + Web3PromiEvent.on('receipt', receiptInfo => { expect(receiptInfo).toStrictEqual(formattedReceiptInfo); done(undefined); }); @@ -250,7 +250,7 @@ describe('sendTransaction', () => { ); it.each(testData)( - `should resolve promiEvent with expectedReceiptInfo\n ${testMessage}`, + `should resolve Web3PromiEvent with expectedReceiptInfo\n ${testMessage}`, async (_, inputTransaction, sendTransactionOptions) => { const formattedReceiptInfo = format( receiptInfoSchema, @@ -291,14 +291,14 @@ describe('sendTransaction', () => { expectedReceiptInfo, ); - const promiEvent = sendTransaction( + const Web3PromiEvent = sendTransaction( web3Context, inputTransaction, DEFAULT_RETURN_FORMAT, sendTransactionOptions, ); - promiEvent.on('confirmation', () => undefined); - await promiEvent; + Web3PromiEvent.on('confirmation', () => undefined); + await Web3PromiEvent; expect(rpcMethods.getTransactionReceipt).toHaveBeenCalledWith( web3Context.requestManager, @@ -306,7 +306,7 @@ describe('sendTransaction', () => { ); expect(watchTransactionForConfirmationsSpy).toHaveBeenCalledWith( web3Context, - promiEvent, + Web3PromiEvent, formattedReceiptInfo, expectedTransactionHash, DEFAULT_RETURN_FORMAT, diff --git a/packages/web3-utils/package.json b/packages/web3-utils/package.json index 85eec15b75e..3800e10a257 100644 --- a/packages/web3-utils/package.json +++ b/packages/web3-utils/package.json @@ -42,6 +42,6 @@ "dependencies": { "web3-errors": "1.0.0-alpha.0", "web3-validator": "^0.1.0-alpha.0", - "ethereum-cryptography": "^0.2.0" + "ethereum-cryptography": "^1.0.3" } } diff --git a/packages/web3/package.json b/packages/web3/package.json index 1b14f505494..ced7ea6fc4c 100644 --- a/packages/web3/package.json +++ b/packages/web3/package.json @@ -59,6 +59,7 @@ "web3-eth-accounts": "4.0.0-alpha.0", "web3-eth-contract": "4.0.0-alpha.0", "web3-eth-ens": "4.0.0-alpha.0", + "web3-eth-personal": "4.0.0-alpha.0", "web3-eth-iban": "4.0.0-alpha.0", "web3-net": "^4.0.0-alpha.0", "web3-utils": "4.0.0-alpha.1" diff --git a/packages/web3/src/web3.ts b/packages/web3/src/web3.ts index f87e4caffa0..626813f4083 100644 --- a/packages/web3/src/web3.ts +++ b/packages/web3/src/web3.ts @@ -17,9 +17,11 @@ along with web3.js. If not, see . // eslint-disable-next-line max-classes-per-file import { EthExecutionAPI } from 'web3-common'; import { SupportedProviders, Web3Context } from 'web3-core'; -import Eth from 'web3-eth'; -import { Iban } from 'web3-eth-iban'; +import Web3Eth from 'web3-eth'; +import Web3Iban from 'web3-eth-iban'; +import Web3Net from 'web3-net'; import { ENS, registryAddresses } from 'web3-eth-ens'; +import Web3Personal from 'web3-eth-personal'; import { ContractAbi, encodeFunctionCall, @@ -44,12 +46,25 @@ import { decrypt, Wallet, } from 'web3-eth-accounts'; +import * as utils from 'web3-utils'; import { Address } from 'web3-utils'; export class Web3 extends Web3Context { - public eth: Eth & { - Iban: typeof Iban; + public static utils = utils; + public static modules = { + Web3Eth, + Web3Iban, + Web3Net, + Web3Ens: ENS, + Web3Personal, + }; + + public eth: Web3Eth & { + Iban: typeof Web3Iban; ens: ENS; + utils: typeof utils; + net: Web3Net; + personal: Web3Personal; Contract: typeof Contract & { setProvider: (provider: SupportedProviders) => void; }; @@ -76,7 +91,7 @@ export class Web3 extends Web3Context { }; }; - public constructor(provider: SupportedProviders) { + public constructor(provider: SupportedProviders | string) { const accountProvider = { create, privateKeyToAccount, @@ -116,7 +131,7 @@ export class Web3 extends Web3Context { } } - const eth = self.use(Eth); + const eth = self.use(Web3Eth); // Eth Module this.eth = Object.assign(eth, { @@ -124,7 +139,12 @@ export class Web3 extends Web3Context { ens: self.use(ENS, registryAddresses.main), // registry address defaults to main network // Iban helpers - Iban, + Iban: Web3Iban, + + net: self.use(Web3Net), + personal: self.use(Web3Personal), + + utils, // Contract helper and module Contract: ContractBuilder, diff --git a/tsconfig.json b/tsconfig.json index fd057663da0..4f777846637 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -2,7 +2,7 @@ "compilerOptions": { "resolveJsonModule": true, "forceConsistentCasingInFileNames": true, - "target": "es2020", + "target": "es2016", "module": "commonjs", "declaration": true, "moduleResolution": "node", diff --git a/yarn.lock b/yarn.lock index e83fda21cde..4363b77e76f 100644 --- a/yarn.lock +++ b/yarn.lock @@ -1718,11 +1718,21 @@ resolved "https://registry.yarnpkg.com/@microsoft/tsdoc/-/tsdoc-0.14.1.tgz#155ef21065427901994e765da8a0ba0eaae8b8bd" integrity sha512-6Wci+Tp3CgPt/B9B0a3J4s3yMgLNSku6w5TV6mN+61C71UqsRBv2FUibBf3tPGlNxebgPHMEUzKpb1ggE8KCKw== +"@noble/hashes@1.0.0", "@noble/hashes@~1.0.0": + version "1.0.0" + resolved "https://registry.yarnpkg.com/@noble/hashes/-/hashes-1.0.0.tgz#d5e38bfbdaba174805a4e649f13be9a9ed3351ae" + integrity sha512-DZVbtY62kc3kkBtMHqwCOfXrT/hnoORy5BJ4+HU1IR59X0KWAOqsfzQPcUl/lQLlG7qXbe/fZ3r/emxtAl+sqg== + "@noble/hashes@^0.4.4": version "0.4.5" resolved "https://registry.yarnpkg.com/@noble/hashes/-/hashes-0.4.5.tgz#f69a963b0c59c1145bc5aca1f3eef58a48bf9a59" integrity sha512-oK/2b9gHb1CfiFwpPHQs010WgROn4ioilT7TFwxMVwuDaXEJP3QPhyedYbOpgM4JDBgT9n5gaispBQlkaAgT6g== +"@noble/secp256k1@1.5.5", "@noble/secp256k1@~1.5.2": + version "1.5.5" + resolved "https://registry.yarnpkg.com/@noble/secp256k1/-/secp256k1-1.5.5.tgz#315ab5745509d1a8c8e90d0bdf59823ccf9bcfc3" + integrity sha512-sZ1W6gQzYnu45wPrWx8D3kwI2/U29VYTx9OjbDAd7jwRItJ0cSTMPRL/C8AWZFn9kWFLQGqEXVEE86w4Z8LpIQ== + "@noble/secp256k1@^1.3.3": version "1.3.4" resolved "https://registry.yarnpkg.com/@noble/secp256k1/-/secp256k1-1.3.4.tgz#158ded712d09237c0d3428be60dc01ce8ebab9fb" @@ -1925,6 +1935,28 @@ resolved "https://registry.yarnpkg.com/@openzeppelin/contracts/-/contracts-4.6.0.tgz#c91cf64bc27f573836dba4122758b4743418c1b3" integrity sha512-8vi4d50NNya/bQqCmaVzvHNmwHvS0OBKb7HNtuNwEE3scXWrP31fKQoGxNMT+KbzmrNZzatE3QK5p2gFONI/hg== +"@scure/base@~1.0.0": + version "1.0.0" + resolved "https://registry.yarnpkg.com/@scure/base/-/base-1.0.0.tgz#109fb595021de285f05a7db6806f2f48296fcee7" + integrity sha512-gIVaYhUsy+9s58m/ETjSJVKHhKTBMmcRb9cEV5/5dwvfDlfORjKrFsDeDHWRrm6RjcPvCLZFwGJjAjLj1gg4HA== + +"@scure/bip32@1.0.1": + version "1.0.1" + resolved "https://registry.yarnpkg.com/@scure/bip32/-/bip32-1.0.1.tgz#1409bdf9f07f0aec99006bb0d5827693418d3aa5" + integrity sha512-AU88KKTpQ+YpTLoicZ/qhFhRRIo96/tlb+8YmDDHR9yiKVjSsFZiefJO4wjS2PMTkz5/oIcw84uAq/8pleQURA== + dependencies: + "@noble/hashes" "~1.0.0" + "@noble/secp256k1" "~1.5.2" + "@scure/base" "~1.0.0" + +"@scure/bip39@1.0.0": + version "1.0.0" + resolved "https://registry.yarnpkg.com/@scure/bip39/-/bip39-1.0.0.tgz#47504e58de9a56a4bbed95159d2d6829fa491bb0" + integrity sha512-HrtcikLbd58PWOkl02k9V6nXWQyoa7A0+Ek9VF7z17DDk9XZAFUcIdqfh0jJXLypmizc5/8P6OxoUeKliiWv4w== + dependencies: + "@noble/hashes" "~1.0.0" + "@scure/base" "~1.0.0" + "@sinonjs/commons@^1.7.0": version "1.8.3" resolved "https://registry.yarnpkg.com/@sinonjs/commons/-/commons-1.8.3.tgz#3802ddd21a50a949b6721ddd72da36e67e7f1b2d" @@ -4931,15 +4963,6 @@ ethereum-cryptography@^0.1.3: secp256k1 "^4.0.1" setimmediate "^1.0.5" -ethereum-cryptography@^0.2.0: - version "0.2.0" - resolved "https://registry.yarnpkg.com/ethereum-cryptography/-/ethereum-cryptography-0.2.0.tgz#6a163130141abe85e0300646eee95323ae725555" - integrity sha512-6w64pvUvH3InBwNhax5j7brR4aGbdbd9B1R1uRwK9jNMTmyWMd7mSBxcGlMQv23qh+l/n0yjbQp2j0Q/gxhRdw== - dependencies: - micro-base "^0.9.0" - noble-hashes "^0.2.1" - noble-secp256k1 "^1.2.14" - ethereum-cryptography@^0.2.1: version "0.2.1" resolved "https://registry.yarnpkg.com/ethereum-cryptography/-/ethereum-cryptography-0.2.1.tgz#7a2cce5c47157eb6992229cf26ccd889d5ee4754" @@ -4949,6 +4972,16 @@ ethereum-cryptography@^0.2.1: "@noble/secp256k1" "^1.3.3" micro-base "^0.10.0" +ethereum-cryptography@^1.0.3: + version "1.0.3" + resolved "https://registry.yarnpkg.com/ethereum-cryptography/-/ethereum-cryptography-1.0.3.tgz#b1f8f4e702434b2016248dbb2f9fdd60c54772d8" + integrity sha512-NQLTW0x0CosoVb/n79x/TRHtfvS3hgNUPTUSCu0vM+9k6IIhHFFrAOJReneexjZsoZxMjJHnJn4lrE8EbnSyqQ== + dependencies: + "@noble/hashes" "1.0.0" + "@noble/secp256k1" "1.5.5" + "@scure/bip32" "1.0.1" + "@scure/bip39" "1.0.0" + ethereum-protocol@^1.0.1: version "1.0.1" resolved "https://registry.yarnpkg.com/ethereum-protocol/-/ethereum-protocol-1.0.1.tgz#b7d68142f4105e0ae7b5e178cf42f8d4dc4b93cf" @@ -7923,11 +7956,6 @@ micro-base@^0.10.0: resolved "https://registry.yarnpkg.com/micro-base/-/micro-base-0.10.0.tgz#2a324c7836920b2cbca674f46d0644b7e56e4012" integrity sha512-huKVznyEDZVO7pcYoVZMBR6prkxzkJSTT96T2tyHY1Wk3Sywcpb7NwxHAwKf/fmfqsdFuY2rDRR3UYkY6Uh9LQ== -micro-base@^0.9.0: - version "0.9.0" - resolved "https://registry.yarnpkg.com/micro-base/-/micro-base-0.9.0.tgz#09cfe20285bec0ea97f41dc3d10e3fba3d0266ee" - integrity sha512-4+tOMKidYT5nQ6/UNmYrGVO5PMcnJdfuR4NC8HK8s2H61B4itOhA9yrsjBdqGV7ecdtej36x3YSIfPLRmPrspg== - micromatch@^3.1.10: version "3.1.10" resolved "https://registry.yarnpkg.com/micromatch/-/micromatch-3.1.10.tgz#70859bc95c9840952f359a068a3fc49f9ecfac23" @@ -8246,16 +8274,6 @@ neo-async@^2.6.0, neo-async@^2.6.2: resolved "https://registry.yarnpkg.com/neo-async/-/neo-async-2.6.2.tgz#b4aafb93e3aeb2d8174ca53cf163ab7d7308305f" integrity sha512-Yd3UES5mWCSqR+qNT93S3UoYUkqAZ9lLg8a7g9rimsWmYGK8cVToA4/sF3RrshdyV3sAGMXVUmpMYOw+dLpOuw== -noble-hashes@^0.2.1: - version "0.2.2" - resolved "https://registry.yarnpkg.com/noble-hashes/-/noble-hashes-0.2.2.tgz#f174cc18ba2fd1ee8b416e4da568f6706f00bb34" - integrity sha512-5wKykPleHvJ8y6htmb4+4ecgHA0n1F4n0xtfMdXjkhqoQsZE9QTp+nriQzss9RQKJ86GUWZwXnq0CM4VW8ApSg== - -noble-secp256k1@^1.2.14: - version "1.2.14" - resolved "https://registry.yarnpkg.com/noble-secp256k1/-/noble-secp256k1-1.2.14.tgz#39429c941d51211ca40161569cee03e61d72599e" - integrity sha512-GSCXyoZBUaaPwVWdYncMEmzlSUjF9J/YeEHpklYJCyg8wPuJP3NzDx0BkiwArzINkdX2HJHvUJhL6vVWPOQQcg== - node-addon-api@^2.0.0: version "2.0.2" resolved "https://registry.yarnpkg.com/node-addon-api/-/node-addon-api-2.0.2.tgz#432cfa82962ce494b132e9d72a15b29f71ff5d32" From 2e8eb6e18bbf3853bf77971e2ac865be53739280 Mon Sep 17 00:00:00 2001 From: Nazar Hussain Date: Mon, 13 Jun 2022 18:31:52 +0200 Subject: [PATCH 02/26] :white_check_mark: Update failing tests --- .eslintrc.js | 2 +- .../web3-common/test/unit/formatters.test.ts | 24 +++++++++---------- packages/web3-core/src/web3_context.ts | 4 ++-- .../web3-core/src/web3_request_manager.ts | 2 +- packages/web3-eth-ens/src/ens.ts | 3 ++- packages/web3-eth/src/web3_eth.ts | 4 +++- .../web3-utils/test/fixtures/converters.ts | 4 ---- .../test/fixtures/string_manipulation.ts | 9 +------ .../web3-utils/test/fixtures/validation.ts | 5 ++-- .../test/fixtures/validation.ts | 14 +++++------ tools/eslint-config-web3-base/ts.js | 1 - 11 files changed, 30 insertions(+), 42 deletions(-) diff --git a/.eslintrc.js b/.eslintrc.js index 672cf7e7b87..e9a13140da7 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -2,10 +2,10 @@ module.exports = { root: true, env: { browser: true, - es2021: true, node: true, }, parserOptions: { + ecmaVersion: 2016, project: './tsconfig.json', tsconfigRootDir: __dirname, sourceType: 'module', diff --git a/packages/web3-common/test/unit/formatters.test.ts b/packages/web3-common/test/unit/formatters.test.ts index 428996fb1a0..2b3b5f199a3 100644 --- a/packages/web3-common/test/unit/formatters.test.ts +++ b/packages/web3-common/test/unit/formatters.test.ts @@ -16,7 +16,7 @@ along with web3.js. If not, see . */ import * as utils from 'web3-utils'; -import { Iban } from 'web3-eth-iban'; +import { Web3Iban } from 'web3-eth-iban'; import { inputAddressFormatter, inputBlockNumberFormatter, @@ -54,8 +54,8 @@ describe('formatters', () => { jest.spyOn(utils, 'isHexStrict').mockReturnValue(true); jest.spyOn(utils, 'isAddress').mockReturnValue(true); jest.spyOn(utils, 'sha3Raw').mockReturnValue(sha3Result); - jest.spyOn(Iban, 'isValid').mockImplementation(() => false); - jest.spyOn(Iban, 'isDirect').mockImplementation(() => false); + jest.spyOn(Web3Iban, 'isValid').mockImplementation(() => false); + jest.spyOn(Web3Iban, 'isDirect').mockImplementation(() => false); }); describe('outputProofFormatter', () => { @@ -82,9 +82,9 @@ describe('formatters', () => { describe('outputBigIntegerFormatter', () => { it('should convert input to number', () => { - const result = outputBigIntegerFormatter(12n); + const result = outputBigIntegerFormatter(BigInt(12)); - expect(utils.toNumber).toHaveBeenCalledWith(12n); + expect(utils.toNumber).toHaveBeenCalledWith(BigInt(12)); expect(result).toEqual(toNumberResult); }); }); @@ -139,13 +139,13 @@ describe('formatters', () => { describe('inputAddressFormatter', () => { it('should return lowercase address if given value is iban', () => { const address = '0x00c5496aee77c1ba1f0854206a26dda82a81d6d8'; - Iban.prototype.toAddress = jest.fn(() => address); + Web3Iban.prototype.toAddress = jest.fn(() => address); - jest.spyOn(Iban, 'isValid').mockImplementation(() => true); - jest.spyOn(Iban, 'isDirect').mockImplementation(() => true); + jest.spyOn(Web3Iban, 'isValid').mockImplementation(() => true); + jest.spyOn(Web3Iban, 'isDirect').mockImplementation(() => true); expect(inputAddressFormatter('XE7338O073KYGTWWZN0F2WZ0R8PX5ZPPZS')).toBe(address); - expect(Iban.prototype.toAddress).toHaveBeenCalled(); + expect(Web3Iban.prototype.toAddress).toHaveBeenCalled(); }); it('should return lower case value if valid address', () => { @@ -243,13 +243,13 @@ describe('formatters', () => { it.each(['gasPrice', 'gas', 'value', 'maxPriorityFeePerGas', 'maxFeePerGas', 'nonce'])( 'should convert "%s" number value to hex', attr => { - jest.spyOn(utils, 'toNumber').mockReturnValue(5678n); + jest.spyOn(utils, 'toNumber').mockReturnValue(BigInt(5678)); expect( - txInputOptionsFormatter({ ...txInput, data: '0xff0011', [attr]: 5678n }), + txInputOptionsFormatter({ ...txInput, data: '0xff0011', [attr]: BigInt(5678) }), ).toEqual(expect.objectContaining({ [attr]: numberToHexResult })); - expect(utils.numberToHex).toHaveBeenCalledWith(5678n); + expect(utils.numberToHex).toHaveBeenCalledWith(BigInt(5678)); }, ); }); diff --git a/packages/web3-core/src/web3_context.ts b/packages/web3-core/src/web3_context.ts index 15ef63eae5d..d23a4e9fa54 100644 --- a/packages/web3-core/src/web3_context.ts +++ b/packages/web3-core/src/web3_context.ts @@ -233,7 +233,7 @@ export class Web3Context< return this.requestManager.provider; } - public set provider(provider: SupportedProviders) { + public set provider(provider: SupportedProviders | string) { this.requestManager.setProvider(provider); } @@ -241,7 +241,7 @@ export class Web3Context< return this.requestManager.provider; } - public set currentProvider(provider: SupportedProviders) { + public set currentProvider(provider: SupportedProviders | string) { this.requestManager.setProvider(provider); } diff --git a/packages/web3-core/src/web3_request_manager.ts b/packages/web3-core/src/web3_request_manager.ts index 2a2a00e5d14..fc0b356f000 100644 --- a/packages/web3-core/src/web3_request_manager.ts +++ b/packages/web3-core/src/web3_request_manager.ts @@ -64,7 +64,7 @@ export class Web3RequestManager< }> { private _provider!: SupportedProviders; - public constructor(provider?: SupportedProviders, net?: Socket) { + public constructor(provider?: SupportedProviders | string, net?: Socket) { super(); if (provider) { diff --git a/packages/web3-eth-ens/src/ens.ts b/packages/web3-eth-ens/src/ens.ts index 35817eee341..62aa7a5b4d4 100644 --- a/packages/web3-eth-ens/src/ens.ts +++ b/packages/web3-eth-ens/src/ens.ts @@ -42,7 +42,8 @@ export class ENS extends Web3Context { registryAddr?: string, provider?: | SupportedProviders - | Web3ContextObject, + | Web3ContextObject + | string, ) { super(provider ?? ''); this.registryAddress = registryAddr ?? registryAddresses.main; // will default to main registry address diff --git a/packages/web3-eth/src/web3_eth.ts b/packages/web3-eth/src/web3_eth.ts index 6508d7cc309..3cf00da5ffe 100644 --- a/packages/web3-eth/src/web3_eth.ts +++ b/packages/web3-eth/src/web3_eth.ts @@ -54,7 +54,9 @@ type RegisteredSubscription = { }; export class Web3Eth extends Web3Context { - public constructor(providerOrContext: SupportedProviders | Web3ContextInitOptions) { + public constructor( + providerOrContext: SupportedProviders | Web3ContextInitOptions | string, + ) { super( typeof providerOrContext === 'object' && (providerOrContext as Web3ContextInitOptions).provider diff --git a/packages/web3-utils/test/fixtures/converters.ts b/packages/web3-utils/test/fixtures/converters.ts index 78d6af94b10..ad90c87af35 100644 --- a/packages/web3-utils/test/fixtures/converters.ts +++ b/packages/web3-utils/test/fixtures/converters.ts @@ -77,7 +77,6 @@ export const numberToHexValidData: [Numbers, HexString][] = [ [256, '0x100'], [54, '0x36'], [BigInt(12), '0xc'], - [12n, '0xc'], ['768', '0x300'], ['-768', '-0x300'], [-255, '-0xff'], @@ -136,7 +135,6 @@ export const utf8ToHexValidData: [string, HexString][] = [ export const utf8ToHexInvalidData: [any, string][] = [ [12, 'value "12" at "/0" must pass "string" validation'], [BigInt(12), 'value "12" at "/0" must pass "string" validation'], - [12n, 'value "12" at "/0" must pass "string" validation'], // Using "null" value intentionally for validation // eslint-disable-next-line no-null/no-null [null, 'value at "/0" must pass "string" validation'], @@ -197,7 +195,6 @@ export const toHexValidData: [Numbers | Bytes | Address | boolean, [HexString, V [255, ['0xff', 'uint256']], [256, ['0x100', 'uint256']], [BigInt(12), ['0xc', 'bigint']], - [12n, ['0xc', 'bigint']], ['768', ['0x373638', 'string']], ['-768', ['0x2d373638', 'string']], [-255, ['-0xff', 'int256']], @@ -216,7 +213,6 @@ const conversionBaseData: [[Numbers, EtherUnits], string][] = [ [[123, 'wei'], '123'], [['123', 'wei'], '123'], [[BigInt(123), 'wei'], '123'], - [[123n, 'wei'], '123'], [['1000', 'wei'], '1000'], [['1', 'kwei'], '0.001'], [['1', 'mwei'], '0.000001'], diff --git a/packages/web3-utils/test/fixtures/string_manipulation.ts b/packages/web3-utils/test/fixtures/string_manipulation.ts index 9f70d07d149..df12fc40f1d 100644 --- a/packages/web3-utils/test/fixtures/string_manipulation.ts +++ b/packages/web3-utils/test/fixtures/string_manipulation.ts @@ -27,8 +27,6 @@ export const padLeftData: [[Numbers, number, string], HexString][] = [ [['-abcd', 8, '0'], '000-abcd'], [[BigInt('9007199254740992'), 32, '0'], '0x00000000000000000020000000000000'], [[BigInt('-9007199254740992'), 32, '0'], '-0x00000000000000000020000000000000'], - [[9007199254740992n, 32, '0'], '0x00000000000000000020000000000000'], - [[-9007199254740992n, 32, '0'], '-0x00000000000000000020000000000000'], [[-13, 10, '0'], '-0x000000000d'], [['9.5', 8, '0'], '000009.5'], ]; @@ -52,10 +50,8 @@ export const padRightData: [[Numbers, number, string], HexString][] = [ [['-0x01', 64, 'f'], '-0x01ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff'], [['zxy', 11, '0'], 'zxy00000000'], [['-abcd', 32, '1'], '-abcd111111111111111111111111111'], - [[10000n, 8, '0'], '0x27100000'], [[BigInt(10000), 8, '0'], '0x27100000'], [[BigInt(-14), 8, '0'], '-0xe0000000'], - [[-14n, 8, '0'], '-0xe0000000'], [['15.5', 8, '0'], '15.50000'], ]; @@ -67,8 +63,6 @@ export const toTwosComplementData: [[Numbers, number], HexString][] = [ [['-0x1', 32], '0xffffffffffffffffffffffffffffffff'], [[BigInt('9007199254740992'), 32], '0x00000000000000000020000000000000'], [[BigInt('-9007199254740992'), 32], '0xffffffffffffffffffe0000000000000'], - [[9007199254740992n, 32], '0x00000000000000000020000000000000'], - [[-9007199254740992n, 32], '0xffffffffffffffffffe0000000000000'], [['13', 32], '0x0000000000000000000000000000000d'], [['-13', 32], '0xfffffffffffffffffffffffffffffff3'], [[-16, 2], '0xf0'], @@ -81,7 +75,6 @@ export const fromTwosComplementData: [[Numbers, number], number | bigint][] = [ [['0xfffffffffffffffffffffffffffffff3', 32], -13], [['0xf0', 2], -16], [['0xffffffffffffffffffffffffffffff00', 32], -256], - [['0xffffffffffffffffffe0000000000000', 32], -9007199254740992n], [[1000, 64], 1000], [[-1000, 64], -1000], [[BigInt(9), 1], -7], @@ -107,7 +100,7 @@ export const toTwosComplementInvalidData: [[Numbers, number], string][] = [ 'Invalid value given "value: -0x1000, nibbleWidth: 3". Error: value greater than the nibble width.', ], [ - [-160000n, 1], + [BigInt(-160000), 1], 'Invalid value given "value: -160000, nibbleWidth: 1". Error: value greater than the nibble width.', ], ]; diff --git a/packages/web3-utils/test/fixtures/validation.ts b/packages/web3-utils/test/fixtures/validation.ts index 05a417d9543..3d85fe5ef6f 100644 --- a/packages/web3-utils/test/fixtures/validation.ts +++ b/packages/web3-utils/test/fixtures/validation.ts @@ -24,7 +24,7 @@ export const compareBlockNumbersValidData: [[Numbers, Numbers], number][] = [ [[2, 1], 1], [[BigInt(1), BigInt(1)], 0], [[BigInt(1), BigInt(2)], -1], - [[BigInt(2), 1n], 1], + [[BigInt(2), BigInt(1)], 1], [[1, BigInt(1)], 0], [[1, BigInt(2)], -1], [[2, BigInt(1)], 1], @@ -34,7 +34,6 @@ export const compareBlockNumbersValidData: [[Numbers, Numbers], number][] = [ [['pending', 'pending'], 0], [['latest', 'latest'], 0], [['earliest', 2], -1], - [['earliest', 2n], -1], [['earliest', 'pending'], -1], [['genesis', 2], -1], [['genesis', 'latest'], -1], @@ -43,7 +42,7 @@ export const compareBlockNumbersValidData: [[Numbers, Numbers], number][] = [ [[13532346, 13532300], 1], [['pending', 'latest'], 1], [['latest', 0], 1], - [['latest', 1n], 1], + [['latest', BigInt(1)], 1], [['pending', 0], 1], [['pending', BigInt(1)], 1], ]; diff --git a/packages/web3-validator/test/fixtures/validation.ts b/packages/web3-validator/test/fixtures/validation.ts index bff53863f12..c8a958f2330 100644 --- a/packages/web3-validator/test/fixtures/validation.ts +++ b/packages/web3-validator/test/fixtures/validation.ts @@ -137,8 +137,7 @@ export const invalidHexStrictData: any[] = [ '0', 1, BigInt(12), - 12n, - -255n, + BigInt(-255), -42, 4.2, ]; @@ -150,8 +149,7 @@ export const validHexData: any[] = [ '0', 1, BigInt(12), - 12n, - -255n, + BigInt(-255), ]; export const validCheckAddressCheckSumData: any[] = [ @@ -195,7 +193,7 @@ export const compareBlockNumbersValidData: [[any, any], number][] = [ [[2, 1], 1], [[BigInt(1), BigInt(1)], 0], [[BigInt(1), BigInt(2)], -1], - [[BigInt(2), 1n], 1], + [[BigInt(2), BigInt(1)], 1], [[1, BigInt(1)], 0], [[1, BigInt(2)], -1], [[2, BigInt(1)], 1], @@ -205,7 +203,7 @@ export const compareBlockNumbersValidData: [[any, any], number][] = [ [['pending', 'pending'], 0], [['latest', 'latest'], 0], [['earliest', 2], -1], - [['earliest', 2n], -1], + [['earliest', BigInt(2)], -1], [['earliest', 'pending'], -1], [['genesis', 2], -1], [['genesis', 'latest'], -1], @@ -214,7 +212,7 @@ export const compareBlockNumbersValidData: [[any, any], number][] = [ [[13532346, 13532300], 1], [['pending', 'latest'], 1], [['latest', 0], 1], - [['latest', 1n], 1], + [['latest', BigInt(1)], 1], [['pending', 0], 1], [['pending', BigInt(1)], 1], ]; @@ -299,7 +297,7 @@ export const invalidTopicInBloomData: any[] = [ ], ]; -export const validBigIntData: any[] = [90071992547409911n, BigInt(42), BigInt('1337')]; +export const validBigIntData: any[] = [BigInt('90071992547409911'), BigInt(42), BigInt('1337')]; export const invalidBigIntData: any[] = [3, '3', '3n']; diff --git a/tools/eslint-config-web3-base/ts.js b/tools/eslint-config-web3-base/ts.js index 843710f0fe6..3ffb239546d 100644 --- a/tools/eslint-config-web3-base/ts.js +++ b/tools/eslint-config-web3-base/ts.js @@ -49,7 +49,6 @@ module.exports = { 'eslint:recommended', 'plugin:@typescript-eslint/recommended', 'plugin:@typescript-eslint/recommended-requiring-type-checking', - 'plugin:@typescript-eslint/recommended', 'plugin:jsdoc/recommended', 'prettier', 'plugin:import/errors', From b527ca80198b219043b4835071d6890bc7615852 Mon Sep 17 00:00:00 2001 From: Nazar Hussain Date: Mon, 13 Jun 2022 19:16:45 +0200 Subject: [PATCH 03/26] :white_check_mark: Fix failing tests --- packages/web3-eth-contract/src/contract.ts | 4 ++-- packages/web3-eth-contract/src/types.ts | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/packages/web3-eth-contract/src/contract.ts b/packages/web3-eth-contract/src/contract.ts index 893568b9f60..f71265b158f 100644 --- a/packages/web3-eth-contract/src/contract.ts +++ b/packages/web3-eth-contract/src/contract.ts @@ -27,7 +27,7 @@ import { Web3EventEmitter, ReceiptInfo, } from 'web3-common'; -import { Web3Context, Web3ContextObject } from 'web3-core'; +import { Web3Context, Web3ContextInitOptions } from 'web3-core'; import { call, estimateGas, @@ -162,7 +162,7 @@ export class Contract address?: Address, options?: ContractInitOptions, context?: Partial< - Web3ContextObject< + Web3ContextInitOptions< EthExecutionAPI, { logs: typeof LogsSubscription; diff --git a/packages/web3-eth-contract/src/types.ts b/packages/web3-eth-contract/src/types.ts index 0d11f47167f..663adb3785e 100644 --- a/packages/web3-eth-contract/src/types.ts +++ b/packages/web3-eth-contract/src/types.ts @@ -61,7 +61,7 @@ export interface ContractInitOptions { readonly from?: Address; readonly data?: Bytes; readonly gasLimit?: Uint; - readonly provider: SupportedProviders; + readonly provider: SupportedProviders | string; } export type TransactionReceipt = ReceiptInfo; From 57e6755e5471f8e676e8c88fdd123f443acedb48 Mon Sep 17 00:00:00 2001 From: Nazar Hussain Date: Tue, 14 Jun 2022 11:09:00 +0200 Subject: [PATCH 04/26] :art: Add version attribute to 'Web3' class --- packages/web3/src/web3.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/packages/web3/src/web3.ts b/packages/web3/src/web3.ts index 626813f4083..18bd8b1d388 100644 --- a/packages/web3/src/web3.ts +++ b/packages/web3/src/web3.ts @@ -48,8 +48,10 @@ import { } from 'web3-eth-accounts'; import * as utils from 'web3-utils'; import { Address } from 'web3-utils'; +import packageJson from '../package.json'; export class Web3 extends Web3Context { + public static version = packageJson.version; public static utils = utils; public static modules = { Web3Eth, From c0757de95872f705e718d239573051ba500e762a Mon Sep 17 00:00:00 2001 From: Nazar Hussain Date: Tue, 14 Jun 2022 11:12:00 +0200 Subject: [PATCH 05/26] :truck: Rename the misused promievent names --- .../test/integration/contract_deploy.test.ts | 24 +++++++++---------- packages/web3-eth-ens/src/registry.ts | 4 ++-- .../send_signed_transaction.test.ts | 22 ++++++++--------- .../send_transaction.test.ts | 22 ++++++++--------- 4 files changed, 36 insertions(+), 36 deletions(-) diff --git a/packages/web3-eth-contract/test/integration/contract_deploy.test.ts b/packages/web3-eth-contract/test/integration/contract_deploy.test.ts index d7eeaee0719..fad447f63ba 100644 --- a/packages/web3-eth-contract/test/integration/contract_deploy.test.ts +++ b/packages/web3-eth-contract/test/integration/contract_deploy.test.ts @@ -97,11 +97,11 @@ describe('contract', () => { it('should emit the "transactionHash" event', async () => { const handler = jest.fn(); - const Web3PromiEvent = contract.deploy(deployOptions).send(sendOptions); + const promiEvent = contract.deploy(deployOptions).send(sendOptions); - Web3PromiEvent.on('transactionHash', handler); + promiEvent.on('transactionHash', handler); // Deploy the contract - await Web3PromiEvent; + await promiEvent; expect(handler).toHaveBeenCalled(); }); @@ -109,11 +109,11 @@ describe('contract', () => { it('should emit the "sending" event', async () => { const handler = jest.fn(); - const Web3PromiEvent = contract.deploy(deployOptions).send(sendOptions); + const promiEvent = contract.deploy(deployOptions).send(sendOptions); - Web3PromiEvent.on('sending', handler); + promiEvent.on('sending', handler); // Deploy the contract - await Web3PromiEvent; + await promiEvent; expect(handler).toHaveBeenCalled(); }); @@ -121,11 +121,11 @@ describe('contract', () => { it('should emit the "sent" event', async () => { const handler = jest.fn(); - const Web3PromiEvent = contract.deploy(deployOptions).send(sendOptions); + const promiEvent = contract.deploy(deployOptions).send(sendOptions); - Web3PromiEvent.on('sent', handler); + promiEvent.on('sent', handler); // Deploy the contract - await Web3PromiEvent; + await promiEvent; expect(handler).toHaveBeenCalled(); }); @@ -133,11 +133,11 @@ describe('contract', () => { it('should emit the "receipt" event', async () => { const handler = jest.fn(); - const Web3PromiEvent = contract.deploy(deployOptions).send(sendOptions); + const promiEvent = contract.deploy(deployOptions).send(sendOptions); - Web3PromiEvent.on('receipt', handler); + promiEvent.on('receipt', handler); // Deploy the contract - await Web3PromiEvent; + await promiEvent; expect(handler).toHaveBeenCalled(); }); diff --git a/packages/web3-eth-ens/src/registry.ts b/packages/web3-eth-ens/src/registry.ts index 334ca106a3e..93ce61b5262 100644 --- a/packages/web3-eth-ens/src/registry.ts +++ b/packages/web3-eth-ens/src/registry.ts @@ -69,9 +69,9 @@ export class Registry { txConfig: NonPayableCallOptions, // TODO: web3-eth txconfig should be replaced with sendTransaction type ) { try { - const Web3PromiEvent = this.contract.methods.setTTL(namehash(name), ttl).send(txConfig); + const promiEvent = this.contract.methods.setTTL(namehash(name), ttl).send(txConfig); - return Web3PromiEvent; + return promiEvent; } catch (error) { throw new Error(); // TODO: TransactionRevertError Needs to be added after web3-eth call method is implemented } diff --git a/packages/web3-eth/test/unit/rpc_method_wrappers/send_signed_transaction.test.ts b/packages/web3-eth/test/unit/rpc_method_wrappers/send_signed_transaction.test.ts index bd715f1cac7..1d8d6cf9229 100644 --- a/packages/web3-eth/test/unit/rpc_method_wrappers/send_signed_transaction.test.ts +++ b/packages/web3-eth/test/unit/rpc_method_wrappers/send_signed_transaction.test.ts @@ -58,12 +58,12 @@ describe('sendTransaction', () => { inputSignedTransaction, DEFAULT_RETURN_FORMAT, ); - const Web3PromiEvent = sendSignedTransaction( + const promiEvent = sendSignedTransaction( web3Context, inputSignedTransaction, DEFAULT_RETURN_FORMAT, ); - Web3PromiEvent.on('sending', signedTransaction => { + promiEvent.on('sending', signedTransaction => { expect(signedTransaction).toStrictEqual(inputSignedTransactionFormatted); done(undefined); }); @@ -104,12 +104,12 @@ describe('sendTransaction', () => { inputSignedTransaction, DEFAULT_RETURN_FORMAT, ); - const Web3PromiEvent = sendSignedTransaction( + const promiEvent = sendSignedTransaction( web3Context, inputSignedTransaction, DEFAULT_RETURN_FORMAT, ); - Web3PromiEvent.on('sent', signedTransaction => { + promiEvent.on('sent', signedTransaction => { expect(signedTransaction).toStrictEqual(inputSignedTransactionFormatted); done(undefined); }); @@ -129,12 +129,12 @@ describe('sendTransaction', () => { expectedTransactionHash, ); - const Web3PromiEvent = sendSignedTransaction( + const promiEvent = sendSignedTransaction( web3Context, inputSignedTransaction, DEFAULT_RETURN_FORMAT, ); - Web3PromiEvent.on('transactionHash', transactionHash => { + promiEvent.on('transactionHash', transactionHash => { expect(transactionHash).toStrictEqual(expectedTransactionHash); done(undefined); }); @@ -203,12 +203,12 @@ describe('sendTransaction', () => { expectedReceiptInfo, ); - const Web3PromiEvent = sendSignedTransaction( + const promiEvent = sendSignedTransaction( web3Context, inputSignedTransaction, DEFAULT_RETURN_FORMAT, ); - Web3PromiEvent.on('receipt', receiptInfo => { + promiEvent.on('receipt', receiptInfo => { expect(receiptInfo).toStrictEqual(formattedReceiptInfo); done(undefined); }); @@ -258,13 +258,13 @@ describe('sendTransaction', () => { expectedReceiptInfo, ); - const Web3PromiEvent = sendSignedTransaction( + const promiEvent = sendSignedTransaction( web3Context, inputTransaction, DEFAULT_RETURN_FORMAT, ); - Web3PromiEvent.on('confirmation', () => undefined); - await Web3PromiEvent; + promiEvent.on('confirmation', () => undefined); + await promiEvent; expect(rpcMethods.getTransactionReceipt).toHaveBeenCalledWith( web3Context.requestManager, diff --git a/packages/web3-eth/test/unit/rpc_method_wrappers/send_transaction.test.ts b/packages/web3-eth/test/unit/rpc_method_wrappers/send_transaction.test.ts index 9350f8e6115..8e635bc0b6c 100644 --- a/packages/web3-eth/test/unit/rpc_method_wrappers/send_transaction.test.ts +++ b/packages/web3-eth/test/unit/rpc_method_wrappers/send_transaction.test.ts @@ -87,13 +87,13 @@ describe('sendTransaction', () => { (rpcMethods.getTransactionReceipt as jest.Mock).mockResolvedValue( expectedReceiptInfo, ); - const Web3PromiEvent = sendTransaction( + const promiEvent = sendTransaction( web3Context, inputTransaction, DEFAULT_RETURN_FORMAT, sendTransactionOptions, ); - Web3PromiEvent.on('sending', transaction => { + promiEvent.on('sending', transaction => { expect(transaction).toStrictEqual(formattedTransaction); done(undefined); }); @@ -130,13 +130,13 @@ describe('sendTransaction', () => { (rpcMethods.getTransactionReceipt as jest.Mock).mockResolvedValue( expectedReceiptInfo, ); - const Web3PromiEvent = sendTransaction( + const promiEvent = sendTransaction( web3Context, inputTransaction, DEFAULT_RETURN_FORMAT, sendTransactionOptions, ); - Web3PromiEvent.on('sent', transaction => { + promiEvent.on('sent', transaction => { expect(transaction).toStrictEqual(formattedTransaction); done(undefined); }); @@ -155,13 +155,13 @@ describe('sendTransaction', () => { expectedReceiptInfo, ); - const Web3PromiEvent = sendTransaction( + const promiEvent = sendTransaction( web3Context, inputTransaction, DEFAULT_RETURN_FORMAT, sendTransactionOptions, ); - Web3PromiEvent.on('transactionHash', transactionHash => { + promiEvent.on('transactionHash', transactionHash => { expect(transactionHash).toStrictEqual(expectedTransactionHash); done(undefined); }); @@ -235,13 +235,13 @@ describe('sendTransaction', () => { (rpcMethods.getTransactionReceipt as jest.Mock).mockResolvedValueOnce( formattedReceiptInfo, ); - const Web3PromiEvent = sendTransaction( + const promiEvent = sendTransaction( web3Context, inputTransaction, DEFAULT_RETURN_FORMAT, sendTransactionOptions, ); - Web3PromiEvent.on('receipt', receiptInfo => { + promiEvent.on('receipt', receiptInfo => { expect(receiptInfo).toStrictEqual(formattedReceiptInfo); done(undefined); }); @@ -291,14 +291,14 @@ describe('sendTransaction', () => { expectedReceiptInfo, ); - const Web3PromiEvent = sendTransaction( + const promiEvent = sendTransaction( web3Context, inputTransaction, DEFAULT_RETURN_FORMAT, sendTransactionOptions, ); - Web3PromiEvent.on('confirmation', () => undefined); - await Web3PromiEvent; + promiEvent.on('confirmation', () => undefined); + await promiEvent; expect(rpcMethods.getTransactionReceipt).toHaveBeenCalledWith( web3Context.requestManager, From f785298e0756653f88ebc2893ea90010600e914d Mon Sep 17 00:00:00 2001 From: Nazar Hussain Date: Tue, 14 Jun 2022 11:56:03 +0200 Subject: [PATCH 06/26] :pencil2: Fix the typos in tests --- .../unit/rpc_method_wrappers/send_signed_transaction.test.ts | 2 +- .../test/unit/rpc_method_wrappers/send_transaction.test.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/web3-eth/test/unit/rpc_method_wrappers/send_signed_transaction.test.ts b/packages/web3-eth/test/unit/rpc_method_wrappers/send_signed_transaction.test.ts index 1d8d6cf9229..a086aac64fe 100644 --- a/packages/web3-eth/test/unit/rpc_method_wrappers/send_signed_transaction.test.ts +++ b/packages/web3-eth/test/unit/rpc_method_wrappers/send_signed_transaction.test.ts @@ -272,7 +272,7 @@ describe('sendTransaction', () => { ); expect(watchTransactionForConfirmationsSpy).toHaveBeenCalledWith( web3Context, - Web3PromiEvent, + promiEvent, formattedReceiptInfo, expectedTransactionHash, DEFAULT_RETURN_FORMAT, diff --git a/packages/web3-eth/test/unit/rpc_method_wrappers/send_transaction.test.ts b/packages/web3-eth/test/unit/rpc_method_wrappers/send_transaction.test.ts index 8e635bc0b6c..fd9584df7ed 100644 --- a/packages/web3-eth/test/unit/rpc_method_wrappers/send_transaction.test.ts +++ b/packages/web3-eth/test/unit/rpc_method_wrappers/send_transaction.test.ts @@ -306,7 +306,7 @@ describe('sendTransaction', () => { ); expect(watchTransactionForConfirmationsSpy).toHaveBeenCalledWith( web3Context, - Web3PromiEvent, + promiEvent, formattedReceiptInfo, expectedTransactionHash, DEFAULT_RETURN_FORMAT, From ed1708c20afa97a818cd9f55660947d0497a5d9f Mon Sep 17 00:00:00 2001 From: Nazar Hussain Date: Tue, 14 Jun 2022 12:16:26 +0200 Subject: [PATCH 07/26] :pencil2: Fix some typo in tests files --- packages/web3-eth/test/integration/defaults.test.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/packages/web3-eth/test/integration/defaults.test.ts b/packages/web3-eth/test/integration/defaults.test.ts index 61ee5e4ccb6..67bc6e301dc 100644 --- a/packages/web3-eth/test/integration/defaults.test.ts +++ b/packages/web3-eth/test/integration/defaults.test.ts @@ -19,7 +19,7 @@ import WebSocketProvider from 'web3-providers-ws'; import { Contract } from 'web3-eth-contract'; import { hexToNumber, numberToHex } from 'web3-utils'; import { TransactionBuilder, TransactionTypeParser, Web3Context } from 'web3-core'; -import { DEFAULT_RETURN_FORMAT, PromiEvent } from 'web3-common'; +import { DEFAULT_RETURN_FORMAT, Web3PromiEvent } from 'web3-common'; import { prepareTransactionForSigning, ReceiptInfo, @@ -297,7 +297,7 @@ describe('defaults', () => { const from = accounts[0]; const to = accounts[1]; const value = `0x1`; - const sentTx: PromiEvent = eth.sendTransaction({ + const sentTx: Web3PromiEvent = eth.sendTransaction({ to, value, from, @@ -357,7 +357,7 @@ describe('defaults', () => { // }, // }); // - // const sentTx: PromiEvent = eth2.sendTransaction({ + // const sentTx: Web3PromiEvent = eth2.sendTransaction({ // to: accounts[1], // value: '0x1', // from: accounts[0], @@ -374,7 +374,7 @@ describe('defaults', () => { // ]); // expect((res as ReceiptInfo).status).toBe('0x1'); // - // const sentTx2: PromiEvent = eth2.sendTransaction({ + // const sentTx2: Web3PromiEvent = eth2.sendTransaction({ // to: accounts[1], // value: '0x1', // from: accounts[0], From 6e74b6cc64f44706400d8c02a83bbcf10016edec Mon Sep 17 00:00:00 2001 From: Nazar Hussain Date: Tue, 14 Jun 2022 14:27:38 +0200 Subject: [PATCH 08/26] :art: Improve the code as per feedback --- packages/web3-common/src/formatters.ts | 6 ++-- .../web3-common/src/web3_base_provider.ts | 29 ++++++++++++++-- .../web3-common/test/unit/formatters.test.ts | 14 ++++---- .../src/{web3_iban.ts => iban.ts} | 32 ++++++++--------- packages/web3-eth-iban/src/index.ts | 6 ++-- packages/web3-eth-iban/test/unit/iban.test.ts | 34 +++++++++---------- packages/web3-eth-personal/src/index.ts | 6 ++-- .../src/{eth_personal.ts => personal.ts} | 2 +- packages/web3-net/src/index.ts | 6 ++-- packages/web3-net/src/{web3_net.ts => net.ts} | 2 +- .../test/unit/rpc_method_wrappers.test.ts | 6 ++-- .../test/unit/web3_net_methods.test.ts | 6 ++-- packages/web3/src/web3.ts | 26 +++++++------- scripts/system_tests_utils.ts | 8 ++--- 14 files changed, 104 insertions(+), 79 deletions(-) rename packages/web3-eth-iban/src/{web3_iban.ts => iban.ts} (86%) rename packages/web3-eth-personal/src/{eth_personal.ts => personal.ts} (97%) rename packages/web3-net/src/{web3_net.ts => net.ts} (96%) diff --git a/packages/web3-common/src/formatters.ts b/packages/web3-common/src/formatters.ts index aefaf4051f7..41d6d811610 100644 --- a/packages/web3-common/src/formatters.ts +++ b/packages/web3-common/src/formatters.ts @@ -16,7 +16,7 @@ along with web3.js. If not, see . */ import { FormatterError } from 'web3-errors'; -import { Web3Iban } from 'web3-eth-iban'; +import { Iban } from 'web3-eth-iban'; import { BlockTags, Filter, @@ -121,8 +121,8 @@ export const inputDefaultBlockNumberFormatter = ( }; export const inputAddressFormatter = (address: string): string | never => { - if (Web3Iban.isValid(address) && Web3Iban.isDirect(address)) { - const iban = new Web3Iban(address); + if (Iban.isValid(address) && Iban.isDirect(address)) { + const iban = new Iban(address); return iban.toAddress().toLowerCase(); } diff --git a/packages/web3-common/src/web3_base_provider.ts b/packages/web3-common/src/web3_base_provider.ts index 68de4428326..37a7e13a05d 100644 --- a/packages/web3-common/src/web3_base_provider.ts +++ b/packages/web3-common/src/web3_base_provider.ts @@ -15,6 +15,7 @@ You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see . */ +import { Web3Error } from 'web3-errors'; import { EthExecutionAPI } from './eth_execution_api'; import { Web3APIPayload, @@ -61,13 +62,37 @@ export abstract class Web3BaseProvider, // Used "null" value to match the legacy version // eslint-disable-next-line @typescript-eslint/ban-types - cb: (err?: Error | null, response?: JsonRpcResponse) => void, + cb: (err?: Error | Web3Error | null, response?: JsonRpcResponse) => void, ) { this.request(payload) .then(response => { cb(undefined, response); }) - .catch((err: Error) => { + .catch((err: Error | Web3Error) => { + cb(err); + }); + } + + /** + * @deprecated Please use `.request` instead. + * + * @param payload - Request Payload + * @param cb - Callback + */ + public sendAsync< + Method extends Web3APIMethod, + ResponseType = Web3APIReturnType, + >( + payload: Web3APIPayload, + // Used "null" value to match the legacy version + // eslint-disable-next-line @typescript-eslint/ban-types + cb: (err?: Error | Web3Error | null, response?: JsonRpcResponse) => void, + ) { + this.request(payload) + .then(response => { + cb(undefined, response); + }) + .catch((err: Error | Web3Error) => { cb(err); }); } diff --git a/packages/web3-common/test/unit/formatters.test.ts b/packages/web3-common/test/unit/formatters.test.ts index 2b3b5f199a3..8930bcd8d8f 100644 --- a/packages/web3-common/test/unit/formatters.test.ts +++ b/packages/web3-common/test/unit/formatters.test.ts @@ -16,7 +16,7 @@ along with web3.js. If not, see . */ import * as utils from 'web3-utils'; -import { Web3Iban } from 'web3-eth-iban'; +import { Iban } from 'web3-eth-iban'; import { inputAddressFormatter, inputBlockNumberFormatter, @@ -54,8 +54,8 @@ describe('formatters', () => { jest.spyOn(utils, 'isHexStrict').mockReturnValue(true); jest.spyOn(utils, 'isAddress').mockReturnValue(true); jest.spyOn(utils, 'sha3Raw').mockReturnValue(sha3Result); - jest.spyOn(Web3Iban, 'isValid').mockImplementation(() => false); - jest.spyOn(Web3Iban, 'isDirect').mockImplementation(() => false); + jest.spyOn(Iban, 'isValid').mockImplementation(() => false); + jest.spyOn(Iban, 'isDirect').mockImplementation(() => false); }); describe('outputProofFormatter', () => { @@ -139,13 +139,13 @@ describe('formatters', () => { describe('inputAddressFormatter', () => { it('should return lowercase address if given value is iban', () => { const address = '0x00c5496aee77c1ba1f0854206a26dda82a81d6d8'; - Web3Iban.prototype.toAddress = jest.fn(() => address); + Iban.prototype.toAddress = jest.fn(() => address); - jest.spyOn(Web3Iban, 'isValid').mockImplementation(() => true); - jest.spyOn(Web3Iban, 'isDirect').mockImplementation(() => true); + jest.spyOn(Iban, 'isValid').mockImplementation(() => true); + jest.spyOn(Iban, 'isDirect').mockImplementation(() => true); expect(inputAddressFormatter('XE7338O073KYGTWWZN0F2WZ0R8PX5ZPPZS')).toBe(address); - expect(Web3Iban.prototype.toAddress).toHaveBeenCalled(); + expect(Iban.prototype.toAddress).toHaveBeenCalled(); }); it('should return lower case value if valid address', () => { diff --git a/packages/web3-eth-iban/src/web3_iban.ts b/packages/web3-eth-iban/src/iban.ts similarity index 86% rename from packages/web3-eth-iban/src/web3_iban.ts rename to packages/web3-eth-iban/src/iban.ts index 1847f1bff6d..2dee4210e3e 100644 --- a/packages/web3-eth-iban/src/web3_iban.ts +++ b/packages/web3-eth-iban/src/iban.ts @@ -19,7 +19,7 @@ import { toChecksumAddress, isAddress, leftPad, hexToNumber, HexString } from 'w import { InvalidAddressError } from 'web3-errors'; import { IbanOptions } from './types'; -export class Web3Iban { +export class Iban { private readonly _iban: string; public static isDirect(iban: string): boolean { @@ -36,7 +36,7 @@ export class Web3Iban { * @param iban */ public constructor(iban: string) { - if (Web3Iban.isIndirect(iban) || Web3Iban.isDirect(iban)) { + if (Iban.isIndirect(iban) || Iban.isDirect(iban)) { this._iban = iban; } else { throw new Error('Invalid IBAN was provided'); @@ -100,13 +100,13 @@ export class Web3Iban { private static readonly _isValid = (iban: string): boolean => /^XE[0-9]{2}(ETH[0-9A-Z]{13}|[0-9A-Z]{30,31})$/.test(iban) && - Web3Iban._mod9710(Web3Iban._iso13616Prepare(iban)) === 1; + Iban._mod9710(Iban._iso13616Prepare(iban)) === 1; /** * check if iban number is direct */ public isDirect(): boolean { - return Web3Iban.isDirect(this._iban); + return Iban.isDirect(this._iban); } /** @@ -116,7 +116,7 @@ export class Web3Iban { if (this.isDirect()) { // check if Iban can be converted to an address const base36 = this._iban.slice(4); - const parsedBigInt = Web3Iban._parseInt(base36, 36); // convert the base36 string to a bigint + const parsedBigInt = Iban._parseInt(base36, 36); // convert the base36 string to a bigint const paddedBigInt = leftPad(parsedBigInt, 40); return toChecksumAddress(paddedBigInt); } @@ -128,7 +128,7 @@ export class Web3Iban { * @param iban */ public static toAddress = (iban: string): HexString => { - const ibanObject = new Web3Iban(iban); + const ibanObject = new Iban(iban); return ibanObject.toAddress(); }; @@ -139,13 +139,13 @@ export class Web3Iban { * * @param bban */ - public static fromBban(bban: string): Web3Iban { + public static fromBban(bban: string): Iban { const countryCode = 'XE'; const remainder = this._mod9710(this._iso13616Prepare(`${countryCode}00${bban}`)); const checkDigit = `0${(98 - remainder).toString()}`.slice(-2); - return new Web3Iban(`${countryCode}${checkDigit}${bban}`); + return new Iban(`${countryCode}${checkDigit}${bban}`); } /** @@ -153,7 +153,7 @@ export class Web3Iban { * * @param address */ - public static fromAddress(address: HexString): Web3Iban { + public static fromAddress(address: HexString): Iban { if (!isAddress(address)) { throw new InvalidAddressError(address); } @@ -161,7 +161,7 @@ export class Web3Iban { const num = BigInt(hexToNumber(address)); const base36 = num.toString(36); const padded = leftPad(base36, 15); - return Web3Iban.fromBban(padded.toUpperCase()); + return Iban.fromBban(padded.toUpperCase()); } /** @@ -170,7 +170,7 @@ export class Web3Iban { * @param address */ public static toIban(address: HexString): string { - return Web3Iban.fromAddress(address).toString(); + return Iban.fromAddress(address).toString(); } /** @@ -178,8 +178,8 @@ export class Web3Iban { * * @param options */ - public static createIndirect(options: IbanOptions): Web3Iban { - return Web3Iban.fromBban(`ETH${options.institution}${options.identifier}`); + public static createIndirect(options: IbanOptions): Iban { + return Iban.fromBban(`ETH${options.institution}${options.identifier}`); } /** @@ -207,7 +207,7 @@ export class Web3Iban { * Should be called to check if iban is correct */ public isValid(): boolean { - return Web3Iban._isValid(this._iban); + return Iban._isValid(this._iban); } /** @@ -216,7 +216,7 @@ export class Web3Iban { * @param iban */ public static isValid(iban: string) { - return Web3Iban._isValid(iban); + return Iban._isValid(iban); } public toString(): string { @@ -227,6 +227,6 @@ export class Web3Iban { * check if iban number if indirect */ public isIndirect(): boolean { - return Web3Iban.isIndirect(this._iban); + return Iban.isIndirect(this._iban); } } diff --git a/packages/web3-eth-iban/src/index.ts b/packages/web3-eth-iban/src/index.ts index 93b91ba658a..4f3bba15159 100644 --- a/packages/web3-eth-iban/src/index.ts +++ b/packages/web3-eth-iban/src/index.ts @@ -15,9 +15,9 @@ You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see . */ -import { Web3Iban } from './web3_iban'; +import { Iban } from './iban'; -export * from './web3_iban'; +export * from './iban'; export * from './types'; -export default Web3Iban; +export default Iban; diff --git a/packages/web3-eth-iban/test/unit/iban.test.ts b/packages/web3-eth-iban/test/unit/iban.test.ts index 35ab1207190..d7f3f63b90b 100644 --- a/packages/web3-eth-iban/test/unit/iban.test.ts +++ b/packages/web3-eth-iban/test/unit/iban.test.ts @@ -15,7 +15,7 @@ You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see . */ -import { Web3Iban } from '../../src/web3_iban'; +import { Iban } from '../../src/iban'; import { validIbanToAddressData, validFromBbanData, @@ -33,7 +33,7 @@ describe('iban', () => { describe('create', () => { describe('valid cases', () => { it.each(validIbanToAddressData)('%s', () => { - const iban = new Web3Iban('XE7338O073KYGTWWZN0F2WZ0R8PX5ZPPZS'); + const iban = new Iban('XE7338O073KYGTWWZN0F2WZ0R8PX5ZPPZS'); expect(typeof iban).toBe('object'); }); }); @@ -42,13 +42,13 @@ describe('iban', () => { describe('toAddress', () => { describe('valid cases', () => { it.each(validIbanToAddressData)('%s', (input, output) => { - const iban = new Web3Iban(input); + const iban = new Iban(input); expect(iban.toAddress()).toBe(output); }); }); describe('invalid cases', () => { it.each(invalidIbanToAddressData)('%s', (input, output) => { - const iban = new Web3Iban(input); + const iban = new Iban(input); expect(() => iban.toAddress()).toThrow(output); }); }); @@ -57,12 +57,12 @@ describe('iban', () => { describe('toAddress static method', () => { describe('valid cases', () => { it.each(validIbanToAddressData)('%s', (input, output) => { - expect(Web3Iban.toAddress(input)).toBe(output); + expect(Iban.toAddress(input)).toBe(output); }); }); describe('invalid cases', () => { it.each(invalidIbanToAddressData)('%s', (input, output) => { - expect(() => Web3Iban.toAddress(input)).toThrow(output); + expect(() => Iban.toAddress(input)).toThrow(output); }); }); }); @@ -70,7 +70,7 @@ describe('iban', () => { describe('toIban', () => { describe('valid cases', () => { it.each(validIbanToAddressData)('%s', (output, input) => { - expect(Web3Iban.toIban(input)).toBe(output); + expect(Iban.toIban(input)).toBe(output); }); }); }); @@ -78,7 +78,7 @@ describe('iban', () => { describe('fromAddress', () => { describe('valid cases', () => { it.each(validIbanToAddressData)('%s', (output, input) => { - expect(Web3Iban.fromAddress(input).toString()).toBe(output); + expect(Iban.fromAddress(input).toString()).toBe(output); }); }); }); @@ -86,7 +86,7 @@ describe('iban', () => { describe('fromBban', () => { describe('valid cases', () => { it.each(validFromBbanData)('%s', (input, output) => { - expect(Web3Iban.fromBban(input).toString()).toBe(output); + expect(Iban.fromBban(input).toString()).toBe(output); }); }); }); @@ -94,7 +94,7 @@ describe('iban', () => { describe('createIndirect', () => { describe('valid cases', () => { it.each(validCreateIndirectData)('%s', (input, output) => { - expect(Web3Iban.createIndirect(input).toString()).toBe(output); + expect(Iban.createIndirect(input).toString()).toBe(output); }); }); }); @@ -102,7 +102,7 @@ describe('iban', () => { describe('isValid', () => { describe('valid cases', () => { it.each(isValidData)('%s', (input, output) => { - const iban = new Web3Iban(input); + const iban = new Iban(input); expect(iban.isValid()).toBe(output); }); }); @@ -111,7 +111,7 @@ describe('iban', () => { describe('isValid static', () => { describe('valid cases', () => { it.each(isValidData)('%s', (input, output) => { - expect(Web3Iban.isValid(input)).toBe(output); + expect(Iban.isValid(input)).toBe(output); }); }); }); @@ -119,7 +119,7 @@ describe('iban', () => { describe('isDirect', () => { describe('valid cases', () => { it.each(validIsDirectData)('%s', (input, output) => { - expect(Web3Iban.isValid(input)).toBe(output); + expect(Iban.isValid(input)).toBe(output); }); }); }); @@ -127,7 +127,7 @@ describe('iban', () => { describe('isIndirect', () => { describe('valid cases', () => { it.each(validIsIndirectData)('%s', (input, output) => { - expect(Web3Iban.isIndirect(input)).toBe(output); + expect(Iban.isIndirect(input)).toBe(output); }); }); }); @@ -135,7 +135,7 @@ describe('iban', () => { describe('client', () => { describe('valid cases', () => { it.each(validClientData)('%s', (input, output) => { - const iban = new Web3Iban(input); + const iban = new Iban(input); expect(iban.client()).toBe(output); }); }); @@ -144,7 +144,7 @@ describe('iban', () => { describe('institution', () => { describe('valid cases', () => { it.each(validInstitutionData)('%s', (input, output) => { - const iban = new Web3Iban(input); + const iban = new Iban(input); expect(iban.institution()).toBe(output); }); }); @@ -153,7 +153,7 @@ describe('iban', () => { describe('checksum', () => { describe('valid cases', () => { it.each(validChecksumData)('%s', (input, output) => { - const iban = new Web3Iban(input); + const iban = new Iban(input); expect(iban.checksum()).toBe(output); }); }); diff --git a/packages/web3-eth-personal/src/index.ts b/packages/web3-eth-personal/src/index.ts index 6c52da72cdd..d963091825b 100644 --- a/packages/web3-eth-personal/src/index.ts +++ b/packages/web3-eth-personal/src/index.ts @@ -15,9 +15,9 @@ You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see . */ -import { EthPersonal } from './eth_personal'; +import { Personal } from './personal'; export * from './types'; -export * from './eth_personal'; +export * from './personal'; -export default EthPersonal; +export default Personal; diff --git a/packages/web3-eth-personal/src/eth_personal.ts b/packages/web3-eth-personal/src/personal.ts similarity index 97% rename from packages/web3-eth-personal/src/eth_personal.ts rename to packages/web3-eth-personal/src/personal.ts index 86c4d3df19f..0981bf9ae80 100644 --- a/packages/web3-eth-personal/src/eth_personal.ts +++ b/packages/web3-eth-personal/src/personal.ts @@ -21,7 +21,7 @@ import { Address, HexString } from 'web3-utils'; import { EthPersonalAPI } from './eth_personal_api'; import * as rpcWrappers from './rpc_method_wrappers'; -export class EthPersonal extends Web3Context { +export class Personal extends Web3Context { public async getAccounts() { return rpcWrappers.getAccounts(this.requestManager); } diff --git a/packages/web3-net/src/index.ts b/packages/web3-net/src/index.ts index 427a9f6b088..342cf6901bc 100644 --- a/packages/web3-net/src/index.ts +++ b/packages/web3-net/src/index.ts @@ -15,11 +15,11 @@ You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see . */ -import { Web3Net } from './web3_net'; +import { Net } from './net'; -export * from './web3_net'; +export * from './net'; export * as rpcMethods from './rpc_methods'; export * from './rpc_method_wrappers'; export * from './web3_net_api'; -export default Web3Net; +export default Net; diff --git a/packages/web3-net/src/web3_net.ts b/packages/web3-net/src/net.ts similarity index 96% rename from packages/web3-net/src/web3_net.ts rename to packages/web3-net/src/net.ts index 3bb7ec4426d..e432f41c0a9 100644 --- a/packages/web3-net/src/web3_net.ts +++ b/packages/web3-net/src/net.ts @@ -20,7 +20,7 @@ import { Web3Context } from 'web3-core'; import * as rpcMethodsWrappers from './rpc_method_wrappers'; import { Web3NetAPI } from './web3_net_api'; -export class Web3Net extends Web3Context { +export class Net extends Web3Context { public async getId( returnFormat: ReturnFormat = DEFAULT_RETURN_FORMAT as ReturnFormat, ) { diff --git a/packages/web3-net/test/unit/rpc_method_wrappers.test.ts b/packages/web3-net/test/unit/rpc_method_wrappers.test.ts index bbd159c1df8..bb781c4d43e 100644 --- a/packages/web3-net/test/unit/rpc_method_wrappers.test.ts +++ b/packages/web3-net/test/unit/rpc_method_wrappers.test.ts @@ -15,7 +15,7 @@ You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see . */ -import { Web3Net } from '../../src'; +import { Net } from '../../src'; import { getIdValidData, getPeerCountValidData } from '../fixtures/rpc_method_wrappers'; import * as rpcMethods from '../../src/rpc_methods'; import { getId, getPeerCount, isListening } from '../../src/rpc_method_wrappers'; @@ -23,10 +23,10 @@ import { getId, getPeerCount, isListening } from '../../src/rpc_method_wrappers' jest.mock('../../src/rpc_methods'); describe('rpc_method_wrappers', () => { - let web3Net: Web3Net; + let web3Net: Net; beforeAll(() => { - web3Net = new Web3Net('http://127.0.0.1:8545'); + web3Net = new Net('http://127.0.0.1:8545'); }); describe('should call RPC method', () => { diff --git a/packages/web3-net/test/unit/web3_net_methods.test.ts b/packages/web3-net/test/unit/web3_net_methods.test.ts index 7c2c9b53758..ede2c46a7e6 100644 --- a/packages/web3-net/test/unit/web3_net_methods.test.ts +++ b/packages/web3-net/test/unit/web3_net_methods.test.ts @@ -15,17 +15,17 @@ You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see . */ -import { Web3Net } from '../../src'; +import { Net } from '../../src'; import * as rpcMethodWrappers from '../../src/rpc_method_wrappers'; import { getDataFormat } from '../fixtures/web3_net_methods'; jest.mock('../../src/rpc_method_wrappers'); describe('web3_eth_methods', () => { - let web3Net: Web3Net; + let web3Net: Net; beforeAll(() => { - web3Net = new Web3Net('http://127.0.0.1:8545'); + web3Net = new Net('http://127.0.0.1:8545'); }); describe('should call RPC method', () => { diff --git a/packages/web3/src/web3.ts b/packages/web3/src/web3.ts index 18bd8b1d388..4405091cf14 100644 --- a/packages/web3/src/web3.ts +++ b/packages/web3/src/web3.ts @@ -18,10 +18,10 @@ along with web3.js. If not, see . import { EthExecutionAPI } from 'web3-common'; import { SupportedProviders, Web3Context } from 'web3-core'; import Web3Eth from 'web3-eth'; -import Web3Iban from 'web3-eth-iban'; -import Web3Net from 'web3-net'; +import Iban from 'web3-eth-iban'; +import Net from 'web3-net'; import { ENS, registryAddresses } from 'web3-eth-ens'; -import Web3Personal from 'web3-eth-personal'; +import Personal from 'web3-eth-personal'; import { ContractAbi, encodeFunctionCall, @@ -55,18 +55,18 @@ export class Web3 extends Web3Context { public static utils = utils; public static modules = { Web3Eth, - Web3Iban, - Web3Net, - Web3Ens: ENS, - Web3Personal, + Iban, + Net, + ENS, + Personal, }; public eth: Web3Eth & { - Iban: typeof Web3Iban; + Iban: typeof Iban; ens: ENS; utils: typeof utils; - net: Web3Net; - personal: Web3Personal; + net: Net; + personal: Personal; Contract: typeof Contract & { setProvider: (provider: SupportedProviders) => void; }; @@ -141,10 +141,10 @@ export class Web3 extends Web3Context { ens: self.use(ENS, registryAddresses.main), // registry address defaults to main network // Iban helpers - Iban: Web3Iban, + Iban, - net: self.use(Web3Net), - personal: self.use(Web3Personal), + net: self.use(Net), + personal: self.use(Personal), utils, diff --git a/scripts/system_tests_utils.ts b/scripts/system_tests_utils.ts index fa3e03e5c29..79108eb5fa9 100644 --- a/scripts/system_tests_utils.ts +++ b/scripts/system_tests_utils.ts @@ -19,7 +19,7 @@ along with web3.js. If not, see . import fetch from 'cross-fetch'; // eslint-disable-next-line import/no-extraneous-dependencies -import { EthPersonal } from 'web3-eth-personal'; +import { Personal } from 'web3-eth-personal'; // eslint-disable-next-line import/no-extraneous-dependencies import { create as createAccount } from 'web3-eth-accounts'; @@ -54,7 +54,7 @@ export const createNewAccount = async (config?: { const acc = createAccount(); const clientUrl = getSystemTestProvider().replace('ws://', 'http://'); if (config?.unlock) { - const web3Personal = new EthPersonal(clientUrl); + const web3Personal = new Personal(clientUrl); await web3Personal.importRawKey( getSystemTestBackend() === 'geth' ? acc.privateKey.slice(2) : acc.privateKey, '123456', @@ -63,7 +63,7 @@ export const createNewAccount = async (config?: { } if (config?.refill) { - const web3Personal = new EthPersonal(clientUrl); + const web3Personal = new Personal(clientUrl); const web3Eth = new Web3Eth(clientUrl); const accList = await web3Personal.getAccounts(); await web3Eth.sendTransaction({ @@ -137,7 +137,7 @@ export const getSystemTestAccounts = async (): Promise => { if (getSystemTestBackend() === 'geth') { const web3Eth = new Web3Eth(clientUrl); - const web3Personal = new EthPersonal(clientUrl); + const web3Personal = new Personal(clientUrl); await web3Eth.sendTransaction({ from: await web3Eth.getCoinbase(), From c9f593a3146eeca0308b4b0987dbf8b43edfe2f0 Mon Sep 17 00:00:00 2001 From: Nazar Hussain Date: Tue, 14 Jun 2022 14:28:52 +0200 Subject: [PATCH 09/26] :art: Improve code with feedback --- .../test/unit/eth_personal.test.ts | 62 +++++++++---------- 1 file changed, 28 insertions(+), 34 deletions(-) diff --git a/packages/web3-eth-personal/test/unit/eth_personal.test.ts b/packages/web3-eth-personal/test/unit/eth_personal.test.ts index 1dcbdecf668..3764f44b56a 100644 --- a/packages/web3-eth-personal/test/unit/eth_personal.test.ts +++ b/packages/web3-eth-personal/test/unit/eth_personal.test.ts @@ -18,20 +18,20 @@ along with web3.js. If not, see . import * as utils from 'web3-utils'; import * as eth from 'web3-eth'; import { validator } from 'web3-validator'; -import { EthPersonal } from '../../src/index'; +import { Personal } from '../../src/index'; jest.mock('web3-utils'); jest.mock('web3-eth'); -describe('EthPersonal', () => { - let ethPersonal: EthPersonal; +describe('Personal', () => { + let personal: Personal; let sendSpy: jest.SpyInstance; let validateSpy: jest.SpyInstance; beforeEach(() => { - ethPersonal = new EthPersonal('http://localhost:8545'); + personal = new Personal('http://localhost:8545'); - sendSpy = jest.spyOn(ethPersonal.requestManager, 'send').mockImplementation(async () => { + sendSpy = jest.spyOn(personal.requestManager, 'send').mockImplementation(async () => { return Promise.resolve('0x0'); }); @@ -44,7 +44,7 @@ describe('EthPersonal', () => { it('should call the correct method for request manager', async () => { sendSpy.mockResolvedValue(['0x528ABBBa47c33600245066398072799A9b7e2d9E']); - await ethPersonal.getAccounts(); + await personal.getAccounts(); expect(sendSpy).toHaveBeenCalledWith({ method: 'personal_listAccounts', params: [] }); }); @@ -53,7 +53,7 @@ describe('EthPersonal', () => { const result = ['0x528ABBBa47c33600245066398072799A9b7e2d9E']; sendSpy.mockResolvedValue(result); - await ethPersonal.getAccounts(); + await personal.getAccounts(); expect(utils.toChecksumAddress).toHaveBeenCalledTimes(1); expect(utils.toChecksumAddress).toHaveBeenCalledWith(result[0], 0, result); @@ -62,7 +62,7 @@ describe('EthPersonal', () => { describe('newAccount', () => { it('should call the correct method for request manager', async () => { - await ethPersonal.newAccount('password'); + await personal.newAccount('password'); expect(sendSpy).toHaveBeenCalledWith({ method: 'personal_newAccount', @@ -71,7 +71,7 @@ describe('EthPersonal', () => { }); it('should validate user input', async () => { - await ethPersonal.newAccount('password'); + await personal.newAccount('password'); expect(validateSpy).toHaveBeenCalledTimes(1); expect(validateSpy).toHaveBeenCalledWith(['string'], ['password']); @@ -81,7 +81,7 @@ describe('EthPersonal', () => { const result = '0x528ABBBa47c33600245066398072799A9b7e2d9E'; sendSpy.mockResolvedValue(result); - await ethPersonal.newAccount('password'); + await personal.newAccount('password'); expect(utils.toChecksumAddress).toHaveBeenCalledTimes(1); expect(utils.toChecksumAddress).toHaveBeenCalledWith(result); @@ -90,7 +90,7 @@ describe('EthPersonal', () => { describe('unlockAccount', () => { it('should call the correct method for request manager', async () => { - await ethPersonal.unlockAccount( + await personal.unlockAccount( '0x528ABBBa47c33600245066398072799A9b7e2d9E', 'password', 30, @@ -103,7 +103,7 @@ describe('EthPersonal', () => { }); it('should validate user input', async () => { - await ethPersonal.unlockAccount( + await personal.unlockAccount( '0x528ABBBa47c33600245066398072799A9b7e2d9E', 'password', 30, @@ -119,7 +119,7 @@ describe('EthPersonal', () => { describe('lockAccount', () => { it('should call the correct method for request manager', async () => { - await ethPersonal.lockAccount('0x528ABBBa47c33600245066398072799A9b7e2d9E'); + await personal.lockAccount('0x528ABBBa47c33600245066398072799A9b7e2d9E'); expect(sendSpy).toHaveBeenCalledWith({ method: 'personal_lockAccount', @@ -128,7 +128,7 @@ describe('EthPersonal', () => { }); it('should validate user input', async () => { - await ethPersonal.lockAccount('0x528ABBBa47c33600245066398072799A9b7e2d9E'); + await personal.lockAccount('0x528ABBBa47c33600245066398072799A9b7e2d9E'); expect(validateSpy).toHaveBeenCalledTimes(1); expect(validateSpy).toHaveBeenCalledWith( @@ -140,10 +140,7 @@ describe('EthPersonal', () => { describe('importRawKey', () => { it('should call the correct method for request manager', async () => { - await ethPersonal.importRawKey( - '0x528ABBBa47c33600245066398072799A9b7e2d9E', - 'password', - ); + await personal.importRawKey('0x528ABBBa47c33600245066398072799A9b7e2d9E', 'password'); expect(sendSpy).toHaveBeenCalledWith({ method: 'personal_importRawKey', @@ -152,10 +149,7 @@ describe('EthPersonal', () => { }); it('should validate user input', async () => { - await ethPersonal.importRawKey( - '0x528ABBBa47c33600245066398072799A9b7e2d9E', - 'password', - ); + await personal.importRawKey('0x528ABBBa47c33600245066398072799A9b7e2d9E', 'password'); expect(validateSpy).toHaveBeenCalledTimes(1); expect(validateSpy).toHaveBeenCalledWith( @@ -173,7 +167,7 @@ describe('EthPersonal', () => { }; jest.spyOn(eth, 'formatTransaction').mockReturnValue(tx); - await ethPersonal.sendTransaction(tx, 'password'); + await personal.sendTransaction(tx, 'password'); expect(sendSpy).toHaveBeenCalledWith({ method: 'personal_sendTransaction', @@ -188,7 +182,7 @@ describe('EthPersonal', () => { }; jest.spyOn(eth, 'formatTransaction').mockReturnValue(tx); - await ethPersonal.sendTransaction(tx, 'password'); + await personal.sendTransaction(tx, 'password'); expect(eth.formatTransaction).toHaveBeenCalledTimes(1); expect(eth.formatTransaction).toHaveBeenCalledWith(tx, { @@ -206,7 +200,7 @@ describe('EthPersonal', () => { }; jest.spyOn(eth, 'formatTransaction').mockReturnValue(tx); - await ethPersonal.signTransaction(tx, 'password'); + await personal.signTransaction(tx, 'password'); expect(sendSpy).toHaveBeenCalledWith({ method: 'personal_signTransaction', @@ -221,7 +215,7 @@ describe('EthPersonal', () => { }; jest.spyOn(eth, 'formatTransaction').mockReturnValue(tx); - await ethPersonal.signTransaction(tx, 'password'); + await personal.signTransaction(tx, 'password'); expect(eth.formatTransaction).toHaveBeenCalledTimes(1); expect(eth.formatTransaction).toHaveBeenCalledWith(tx, { @@ -237,7 +231,7 @@ describe('EthPersonal', () => { jest.spyOn(utils, 'isHexStrict').mockReturnValue(true); - await ethPersonal.sign(data, '0x528ABBBa47c33600245066398072799A9b7e2d9E', 'password'); + await personal.sign(data, '0x528ABBBa47c33600245066398072799A9b7e2d9E', 'password'); expect(sendSpy).toHaveBeenCalledWith({ method: 'personal_sign', @@ -251,7 +245,7 @@ describe('EthPersonal', () => { jest.spyOn(utils, 'isHexStrict').mockReturnValue(false); jest.spyOn(utils, 'utf8ToHex').mockReturnValue(data); - await ethPersonal.sign(data, '0x528ABBBa47c33600245066398072799A9b7e2d9E', 'password'); + await personal.sign(data, '0x528ABBBa47c33600245066398072799A9b7e2d9E', 'password'); expect(utils.utf8ToHex).toHaveBeenCalledTimes(1); expect(utils.utf8ToHex).toHaveBeenCalledWith(data); @@ -262,7 +256,7 @@ describe('EthPersonal', () => { jest.spyOn(utils, 'isHexStrict').mockReturnValue(true); - await ethPersonal.sign(data, '0x528ABBBa47c33600245066398072799A9b7e2d9E', 'password'); + await personal.sign(data, '0x528ABBBa47c33600245066398072799A9b7e2d9E', 'password'); expect(utils.utf8ToHex).toHaveBeenCalledTimes(0); }); @@ -272,7 +266,7 @@ describe('EthPersonal', () => { jest.spyOn(utils, 'isHexStrict').mockReturnValue(true); - await ethPersonal.sign(data, '0x528ABBBa47c33600245066398072799A9b7e2d9E', 'password'); + await personal.sign(data, '0x528ABBBa47c33600245066398072799A9b7e2d9E', 'password'); expect(validateSpy).toHaveBeenCalledTimes(1); expect(validateSpy).toHaveBeenCalledWith( @@ -288,7 +282,7 @@ describe('EthPersonal', () => { jest.spyOn(utils, 'isHexStrict').mockReturnValue(true); - await ethPersonal.ecRecover(data, '0x000000'); + await personal.ecRecover(data, '0x000000'); expect(sendSpy).toHaveBeenCalledWith({ method: 'personal_ecRecover', @@ -302,7 +296,7 @@ describe('EthPersonal', () => { jest.spyOn(utils, 'isHexStrict').mockReturnValue(false); jest.spyOn(utils, 'utf8ToHex').mockReturnValue(data); - await ethPersonal.ecRecover(data, 'password'); + await personal.ecRecover(data, 'password'); expect(utils.utf8ToHex).toHaveBeenCalledTimes(1); expect(utils.utf8ToHex).toHaveBeenCalledWith(data); @@ -313,7 +307,7 @@ describe('EthPersonal', () => { jest.spyOn(utils, 'isHexStrict').mockReturnValue(true); - await ethPersonal.ecRecover(data, 'password'); + await personal.ecRecover(data, 'password'); expect(utils.utf8ToHex).toHaveBeenCalledTimes(0); }); @@ -323,7 +317,7 @@ describe('EthPersonal', () => { jest.spyOn(utils, 'isHexStrict').mockReturnValue(true); - await ethPersonal.ecRecover(data, 'password'); + await personal.ecRecover(data, 'password'); expect(validateSpy).toHaveBeenCalledTimes(1); expect(validateSpy).toHaveBeenCalledWith(['bytes', 'string'], [data, 'password']); From 257f12787ba675e9eea3b0731ea90d871b8636ca Mon Sep 17 00:00:00 2001 From: Nazar Hussain Date: Tue, 14 Jun 2022 14:39:54 +0200 Subject: [PATCH 10/26] :art: Fix some typo in refactoring --- .../web3-eth-personal/test/integration/personal.test.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/packages/web3-eth-personal/test/integration/personal.test.ts b/packages/web3-eth-personal/test/integration/personal.test.ts index 2ca134af023..983a8007c77 100644 --- a/packages/web3-eth-personal/test/integration/personal.test.ts +++ b/packages/web3-eth-personal/test/integration/personal.test.ts @@ -17,7 +17,7 @@ along with web3.js. If not, see . import { isHexStrict } from 'web3-validator'; import { toChecksumAddress } from 'web3-utils'; import WebSocketProvider from 'web3-providers-ws'; -import { EthPersonal } from '../../src/index'; +import { Personal } from '../../src/index'; import { importedAccount } from '../config/personal.config'; import { getSystemTestBackend, @@ -27,12 +27,12 @@ import { } from '../fixtures/system_test_utils'; describe('personal integration tests', () => { - let ethPersonal: EthPersonal; + let ethPersonal: Personal; let accounts: string[]; let clientUrl: string; beforeAll(() => { clientUrl = getSystemTestProvider(); - ethPersonal = new EthPersonal(clientUrl); + ethPersonal = new Personal(clientUrl); }); beforeEach(async () => { accounts = await getSystemTestAccounts(); From 15b86400ed1d2506412f62dd59d59b01b7962bc3 Mon Sep 17 00:00:00 2001 From: Nazar Hussain Date: Tue, 14 Jun 2022 11:02:41 +0200 Subject: [PATCH 11/26] :building_construction: Update the default return format to bigint --- packages/web3-common/src/formatter.ts | 3 +- packages/web3-eth-ens/src/ens.ts | 12 +++- .../test/unit/eth_personal.test.ts | 4 +- packages/web3-eth/src/constants.ts | 20 ++++++ packages/web3-eth/src/rpc_method_wrappers.ts | 72 ++++++++++--------- .../src/utils/detect_transaction_type.ts | 5 +- .../src/utils/get_transaction_gas_pricing.ts | 11 +-- .../web3-eth/src/utils/transaction_builder.ts | 11 +-- .../send_transaction.test.ts | 2 +- 9 files changed, 84 insertions(+), 56 deletions(-) create mode 100644 packages/web3-eth/src/constants.ts diff --git a/packages/web3-common/src/formatter.ts b/packages/web3-common/src/formatter.ts index 8f877323c87..f831009627f 100644 --- a/packages/web3-common/src/formatter.ts +++ b/packages/web3-common/src/formatter.ts @@ -60,9 +60,8 @@ export type DataFormat = { readonly bytes: FMT_BYTES; }; -export const DEFAULT_RETURN_FORMAT = { number: FMT_NUMBER.HEX, bytes: FMT_BYTES.HEX } as const; +export const DEFAULT_RETURN_FORMAT = { number: FMT_NUMBER.BIGINT, bytes: FMT_BYTES.HEX } as const; -// Added `undefined` to cover optional type export type FormatType = number extends Extract ? NumberTypes[F['number']] | Exclude : Buffer extends Extract diff --git a/packages/web3-eth-ens/src/ens.ts b/packages/web3-eth-ens/src/ens.ts index 62aa7a5b4d4..875bfcaeccf 100644 --- a/packages/web3-eth-ens/src/ens.ts +++ b/packages/web3-eth-ens/src/ens.ts @@ -24,7 +24,7 @@ import { import { Web3Context, SupportedProviders, Web3ContextObject } from 'web3-core'; import { getId, Web3NetAPI } from 'web3-net'; import { Address } from 'web3-utils'; -import { EthExecutionAPI, DEFAULT_RETURN_FORMAT } from 'web3-common'; +import { EthExecutionAPI, DEFAULT_RETURN_FORMAT, FormatType, FMT_NUMBER } from 'web3-common'; import { NonPayableCallOptions, Contract } from 'web3-eth-contract'; import { RESOLVER } from './abi/resolver'; import { Registry } from './registry'; @@ -71,7 +71,10 @@ export class ENS extends Web3Context { name: string, address: Address, txConfig: NonPayableCallOptions, - ): Promise { + ): Promise< + | FormatType + | FormatType + > { return this._registry.setResolver(name, address, txConfig); } @@ -289,7 +292,10 @@ export class ENS extends Web3Context { if (this._detectedAddress) { return this._detectedAddress; } - const networkType = await getId(this, DEFAULT_RETURN_FORMAT); // get the network from provider + const networkType = await getId(this, { + ...DEFAULT_RETURN_FORMAT, + number: FMT_NUMBER.HEX, + }); // get the network from provider const addr = registryAddresses[networkType]; if (typeof addr === 'undefined') { diff --git a/packages/web3-eth-personal/test/unit/eth_personal.test.ts b/packages/web3-eth-personal/test/unit/eth_personal.test.ts index 3764f44b56a..57cf608fa17 100644 --- a/packages/web3-eth-personal/test/unit/eth_personal.test.ts +++ b/packages/web3-eth-personal/test/unit/eth_personal.test.ts @@ -187,7 +187,7 @@ describe('Personal', () => { expect(eth.formatTransaction).toHaveBeenCalledTimes(1); expect(eth.formatTransaction).toHaveBeenCalledWith(tx, { bytes: 'BYTES_HEX', - number: 'NUMBER_HEX', + number: 'NUMBER_BIGINT', }); }); }); @@ -220,7 +220,7 @@ describe('Personal', () => { expect(eth.formatTransaction).toHaveBeenCalledTimes(1); expect(eth.formatTransaction).toHaveBeenCalledWith(tx, { bytes: 'BYTES_HEX', - number: 'NUMBER_HEX', + number: 'NUMBER_BIGINT', }); }); }); diff --git a/packages/web3-eth/src/constants.ts b/packages/web3-eth/src/constants.ts new file mode 100644 index 00000000000..b2318c507a7 --- /dev/null +++ b/packages/web3-eth/src/constants.ts @@ -0,0 +1,20 @@ +/* +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 . +*/ +import { FMT_BYTES, FMT_NUMBER } from 'web3-common'; + +export const ETH_DATA_FORMAT = { bytes: FMT_BYTES.HEX, number: FMT_NUMBER.HEX } as const; +export const STRING_NUMBER_FORMAT = { bytes: FMT_BYTES.HEX, number: FMT_NUMBER.STR } as const; diff --git a/packages/web3-eth/src/rpc_method_wrappers.ts b/packages/web3-eth/src/rpc_method_wrappers.ts index 702cab36f83..ff2fdc5fc5f 100644 --- a/packages/web3-eth/src/rpc_method_wrappers.ts +++ b/packages/web3-eth/src/rpc_method_wrappers.ts @@ -75,6 +75,7 @@ import { getTransactionGasPricing } from './utils/get_transaction_gas_pricing'; import { waitForTransactionReceipt } from './utils/wait_for_transaction_receipt'; import { watchTransactionForConfirmations } from './utils/watch_transaction_for_confirmations'; import { Web3EthExecutionAPI } from './web3_eth_execution_api'; +import { ETH_DATA_FORMAT, STRING_NUMBER_FORMAT } from './constants'; export const getProtocolVersion = async (web3Context: Web3Context) => rpcMethods.getProtocolVersion(web3Context.requestManager); @@ -145,7 +146,7 @@ export async function getBalance( ) { const blockNumberFormatted = isBlockTag(blockNumber as string) ? (blockNumber as BlockTag) - : format({ eth: 'uint' }, blockNumber as Numbers, DEFAULT_RETURN_FORMAT); + : format({ eth: 'uint' }, blockNumber as Numbers, ETH_DATA_FORMAT); const response = await rpcMethods.getBalance( web3Context.requestManager, address, @@ -169,10 +170,10 @@ export async function getStorageAt( blockNumber: BlockNumberOrTag = web3Context.defaultBlock, returnFormat: ReturnFormat, ) { - const storageSlotFormatted = format({ eth: 'uint' }, storageSlot, DEFAULT_RETURN_FORMAT); + const storageSlotFormatted = format({ eth: 'uint' }, storageSlot, ETH_DATA_FORMAT); const blockNumberFormatted = isBlockTag(blockNumber as string) ? (blockNumber as BlockTag) - : format({ eth: 'uint' }, blockNumber as Numbers, DEFAULT_RETURN_FORMAT); + : format({ eth: 'uint' }, blockNumber as Numbers, ETH_DATA_FORMAT); const response = await rpcMethods.getStorageAt( web3Context.requestManager, address, @@ -197,7 +198,7 @@ export async function getCode( ) { const blockNumberFormatted = isBlockTag(blockNumber as string) ? (blockNumber as BlockTag) - : format({ eth: 'uint' }, blockNumber as Numbers, DEFAULT_RETURN_FORMAT); + : format({ eth: 'uint' }, blockNumber as Numbers, ETH_DATA_FORMAT); const response = await rpcMethods.getCode( web3Context.requestManager, address, @@ -221,7 +222,7 @@ export async function getBlock( ) { let response; if (isBytes(block)) { - const blockHashFormatted = format({ eth: 'bytes32' }, block, DEFAULT_RETURN_FORMAT); + const blockHashFormatted = format({ eth: 'bytes32' }, block, ETH_DATA_FORMAT); response = await rpcMethods.getBlockByHash( web3Context.requestManager, blockHashFormatted as HexString, @@ -230,7 +231,7 @@ export async function getBlock( } else { const blockNumberFormatted = isBlockTag(block as string) ? (block as BlockTag) - : format({ eth: 'uint' }, block as Numbers, DEFAULT_RETURN_FORMAT); + : format({ eth: 'uint' }, block as Numbers, ETH_DATA_FORMAT); response = await rpcMethods.getBlockByNumber( web3Context.requestManager, blockNumberFormatted, @@ -254,7 +255,7 @@ export async function getBlockTransactionCount( ) { let response; if (isBytes(block)) { - const blockHashFormatted = format({ eth: 'bytes32' }, block, DEFAULT_RETURN_FORMAT); + const blockHashFormatted = format({ eth: 'bytes32' }, block, ETH_DATA_FORMAT); response = await rpcMethods.getBlockTransactionCountByHash( web3Context.requestManager, blockHashFormatted as HexString, @@ -262,7 +263,7 @@ export async function getBlockTransactionCount( } else { const blockNumberFormatted = isBlockTag(block as string) ? (block as BlockTag) - : format({ eth: 'uint' }, block as Numbers, DEFAULT_RETURN_FORMAT); + : format({ eth: 'uint' }, block as Numbers, ETH_DATA_FORMAT); response = await rpcMethods.getBlockTransactionCountByNumber( web3Context.requestManager, blockNumberFormatted, @@ -285,7 +286,7 @@ export async function getBlockUncleCount( ) { let response; if (isBytes(block)) { - const blockHashFormatted = format({ eth: 'bytes32' }, block, DEFAULT_RETURN_FORMAT); + const blockHashFormatted = format({ eth: 'bytes32' }, block, ETH_DATA_FORMAT); response = await rpcMethods.getUncleCountByBlockHash( web3Context.requestManager, blockHashFormatted as HexString, @@ -293,7 +294,7 @@ export async function getBlockUncleCount( } else { const blockNumberFormatted = isBlockTag(block as string) ? (block as BlockTag) - : format({ eth: 'uint' }, block as Numbers, DEFAULT_RETURN_FORMAT); + : format({ eth: 'uint' }, block as Numbers, ETH_DATA_FORMAT); response = await rpcMethods.getUncleCountByBlockNumber( web3Context.requestManager, blockNumberFormatted, @@ -316,11 +317,11 @@ export async function getUncle( uncleIndex: Numbers, returnFormat: ReturnFormat, ) { - const uncleIndexFormatted = format({ eth: 'uint' }, uncleIndex, DEFAULT_RETURN_FORMAT); + const uncleIndexFormatted = format({ eth: 'uint' }, uncleIndex, ETH_DATA_FORMAT); let response; if (isBytes(block)) { - const blockHashFormatted = format({ eth: 'bytes32' }, block, DEFAULT_RETURN_FORMAT); + const blockHashFormatted = format({ eth: 'bytes32' }, block, ETH_DATA_FORMAT); response = await rpcMethods.getUncleByBlockHashAndIndex( web3Context.requestManager, blockHashFormatted as HexString, @@ -329,7 +330,7 @@ export async function getUncle( } else { const blockNumberFormatted = isBlockTag(block as string) ? (block as BlockTag) - : format({ eth: 'uint' }, block as Numbers, DEFAULT_RETURN_FORMAT); + : format({ eth: 'uint' }, block as Numbers, ETH_DATA_FORMAT); response = await rpcMethods.getUncleByBlockNumberAndIndex( web3Context.requestManager, blockNumberFormatted, @@ -395,15 +396,11 @@ export async function getTransactionFromBlock( transactionIndex: Numbers, returnFormat: ReturnFormat, ) { - const transactionIndexFormatted = format( - { eth: 'uint' }, - transactionIndex, - DEFAULT_RETURN_FORMAT, - ); + const transactionIndexFormatted = format({ eth: 'uint' }, transactionIndex, ETH_DATA_FORMAT); let response; if (isBytes(block)) { - const blockHashFormatted = format({ eth: 'bytes32' }, block, DEFAULT_RETURN_FORMAT); + const blockHashFormatted = format({ eth: 'bytes32' }, block, ETH_DATA_FORMAT); response = await rpcMethods.getTransactionByBlockHashAndIndex( web3Context.requestManager, blockHashFormatted as HexString, @@ -412,7 +409,7 @@ export async function getTransactionFromBlock( } else { const blockNumberFormatted = isBlockTag(block as string) ? (block as BlockTag) - : format({ eth: 'uint' }, block as Numbers, DEFAULT_RETURN_FORMAT); + : format({ eth: 'uint' }, block as Numbers, ETH_DATA_FORMAT); response = await rpcMethods.getTransactionByBlockNumberAndIndex( web3Context.requestManager, blockNumberFormatted, @@ -470,7 +467,7 @@ export async function getTransactionCount( ) { const blockNumberFormatted = isBlockTag(blockNumber as string) ? (blockNumber as BlockTag) - : format({ eth: 'uint' }, blockNumber as Numbers, DEFAULT_RETURN_FORMAT); + : format({ eth: 'uint' }, blockNumber as Numbers, ETH_DATA_FORMAT); const response = await rpcMethods.getTransactionCount( web3Context.requestManager, address, @@ -505,7 +502,7 @@ export function sendTransaction< ...transaction, from: getTransactionFromAttr(web3Context, transaction), }, - DEFAULT_RETURN_FORMAT, + ETH_DATA_FORMAT, ); if ( @@ -521,7 +518,7 @@ export function sendTransaction< ...(await getTransactionGasPricing( transactionFormatted, web3Context, - DEFAULT_RETURN_FORMAT, + ETH_DATA_FORMAT, )), }; } @@ -796,11 +793,13 @@ export async function signTransaction( ) { const response = await rpcMethods.signTransaction( web3Context.requestManager, - formatTransaction(transaction, DEFAULT_RETURN_FORMAT), + formatTransaction(transaction, ETH_DATA_FORMAT), ); + const unformattedResponse = isString(response as HexStringBytes) - ? { raw: response as HexStringBytes, tx: transaction } + ? { raw: response, tx: transaction } : (response as SignedTransactionInfo); + return { raw: format({ eth: 'bytes' }, unformattedResponse.raw, returnFormat), tx: formatTransaction(unformattedResponse.tx, returnFormat), @@ -824,12 +823,14 @@ export async function call( ) { const blockNumberFormatted = isBlockTag(blockNumber as string) ? (blockNumber as BlockTag) - : format({ eth: 'uint' }, blockNumber as Numbers, DEFAULT_RETURN_FORMAT); + : format({ eth: 'uint' }, blockNumber as Numbers, STRING_NUMBER_FORMAT); + const response = await rpcMethods.call( web3Context.requestManager, - formatTransaction(transaction, DEFAULT_RETURN_FORMAT), + formatTransaction(transaction, ETH_DATA_FORMAT), blockNumberFormatted, ); + return format({ eth: 'bytes' }, response, returnFormat); } @@ -847,10 +848,12 @@ export async function estimateGas( blockNumber: BlockNumberOrTag = web3Context.defaultBlock, returnFormat: ReturnFormat, ) { - const transactionFormatted = formatTransaction(transaction, DEFAULT_RETURN_FORMAT); + const transactionFormatted = formatTransaction(transaction, ETH_DATA_FORMAT); + const blockNumberFormatted = isBlockTag(blockNumber as string) ? (blockNumber as BlockTag) - : format({ eth: 'uint' }, blockNumber as Numbers, DEFAULT_RETURN_FORMAT); + : format({ eth: 'uint' }, blockNumber as Numbers, STRING_NUMBER_FORMAT); + const response = await rpcMethods.estimateGas( web3Context.requestManager, transactionFormatted, @@ -920,12 +923,13 @@ export async function getProof( returnFormat: ReturnFormat, ) { const storageKeysFormatted = storageKeys.map(storageKey => - format({ eth: 'bytes' }, storageKey, DEFAULT_RETURN_FORMAT), + format({ eth: 'bytes' }, storageKey, STRING_NUMBER_FORMAT), ); const blockNumberFormatted = isBlockTag(blockNumber as string) ? (blockNumber as BlockTag) - : format({ eth: 'uint' }, blockNumber as Numbers, DEFAULT_RETURN_FORMAT); + : format({ eth: 'uint' }, blockNumber as Numbers, STRING_NUMBER_FORMAT); + const response = await rpcMethods.getProof( web3Context.requestManager, address, @@ -951,10 +955,12 @@ export async function getFeeHistory( rewardPercentiles: Numbers[], returnFormat: ReturnFormat, ) { - const blockCountFormatted = format({ eth: 'uint' }, blockCount, DEFAULT_RETURN_FORMAT); + const blockCountFormatted = format({ eth: 'uint' }, blockCount, STRING_NUMBER_FORMAT); + const newestBlockFormatted = isBlockTag(newestBlock as string) ? (newestBlock as BlockTag) - : format({ eth: 'uint' }, newestBlock as Numbers, DEFAULT_RETURN_FORMAT); + : format({ eth: 'uint' }, newestBlock as Numbers, STRING_NUMBER_FORMAT); + const rewardPercentilesFormatted = format( { type: 'array', diff --git a/packages/web3-eth/src/utils/detect_transaction_type.ts b/packages/web3-eth/src/utils/detect_transaction_type.ts index ad594c770f3..fbd3bdae5b1 100644 --- a/packages/web3-eth/src/utils/detect_transaction_type.ts +++ b/packages/web3-eth/src/utils/detect_transaction_type.ts @@ -15,15 +15,16 @@ You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see . */ -import { EthExecutionAPI, DEFAULT_RETURN_FORMAT, format } from 'web3-common'; +import { EthExecutionAPI, format } from 'web3-common'; import { TransactionTypeParser, Web3Context } from 'web3-core'; import { isNullish } from 'web3-validator'; +import { ETH_DATA_FORMAT } from '../constants'; import { InternalTransaction, Transaction } from '../types'; export const defaultTransactionTypeParser: TransactionTypeParser = transaction => { const tx = transaction as unknown as Transaction; - if (!isNullish(tx.type)) return format({ eth: 'uint' }, tx.type, DEFAULT_RETURN_FORMAT); + if (!isNullish(tx.type)) return format({ eth: 'uint' }, tx.type, ETH_DATA_FORMAT); if ( !isNullish(tx.maxFeePerGas) || diff --git a/packages/web3-eth/src/utils/get_transaction_gas_pricing.ts b/packages/web3-eth/src/utils/get_transaction_gas_pricing.ts index 1e3f6df679d..281e54ad7ba 100644 --- a/packages/web3-eth/src/utils/get_transaction_gas_pricing.ts +++ b/packages/web3-eth/src/utils/get_transaction_gas_pricing.ts @@ -15,16 +15,11 @@ You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see . */ -import { - EthExecutionAPI, - FormatType, - DataFormat, - format, - DEFAULT_RETURN_FORMAT, -} from 'web3-common'; +import { EthExecutionAPI, FormatType, DataFormat, format } from 'web3-common'; import { Web3Context } from 'web3-core'; import { Numbers } from 'web3-utils'; import { isNullish } from 'web3-validator'; +import { ETH_DATA_FORMAT } from '../constants'; import { Eip1559NotSupportedError, UnsupportedTransactionTypeError } from '../errors'; // eslint-disable-next-line import/no-cycle import { getBlock, getGasPrice } from '../rpc_method_wrappers'; @@ -39,7 +34,7 @@ import { getTransactionType } from './transaction_builder'; * @param returnFormat */ async function getEip1559GasPricing( - transaction: FormatType, + transaction: FormatType, web3Context: Web3Context, returnFormat: ReturnFormat, ): Promise> { diff --git a/packages/web3-eth/src/utils/transaction_builder.ts b/packages/web3-eth/src/utils/transaction_builder.ts index a290778c9eb..f9eabc56253 100644 --- a/packages/web3-eth/src/utils/transaction_builder.ts +++ b/packages/web3-eth/src/utils/transaction_builder.ts @@ -28,6 +28,7 @@ import { privateKeyToAddress } from 'web3-eth-accounts'; import { getId, Web3NetAPI } from 'web3-net'; import { Address, HexString, isAddress } from 'web3-utils'; import { isNullish, isNumber } from 'web3-validator'; +import { ETH_DATA_FORMAT } from '../constants'; import { InvalidTransactionWithSender, LocalWalletNotAvailableError, @@ -94,14 +95,14 @@ export const getTransactionNonce = async ( }; export const getTransactionType = ( - transaction: FormatType, + transaction: FormatType, web3Context: Web3Context, ) => { const inferredType = detectTransactionType(transaction, web3Context); if (!isNullish(inferredType)) return inferredType; if (!isNullish(web3Context.defaultTransactionType)) - return format({ eth: 'uint' }, web3Context.defaultTransactionType, DEFAULT_RETURN_FORMAT); + return format({ eth: 'uint' }, web3Context.defaultTransactionType, ETH_DATA_FORMAT); return undefined; }; @@ -171,13 +172,13 @@ export async function defaultTransactionBuilder { ); it.each(testData)( - `should resolve Web3PromiEvent with expectedReceiptInfo\n ${testMessage}`, + `should resolve promiEvent with expectedReceiptInfo\n ${testMessage}`, async (_, inputTransaction, sendTransactionOptions) => { const formattedReceiptInfo = format( receiptInfoSchema, From ec3716c26c94bb05d3fc7cb92386e8c3cbfa3447 Mon Sep 17 00:00:00 2001 From: Nazar Hussain Date: Tue, 14 Jun 2022 12:06:09 +0200 Subject: [PATCH 12/26] :test_tube: Fix few eth tests --- .../rpc_method_wrappers/send_transaction.test.ts | 13 ++++--------- 1 file changed, 4 insertions(+), 9 deletions(-) diff --git a/packages/web3-eth/test/unit/rpc_method_wrappers/send_transaction.test.ts b/packages/web3-eth/test/unit/rpc_method_wrappers/send_transaction.test.ts index 6e7556341b0..27c1e53a39d 100644 --- a/packages/web3-eth/test/unit/rpc_method_wrappers/send_transaction.test.ts +++ b/packages/web3-eth/test/unit/rpc_method_wrappers/send_transaction.test.ts @@ -31,6 +31,7 @@ import { testData, } from './fixtures/send_transaction'; import { receiptInfoSchema } from '../../../src/schemas'; +import { ETH_DATA_FORMAT } from '../../../src/constants'; jest.mock('../../../src/rpc_methods'); jest.mock('../../../src/utils/wait_for_transaction_receipt'); @@ -80,10 +81,7 @@ describe('sendTransaction', () => { `sending event should emit with formattedTransaction\n ${testMessage}`, async (_, inputTransaction, sendTransactionOptions) => { return new Promise(done => { - const formattedTransaction = formatTransaction( - inputTransaction, - DEFAULT_RETURN_FORMAT, - ); + const formattedTransaction = formatTransaction(inputTransaction, ETH_DATA_FORMAT); (rpcMethods.getTransactionReceipt as jest.Mock).mockResolvedValue( expectedReceiptInfo, ); @@ -104,7 +102,7 @@ describe('sendTransaction', () => { it.each(testData)( `should call rpcMethods.sendTransaction with expected parameters\n ${testMessage}`, async (_, inputTransaction, sendTransactionOptions) => { - const formattedTransaction = formatTransaction(inputTransaction, DEFAULT_RETURN_FORMAT); + const formattedTransaction = formatTransaction(inputTransaction, ETH_DATA_FORMAT); (rpcMethods.getTransactionReceipt as jest.Mock).mockResolvedValue(expectedReceiptInfo); await sendTransaction( web3Context, @@ -123,10 +121,7 @@ describe('sendTransaction', () => { `sent event should emit with formattedTransaction\n ${testMessage}`, async (_, inputTransaction, sendTransactionOptions) => { return new Promise(done => { - const formattedTransaction = formatTransaction( - inputTransaction, - DEFAULT_RETURN_FORMAT, - ); + const formattedTransaction = formatTransaction(inputTransaction, ETH_DATA_FORMAT); (rpcMethods.getTransactionReceipt as jest.Mock).mockResolvedValue( expectedReceiptInfo, ); From 3321461810123223d2c0f490de94aaab9e33325d Mon Sep 17 00:00:00 2001 From: Nazar Hussain Date: Wed, 15 Jun 2022 13:07:37 +0200 Subject: [PATCH 13/26] :white_check_mark: Fix all tests for web3-eth --- packages/web3-common/src/formatter.ts | 1 + packages/web3-common/src/formatters.ts | 6 +- packages/web3-eth-contract/src/contract.ts | 2 +- packages/web3-eth/src/constants.ts | 5 +- packages/web3-eth/src/rpc_method_wrappers.ts | 27 ++--- packages/web3-eth/src/types.ts | 14 +-- .../src/utils/detect_transaction_type.ts | 3 +- .../src/utils/get_transaction_gas_pricing.ts | 3 +- .../web3-eth/src/utils/transaction_builder.ts | 26 ++--- packages/web3-eth/src/web3_eth.ts | 2 +- .../test/fixtures/detect_transaction_type.ts | 10 +- .../test/fixtures/format_transaction.ts | 88 +++++++-------- .../test/integration/defaults.test.ts | 24 ++-- packages/web3-eth/test/integration/helper.ts | 2 +- .../web3-eth/test/integration/rpc.test.ts | 55 ++++----- .../integration/watch_transaction.test.ts | 2 +- .../integration/web3_eth/estimate_gas.test.ts | 4 +- .../web3_eth/send_signed_transaction.test.ts | 106 ++++++++++++------ .../web3_eth/send_transaction.test.ts | 76 ++++++------- .../unit/rpc_method_wrappers/call.test.ts | 9 +- .../rpc_method_wrappers/estimate_gas.test.ts | 10 +- .../rpc_method_wrappers/get_balance.test.ts | 4 +- .../rpc_method_wrappers/get_block.test.ts | 6 +- .../get_block_transaction_count.test.ts | 6 +- .../get_block_uncle_count.test.ts | 6 +- .../unit/rpc_method_wrappers/get_code.test.ts | 4 +- .../get_fee_history.test.ts | 10 +- .../rpc_method_wrappers/get_proof.test.ts | 5 +- .../get_storage_at.test.ts | 6 +- .../get_transaction_count.test.ts | 4 +- .../get_transaction_from_block.test.ts | 8 +- .../rpc_method_wrappers/get_uncle.test.ts | 8 +- .../send_transaction.test.ts | 3 +- .../sign_transaction.test.ts | 7 +- .../web3-validator/src/validation/block.ts | 9 +- 35 files changed, 275 insertions(+), 286 deletions(-) diff --git a/packages/web3-common/src/formatter.ts b/packages/web3-common/src/formatter.ts index f831009627f..7c8ff12749a 100644 --- a/packages/web3-common/src/formatter.ts +++ b/packages/web3-common/src/formatter.ts @@ -61,6 +61,7 @@ export type DataFormat = { }; export const DEFAULT_RETURN_FORMAT = { number: FMT_NUMBER.BIGINT, bytes: FMT_BYTES.HEX } as const; +export const ETH_DATA_FORMAT = { number: FMT_NUMBER.HEX, bytes: FMT_BYTES.HEX } as const; export type FormatType = number extends Extract ? NumberTypes[F['number']] | Exclude diff --git a/packages/web3-common/src/formatters.ts b/packages/web3-common/src/formatters.ts index 41d6d811610..2ef10add60c 100644 --- a/packages/web3-common/src/formatters.ts +++ b/packages/web3-common/src/formatters.ts @@ -359,14 +359,14 @@ export const outputLogFormatter = (log: Partial): LogsOutput => { modifiedLog.id = undefined; } - if (log.blockNumber) { + if (log.blockNumber && isHexStrict(log.blockNumber)) { modifiedLog.blockNumber = hexToNumber(log.blockNumber); } - if (log.transactionIndex) { + if (log.transactionIndex && isHexStrict(log.transactionIndex)) { modifiedLog.transactionIndex = hexToNumber(log.transactionIndex); } - if (log.logIndex) { + if (log.logIndex && isHexStrict(log.logIndex)) { modifiedLog.logIndex = hexToNumber(log.logIndex); } diff --git a/packages/web3-eth-contract/src/contract.ts b/packages/web3-eth-contract/src/contract.ts index f71265b158f..7caae679df9 100644 --- a/packages/web3-eth-contract/src/contract.ts +++ b/packages/web3-eth-contract/src/contract.ts @@ -616,7 +616,7 @@ export class Contract return sendTransaction(this, tx, DEFAULT_RETURN_FORMAT, { transactionResolver: receipt => { - if (receipt.status === '0x0') { + if (receipt.status === BigInt(0)) { throw new Web3ContractError( 'contract deployment error', receipt as ReceiptInfo, diff --git a/packages/web3-eth/src/constants.ts b/packages/web3-eth/src/constants.ts index b2318c507a7..af467cf73af 100644 --- a/packages/web3-eth/src/constants.ts +++ b/packages/web3-eth/src/constants.ts @@ -16,5 +16,6 @@ along with web3.js. If not, see . */ import { FMT_BYTES, FMT_NUMBER } from 'web3-common'; -export const ETH_DATA_FORMAT = { bytes: FMT_BYTES.HEX, number: FMT_NUMBER.HEX } as const; -export const STRING_NUMBER_FORMAT = { bytes: FMT_BYTES.HEX, number: FMT_NUMBER.STR } as const; +export const STR_NUMBER_DATA_FORMAT = { bytes: FMT_BYTES.HEX, number: FMT_NUMBER.STR } as const; +export const HEX_NUMBER_DATA_FORMAT = { bytes: FMT_BYTES.HEX, number: FMT_NUMBER.HEX } as const; +export const NUMBER_DATA_FORMAT = { bytes: FMT_BYTES.HEX, number: FMT_NUMBER.NUMBER } as const; diff --git a/packages/web3-eth/src/rpc_method_wrappers.ts b/packages/web3-eth/src/rpc_method_wrappers.ts index ff2fdc5fc5f..c4126b8cfd7 100644 --- a/packages/web3-eth/src/rpc_method_wrappers.ts +++ b/packages/web3-eth/src/rpc_method_wrappers.ts @@ -22,13 +22,12 @@ import { EthExecutionAPI, format, Web3PromiEvent, - FMT_BYTES, - FMT_NUMBER, DEFAULT_RETURN_FORMAT, TransactionInfo, TransactionWithSender, FormatType, SignedTransactionInfo, + ETH_DATA_FORMAT, } from 'web3-common'; import { Web3Context } from 'web3-core'; import { @@ -75,7 +74,7 @@ import { getTransactionGasPricing } from './utils/get_transaction_gas_pricing'; import { waitForTransactionReceipt } from './utils/wait_for_transaction_receipt'; import { watchTransactionForConfirmations } from './utils/watch_transaction_for_confirmations'; import { Web3EthExecutionAPI } from './web3_eth_execution_api'; -import { ETH_DATA_FORMAT, STRING_NUMBER_FORMAT } from './constants'; +import { NUMBER_DATA_FORMAT, STR_NUMBER_DATA_FORMAT } from './constants'; export const getProtocolVersion = async (web3Context: Web3Context) => rpcMethods.getProtocolVersion(web3Context.requestManager); @@ -597,7 +596,7 @@ export function sendTransaction< transactionReceiptFormatted, ) as unknown as ResolveType, ); - } else if (transactionReceipt.status === '0x0') { + } else if (transactionReceipt.status === BigInt(0)) { reject(transactionReceiptFormatted as unknown as ResolveType); } else { resolve(transactionReceiptFormatted as unknown as ResolveType); @@ -714,7 +713,7 @@ export function sendSignedTransaction< transactionReceiptFormatted, ) as unknown as ResolveType, ); - } else if (transactionReceipt.status === '0x0') { + } else if (transactionReceipt.status === BigInt(0)) { reject(transactionReceiptFormatted as unknown as ResolveType); } else { resolve(transactionReceiptFormatted as unknown as ResolveType); @@ -823,7 +822,7 @@ export async function call( ) { const blockNumberFormatted = isBlockTag(blockNumber as string) ? (blockNumber as BlockTag) - : format({ eth: 'uint' }, blockNumber as Numbers, STRING_NUMBER_FORMAT); + : format({ eth: 'uint' }, blockNumber as Numbers, ETH_DATA_FORMAT); const response = await rpcMethods.call( web3Context.requestManager, @@ -852,7 +851,7 @@ export async function estimateGas( const blockNumberFormatted = isBlockTag(blockNumber as string) ? (blockNumber as BlockTag) - : format({ eth: 'uint' }, blockNumber as Numbers, STRING_NUMBER_FORMAT); + : format({ eth: 'uint' }, blockNumber as Numbers, STR_NUMBER_DATA_FORMAT); const response = await rpcMethods.estimateGas( web3Context.requestManager, @@ -923,12 +922,12 @@ export async function getProof( returnFormat: ReturnFormat, ) { const storageKeysFormatted = storageKeys.map(storageKey => - format({ eth: 'bytes' }, storageKey, STRING_NUMBER_FORMAT), + format({ eth: 'bytes' }, storageKey, STR_NUMBER_DATA_FORMAT), ); const blockNumberFormatted = isBlockTag(blockNumber as string) ? (blockNumber as BlockTag) - : format({ eth: 'uint' }, blockNumber as Numbers, STRING_NUMBER_FORMAT); + : format({ eth: 'uint' }, blockNumber as Numbers, STR_NUMBER_DATA_FORMAT); const response = await rpcMethods.getProof( web3Context.requestManager, @@ -955,11 +954,11 @@ export async function getFeeHistory( rewardPercentiles: Numbers[], returnFormat: ReturnFormat, ) { - const blockCountFormatted = format({ eth: 'uint' }, blockCount, STRING_NUMBER_FORMAT); + const blockCountFormatted = format({ eth: 'uint' }, blockCount, STR_NUMBER_DATA_FORMAT); const newestBlockFormatted = isBlockTag(newestBlock as string) ? (newestBlock as BlockTag) - : format({ eth: 'uint' }, newestBlock as Numbers, STRING_NUMBER_FORMAT); + : format({ eth: 'uint' }, newestBlock as Numbers, STR_NUMBER_DATA_FORMAT); const rewardPercentilesFormatted = format( { @@ -969,11 +968,9 @@ export async function getFeeHistory( }, }, rewardPercentiles, - { - number: FMT_NUMBER.NUMBER, - bytes: FMT_BYTES.HEX, - }, + NUMBER_DATA_FORMAT, ); + const response = await rpcMethods.getFeeHistory( web3Context.requestManager, blockCountFormatted, diff --git a/packages/web3-eth/src/types.ts b/packages/web3-eth/src/types.ts index 8d16b990f3a..4fb01d4b539 100644 --- a/packages/web3-eth/src/types.ts +++ b/packages/web3-eth/src/types.ts @@ -15,14 +15,7 @@ You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see . */ -import { - AccessList, - TransactionHash, - Uncles, - FMT_BYTES, - FMT_NUMBER, - FormatType, -} from 'web3-common'; +import { AccessList, TransactionHash, Uncles, FormatType, ETH_DATA_FORMAT } from 'web3-common'; import { Address, Bytes, Numbers, Uint } from 'web3-utils'; export type ValidChains = 'goerli' | 'kovan' | 'mainnet' | 'rinkeby' | 'ropsten' | 'sepolia'; @@ -126,10 +119,7 @@ export interface TransactionInfo extends Transaction { readonly transactionIndex?: Numbers; } -export type InternalTransaction = FormatType< - Transaction, - { number: FMT_NUMBER.HEX; bytes: FMT_BYTES.HEX } ->; +export type InternalTransaction = FormatType; export interface TransactionCall extends Transaction { to: Address; diff --git a/packages/web3-eth/src/utils/detect_transaction_type.ts b/packages/web3-eth/src/utils/detect_transaction_type.ts index fbd3bdae5b1..910522f7d76 100644 --- a/packages/web3-eth/src/utils/detect_transaction_type.ts +++ b/packages/web3-eth/src/utils/detect_transaction_type.ts @@ -15,10 +15,9 @@ You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see . */ -import { EthExecutionAPI, format } from 'web3-common'; +import { EthExecutionAPI, ETH_DATA_FORMAT, format } from 'web3-common'; import { TransactionTypeParser, Web3Context } from 'web3-core'; import { isNullish } from 'web3-validator'; -import { ETH_DATA_FORMAT } from '../constants'; import { InternalTransaction, Transaction } from '../types'; export const defaultTransactionTypeParser: TransactionTypeParser = transaction => { diff --git a/packages/web3-eth/src/utils/get_transaction_gas_pricing.ts b/packages/web3-eth/src/utils/get_transaction_gas_pricing.ts index 281e54ad7ba..f2262224882 100644 --- a/packages/web3-eth/src/utils/get_transaction_gas_pricing.ts +++ b/packages/web3-eth/src/utils/get_transaction_gas_pricing.ts @@ -15,11 +15,10 @@ You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see . */ -import { EthExecutionAPI, FormatType, DataFormat, format } from 'web3-common'; +import { EthExecutionAPI, FormatType, DataFormat, format, ETH_DATA_FORMAT } from 'web3-common'; import { Web3Context } from 'web3-core'; import { Numbers } from 'web3-utils'; import { isNullish } from 'web3-validator'; -import { ETH_DATA_FORMAT } from '../constants'; import { Eip1559NotSupportedError, UnsupportedTransactionTypeError } from '../errors'; // eslint-disable-next-line import/no-cycle import { getBlock, getGasPrice } from '../rpc_method_wrappers'; diff --git a/packages/web3-eth/src/utils/transaction_builder.ts b/packages/web3-eth/src/utils/transaction_builder.ts index f9eabc56253..04d640f7712 100644 --- a/packages/web3-eth/src/utils/transaction_builder.ts +++ b/packages/web3-eth/src/utils/transaction_builder.ts @@ -18,17 +18,17 @@ along with web3.js. If not, see . import { EthExecutionAPI, DEFAULT_RETURN_FORMAT, + ETH_DATA_FORMAT, FormatType, format, - FMT_NUMBER, - FMT_BYTES, + DataFormat, } from 'web3-common'; import { Web3Context } from 'web3-core'; import { privateKeyToAddress } from 'web3-eth-accounts'; import { getId, Web3NetAPI } from 'web3-net'; import { Address, HexString, isAddress } from 'web3-utils'; import { isNullish, isNumber } from 'web3-validator'; -import { ETH_DATA_FORMAT } from '../constants'; +import { NUMBER_DATA_FORMAT } from '../constants'; import { InvalidTransactionWithSender, LocalWalletNotAvailableError, @@ -60,10 +60,7 @@ export const getTransactionFromAttr = ( if (isNumber(transaction.from)) { if (web3Context.wallet) { return web3Context.wallet.get( - format({ eth: 'uint' }, transaction.from, { - number: FMT_NUMBER.NUMBER, - bytes: FMT_BYTES.HEX, - }), + format({ eth: 'uint' }, transaction.from, NUMBER_DATA_FORMAT), ).address; } throw new LocalWalletNotAvailableError(); @@ -77,21 +74,17 @@ export const getTransactionFromAttr = ( return undefined; }; -export const getTransactionNonce = async ( +export const getTransactionNonce = async ( web3Context: Web3Context, address?: Address, + returnFormat: ReturnFormat = DEFAULT_RETURN_FORMAT as ReturnFormat, ) => { if (isNullish(address)) { // TODO if (web3.eth.accounts.wallet) use address from local wallet throw new UnableToPopulateNonceError(); } - return getTransactionCount( - web3Context, - address, - web3Context.defaultBlock, - DEFAULT_RETURN_FORMAT, - ); + return getTransactionCount(web3Context, address, web3Context.defaultBlock, returnFormat); }; export const getTransactionType = ( @@ -133,10 +126,11 @@ export async function defaultTransactionBuilder { public constructor( - // eslint-disable-next-line @typescript-eslint/no-explicit-any + // eslint-disable-next-line @typescript-eslint/no-explicit-any providerOrContext: SupportedProviders | Web3ContextInitOptions | string, ) { super( diff --git a/packages/web3-eth/test/fixtures/detect_transaction_type.ts b/packages/web3-eth/test/fixtures/detect_transaction_type.ts index 911f568c1e9..78c7934fcee 100644 --- a/packages/web3-eth/test/fixtures/detect_transaction_type.ts +++ b/packages/web3-eth/test/fixtures/detect_transaction_type.ts @@ -15,10 +15,10 @@ You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see . */ -import { DEFAULT_RETURN_FORMAT, FormatType } from 'web3-common'; +import { ETH_DATA_FORMAT, FormatType } from 'web3-common'; import { Transaction } from '../../src/types'; -export const transactionType0x0: FormatType[] = [ +export const transactionType0x0: FormatType[] = [ { from: '0xEB014f8c8B418Db6b45774c326A0E64C78914dC0', to: '0x3535353535353535353535353535353535353535', @@ -33,7 +33,7 @@ export const transactionType0x0: FormatType[] = [ +export const transactionType0x1: FormatType[] = [ { from: '0xEB014f8c8B418Db6b45774c326A0E64C78914dC0', to: '0x3535353535353535353535353535353535353535', @@ -90,7 +90,7 @@ export const transactionType0x1: FormatType[] = [ +export const transactionType0x2: FormatType[] = [ { from: '0xEB014f8c8B418Db6b45774c326A0E64C78914dC0', to: '0x3535353535353535353535353535353535353535', @@ -156,7 +156,7 @@ export const transactionType0x2: FormatType[] = [ +export const transactionTypeUndefined: FormatType[] = [ { from: '0xEB014f8c8B418Db6b45774c326A0E64C78914dC0', to: '0x3535353535353535353535353535353535353535', diff --git a/packages/web3-eth/test/fixtures/format_transaction.ts b/packages/web3-eth/test/fixtures/format_transaction.ts index cd48ae33b16..422913b8cac 100644 --- a/packages/web3-eth/test/fixtures/format_transaction.ts +++ b/packages/web3-eth/test/fixtures/format_transaction.ts @@ -15,101 +15,101 @@ You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see . */ -import { FMT_BYTES, FMT_NUMBER, FormatType } from 'web3-common'; +import { FMT_BYTES, FMT_NUMBER, FormatType, DEFAULT_RETURN_FORMAT } from 'web3-common'; import { Transaction } from '../../src/types'; export const bytesAsHexStringTransaction: FormatType< Transaction, - { number: FMT_NUMBER.HEX; bytes: FMT_BYTES.HEX } + { number: typeof DEFAULT_RETURN_FORMAT.number; bytes: FMT_BYTES.HEX } > = { from: '0xEB014f8c8B418Db6b45774c326A0E64C78914dC0', to: '0x3535353535353535353535353535353535353535', - value: '0x174876e800', - gas: '0x5208', - gasPrice: '0x4a817c800', - type: '0x0', - maxFeePerGas: '0x1229298c00', - maxPriorityFeePerGas: '0x49504f80', + value: BigInt('100000000000'), + gas: BigInt('21000'), + gasPrice: BigInt('20000000000'), + type: BigInt(0), + maxFeePerGas: BigInt('78000000000'), + maxPriorityFeePerGas: BigInt('1230000000'), data: '0x', - nonce: '0x4', + nonce: BigInt(4), chain: 'mainnet', hardfork: 'berlin', - chainId: '0x1', + chainId: BigInt(1), common: { customChain: { name: 'foo', - networkId: '0x4', - chainId: '0x42', + networkId: BigInt(4), + chainId: BigInt(66), }, baseChain: 'mainnet', hardfork: 'berlin', }, - gasLimit: '0x5208', - v: '0x25', + gasLimit: BigInt('21000'), + v: BigInt('37'), r: '0x4f4c17305743700648bc4f6cd3038ec6f6af0df73e31757007b7f59df7bee88d', s: '0x7e1941b264348e80c78c4027afc65a87b0a5e43e86742b8ca0823584c6788fd0', }; export const bytesAsBufferTransaction: FormatType< Transaction, - { number: FMT_NUMBER.HEX; bytes: FMT_BYTES.BUFFER } + { number: typeof DEFAULT_RETURN_FORMAT.number; bytes: FMT_BYTES.BUFFER } > = { from: '0xEB014f8c8B418Db6b45774c326A0E64C78914dC0', to: '0x3535353535353535353535353535353535353535', - value: '0x174876e800', - gas: '0x5208', - gasPrice: '0x4a817c800', - type: '0x0', - maxFeePerGas: '0x1229298c00', - maxPriorityFeePerGas: '0x49504f80', + value: BigInt('100000000000'), + gas: BigInt('21000'), + gasPrice: BigInt('20000000000'), + type: BigInt('0'), + maxFeePerGas: BigInt('78000000000'), + maxPriorityFeePerGas: BigInt('1230000000'), data: Buffer.alloc(0), - nonce: '0x4', + nonce: BigInt(4), chain: 'mainnet', hardfork: 'berlin', - chainId: '0x1', + chainId: BigInt(1), common: { customChain: { name: 'foo', - networkId: '0x4', - chainId: '0x42', + networkId: BigInt(4), + chainId: BigInt(66), }, baseChain: 'mainnet', hardfork: 'berlin', }, - gasLimit: '0x5208', - v: '0x25', + gasLimit: BigInt('21000'), + v: BigInt('37'), r: Buffer.from('4f4c17305743700648bc4f6cd3038ec6f6af0df73e31757007b7f59df7bee88d', 'hex'), s: Buffer.from('7e1941b264348e80c78c4027afc65a87b0a5e43e86742b8ca0823584c6788fd0', 'hex'), }; export const bytesAsUint8ArrayTransaction: FormatType< Transaction, - { number: FMT_NUMBER.HEX; bytes: FMT_BYTES.UINT8ARRAY } + { number: typeof DEFAULT_RETURN_FORMAT.number; bytes: FMT_BYTES.UINT8ARRAY } > = { from: '0xEB014f8c8B418Db6b45774c326A0E64C78914dC0', to: '0x3535353535353535353535353535353535353535', - value: '0x174876e800', - gas: '0x5208', - gasPrice: '0x4a817c800', - type: '0x0', - maxFeePerGas: '0x1229298c00', - maxPriorityFeePerGas: '0x49504f80', + value: BigInt('100000000000'), + gas: BigInt('21000'), + gasPrice: BigInt('20000000000'), + type: BigInt('0'), + maxFeePerGas: BigInt('78000000000'), + maxPriorityFeePerGas: BigInt('1230000000'), data: new Uint8Array(), - nonce: '0x4', + nonce: BigInt(4), chain: 'mainnet', hardfork: 'berlin', - chainId: '0x1', + chainId: BigInt(1), common: { customChain: { name: 'foo', - networkId: '0x4', - chainId: '0x42', + networkId: BigInt(4), + chainId: BigInt(66), }, baseChain: 'mainnet', hardfork: 'berlin', }, - gasLimit: '0x5208', - v: '0x25', + gasLimit: BigInt('21000'), + v: BigInt('37'), r: new Uint8Array( Buffer.from('4f4c17305743700648bc4f6cd3038ec6f6af0df73e31757007b7f59df7bee88d', 'hex'), ), @@ -120,7 +120,7 @@ export const bytesAsUint8ArrayTransaction: FormatType< export const numbersAsHexStringTransaction: FormatType< Transaction, - { number: FMT_NUMBER.HEX; bytes: FMT_BYTES.HEX } + { number: FMT_NUMBER.HEX; bytes: typeof DEFAULT_RETURN_FORMAT.bytes } > = { from: '0xEB014f8c8B418Db6b45774c326A0E64C78914dC0', to: '0x3535353535353535353535353535353535353535', @@ -152,7 +152,7 @@ export const numbersAsHexStringTransaction: FormatType< export const numbersAsNumberTransaction: FormatType< Transaction, - { number: FMT_NUMBER.NUMBER; bytes: FMT_BYTES.HEX } + { number: FMT_NUMBER.NUMBER; bytes: typeof DEFAULT_RETURN_FORMAT.bytes } > = { from: '0xEB014f8c8B418Db6b45774c326A0E64C78914dC0', to: '0x3535353535353535353535353535353535353535', @@ -184,7 +184,7 @@ export const numbersAsNumberTransaction: FormatType< export const numbersAsStringTransaction: FormatType< Transaction, - { number: FMT_NUMBER.STR; bytes: FMT_BYTES.HEX } + { number: FMT_NUMBER.STR; bytes: typeof DEFAULT_RETURN_FORMAT.bytes } > = { from: '0xEB014f8c8B418Db6b45774c326A0E64C78914dC0', to: '0x3535353535353535353535353535353535353535', @@ -216,7 +216,7 @@ export const numbersAsStringTransaction: FormatType< export const numbersAsBigIntTransaction: FormatType< Transaction, - { number: FMT_NUMBER.BIGINT; bytes: FMT_BYTES.HEX } + { number: FMT_NUMBER.BIGINT; bytes: typeof DEFAULT_RETURN_FORMAT.bytes } > = { from: '0xEB014f8c8B418Db6b45774c326A0E64C78914dC0', to: '0x3535353535353535353535353535353535353535', diff --git a/packages/web3-eth/test/integration/defaults.test.ts b/packages/web3-eth/test/integration/defaults.test.ts index 67bc6e301dc..2ba5abd7d3e 100644 --- a/packages/web3-eth/test/integration/defaults.test.ts +++ b/packages/web3-eth/test/integration/defaults.test.ts @@ -215,8 +215,8 @@ describe('defaults', () => { const transactionCount = await eth2.getTransactionCount(acc.address); expect(storage === '0x' ? 0 : Number(hexToNumber(storage))).toBe(0); expect(code).toBe('0x'); - expect(balance).toBe('0x0'); - expect(transactionCount).toBe('0x0'); + expect(balance).toBe(BigInt(0)); + expect(transactionCount).toBe(BigInt(0)); // pass blockNumber to rewrite defaultBlockNumber const balanceWithBlockNumber = await eth2.getBalance(acc.address, 'latest'); @@ -234,8 +234,8 @@ describe('defaults', () => { 'latest', ); expect(Number(hexToNumber(storageWithBlockNumber))).toBe(10); - expect(transactionCountWithBlockNumber).toBe('0x1'); - expect(Number(hexToNumber(balanceWithBlockNumber))).toBeGreaterThan(0); + expect(transactionCountWithBlockNumber).toBe(BigInt(1)); + expect(balanceWithBlockNumber).toBeGreaterThan(0); expect(codeWithBlockNumber.startsWith(BasicBytecode.slice(0, 10))).toBe(true); // set new default block to config @@ -248,8 +248,8 @@ describe('defaults', () => { const transactionCountLatest = await eth2.getTransactionCount(acc.address); expect(codeLatest.startsWith(BasicBytecode.slice(0, 10))).toBe(true); expect(Number(hexToNumber(storageLatest))).toBe(10); - expect(transactionCountLatest).toBe('0x1'); - expect(Number(hexToNumber(balanceLatest))).toBeGreaterThan(0); + expect(transactionCountLatest).toBe(BigInt(1)); + expect(balanceLatest).toBeGreaterThan(0); }); it('transactionBlockTimeout', () => { // default @@ -305,7 +305,7 @@ describe('defaults', () => { const receiptPromise = new Promise((resolve: Resolve) => { sentTx.on('receipt', (params: ReceiptInfo) => { - expect(params.status).toBe('0x1'); + expect(params.status).toBe(BigInt(1)); resolve(); }); }); @@ -367,12 +367,12 @@ describe('defaults', () => { // new Promise((resolve) => setTimeout(resolve, 410)), // new Promise((resolve: Resolve) => { // sentTx.on('receipt', (params: ReceiptInfo) => { - // expect(params.status).toBe('0x1'); + // expect(params.status).toBe(BigInt(1)); // resolve(params); // }); // }), // ]); - // expect((res as ReceiptInfo).status).toBe('0x1'); + // expect((res as ReceiptInfo).status).toBe(BigInt(1)); // // const sentTx2: Web3PromiEvent = eth2.sendTransaction({ // to: accounts[1], @@ -383,7 +383,7 @@ describe('defaults', () => { // new Promise((resolve) => setTimeout(()=>resolve(false), 300)), // new Promise((resolve: Resolve) => { // sentTx2.on('receipt', (params: ReceiptInfo) => { - // expect(params.status).toBe('0x1'); + // expect(params.status).toBe(BigInt(1)); // resolve(params); // }); // }), @@ -782,7 +782,7 @@ describe('defaults', () => { eth2, DEFAULT_RETURN_FORMAT, ); - expect(res?.maxPriorityFeePerGas).toBe(numberToHex(1200000000)); + expect(res?.maxPriorityFeePerGas).toBe(BigInt(1200000000)); // override test const resOverride = await getTransactionGasPricing( @@ -801,7 +801,7 @@ describe('defaults', () => { eth2, DEFAULT_RETURN_FORMAT, ); - expect(resOverride?.maxPriorityFeePerGas).toBe('0x123123123'); + expect(resOverride?.maxPriorityFeePerGas).toBe(BigInt('4883362083')); }); it('transactionBuilder', async () => { // default diff --git a/packages/web3-eth/test/integration/helper.ts b/packages/web3-eth/test/integration/helper.ts index eaaca342405..4a7e912aecd 100644 --- a/packages/web3-eth/test/integration/helper.ts +++ b/packages/web3-eth/test/integration/helper.ts @@ -43,7 +43,7 @@ export const sendFewTxes = async ({ // eslint-disable-next-line no-await-in-loop (await new Promise((resolve: Resolve) => { tx.on('receipt', (params: ReceiptInfo) => { - expect(params.status).toBe('0x1'); + expect(params.status).toBe(BigInt(1)); resolve(params); }); })) as ReceiptInfo, diff --git a/packages/web3-eth/test/integration/rpc.test.ts b/packages/web3-eth/test/integration/rpc.test.ts index 4d089f9f0af..b47ac126051 100644 --- a/packages/web3-eth/test/integration/rpc.test.ts +++ b/packages/web3-eth/test/integration/rpc.test.ts @@ -49,10 +49,10 @@ describe('rpc', () => { let web3Eth: Web3Eth; let accounts: string[] = []; let clientUrl: string; - let blockNumber: number | bigint; + let blockNumber: bigint; let blockHash: string; let transactionHash: string; - let transactionIndex: number | bigint; + let transactionIndex: bigint; let contract: Contract; let deployOptions: Record; @@ -62,18 +62,18 @@ describe('rpc', () => { expect(tx.nonce).toBeDefined(); expect(tx.hash).toBeDefined(); expect(String(tx.hash)?.length).toBe(66); - expect(tx.type).toBe('0x0'); + expect(tx.type).toBe(BigInt(0)); expect(tx.blockHash).toBeDefined(); expect(String(tx.blockHash)?.length).toBe(66); - expect(hexToNumber(String(tx.blockNumber))).toBeGreaterThan(0); + expect(tx.blockNumber).toBeGreaterThan(0); expect(tx.transactionIndex).toBeDefined(); expect(tx.from?.length).toBe(42); expect(tx.to?.length).toBe(42); - expect(tx.value).toBe('0x1'); + expect(tx.value).toBe(BigInt(1)); expect(tx.input).toBe('0x'); expect(tx.r).toBeDefined(); expect(tx.s).toBeDefined(); - expect(hexToNumber(String(tx.gas))).toBeGreaterThan(0); + expect(tx.gas).toBeGreaterThan(0); }; const validateBlock = (b: Block) => { expect(b.nonce).toBeDefined(); @@ -113,7 +113,7 @@ describe('rpc', () => { expect(r.logsBloom).toBeDefined(); expect(r.status).toBeDefined(); expect(String(r.transactionHash)).toHaveLength(66); - expect(hexToNumber(String(r.gasUsed))).toBeGreaterThan(0); + expect(r.gasUsed).toBeGreaterThan(0); }; beforeAll(async () => { @@ -142,7 +142,7 @@ describe('rpc', () => { contract = await contract.deploy(deployOptions).send(sendOptions); }); beforeEach(async () => { - const [receipt]: ReceiptInfo[] = await sendFewTxes({ + const [receipt] = await sendFewTxes({ web3Eth, from: accounts[0], to: accounts[1], @@ -150,10 +150,10 @@ describe('rpc', () => { times: 1, }); - blockNumber = hexToNumber(String(receipt.blockNumber)); + blockNumber = receipt.blockNumber as bigint; blockHash = String(receipt.blockHash); transactionHash = String(receipt.transactionHash); - transactionIndex = hexToNumber(String(receipt.transactionIndex)); + transactionIndex = receipt.transactionIndex as bigint; }); afterAll(() => { if (clientUrl.startsWith('ws')) { @@ -245,28 +245,16 @@ describe('rpc', () => { contract.options.address as string, '0x0', undefined, - { - number: FMT_NUMBER.BIGINT, - bytes: FMT_BYTES.HEX, - }, ); const resString = await web3Eth.getStorageAt( contract.options.address as string, '0x1', undefined, - { - number: FMT_NUMBER.STR, - bytes: FMT_BYTES.HEX, - }, ); const resBool = await web3Eth.getStorageAt( contract.options.address as string, '0x2', undefined, - { - number: FMT_NUMBER.NUMBER, - bytes: FMT_BYTES.HEX, - }, ); expect(hexToNumber(resNumber)).toBe(numberData); @@ -391,11 +379,11 @@ describe('rpc', () => { }), )('getBlockTransactionCount', async ({ block }) => { const res = await web3Eth.getBlockTransactionCount(block); - let shouldBe: string; + let shouldBe: bigint; if (getSystemTestBackend() === 'ganache') { - shouldBe = block === 'earliest' ? '0x0' : '0x1'; + shouldBe = block === 'earliest' ? BigInt(0) : BigInt(1); } else { - shouldBe = ['earliest', 'pending'].includes(String(block)) ? '0x0' : '0x1'; + shouldBe = ['earliest', 'pending'].includes(String(block)) ? BigInt(0) : BigInt(1); } expect(res).toBe(shouldBe); }); @@ -408,7 +396,7 @@ describe('rpc', () => { }), )('getBlockUncleCount', async ({ block }) => { const res = await web3Eth.getBlockUncleCount(block); - expect(res).toBe('0x0'); + expect(res).toBe(BigInt(0)); }); it.each( @@ -509,16 +497,13 @@ describe('rpc', () => { }); itIf(getSystemTestBackend() !== 'ganache')('getProof', async () => { - const numberData = 10; + const numberData = BigInt(10); const stringData = 'str'; const boolData = true; const sendRes = await contract.methods - ?.setValues(numberData, stringData, boolData) + .setValues(numberData, stringData, boolData) .send(sendOptions); - await web3Eth.getStorageAt(contract.options.address as string, 0, undefined, { - number: FMT_NUMBER.BIGINT, - bytes: FMT_BYTES.HEX, - }); + await web3Eth.getStorageAt(contract.options.address as string, 0, undefined); const res = await web3Eth.getProof( contract.options.address as string, ['0x0000000000000000000000000000000000000000000000000000000000000000'], @@ -527,7 +512,7 @@ describe('rpc', () => { // eslint-disable-next-line jest/no-standalone-expect expect(res.storageProof).toBeDefined(); // eslint-disable-next-line jest/no-standalone-expect - expect(hexToNumber(res.storageProof[0].value)).toBe(numberData); + expect(res.storageProof[0].value).toBe(numberData); }); it('getPastLogs', async () => { @@ -539,9 +524,7 @@ describe('rpc', () => { } const res: Array = await web3Eth.getPastLogs({ address: contract.options.address as string, - fromBlock: numberToHex( - Math.min(...resTx.map(d => Number(hexToNumber(d.blockNumber)))), - ), + fromBlock: numberToHex(Math.min(...resTx.map(d => Number(d.blockNumber)))), }); const results = res.map( r => diff --git a/packages/web3-eth/test/integration/watch_transaction.test.ts b/packages/web3-eth/test/integration/watch_transaction.test.ts index 5abefcdeddd..b12be751fdd 100644 --- a/packages/web3-eth/test/integration/watch_transaction.test.ts +++ b/packages/web3-eth/test/integration/watch_transaction.test.ts @@ -127,7 +127,7 @@ describeIf(getSystemTestProvider().startsWith('http'))('watch polling transactio }); await new Promise((resolve: Resolve) => { sentTx.on('receipt', (params: ReceiptInfo) => { - expect(params.status).toBe('0x1'); + expect(params.status).toBe(BigInt(1)); resolve(); }); }); diff --git a/packages/web3-eth/test/integration/web3_eth/estimate_gas.test.ts b/packages/web3-eth/test/integration/web3_eth/estimate_gas.test.ts index 768bacb8fb2..3158063dfbc 100644 --- a/packages/web3-eth/test/integration/web3_eth/estimate_gas.test.ts +++ b/packages/web3-eth/test/integration/web3_eth/estimate_gas.test.ts @@ -43,7 +43,7 @@ describe('Web3Eth.estimateGas', () => { value: '0x1', }; const response = await web3Eth.estimateGas(transaction); - expect(response).toBe('0x5208'); + expect(response).toBe(BigInt(21000)); }); it('should estimate a contract deployment', async () => { @@ -55,6 +55,6 @@ describe('Web3Eth.estimateGas', () => { gas: '0x740b8', }; const response = await web3Eth.estimateGas(transaction); - expect(response).toBe('0x740b8'); + expect(response).toBe(BigInt(475320)); }); }); diff --git a/packages/web3-eth/test/integration/web3_eth/send_signed_transaction.test.ts b/packages/web3-eth/test/integration/web3_eth/send_signed_transaction.test.ts index 8e03ed9eea8..b722215c458 100644 --- a/packages/web3-eth/test/integration/web3_eth/send_signed_transaction.test.ts +++ b/packages/web3-eth/test/integration/web3_eth/send_signed_transaction.test.ts @@ -16,13 +16,15 @@ along with web3.js. If not, see . */ import WebSocketProvider from 'web3-providers-ws'; -import { Address } from 'web3-utils'; +import { Address, Bytes, hexToNumber } from 'web3-utils'; -import { DEFAULT_RETURN_FORMAT, SignedTransactionInfo } from 'web3-common'; +import { DEFAULT_RETURN_FORMAT, format, SignedTransactionInfo } from 'web3-common'; import { isHexStrict } from 'web3-validator'; import Web3Eth, { InternalTransaction, Transaction } from '../../../src'; import { getSystemTestAccounts, getSystemTestProvider } from '../../fixtures/system_test_utils'; import { getTransactionGasPricing } from '../../../src/utils/get_transaction_gas_pricing'; +import { HEX_NUMBER_DATA_FORMAT } from '../../../src/constants'; +import { transactionSchema } from '../../../src/schemas'; describe('Web3Eth.sendSignedTransaction', () => { let web3Eth: Web3Eth; @@ -41,7 +43,11 @@ describe('Web3Eth.sendSignedTransaction', () => { describe('Transaction Types', () => { it('should send a signed simple value transfer - type 0x0', async () => { - const accountNonce = await web3Eth.getTransactionCount(accounts[0]); + const accountNonce = await web3Eth.getTransactionCount( + accounts[0], + undefined, + HEX_NUMBER_DATA_FORMAT, + ); const transaction: InternalTransaction = { nonce: accountNonce, from: accounts[0], @@ -59,15 +65,25 @@ describe('Web3Eth.sendSignedTransaction', () => { ...transaction, ...gasPricing, }); - const response = await web3Eth.sendSignedTransaction(signedTransaction.raw); - expect(response.status).toBe('0x1'); + const response = await web3Eth.sendSignedTransaction( + typeof signedTransaction.raw === 'string' + ? signedTransaction.raw + : signedTransaction.raw.raw, + ); + expect(response.status).toBe(BigInt(1)); const minedTransactionData = await web3Eth.getTransaction(response.transactionHash); - expect(minedTransactionData).toMatchObject(transaction); + expect(minedTransactionData).toMatchObject( + format(transactionSchema, transaction, DEFAULT_RETURN_FORMAT), + ); }); it('should send a signed simple value transfer - type 0x1', async () => { - const accountNonce = await web3Eth.getTransactionCount(accounts[0]); + const accountNonce = await web3Eth.getTransactionCount( + accounts[0], + undefined, + HEX_NUMBER_DATA_FORMAT, + ); const transaction: InternalTransaction = { nonce: accountNonce, from: accounts[0], @@ -86,15 +102,25 @@ describe('Web3Eth.sendSignedTransaction', () => { ...transaction, ...gasPricing, }); - const response = await web3Eth.sendSignedTransaction(signedTransaction.raw); - expect(response.status).toBe('0x1'); + const response = await web3Eth.sendSignedTransaction( + typeof signedTransaction.raw === 'string' + ? signedTransaction.raw + : signedTransaction.raw.raw, + ); + expect(response.status).toBe(BigInt(1)); const minedTransactionData = await web3Eth.getTransaction(response.transactionHash); - expect(minedTransactionData).toMatchObject(transaction); + expect(minedTransactionData).toMatchObject( + format(transactionSchema, transaction, DEFAULT_RETURN_FORMAT), + ); }); it('should send a signed simple value transfer - type 0x2', async () => { - const accountNonce = await web3Eth.getTransactionCount(accounts[0]); + const accountNonce = await web3Eth.getTransactionCount( + accounts[0], + undefined, + HEX_NUMBER_DATA_FORMAT, + ); const transaction: InternalTransaction = { nonce: accountNonce, from: accounts[0], @@ -112,18 +138,28 @@ describe('Web3Eth.sendSignedTransaction', () => { ...transaction, ...gasPricing, }); - const response = await web3Eth.sendSignedTransaction(signedTransaction.raw); - expect(response.status).toBe('0x1'); + const response = await web3Eth.sendSignedTransaction( + typeof signedTransaction.raw === 'string' + ? signedTransaction.raw + : signedTransaction.raw.raw, + ); + expect(response.status).toBe(BigInt(1)); const minedTransactionData = await web3Eth.getTransaction(response.transactionHash); - expect(minedTransactionData).toMatchObject(transaction); + expect(minedTransactionData).toMatchObject( + format(transactionSchema, transaction, DEFAULT_RETURN_FORMAT), + ); }); }); it('should send a signed contract deployment', async () => { const greeterContractDeploymentData = '0x60806040523480156200001157600080fd5b5060405162000a6a38038062000a6a8339818101604052810190620000379190620002a4565b80600090805190602001906200004f92919062000057565b505062000359565b828054620000659062000324565b90600052602060002090601f016020900481019282620000895760008555620000d5565b82601f10620000a457805160ff1916838001178555620000d5565b82800160010185558215620000d5579182015b82811115620000d4578251825591602001919060010190620000b7565b5b509050620000e49190620000e8565b5090565b5b8082111562000103576000816000905550600101620000e9565b5090565b6000604051905090565b600080fd5b600080fd5b600080fd5b600080fd5b6000601f19601f8301169050919050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052604160045260246000fd5b620001708262000125565b810181811067ffffffffffffffff8211171562000192576200019162000136565b5b80604052505050565b6000620001a762000107565b9050620001b5828262000165565b919050565b600067ffffffffffffffff821115620001d857620001d762000136565b5b620001e38262000125565b9050602081019050919050565b60005b8381101562000210578082015181840152602081019050620001f3565b8381111562000220576000848401525b50505050565b60006200023d6200023784620001ba565b6200019b565b9050828152602081018484840111156200025c576200025b62000120565b5b62000269848285620001f0565b509392505050565b600082601f8301126200028957620002886200011b565b5b81516200029b84826020860162000226565b91505092915050565b600060208284031215620002bd57620002bc62000111565b5b600082015167ffffffffffffffff811115620002de57620002dd62000116565b5b620002ec8482850162000271565b91505092915050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052602260045260246000fd5b600060028204905060018216806200033d57607f821691505b602082108103620003535762000352620002f5565b5b50919050565b61070180620003696000396000f3fe608060405234801561001057600080fd5b50600436106100365760003560e01c8063a41368621461003b578063cfae32171461006c575b600080fd5b6100556004803603810190610050919061043f565b61008a565b60405161006392919061052b565b60405180910390f35b6100746101b0565b604051610081919061055b565b60405180910390f35b600060607f0d363f2fba46ab11b6db8da0125b0d5484787c44e265b48810735998bab12b756000846040516100c0929190610672565b60405180910390a182600090805190602001906100de929190610242565b507f7d7846723bda52976e0286c6efffee937ee9f76817a867ec70531ad29fb1fc0e600060405161010f91906106a9565b60405180910390a160016000808054610127906105ac565b80601f0160208091040260200160405190810160405280929190818152602001828054610153906105ac565b80156101a05780601f10610175576101008083540402835291602001916101a0565b820191906000526020600020905b81548152906001019060200180831161018357829003601f168201915b5050505050905091509150915091565b6060600080546101bf906105ac565b80601f01602080910402602001604051908101604052809291908181526020018280546101eb906105ac565b80156102385780601f1061020d57610100808354040283529160200191610238565b820191906000526020600020905b81548152906001019060200180831161021b57829003601f168201915b5050505050905090565b82805461024e906105ac565b90600052602060002090601f01602090048101928261027057600085556102b7565b82601f1061028957805160ff19168380011785556102b7565b828001600101855582156102b7579182015b828111156102b657825182559160200191906001019061029b565b5b5090506102c491906102c8565b5090565b5b808211156102e15760008160009055506001016102c9565b5090565b6000604051905090565b600080fd5b600080fd5b600080fd5b600080fd5b6000601f19601f8301169050919050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052604160045260246000fd5b61034c82610303565b810181811067ffffffffffffffff8211171561036b5761036a610314565b5b80604052505050565b600061037e6102e5565b905061038a8282610343565b919050565b600067ffffffffffffffff8211156103aa576103a9610314565b5b6103b382610303565b9050602081019050919050565b82818337600083830152505050565b60006103e26103dd8461038f565b610374565b9050828152602081018484840111156103fe576103fd6102fe565b5b6104098482856103c0565b509392505050565b600082601f830112610426576104256102f9565b5b81356104368482602086016103cf565b91505092915050565b600060208284031215610455576104546102ef565b5b600082013567ffffffffffffffff811115610473576104726102f4565b5b61047f84828501610411565b91505092915050565b60008115159050919050565b61049d81610488565b82525050565b600081519050919050565b600082825260208201905092915050565b60005b838110156104dd5780820151818401526020810190506104c2565b838111156104ec576000848401525b50505050565b60006104fd826104a3565b61050781856104ae565b93506105178185602086016104bf565b61052081610303565b840191505092915050565b60006040820190506105406000830185610494565b818103602083015261055281846104f2565b90509392505050565b6000602082019050818103600083015261057581846104f2565b905092915050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052602260045260246000fd5b600060028204905060018216806105c457607f821691505b6020821081036105d7576105d661057d565b5b50919050565b60008190508160005260206000209050919050565b600081546105ff816105ac565b61060981866104ae565b94506001821660008114610624576001811461063657610669565b60ff1983168652602086019350610669565b61063f856105dd565b60005b8381101561066157815481890152600182019150602081019050610642565b808801955050505b50505092915050565b6000604082019050818103600083015261068c81856105f2565b905081810360208301526106a081846104f2565b90509392505050565b600060208201905081810360008301526106c381846105f2565b90509291505056fea2646970667358221220fe0f28c9f8ef0a13a95934b974e7bc2ca6762b40a5b93ccd6ca2038f454bf52764736f6c634300080e003300000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000017736f6c79656e7420677265656e2069732070656f706c65000000000000000000'; - const accountNonce = await web3Eth.getTransactionCount(accounts[0]); + const accountNonce = await web3Eth.getTransactionCount( + accounts[0], + undefined, + HEX_NUMBER_DATA_FORMAT, + ); const transaction: InternalTransaction = { nonce: accountNonce, from: accounts[0], @@ -137,16 +173,16 @@ describe('Web3Eth.sendSignedTransaction', () => { DEFAULT_RETURN_FORMAT, ); const signedTransaction = await web3Eth.signTransaction({ ...transaction, ...gasPricing }); - const response = await web3Eth.sendSignedTransaction(signedTransaction.raw); - expect(response.status).toBe('0x1'); + const response = await web3Eth.sendSignedTransaction(signedTransaction.raw as Bytes); + expect(response.status).toBe(BigInt(1)); const minedTransactionData = await web3Eth.getTransaction(response.transactionHash); expect(minedTransactionData).toMatchObject({ - nonce: accountNonce, + nonce: BigInt(hexToNumber(accountNonce)), from: accounts[0], input: greeterContractDeploymentData, - type: '0x0', - gas: '0x740b8', + type: BigInt(0), + gas: BigInt(475320), }); }); @@ -203,19 +239,19 @@ describe('Web3Eth.sendSignedTransaction', () => { it('should listen to the receipt event', async () => { const expectedTransactionReceipt = { blockHash: expect.any(String), - blockNumber: expect.any(String), - cumulativeGasUsed: expect.any(String), - effectiveGasPrice: expect.any(String), - gasUsed: expect.any(String), + blockNumber: expect.any(BigInt), + cumulativeGasUsed: expect.any(BigInt), + effectiveGasPrice: expect.any(BigInt), + gasUsed: expect.any(BigInt), logs: [], logsBloom: '0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000', - status: '0x1', + status: BigInt(1), from: transaction.from, to: transaction.to, transactionHash: expect.any(String), - transactionIndex: '0x0', - type: '0x0', + transactionIndex: BigInt(0), + type: BigInt(0), }; const promiEvent = web3Eth.sendSignedTransaction(signedTransaction.raw); promiEvent.on('receipt', data => { @@ -226,22 +262,22 @@ describe('Web3Eth.sendSignedTransaction', () => { it('should listen to the confirmation event', async () => { const expectedTransactionConfirmation = { - confirmationNumber: expect.any(String), + confirmationNumber: expect.any(BigInt), receipt: { blockHash: expect.any(String), - blockNumber: expect.any(String), - cumulativeGasUsed: expect.any(String), - effectiveGasPrice: expect.any(String), - gasUsed: expect.any(String), + blockNumber: expect.any(BigInt), + cumulativeGasUsed: expect.any(BigInt), + effectiveGasPrice: expect.any(BigInt), + gasUsed: expect.any(BigInt), logs: [], logsBloom: '0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000', - status: '0x1', + status: BigInt(1), from: transaction.from, to: transaction.to, transactionHash: expect.any(String), - transactionIndex: '0x0', - type: '0x0', + transactionIndex: BigInt(0), + type: BigInt(0), }, latestBlockHash: expect.any(String), }; diff --git a/packages/web3-eth/test/integration/web3_eth/send_transaction.test.ts b/packages/web3-eth/test/integration/web3_eth/send_transaction.test.ts index ee2b8c04da1..7eb08da1f2d 100644 --- a/packages/web3-eth/test/integration/web3_eth/send_transaction.test.ts +++ b/packages/web3-eth/test/integration/web3_eth/send_transaction.test.ts @@ -46,10 +46,10 @@ describe('Web3Eth.sendTransaction', () => { const transaction: Transaction = { from: accounts[0], to: '0x0000000000000000000000000000000000000000', - value: '0x1', + value: BigInt(1), }; const response = await web3Eth.sendTransaction(transaction); - expect(response.status).toBe('0x1'); + expect(response.status).toBe(BigInt(1)); const minedTransactionData = await web3Eth.getTransaction(response.transactionHash); expect(minedTransactionData).toMatchObject(transaction); @@ -76,10 +76,10 @@ describe('Web3Eth.sendTransaction', () => { const transaction: TransactionWithLocalWalletIndex = { from: 0, to: '0x0000000000000000000000000000000000000000', - value: '0x1', + value: BigInt(1), }; const response = await web3EthWithWallet.sendTransaction(transaction); - expect(response.status).toBe('0x1'); + expect(response.status).toBe(BigInt(1)); const minedTransactionData = await web3EthWithWallet.getTransaction( response.transactionHash, @@ -87,7 +87,7 @@ describe('Web3Eth.sendTransaction', () => { expect(minedTransactionData).toMatchObject({ from: accountsWithKeys[0].address.toLowerCase(), to: '0x0000000000000000000000000000000000000000', - value: '0x1', + value: BigInt(1), }); }); @@ -95,10 +95,10 @@ describe('Web3Eth.sendTransaction', () => { const transaction: Transaction = { from: accounts[0], to: '0x0000000000000000000000000000000000000000', - value: '0x0', + value: BigInt(0), }; const response = await web3Eth.sendTransaction(transaction); - expect(response.status).toBe('0x1'); + expect(response.status).toBe(BigInt(1)); const minedTransactionData = await web3Eth.getTransaction(response.transactionHash); expect(minedTransactionData).toMatchObject(transaction); @@ -113,17 +113,17 @@ describe('Web3Eth.sendTransaction', () => { const transaction: Transaction = { from: accounts[0], data: greeterContractDeploymentData, - gas: '0x740b8', + gas: BigInt('475320'), }; const response = await web3Eth.sendTransaction(transaction); - expect(response.status).toBe('0x1'); + expect(response.status).toBe(BigInt(1)); expect(response.contractAddress).toBeDefined(); const minedTransactionData = await web3Eth.getTransaction(response.transactionHash); expect(minedTransactionData).toMatchObject({ from: accounts[0], input: greeterContractDeploymentData, - gas: '0x740b8', + gas: BigInt('475320'), }); greeterContractAddress = response.contractAddress as string; @@ -138,7 +138,7 @@ describe('Web3Eth.sendTransaction', () => { data: contractFunctionCall, }; const response = await web3Eth.sendTransaction(transaction); - expect(response.status).toBe('0x1'); + expect(response.status).toBe(BigInt(1)); const minedTransactionData = await web3Eth.getTransaction(response.transactionHash); expect(minedTransactionData).toMatchObject({ @@ -154,12 +154,12 @@ describe('Web3Eth.sendTransaction', () => { const transaction: Transaction = { from: accounts[0], to: '0x0000000000000000000000000000000000000000', - value: '0x1', - type: '0x0', + value: BigInt(1), + type: BigInt(0), }; const response = await web3Eth.sendTransaction(transaction); - expect(response.type).toBe('0x0'); - expect(response.status).toBe('0x1'); + expect(response.type).toBe(BigInt(0)); + expect(response.status).toBe(BigInt(1)); const minedTransactionData = await web3Eth.getTransaction(response.transactionHash); expect(minedTransactionData).toMatchObject(transaction); @@ -169,16 +169,16 @@ describe('Web3Eth.sendTransaction', () => { const transaction: Transaction = { from: accounts[0], to: '0x0000000000000000000000000000000000000000', - value: '0x1', - type: '0x1', + value: BigInt(1), + type: BigInt(1), // TODO If this property is not included, tx gets default to type: 0x0 // from what I can tell our library isn't doing this, but it happens // with both Geth and Ganache, so I'm not sure accessList: [], }; const response = await web3Eth.sendTransaction(transaction); - expect(response.type).toBe('0x1'); - expect(response.status).toBe('0x1'); + expect(response.type).toBe(BigInt(1)); + expect(response.status).toBe(BigInt(1)); const minedTransactionData = await web3Eth.getTransaction(response.transactionHash); expect(minedTransactionData).toMatchObject(transaction); @@ -188,12 +188,12 @@ describe('Web3Eth.sendTransaction', () => { const transaction: Transaction = { from: accounts[0], to: '0x0000000000000000000000000000000000000000', - value: '0x1', - type: '0x2', + value: BigInt(1), + type: BigInt(2), }; const response = await web3Eth.sendTransaction(transaction); - expect(response.type).toBe('0x2'); - expect(response.status).toBe('0x1'); + expect(response.type).toBe(BigInt(2)); + expect(response.status).toBe(BigInt(1)); const minedTransactionData = await web3Eth.getTransaction(response.transactionHash); expect(minedTransactionData).toMatchObject(transaction); @@ -238,19 +238,19 @@ describe('Web3Eth.sendTransaction', () => { it('should listen to the receipt event', async () => { const expectedTransactionReceipt = { blockHash: expect.any(String), - blockNumber: expect.any(String), - cumulativeGasUsed: expect.any(String), - effectiveGasPrice: expect.any(String), - gasUsed: expect.any(String), + blockNumber: expect.any(BigInt), + cumulativeGasUsed: expect.any(BigInt), + effectiveGasPrice: expect.any(BigInt), + gasUsed: expect.any(BigInt), logs: [], logsBloom: '0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000', - status: '0x1', + status: BigInt(1), from: transaction.from, to: transaction.to, transactionHash: expect.any(String), - transactionIndex: '0x0', - type: '0x0', + transactionIndex: BigInt(0), + type: BigInt(0), }; const promiEvent = web3Eth.sendTransaction(transaction); promiEvent.on('receipt', data => { @@ -261,22 +261,22 @@ describe('Web3Eth.sendTransaction', () => { it('should listen to the confirmation event', async () => { const expectedTransactionConfirmation = { - confirmationNumber: expect.any(String), + confirmationNumber: expect.any(BigInt), receipt: { blockHash: expect.any(String), - blockNumber: expect.any(String), - cumulativeGasUsed: expect.any(String), - effectiveGasPrice: expect.any(String), - gasUsed: expect.any(String), + blockNumber: expect.any(BigInt), + cumulativeGasUsed: expect.any(BigInt), + effectiveGasPrice: expect.any(BigInt), + gasUsed: expect.any(BigInt), logs: [], logsBloom: '0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000', - status: '0x1', + status: BigInt(1), from: transaction.from, to: transaction.to, transactionHash: expect.any(String), - transactionIndex: '0x0', - type: '0x0', + transactionIndex: BigInt(0), + type: BigInt(0), }, latestBlockHash: expect.any(String), }; diff --git a/packages/web3-eth/test/unit/rpc_method_wrappers/call.test.ts b/packages/web3-eth/test/unit/rpc_method_wrappers/call.test.ts index 26cf97f53d4..630b088f1fb 100644 --- a/packages/web3-eth/test/unit/rpc_method_wrappers/call.test.ts +++ b/packages/web3-eth/test/unit/rpc_method_wrappers/call.test.ts @@ -16,7 +16,7 @@ along with web3.js. If not, see . */ import { Web3Context } from 'web3-core'; import { isNullish } from 'web3-validator'; -import { DEFAULT_RETURN_FORMAT, FMT_BYTES, FMT_NUMBER, format } from 'web3-common'; +import { DEFAULT_RETURN_FORMAT, ETH_DATA_FORMAT, FMT_BYTES, FMT_NUMBER, format } from 'web3-common'; import { call as rpcMethodsCall } from '../../../src/rpc_methods'; import { Web3EthExecutionAPI } from '../../../src/web3_eth_execution_api'; @@ -37,10 +37,7 @@ describe('call', () => { `should call rpcMethods.call with expected parameters\nTitle: %s\nInput parameters: %s\n`, async (_, inputParameters) => { const [inputTransaction, inputBlockNumber] = inputParameters; - const inputTransactionFormatted = formatTransaction( - inputTransaction, - DEFAULT_RETURN_FORMAT, - ); + const inputTransactionFormatted = formatTransaction(inputTransaction, ETH_DATA_FORMAT); let inputBlockNumberFormatted; @@ -50,7 +47,7 @@ describe('call', () => { inputBlockNumberFormatted = format( { eth: 'uint' }, inputBlockNumber, - DEFAULT_RETURN_FORMAT, + ETH_DATA_FORMAT, ); } diff --git a/packages/web3-eth/test/unit/rpc_method_wrappers/estimate_gas.test.ts b/packages/web3-eth/test/unit/rpc_method_wrappers/estimate_gas.test.ts index 60a39c04507..dbd11cc889f 100644 --- a/packages/web3-eth/test/unit/rpc_method_wrappers/estimate_gas.test.ts +++ b/packages/web3-eth/test/unit/rpc_method_wrappers/estimate_gas.test.ts @@ -16,13 +16,14 @@ along with web3.js. If not, see . */ import { Web3Context } from 'web3-core'; import { isNullish } from 'web3-validator'; -import { DEFAULT_RETURN_FORMAT, FMT_BYTES, FMT_NUMBER, format } from 'web3-common'; +import { DEFAULT_RETURN_FORMAT, ETH_DATA_FORMAT, FMT_BYTES, FMT_NUMBER, format } from 'web3-common'; import { estimateGas as rpcMethodsEstimateGas } from '../../../src/rpc_methods'; import { Web3EthExecutionAPI } from '../../../src/web3_eth_execution_api'; import { estimateGas } from '../../../src/rpc_method_wrappers'; import { mockRpcResponse, testData } from './fixtures/estimate_gas'; import { formatTransaction } from '../../../src'; +import { STR_NUMBER_DATA_FORMAT } from '../../../src/constants'; jest.mock('../../../src/rpc_methods'); @@ -37,10 +38,7 @@ describe('call', () => { `should call rpcMethods.estimateGas with expected parameters\nTitle: %s\nInput parameters: %s\n`, async (_, inputParameters) => { const [inputTransaction, inputBlockNumber] = inputParameters; - const inputTransactionFormatted = formatTransaction( - inputTransaction, - DEFAULT_RETURN_FORMAT, - ); + const inputTransactionFormatted = formatTransaction(inputTransaction, ETH_DATA_FORMAT); let inputBlockNumberFormatted; @@ -50,7 +48,7 @@ describe('call', () => { inputBlockNumberFormatted = format( { eth: 'uint' }, inputBlockNumber, - DEFAULT_RETURN_FORMAT, + STR_NUMBER_DATA_FORMAT, ); } diff --git a/packages/web3-eth/test/unit/rpc_method_wrappers/get_balance.test.ts b/packages/web3-eth/test/unit/rpc_method_wrappers/get_balance.test.ts index dc355b80711..507c598e202 100644 --- a/packages/web3-eth/test/unit/rpc_method_wrappers/get_balance.test.ts +++ b/packages/web3-eth/test/unit/rpc_method_wrappers/get_balance.test.ts @@ -15,7 +15,7 @@ You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see . */ import { Web3Context } from 'web3-core'; -import { DEFAULT_RETURN_FORMAT, FMT_BYTES, FMT_NUMBER, format } from 'web3-common'; +import { DEFAULT_RETURN_FORMAT, ETH_DATA_FORMAT, FMT_BYTES, FMT_NUMBER, format } from 'web3-common'; import { isNullish } from 'web3-validator'; import { getBalance as rpcMethodsGetBalance } from '../../../src/rpc_methods'; @@ -45,7 +45,7 @@ describe('getBalance', () => { inputBlockNumberFormatted = format( { eth: 'uint' }, inputBlockNumber, - DEFAULT_RETURN_FORMAT, + ETH_DATA_FORMAT, ); } diff --git a/packages/web3-eth/test/unit/rpc_method_wrappers/get_block.test.ts b/packages/web3-eth/test/unit/rpc_method_wrappers/get_block.test.ts index d4affe05a66..c7af128c43c 100644 --- a/packages/web3-eth/test/unit/rpc_method_wrappers/get_block.test.ts +++ b/packages/web3-eth/test/unit/rpc_method_wrappers/get_block.test.ts @@ -15,7 +15,7 @@ You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see . */ import { Web3Context } from 'web3-core'; -import { DEFAULT_RETURN_FORMAT, FMT_BYTES, FMT_NUMBER, format } from 'web3-common'; +import { DEFAULT_RETURN_FORMAT, ETH_DATA_FORMAT, FMT_BYTES, FMT_NUMBER, format } from 'web3-common'; import { isBytes, isNullish } from 'web3-validator'; import { Bytes } from 'web3-utils'; @@ -43,11 +43,11 @@ describe('getBlock', () => { let inputBlockFormatted; if (inputBlockIsBytes) { - inputBlockFormatted = format({ eth: 'bytes32' }, inputBlock, DEFAULT_RETURN_FORMAT); + inputBlockFormatted = format({ eth: 'bytes32' }, inputBlock, ETH_DATA_FORMAT); } else if (isNullish(inputBlock)) { inputBlockFormatted = web3Context.defaultBlock; } else { - inputBlockFormatted = format({ eth: 'uint' }, inputBlock, DEFAULT_RETURN_FORMAT); + inputBlockFormatted = format({ eth: 'uint' }, inputBlock, ETH_DATA_FORMAT); } await getBlock(web3Context, ...inputParameters, DEFAULT_RETURN_FORMAT); diff --git a/packages/web3-eth/test/unit/rpc_method_wrappers/get_block_transaction_count.test.ts b/packages/web3-eth/test/unit/rpc_method_wrappers/get_block_transaction_count.test.ts index 8ccfb336c86..d07b127ba93 100644 --- a/packages/web3-eth/test/unit/rpc_method_wrappers/get_block_transaction_count.test.ts +++ b/packages/web3-eth/test/unit/rpc_method_wrappers/get_block_transaction_count.test.ts @@ -15,7 +15,7 @@ You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see . */ import { Web3Context } from 'web3-core'; -import { DEFAULT_RETURN_FORMAT, FMT_BYTES, FMT_NUMBER, format } from 'web3-common'; +import { DEFAULT_RETURN_FORMAT, ETH_DATA_FORMAT, FMT_BYTES, FMT_NUMBER, format } from 'web3-common'; import { isBytes, isNullish } from 'web3-validator'; import { Bytes } from 'web3-utils'; @@ -45,11 +45,11 @@ describe('getBlockTransactionCount', () => { let inputBlockFormatted; if (inputBlockIsBytes) { - inputBlockFormatted = format({ eth: 'bytes32' }, inputBlock, DEFAULT_RETURN_FORMAT); + inputBlockFormatted = format({ eth: 'bytes32' }, inputBlock, ETH_DATA_FORMAT); } else if (isNullish(inputBlock)) { inputBlockFormatted = web3Context.defaultBlock; } else { - inputBlockFormatted = format({ eth: 'uint' }, inputBlock, DEFAULT_RETURN_FORMAT); + inputBlockFormatted = format({ eth: 'uint' }, inputBlock, ETH_DATA_FORMAT); } await getBlockTransactionCount(web3Context, ...inputParameters, DEFAULT_RETURN_FORMAT); diff --git a/packages/web3-eth/test/unit/rpc_method_wrappers/get_block_uncle_count.test.ts b/packages/web3-eth/test/unit/rpc_method_wrappers/get_block_uncle_count.test.ts index 25a5186c597..f3ad477ce44 100644 --- a/packages/web3-eth/test/unit/rpc_method_wrappers/get_block_uncle_count.test.ts +++ b/packages/web3-eth/test/unit/rpc_method_wrappers/get_block_uncle_count.test.ts @@ -15,7 +15,7 @@ You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see . */ import { Web3Context } from 'web3-core'; -import { DEFAULT_RETURN_FORMAT, FMT_BYTES, FMT_NUMBER, format } from 'web3-common'; +import { DEFAULT_RETURN_FORMAT, ETH_DATA_FORMAT, FMT_BYTES, FMT_NUMBER, format } from 'web3-common'; import { isBytes, isNullish } from 'web3-validator'; import { Bytes } from 'web3-utils'; @@ -42,11 +42,11 @@ describe('getBlockUncleCount', () => { let inputBlockFormatted; if (inputBlockIsBytes) { - inputBlockFormatted = format({ eth: 'bytes32' }, inputBlock, DEFAULT_RETURN_FORMAT); + inputBlockFormatted = format({ eth: 'bytes32' }, inputBlock, ETH_DATA_FORMAT); } else if (isNullish(inputBlock)) { inputBlockFormatted = web3Context.defaultBlock; } else { - inputBlockFormatted = format({ eth: 'uint' }, inputBlock, DEFAULT_RETURN_FORMAT); + inputBlockFormatted = format({ eth: 'uint' }, inputBlock, ETH_DATA_FORMAT); } await getBlockUncleCount(web3Context, inputBlock, DEFAULT_RETURN_FORMAT); diff --git a/packages/web3-eth/test/unit/rpc_method_wrappers/get_code.test.ts b/packages/web3-eth/test/unit/rpc_method_wrappers/get_code.test.ts index f4345f15eaf..e003b5902d1 100644 --- a/packages/web3-eth/test/unit/rpc_method_wrappers/get_code.test.ts +++ b/packages/web3-eth/test/unit/rpc_method_wrappers/get_code.test.ts @@ -15,7 +15,7 @@ You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see . */ import { Web3Context } from 'web3-core'; -import { DEFAULT_RETURN_FORMAT, FMT_BYTES, FMT_NUMBER, format } from 'web3-common'; +import { DEFAULT_RETURN_FORMAT, ETH_DATA_FORMAT, FMT_BYTES, FMT_NUMBER, format } from 'web3-common'; import { isNullish } from 'web3-validator'; import { getCode as rpcMethodsGetCode } from '../../../src/rpc_methods'; @@ -45,7 +45,7 @@ describe('getCode', () => { inputBlockNumberFormatted = format( { eth: 'uint' }, inputBlockNumber, - DEFAULT_RETURN_FORMAT, + ETH_DATA_FORMAT, ); } diff --git a/packages/web3-eth/test/unit/rpc_method_wrappers/get_fee_history.test.ts b/packages/web3-eth/test/unit/rpc_method_wrappers/get_fee_history.test.ts index 75bf477334d..fce5540063c 100644 --- a/packages/web3-eth/test/unit/rpc_method_wrappers/get_fee_history.test.ts +++ b/packages/web3-eth/test/unit/rpc_method_wrappers/get_fee_history.test.ts @@ -23,6 +23,7 @@ import { Web3EthExecutionAPI } from '../../../src/web3_eth_execution_api'; import { getFeeHistory } from '../../../src/rpc_method_wrappers'; import { mockRpcResponse, testData } from './fixtures/get_fee_history'; import { feeHistorySchema } from '../../../src/schemas'; +import { NUMBER_DATA_FORMAT, STR_NUMBER_DATA_FORMAT } from '../../../src/constants'; jest.mock('../../../src/rpc_methods'); @@ -40,7 +41,7 @@ describe('getFeeHistory', () => { const inputBlockCountFormatted = format( { eth: 'uint' }, inputBlockCount, - DEFAULT_RETURN_FORMAT, + STR_NUMBER_DATA_FORMAT, ); const inputRewardPercentilesFormatted = format( { @@ -50,10 +51,7 @@ describe('getFeeHistory', () => { }, }, inputRewardPercentiles, - { - number: FMT_NUMBER.NUMBER, - bytes: FMT_BYTES.HEX, - }, + NUMBER_DATA_FORMAT, ); let inputNewestBlockFormatted; @@ -64,7 +62,7 @@ describe('getFeeHistory', () => { inputNewestBlockFormatted = format( { eth: 'uint' }, inputNewestBlock, - DEFAULT_RETURN_FORMAT, + STR_NUMBER_DATA_FORMAT, ); } diff --git a/packages/web3-eth/test/unit/rpc_method_wrappers/get_proof.test.ts b/packages/web3-eth/test/unit/rpc_method_wrappers/get_proof.test.ts index 92edc6b8c9b..ab2d48f5c56 100644 --- a/packages/web3-eth/test/unit/rpc_method_wrappers/get_proof.test.ts +++ b/packages/web3-eth/test/unit/rpc_method_wrappers/get_proof.test.ts @@ -23,6 +23,7 @@ import { Web3EthExecutionAPI } from '../../../src/web3_eth_execution_api'; import { getProof } from '../../../src/rpc_method_wrappers'; import { mockRpcResponse, testData } from './fixtures/get_proof'; import { accountSchema } from '../../../src/schemas'; +import { STR_NUMBER_DATA_FORMAT } from '../../../src/constants'; jest.mock('../../../src/rpc_methods'); @@ -38,7 +39,7 @@ describe('getProof', () => { async (_, inputParameters) => { const [inputAddress, inputStorageKey, inputBlockNumber] = inputParameters; const inputStorageKeyFormatted = inputStorageKey.map(s => - format({ eth: 'bytes' }, s, DEFAULT_RETURN_FORMAT), + format({ eth: 'bytes' }, s, STR_NUMBER_DATA_FORMAT), ); let inputBlockNumberFormatted; @@ -49,7 +50,7 @@ describe('getProof', () => { inputBlockNumberFormatted = format( { eth: 'uint' }, inputBlockNumber, - DEFAULT_RETURN_FORMAT, + STR_NUMBER_DATA_FORMAT, ); } diff --git a/packages/web3-eth/test/unit/rpc_method_wrappers/get_storage_at.test.ts b/packages/web3-eth/test/unit/rpc_method_wrappers/get_storage_at.test.ts index ceb0a9ff4e4..13aafec3d93 100644 --- a/packages/web3-eth/test/unit/rpc_method_wrappers/get_storage_at.test.ts +++ b/packages/web3-eth/test/unit/rpc_method_wrappers/get_storage_at.test.ts @@ -15,7 +15,7 @@ You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see . */ import { Web3Context } from 'web3-core'; -import { DEFAULT_RETURN_FORMAT, FMT_BYTES, FMT_NUMBER, format } from 'web3-common'; +import { DEFAULT_RETURN_FORMAT, ETH_DATA_FORMAT, FMT_BYTES, FMT_NUMBER, format } from 'web3-common'; import { isNullish } from 'web3-validator'; import { getStorageAt as rpcMethodsGetStorageAt } from '../../../src/rpc_methods'; @@ -39,7 +39,7 @@ describe('getStorageAt', () => { const inputStorageSlotFormatted = format( { eth: 'uint' }, inputStorageSlot, - DEFAULT_RETURN_FORMAT, + ETH_DATA_FORMAT, ); let inputBlockNumberFormatted; @@ -50,7 +50,7 @@ describe('getStorageAt', () => { inputBlockNumberFormatted = format( { eth: 'uint' }, inputBlockNumber, - DEFAULT_RETURN_FORMAT, + ETH_DATA_FORMAT, ); } diff --git a/packages/web3-eth/test/unit/rpc_method_wrappers/get_transaction_count.test.ts b/packages/web3-eth/test/unit/rpc_method_wrappers/get_transaction_count.test.ts index 85d6f61c441..20749b99221 100644 --- a/packages/web3-eth/test/unit/rpc_method_wrappers/get_transaction_count.test.ts +++ b/packages/web3-eth/test/unit/rpc_method_wrappers/get_transaction_count.test.ts @@ -15,7 +15,7 @@ You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see . */ import { Web3Context } from 'web3-core'; -import { DEFAULT_RETURN_FORMAT, FMT_BYTES, FMT_NUMBER, format } from 'web3-common'; +import { DEFAULT_RETURN_FORMAT, ETH_DATA_FORMAT, FMT_BYTES, FMT_NUMBER, format } from 'web3-common'; import { isNullish } from 'web3-validator'; import { getTransactionCount as rpcMethodsGetTransactionCount } from '../../../src/rpc_methods'; @@ -45,7 +45,7 @@ describe('getTransactionCount', () => { inputBlockNumberFormatted = format( { eth: 'uint' }, inputBlockNumber, - DEFAULT_RETURN_FORMAT, + ETH_DATA_FORMAT, ); } diff --git a/packages/web3-eth/test/unit/rpc_method_wrappers/get_transaction_from_block.test.ts b/packages/web3-eth/test/unit/rpc_method_wrappers/get_transaction_from_block.test.ts index f1313f03713..75c0aef8991 100644 --- a/packages/web3-eth/test/unit/rpc_method_wrappers/get_transaction_from_block.test.ts +++ b/packages/web3-eth/test/unit/rpc_method_wrappers/get_transaction_from_block.test.ts @@ -15,7 +15,7 @@ You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see . */ import { Web3Context } from 'web3-core'; -import { DEFAULT_RETURN_FORMAT, FMT_BYTES, FMT_NUMBER, format } from 'web3-common'; +import { DEFAULT_RETURN_FORMAT, ETH_DATA_FORMAT, FMT_BYTES, FMT_NUMBER, format } from 'web3-common'; import { isBytes, isNullish } from 'web3-validator'; import { Bytes } from 'web3-utils'; @@ -45,17 +45,17 @@ describe('getTransactionFromBlock', () => { const inputTransactionIndexFormatted = format( { eth: 'uint' }, inputTransactionIndex, - DEFAULT_RETURN_FORMAT, + ETH_DATA_FORMAT, ); let inputBlockFormatted; if (inputBlockIsBytes) { - inputBlockFormatted = format({ eth: 'bytes32' }, inputBlock, DEFAULT_RETURN_FORMAT); + inputBlockFormatted = format({ eth: 'bytes32' }, inputBlock, ETH_DATA_FORMAT); } else if (isNullish(inputBlock)) { inputBlockFormatted = web3Context.defaultBlock; } else { - inputBlockFormatted = format({ eth: 'uint' }, inputBlock, DEFAULT_RETURN_FORMAT); + inputBlockFormatted = format({ eth: 'uint' }, inputBlock, ETH_DATA_FORMAT); } await getTransactionFromBlock(web3Context, ...inputParameters, DEFAULT_RETURN_FORMAT); diff --git a/packages/web3-eth/test/unit/rpc_method_wrappers/get_uncle.test.ts b/packages/web3-eth/test/unit/rpc_method_wrappers/get_uncle.test.ts index f6a92913d15..fa4f9dee060 100644 --- a/packages/web3-eth/test/unit/rpc_method_wrappers/get_uncle.test.ts +++ b/packages/web3-eth/test/unit/rpc_method_wrappers/get_uncle.test.ts @@ -15,7 +15,7 @@ You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see . */ import { Web3Context } from 'web3-core'; -import { DEFAULT_RETURN_FORMAT, FMT_BYTES, FMT_NUMBER, format } from 'web3-common'; +import { DEFAULT_RETURN_FORMAT, ETH_DATA_FORMAT, FMT_BYTES, FMT_NUMBER, format } from 'web3-common'; import { isBytes, isNullish } from 'web3-validator'; import { Bytes } from 'web3-utils'; @@ -45,17 +45,17 @@ describe('getUncle', () => { const inputUncleIndexFormatted = format( { eth: 'uint' }, inputUncleIndex, - DEFAULT_RETURN_FORMAT, + ETH_DATA_FORMAT, ); let inputBlockFormatted; if (inputBlockIsBytes) { - inputBlockFormatted = format({ eth: 'bytes32' }, inputBlock, DEFAULT_RETURN_FORMAT); + inputBlockFormatted = format({ eth: 'bytes32' }, inputBlock, ETH_DATA_FORMAT); } else if (isNullish(inputBlock)) { inputBlockFormatted = web3Context.defaultBlock; } else { - inputBlockFormatted = format({ eth: 'uint' }, inputBlock, DEFAULT_RETURN_FORMAT); + inputBlockFormatted = format({ eth: 'uint' }, inputBlock, ETH_DATA_FORMAT); } await getUncle(web3Context, ...inputParameters, DEFAULT_RETURN_FORMAT); diff --git a/packages/web3-eth/test/unit/rpc_method_wrappers/send_transaction.test.ts b/packages/web3-eth/test/unit/rpc_method_wrappers/send_transaction.test.ts index 27c1e53a39d..b34893a6602 100644 --- a/packages/web3-eth/test/unit/rpc_method_wrappers/send_transaction.test.ts +++ b/packages/web3-eth/test/unit/rpc_method_wrappers/send_transaction.test.ts @@ -15,7 +15,7 @@ You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see . */ import { Web3Context } from 'web3-core'; -import { DEFAULT_RETURN_FORMAT, format } from 'web3-common'; +import { DEFAULT_RETURN_FORMAT, ETH_DATA_FORMAT, format } from 'web3-common'; import { isNullish } from 'web3-validator'; import * as rpcMethods from '../../../src/rpc_methods'; @@ -31,7 +31,6 @@ import { testData, } from './fixtures/send_transaction'; import { receiptInfoSchema } from '../../../src/schemas'; -import { ETH_DATA_FORMAT } from '../../../src/constants'; jest.mock('../../../src/rpc_methods'); jest.mock('../../../src/utils/wait_for_transaction_receipt'); diff --git a/packages/web3-eth/test/unit/rpc_method_wrappers/sign_transaction.test.ts b/packages/web3-eth/test/unit/rpc_method_wrappers/sign_transaction.test.ts index 5977322e369..cf15c94ff5d 100644 --- a/packages/web3-eth/test/unit/rpc_method_wrappers/sign_transaction.test.ts +++ b/packages/web3-eth/test/unit/rpc_method_wrappers/sign_transaction.test.ts @@ -15,7 +15,7 @@ You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see . */ import { Web3Context } from 'web3-core'; -import { DEFAULT_RETURN_FORMAT, FMT_BYTES, FMT_NUMBER, format } from 'web3-common'; +import { DEFAULT_RETURN_FORMAT, ETH_DATA_FORMAT, FMT_BYTES, FMT_NUMBER, format } from 'web3-common'; import { signTransaction as rpcMethodsSignTransaction } from '../../../src/rpc_methods'; import { Web3EthExecutionAPI } from '../../../src/web3_eth_execution_api'; @@ -36,10 +36,7 @@ describe('signTransaction', () => { `should call rpcMethods.signTransaction with expected parameters\nTitle: %s\nInput parameters: %s\n`, async (_, inputParameters) => { const [inputTransaction] = inputParameters; - const inputTransactionFormatted = formatTransaction( - inputTransaction, - DEFAULT_RETURN_FORMAT, - ); + const inputTransactionFormatted = formatTransaction(inputTransaction, ETH_DATA_FORMAT); (rpcMethodsSignTransaction as jest.Mock).mockResolvedValueOnce(mockRpcResponse.raw); diff --git a/packages/web3-validator/src/validation/block.ts b/packages/web3-validator/src/validation/block.ts index 1d5206fb06a..6f273c6c9ca 100644 --- a/packages/web3-validator/src/validation/block.ts +++ b/packages/web3-validator/src/validation/block.ts @@ -16,10 +16,9 @@ along with web3.js. If not, see . */ import { BlockTags } from '../types'; -import { isHexStrict } from './string'; +import { isUInt } from './numbers'; -export const isBlockNumber = (value: string): boolean => - isHexStrict(value) && !value.startsWith('-'); +export const isBlockNumber = (value: string | number | bigint): boolean => isUInt(value); /** * Returns true if the given blockNumber is 'latest', 'pending', or 'earliest. @@ -34,5 +33,5 @@ export const isBlockTag = (value: string) => * * @param value */ -export const isBlockNumberOrTag = (value: string) => - (isHexStrict(value) && !value.startsWith('-')) || isBlockTag(value); +export const isBlockNumberOrTag = (value: string | number | bigint) => + isBlockTag(value as string) || isBlockNumber(value); From 3bfa8a5f8c0270ba60ddc54c7a28d4636feccb07 Mon Sep 17 00:00:00 2001 From: Nazar Hussain Date: Wed, 15 Jun 2022 13:30:40 +0200 Subject: [PATCH 14/26] :art: Add more test cases for the validator --- .../web3-validator/src/validation/numbers.ts | 4 +++ .../test/fixtures/validation.ts | 25 ++++++++++++++++--- .../test/unit/validation/block.test.ts | 4 +-- 3 files changed, 27 insertions(+), 6 deletions(-) diff --git a/packages/web3-validator/src/validation/numbers.ts b/packages/web3-validator/src/validation/numbers.ts index 10e474377e9..afcbd60e37e 100644 --- a/packages/web3-validator/src/validation/numbers.ts +++ b/packages/web3-validator/src/validation/numbers.ts @@ -36,6 +36,10 @@ export const isUInt = ( return false; } + if (typeof value === 'string' && value.length === 0) { + return false; + } + let size!: number; if (options?.abiType) { diff --git a/packages/web3-validator/test/fixtures/validation.ts b/packages/web3-validator/test/fixtures/validation.ts index c8a958f2330..403fc9b8be7 100644 --- a/packages/web3-validator/test/fixtures/validation.ts +++ b/packages/web3-validator/test/fixtures/validation.ts @@ -28,7 +28,7 @@ export const validUintData: any[] = [ // Using "null" value intentionally for validation // eslint-disable-next-line no-null/no-null -export const invalidUintData: any[] = ['-0x48', '-12', -1, true, undefined, null]; +export const invalidUintData: any[] = ['-0x48', '-12', -1, true, undefined, null, '']; export const validUintDataWithSize: [any, number][] = [ ['0x48', 8], @@ -36,10 +36,16 @@ export const validUintDataWithSize: [any, number][] = [ ['0x0dec0518fa672a70027b04c286582e543ab17319fbdd384fa7bc8f3d5a542c0b', 256], ['1', 16], [1, 8], + [0, 8], + ['0x0', 8], + ['0x1', 8], [BigInt(12), 64], ]; export const invalidUintDataWithSize: [any, number][] = [ + ['', 8], + [-1, 8], + ['-0x1233', 8], ['0x4812', 8], ['0x123ccdef', 16], ['0x0dec0518fa672a70027b04c286582e543ab17319fbdd384fa7bc8f3d5a542c0b', 8], @@ -310,10 +316,20 @@ export const validBlockNumberData: any[] = [ '0x2C941171bD2A7aEda7c2767c438DfF36EAaFdaFc', '0x1', '0xcd', + '1', + 0, + 12, + '0', + '0x0', + '0x12', ]; export const invalidBlockNumberData: any[] = [ - ...invalidHexStrictData, + '45a', + '', + BigInt(-255), + -42, + 4.2, '-0xcd', '-0x0dec0518fa672a70027b04c286582e543ab17319fbdd384fa7bc8f3d5a542c0b', ]; @@ -321,7 +337,8 @@ export const invalidBlockNumberData: any[] = [ export const validBlockTagData: string[] = ['latest', 'pending', 'earliest']; export const invalidBlockTagData: any[] = [ - ...invalidHexStrictData, + 'User', + '0xal', 'EARLIEST', 'LATEST', 'PENDING', @@ -402,7 +419,7 @@ export const validFilterObjectData: Filter[] = [ export const invalidFilterObjectData: any[] = [ { - fromBlock: 42, + fromBlock: '42a', }, { toBlock: -42, diff --git a/packages/web3-validator/test/unit/validation/block.test.ts b/packages/web3-validator/test/unit/validation/block.test.ts index b9e3c776692..d0007b3b3c3 100644 --- a/packages/web3-validator/test/unit/validation/block.test.ts +++ b/packages/web3-validator/test/unit/validation/block.test.ts @@ -54,13 +54,13 @@ describe('validation', () => { }); describe('isBlockNumberOrTag', () => { describe('valid cases', () => { - it.each([...validBlockTagData, ...validBlockNumberData])('%s', input => { + it.each([...validBlockTagData, ...validBlockNumberData])('%j', input => { expect(isBlockNumberOrTag(input)).toBeTruthy(); }); }); describe('invalid cases', () => { - it.each([...invalidBlockTagData, ...invalidBlockNumberData])('%s', input => { + it.each([...invalidBlockTagData, ...invalidBlockNumberData])('%o', input => { expect(isBlockNumberOrTag(input)).toBeFalsy(); }); }); From d080142a555597e217e3a671c9dbd6773b630a0d Mon Sep 17 00:00:00 2001 From: Nazar Hussain Date: Wed, 15 Jun 2022 14:26:14 +0200 Subject: [PATCH 15/26] :white_check_mark: Fix tests for eth-personal --- packages/web3-eth-personal/src/rpc_method_wrappers.ts | 6 +++--- .../web3-eth-personal/test/unit/eth_personal.test.ts | 11 +++-------- 2 files changed, 6 insertions(+), 11 deletions(-) diff --git a/packages/web3-eth-personal/src/rpc_method_wrappers.ts b/packages/web3-eth-personal/src/rpc_method_wrappers.ts index 3d8644c5f56..99697ac9230 100644 --- a/packages/web3-eth-personal/src/rpc_method_wrappers.ts +++ b/packages/web3-eth-personal/src/rpc_method_wrappers.ts @@ -15,7 +15,7 @@ You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see . */ -import { DEFAULT_RETURN_FORMAT } from 'web3-common'; +import { ETH_DATA_FORMAT } from 'web3-common'; import { formatTransaction, Transaction } from 'web3-eth'; import { Address, HexString, isHexStrict, toChecksumAddress, utf8ToHex } from 'web3-utils'; import { validator } from 'web3-validator'; @@ -78,7 +78,7 @@ export const sendTransaction = async ( tx: Transaction, passphrase: string, ) => { - const formattedTx = formatTransaction(tx, DEFAULT_RETURN_FORMAT); + const formattedTx = formatTransaction(tx, ETH_DATA_FORMAT); return rpcSendTransaction(requestManager, formattedTx, passphrase); }; @@ -88,7 +88,7 @@ export const signTransaction = async ( tx: Transaction, passphrase: string, ) => { - const formattedTx = formatTransaction(tx, DEFAULT_RETURN_FORMAT); + const formattedTx = formatTransaction(tx, ETH_DATA_FORMAT); return rpcSignTransaction(requestManager, formattedTx, passphrase); }; diff --git a/packages/web3-eth-personal/test/unit/eth_personal.test.ts b/packages/web3-eth-personal/test/unit/eth_personal.test.ts index 57cf608fa17..f9385d47d96 100644 --- a/packages/web3-eth-personal/test/unit/eth_personal.test.ts +++ b/packages/web3-eth-personal/test/unit/eth_personal.test.ts @@ -15,6 +15,7 @@ You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see . */ +import { ETH_DATA_FORMAT } from 'web3-common'; import * as utils from 'web3-utils'; import * as eth from 'web3-eth'; import { validator } from 'web3-validator'; @@ -185,10 +186,7 @@ describe('Personal', () => { await personal.sendTransaction(tx, 'password'); expect(eth.formatTransaction).toHaveBeenCalledTimes(1); - expect(eth.formatTransaction).toHaveBeenCalledWith(tx, { - bytes: 'BYTES_HEX', - number: 'NUMBER_BIGINT', - }); + expect(eth.formatTransaction).toHaveBeenCalledWith(tx, ETH_DATA_FORMAT); }); }); @@ -218,10 +216,7 @@ describe('Personal', () => { await personal.signTransaction(tx, 'password'); expect(eth.formatTransaction).toHaveBeenCalledTimes(1); - expect(eth.formatTransaction).toHaveBeenCalledWith(tx, { - bytes: 'BYTES_HEX', - number: 'NUMBER_BIGINT', - }); + expect(eth.formatTransaction).toHaveBeenCalledWith(tx, ETH_DATA_FORMAT); }); }); From baed875deaa87a4c564cdc8ee84efa675a35af78 Mon Sep 17 00:00:00 2001 From: Nazar Hussain Date: Wed, 15 Jun 2022 14:31:12 +0200 Subject: [PATCH 16/26] :white_check_mark: Fix contracts tests --- .../test/integration/contract_methods.test.ts | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/packages/web3-eth-contract/test/integration/contract_methods.test.ts b/packages/web3-eth-contract/test/integration/contract_methods.test.ts index d6e7c238b82..2669e548df2 100644 --- a/packages/web3-eth-contract/test/integration/contract_methods.test.ts +++ b/packages/web3-eth-contract/test/integration/contract_methods.test.ts @@ -65,7 +65,10 @@ describe('contract', () => { .send(sendOptions); expect(receipt).toEqual( - expect.objectContaining({ status: '0x1', transactionHash: expect.any(String) }), + expect.objectContaining({ + status: BigInt(1), + transactionHash: expect.any(String), + }), ); }); @@ -78,14 +81,20 @@ describe('contract', () => { }); expect(receipt).toEqual( - expect.objectContaining({ status: '0x1', transactionHash: expect.any(String) }), + expect.objectContaining({ + status: BigInt(1), + transactionHash: expect.any(String), + }), ); }); // TODO: Get and match the revert error message it('should returns errors on reverts', async () => { return expect(contract.methods.reverts().send(sendOptions)).rejects.toEqual( - expect.objectContaining({ status: '0x0', transactionHash: expect.any(String) }), + expect.objectContaining({ + status: BigInt(0), + transactionHash: expect.any(String), + }), ); }); }); From 8634f35b82f9ee1a87c8eefc6e9f2da538591d6d Mon Sep 17 00:00:00 2001 From: Nazar Hussain Date: Thu, 16 Jun 2022 09:42:24 +0200 Subject: [PATCH 17/26] :sparkles: Add optional provider support to web3 --- packages/web3-core/src/utils.ts | 2 +- packages/web3-core/src/web3_context.ts | 33 +++++++----- .../web3-core/src/web3_request_manager.ts | 30 ++++++----- .../src/web3_subscription_manager.ts | 4 +- packages/web3-eth-contract/src/contract.ts | 2 +- packages/web3-eth/src/web3_eth.ts | 53 ++++++++++++------- packages/web3/src/web3.ts | 2 +- .../web3/test/integration/main_web3.test.ts | 50 +++++++++++++++-- 8 files changed, 123 insertions(+), 53 deletions(-) diff --git a/packages/web3-core/src/utils.ts b/packages/web3-core/src/utils.ts index 324f32dc4c5..e63b6c981fb 100644 --- a/packages/web3-core/src/utils.ts +++ b/packages/web3-core/src/utils.ts @@ -41,7 +41,7 @@ export const isLegacySendAsyncProvider = ( export const isSupportedProvider = ( provider: SupportedProviders, -): boolean => +): provider is SupportedProviders => Web3BaseProvider.isWeb3Provider(provider) || isLegacyRequestProvider(provider) || isLegacySendAsyncProvider(provider) || diff --git a/packages/web3-core/src/web3_context.ts b/packages/web3-core/src/web3_context.ts index d23a4e9fa54..fc21438b708 100644 --- a/packages/web3-core/src/web3_context.ts +++ b/packages/web3-core/src/web3_context.ts @@ -21,7 +21,7 @@ import { Web3BaseWalletAccount, Web3AccountProvider, } from 'web3-common'; -import { HexString } from 'web3-utils'; +import { HexString, isNullish } from 'web3-utils'; import { SupportedProviders } from './types'; import { isSupportedProvider } from './utils'; // eslint-disable-next-line import/no-cycle @@ -41,7 +41,7 @@ export type Web3ContextObject< } = any, > = { config: Web3ConfigOptions; - provider: SupportedProviders; + provider?: SupportedProviders | string; requestManager: Web3RequestManager; subscriptionManager?: Web3SubscriptionManager | undefined; registeredSubscriptions?: RegisteredSubs; @@ -59,7 +59,7 @@ export type Web3ContextInitOptions< } = any, > = { config?: Partial; - provider: SupportedProviders | string; + provider?: SupportedProviders | string; requestManager?: Web3RequestManager; subscriptionManager?: Web3SubscriptionManager | undefined; registeredSubscriptions?: RegisteredSubs; @@ -99,17 +99,24 @@ export class Web3Context< public constructor( providerOrContext?: + | string | SupportedProviders - | Web3ContextInitOptions - | string, + | Web3ContextInitOptions, ) { super(); + + // If "providerOrContext" is provided as "string" or an objects matching "SupportedProviders" interface if ( - typeof providerOrContext === 'string' || + isNullish(providerOrContext) || + (typeof providerOrContext === 'string' && providerOrContext.trim() === '') || isSupportedProvider(providerOrContext as SupportedProviders) ) { this._requestManager = new Web3RequestManager( - providerOrContext as SupportedProviders, + providerOrContext as undefined | string | SupportedProviders, + ); + this._subscriptionManager = new Web3SubscriptionManager( + this._requestManager, + {} as RegisteredSubs, ); return; @@ -123,7 +130,7 @@ export class Web3Context< registeredSubscriptions, accountProvider, wallet, - } = providerOrContext as Partial>; + } = providerOrContext as Web3ContextInitOptions; this.setConfig(config ?? {}); @@ -229,19 +236,19 @@ export class Web3Context< }); } - public get provider(): SupportedProviders { + public get provider(): SupportedProviders | string | undefined { return this.requestManager.provider; } - public set provider(provider: SupportedProviders | string) { + public set provider(provider: SupportedProviders | string | undefined) { this.requestManager.setProvider(provider); } - public get currentProvider(): SupportedProviders { + public get currentProvider(): SupportedProviders | string | undefined { return this.requestManager.provider; } - public set currentProvider(provider: SupportedProviders | string) { + public set currentProvider(provider: SupportedProviders | string | undefined) { this.requestManager.setProvider(provider); } @@ -250,7 +257,7 @@ export class Web3Context< return Web3Context.givenProvider; } - public setProvider(provider: SupportedProviders) { + public setProvider(provider?: SupportedProviders | string) { this.provider = provider; } diff --git a/packages/web3-core/src/web3_request_manager.ts b/packages/web3-core/src/web3_request_manager.ts index fc0b356f000..7e702d4f523 100644 --- a/packages/web3-core/src/web3_request_manager.ts +++ b/packages/web3-core/src/web3_request_manager.ts @@ -31,7 +31,6 @@ import { Web3APIRequest, Web3APIReturnType, Web3APISpec, - Web3BaseProvider, Web3EventEmitter, } from 'web3-common'; import HttpProvider from 'web3-providers-http'; @@ -60,14 +59,14 @@ const availableProviders = { export class Web3RequestManager< API extends Web3APISpec = EthExecutionAPI, > extends Web3EventEmitter<{ - [key in Web3RequestManagerEvent]: SupportedProviders; + [key in Web3RequestManagerEvent]: SupportedProviders | undefined; }> { - private _provider!: SupportedProviders; + private _provider?: SupportedProviders; public constructor(provider?: SupportedProviders | string, net?: Socket) { super(); - if (provider) { + if (!isNullish(provider)) { this.setProvider(provider, net); } } @@ -77,10 +76,6 @@ export class Web3RequestManager< } public get provider() { - if (!this._provider) { - throw new ProviderError('Provider not available'); - } - return this._provider; } @@ -89,8 +84,8 @@ export class Web3RequestManager< return availableProviders; } - public setProvider(provider: SupportedProviders | string, net?: Socket) { - let newProvider!: Web3BaseProvider; + public setProvider(provider?: SupportedProviders | string, net?: Socket) { + let newProvider: SupportedProviders | undefined; // autodetect provider if (provider && typeof provider === 'string' && this.providers) { @@ -106,12 +101,17 @@ export class Web3RequestManager< } else if (typeof net === 'object' && typeof net.connect === 'function') { newProvider = new this.providers.IpcProvider(provider, net); } else { - throw new ProviderError(`Can't autodetect provider for "${provider}'"`); + throw new ProviderError(`Can't autodetect provider for "${provider}"`); } + } else if (isNullish(provider)) { + // In case want to unset the provider + newProvider = undefined; + } else { + newProvider = provider as SupportedProviders; } this.emit(Web3RequestManagerEvent.BEFORE_PROVIDER_CHANGE, this._provider); - this._provider = newProvider ?? provider; + this._provider = newProvider; this.emit(Web3RequestManagerEvent.PROVIDER_CHANGED, this._provider); } @@ -142,6 +142,12 @@ export class Web3RequestManager< ): Promise> { const { provider } = this; + if (isNullish(provider)) { + throw new ProviderError( + 'Provider not available. Use `.setProvider` or `.provider=` to initialize the provider.', + ); + } + const payload = jsonRpc.isBatchRequest(request) ? jsonRpc.toBatchPayload(request) : jsonRpc.toPayload(request); diff --git a/packages/web3-core/src/web3_subscription_manager.ts b/packages/web3-core/src/web3_subscription_manager.ts index f9751e98d88..b91e7b0326b 100644 --- a/packages/web3-core/src/web3_subscription_manager.ts +++ b/packages/web3-core/src/web3_subscription_manager.ts @@ -126,6 +126,8 @@ export class Web3SubscriptionManager< } public supportsSubscriptions(): boolean { - return isSupportSubscriptions(this.requestManager.provider); + return isNullish(this.requestManager.provider) + ? false + : isSupportSubscriptions(this.requestManager.provider); } } diff --git a/packages/web3-eth-contract/src/contract.ts b/packages/web3-eth-contract/src/contract.ts index f71265b158f..0f64bd784ba 100644 --- a/packages/web3-eth-contract/src/contract.ts +++ b/packages/web3-eth-contract/src/contract.ts @@ -175,7 +175,7 @@ export class Contract super({ ...context, // Pass an empty string to avoid type issue. Error will be thrown from underlying validation - provider: options?.provider ?? context?.provider ?? Contract.givenProvider ?? '', + provider: options?.provider ?? context?.provider ?? Contract.givenProvider, registeredSubscriptions: { logs: LogsSubscription, newHeads: NewHeadsSubscription, diff --git a/packages/web3-eth/src/web3_eth.ts b/packages/web3-eth/src/web3_eth.ts index 34043436fc7..e8bf98cd1ab 100644 --- a/packages/web3-eth/src/web3_eth.ts +++ b/packages/web3-eth/src/web3_eth.ts @@ -18,7 +18,12 @@ along with web3.js. If not, see . // Disabling because returnTypes must be last param to match 1.x params /* eslint-disable default-param-last */ import { DataFormat, DEFAULT_RETURN_FORMAT } from 'web3-common'; -import { SupportedProviders, Web3Context, Web3ContextInitOptions } from 'web3-core'; +import { + isSupportedProvider, + SupportedProviders, + Web3Context, + Web3ContextInitOptions, +} from 'web3-core'; import { Address, Bytes, @@ -55,26 +60,34 @@ type RegisteredSubscription = { export class Web3Eth extends Web3Context { public constructor( - // eslint-disable-next-line @typescript-eslint/no-explicit-any - providerOrContext: SupportedProviders | Web3ContextInitOptions | string, + providerOrContext?: SupportedProviders | Web3ContextInitOptions | string, ) { - super( - typeof providerOrContext === 'object' && - (providerOrContext as Web3ContextInitOptions).provider - ? providerOrContext - : { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - provider: providerOrContext as SupportedProviders, - registeredSubscriptions: { - logs: LogsSubscription, - newPendingTransactions: NewPendingTransactionsSubscription, - newHeads: NewHeadsSubscription, - syncing: SyncingSubscription, - pendingTransactions: NewPendingTransactionsSubscription, // the same as newPendingTransactions. just for support API like in version 1.x - newBlockHeaders: NewHeadsSubscription, // the same as newHeads. just for support API like in version 1.x - }, - }, - ); + if ( + typeof providerOrContext === 'string' || + isSupportedProvider(providerOrContext as SupportedProviders) + ) { + super(providerOrContext); + return; + } + + if (typeof providerOrContext === 'object') { + super(providerOrContext); + + return; + } + + super({ + // eslint-disable-next-line @typescript-eslint/no-explicit-any + provider: providerOrContext as unknown as SupportedProviders, + registeredSubscriptions: { + logs: LogsSubscription, + newPendingTransactions: NewPendingTransactionsSubscription, + newHeads: NewHeadsSubscription, + syncing: SyncingSubscription, + pendingTransactions: NewPendingTransactionsSubscription, // the same as newPendingTransactions. just for support API like in version 1.x + newBlockHeaders: NewHeadsSubscription, // the same as newHeads. just for support API like in version 1.x + }, + }); } public async getProtocolVersion() { return rpcMethods.getProtocolVersion(this.requestManager); diff --git a/packages/web3/src/web3.ts b/packages/web3/src/web3.ts index 4405091cf14..baeb6126fa8 100644 --- a/packages/web3/src/web3.ts +++ b/packages/web3/src/web3.ts @@ -93,7 +93,7 @@ export class Web3 extends Web3Context { }; }; - public constructor(provider: SupportedProviders | string) { + public constructor(provider?: SupportedProviders | string) { const accountProvider = { create, privateKeyToAccount, diff --git a/packages/web3/test/integration/main_web3.test.ts b/packages/web3/test/integration/main_web3.test.ts index ee4e8117587..2d70aede0d0 100644 --- a/packages/web3/test/integration/main_web3.test.ts +++ b/packages/web3/test/integration/main_web3.test.ts @@ -84,6 +84,16 @@ describe('Web3 instance', () => { } }); + it('should be able to create web3 object without provider', () => { + expect(() => new Web3()).not.toThrow(); + }); + + it('should throw error when we make a request when provider not available', async () => { + web3 = new Web3(); + + await expect(web3.eth.getChainId()).rejects.toThrow('Provider not available'); + }); + describeIf(getSystemTestProvider().startsWith('http'))( 'Create Web3 class instance with http string providers', () => { @@ -97,7 +107,7 @@ describe('Web3 instance', () => { ? process.env.INFURA_GOERLI_HTTP.toString().includes('http') : false, )('should create instance with string of external http provider', async () => { - web3 = new Web3(process.env.INFURA_GOERLI_HTTP!); + web3 = new Web3(process.env.INFURA_GOERLI_HTTP); // eslint-disable-next-line jest/no-standalone-expect expect(web3).toBeInstanceOf(Web3); }); @@ -132,14 +142,14 @@ describe('Web3 instance', () => { ? process.env.INFURA_GOERLI_WS.toString().includes('ws') : false, )('should create instance with string of external ws provider', async () => { - web3 = new Web3(process.env.INFURA_GOERLI_WS!); + web3 = new Web3(process.env.INFURA_GOERLI_WS); // eslint-disable-next-line jest/no-standalone-expect expect(web3).toBeInstanceOf(Web3); }); }, ); describe('Web3 providers', () => { - it('should set the provider', async () => { + it('should set the provider with `.provider=`', async () => { web3 = new Web3('http://dummy.com'); web3.provider = clientUrl; @@ -151,7 +161,7 @@ describe('Web3 instance', () => { expect(response).toMatch(/0[xX][0-9a-fA-F]+/); }); - it('setProvider', async () => { + it('should set the provider with `.setProvider`', async () => { let newProvider: Web3BaseProvider; web3 = new Web3('http://dummy.com'); if (clientUrl.startsWith('http')) { @@ -165,6 +175,38 @@ describe('Web3 instance', () => { expect(web3.provider).toBe(newProvider); }); + it('should set the provider with `.setProvider` of empty initialized object', async () => { + web3 = new Web3(); + + web3.setProvider(getSystemTestProvider()); + + await expect(web3.eth.getChainId()).resolves.toBeDefined(); + }); + + it('should set the provider with `.provider=` of empty initialized object', async () => { + web3 = new Web3(); + + web3.provider = getSystemTestProvider(); + + await expect(web3.eth.getChainId()).resolves.toBeDefined(); + }); + + it('should unset the provider with `.setProvider`', async () => { + web3 = new Web3(getSystemTestProvider()); + await expect(web3.eth.getChainId()).resolves.toBeDefined(); + + web3.setProvider(undefined); + await expect(web3.eth.getChainId()).rejects.toThrow('Provider not available'); + }); + + it('should unset the provider with `.provider=`', async () => { + web3 = new Web3(getSystemTestProvider()); + await expect(web3.eth.getChainId()).resolves.toBeDefined(); + + web3.provider = undefined; + await expect(web3.eth.getChainId()).rejects.toThrow('Provider not available'); + }); + it('providers', async () => { const res = Web3.providers; From d7a9d08b498d004eea4c81f9e02d3a2ae7535ed5 Mon Sep 17 00:00:00 2001 From: Nazar Hussain Date: Thu, 16 Jun 2022 09:42:24 +0200 Subject: [PATCH 18/26] :sparkles: Add optional provider support to web3 --- packages/web3-core/src/utils.ts | 2 +- packages/web3-core/src/web3_context.ts | 33 +++++++----- .../web3-core/src/web3_request_manager.ts | 30 ++++++----- .../src/web3_subscription_manager.ts | 4 +- packages/web3-eth-contract/src/contract.ts | 2 +- packages/web3-eth/src/web3_eth.ts | 53 ++++++++++++------- packages/web3/src/web3.ts | 2 +- .../web3/test/integration/main_web3.test.ts | 50 +++++++++++++++-- 8 files changed, 123 insertions(+), 53 deletions(-) diff --git a/packages/web3-core/src/utils.ts b/packages/web3-core/src/utils.ts index 324f32dc4c5..e63b6c981fb 100644 --- a/packages/web3-core/src/utils.ts +++ b/packages/web3-core/src/utils.ts @@ -41,7 +41,7 @@ export const isLegacySendAsyncProvider = ( export const isSupportedProvider = ( provider: SupportedProviders, -): boolean => +): provider is SupportedProviders => Web3BaseProvider.isWeb3Provider(provider) || isLegacyRequestProvider(provider) || isLegacySendAsyncProvider(provider) || diff --git a/packages/web3-core/src/web3_context.ts b/packages/web3-core/src/web3_context.ts index d23a4e9fa54..fc21438b708 100644 --- a/packages/web3-core/src/web3_context.ts +++ b/packages/web3-core/src/web3_context.ts @@ -21,7 +21,7 @@ import { Web3BaseWalletAccount, Web3AccountProvider, } from 'web3-common'; -import { HexString } from 'web3-utils'; +import { HexString, isNullish } from 'web3-utils'; import { SupportedProviders } from './types'; import { isSupportedProvider } from './utils'; // eslint-disable-next-line import/no-cycle @@ -41,7 +41,7 @@ export type Web3ContextObject< } = any, > = { config: Web3ConfigOptions; - provider: SupportedProviders; + provider?: SupportedProviders | string; requestManager: Web3RequestManager; subscriptionManager?: Web3SubscriptionManager | undefined; registeredSubscriptions?: RegisteredSubs; @@ -59,7 +59,7 @@ export type Web3ContextInitOptions< } = any, > = { config?: Partial; - provider: SupportedProviders | string; + provider?: SupportedProviders | string; requestManager?: Web3RequestManager; subscriptionManager?: Web3SubscriptionManager | undefined; registeredSubscriptions?: RegisteredSubs; @@ -99,17 +99,24 @@ export class Web3Context< public constructor( providerOrContext?: + | string | SupportedProviders - | Web3ContextInitOptions - | string, + | Web3ContextInitOptions, ) { super(); + + // If "providerOrContext" is provided as "string" or an objects matching "SupportedProviders" interface if ( - typeof providerOrContext === 'string' || + isNullish(providerOrContext) || + (typeof providerOrContext === 'string' && providerOrContext.trim() === '') || isSupportedProvider(providerOrContext as SupportedProviders) ) { this._requestManager = new Web3RequestManager( - providerOrContext as SupportedProviders, + providerOrContext as undefined | string | SupportedProviders, + ); + this._subscriptionManager = new Web3SubscriptionManager( + this._requestManager, + {} as RegisteredSubs, ); return; @@ -123,7 +130,7 @@ export class Web3Context< registeredSubscriptions, accountProvider, wallet, - } = providerOrContext as Partial>; + } = providerOrContext as Web3ContextInitOptions; this.setConfig(config ?? {}); @@ -229,19 +236,19 @@ export class Web3Context< }); } - public get provider(): SupportedProviders { + public get provider(): SupportedProviders | string | undefined { return this.requestManager.provider; } - public set provider(provider: SupportedProviders | string) { + public set provider(provider: SupportedProviders | string | undefined) { this.requestManager.setProvider(provider); } - public get currentProvider(): SupportedProviders { + public get currentProvider(): SupportedProviders | string | undefined { return this.requestManager.provider; } - public set currentProvider(provider: SupportedProviders | string) { + public set currentProvider(provider: SupportedProviders | string | undefined) { this.requestManager.setProvider(provider); } @@ -250,7 +257,7 @@ export class Web3Context< return Web3Context.givenProvider; } - public setProvider(provider: SupportedProviders) { + public setProvider(provider?: SupportedProviders | string) { this.provider = provider; } diff --git a/packages/web3-core/src/web3_request_manager.ts b/packages/web3-core/src/web3_request_manager.ts index fc0b356f000..7e702d4f523 100644 --- a/packages/web3-core/src/web3_request_manager.ts +++ b/packages/web3-core/src/web3_request_manager.ts @@ -31,7 +31,6 @@ import { Web3APIRequest, Web3APIReturnType, Web3APISpec, - Web3BaseProvider, Web3EventEmitter, } from 'web3-common'; import HttpProvider from 'web3-providers-http'; @@ -60,14 +59,14 @@ const availableProviders = { export class Web3RequestManager< API extends Web3APISpec = EthExecutionAPI, > extends Web3EventEmitter<{ - [key in Web3RequestManagerEvent]: SupportedProviders; + [key in Web3RequestManagerEvent]: SupportedProviders | undefined; }> { - private _provider!: SupportedProviders; + private _provider?: SupportedProviders; public constructor(provider?: SupportedProviders | string, net?: Socket) { super(); - if (provider) { + if (!isNullish(provider)) { this.setProvider(provider, net); } } @@ -77,10 +76,6 @@ export class Web3RequestManager< } public get provider() { - if (!this._provider) { - throw new ProviderError('Provider not available'); - } - return this._provider; } @@ -89,8 +84,8 @@ export class Web3RequestManager< return availableProviders; } - public setProvider(provider: SupportedProviders | string, net?: Socket) { - let newProvider!: Web3BaseProvider; + public setProvider(provider?: SupportedProviders | string, net?: Socket) { + let newProvider: SupportedProviders | undefined; // autodetect provider if (provider && typeof provider === 'string' && this.providers) { @@ -106,12 +101,17 @@ export class Web3RequestManager< } else if (typeof net === 'object' && typeof net.connect === 'function') { newProvider = new this.providers.IpcProvider(provider, net); } else { - throw new ProviderError(`Can't autodetect provider for "${provider}'"`); + throw new ProviderError(`Can't autodetect provider for "${provider}"`); } + } else if (isNullish(provider)) { + // In case want to unset the provider + newProvider = undefined; + } else { + newProvider = provider as SupportedProviders; } this.emit(Web3RequestManagerEvent.BEFORE_PROVIDER_CHANGE, this._provider); - this._provider = newProvider ?? provider; + this._provider = newProvider; this.emit(Web3RequestManagerEvent.PROVIDER_CHANGED, this._provider); } @@ -142,6 +142,12 @@ export class Web3RequestManager< ): Promise> { const { provider } = this; + if (isNullish(provider)) { + throw new ProviderError( + 'Provider not available. Use `.setProvider` or `.provider=` to initialize the provider.', + ); + } + const payload = jsonRpc.isBatchRequest(request) ? jsonRpc.toBatchPayload(request) : jsonRpc.toPayload(request); diff --git a/packages/web3-core/src/web3_subscription_manager.ts b/packages/web3-core/src/web3_subscription_manager.ts index f9751e98d88..b91e7b0326b 100644 --- a/packages/web3-core/src/web3_subscription_manager.ts +++ b/packages/web3-core/src/web3_subscription_manager.ts @@ -126,6 +126,8 @@ export class Web3SubscriptionManager< } public supportsSubscriptions(): boolean { - return isSupportSubscriptions(this.requestManager.provider); + return isNullish(this.requestManager.provider) + ? false + : isSupportSubscriptions(this.requestManager.provider); } } diff --git a/packages/web3-eth-contract/src/contract.ts b/packages/web3-eth-contract/src/contract.ts index 7caae679df9..cca34153531 100644 --- a/packages/web3-eth-contract/src/contract.ts +++ b/packages/web3-eth-contract/src/contract.ts @@ -175,7 +175,7 @@ export class Contract super({ ...context, // Pass an empty string to avoid type issue. Error will be thrown from underlying validation - provider: options?.provider ?? context?.provider ?? Contract.givenProvider ?? '', + provider: options?.provider ?? context?.provider ?? Contract.givenProvider, registeredSubscriptions: { logs: LogsSubscription, newHeads: NewHeadsSubscription, diff --git a/packages/web3-eth/src/web3_eth.ts b/packages/web3-eth/src/web3_eth.ts index 9310506c991..e8bf98cd1ab 100644 --- a/packages/web3-eth/src/web3_eth.ts +++ b/packages/web3-eth/src/web3_eth.ts @@ -18,7 +18,12 @@ along with web3.js. If not, see . // Disabling because returnTypes must be last param to match 1.x params /* eslint-disable default-param-last */ import { DataFormat, DEFAULT_RETURN_FORMAT } from 'web3-common'; -import { SupportedProviders, Web3Context, Web3ContextInitOptions } from 'web3-core'; +import { + isSupportedProvider, + SupportedProviders, + Web3Context, + Web3ContextInitOptions, +} from 'web3-core'; import { Address, Bytes, @@ -55,26 +60,34 @@ type RegisteredSubscription = { export class Web3Eth extends Web3Context { public constructor( - // eslint-disable-next-line @typescript-eslint/no-explicit-any - providerOrContext: SupportedProviders | Web3ContextInitOptions | string, + providerOrContext?: SupportedProviders | Web3ContextInitOptions | string, ) { - super( - typeof providerOrContext === 'object' && - (providerOrContext as Web3ContextInitOptions).provider - ? providerOrContext - : { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - provider: providerOrContext as SupportedProviders, - registeredSubscriptions: { - logs: LogsSubscription, - newPendingTransactions: NewPendingTransactionsSubscription, - newHeads: NewHeadsSubscription, - syncing: SyncingSubscription, - pendingTransactions: NewPendingTransactionsSubscription, // the same as newPendingTransactions. just for support API like in version 1.x - newBlockHeaders: NewHeadsSubscription, // the same as newHeads. just for support API like in version 1.x - }, - }, - ); + if ( + typeof providerOrContext === 'string' || + isSupportedProvider(providerOrContext as SupportedProviders) + ) { + super(providerOrContext); + return; + } + + if (typeof providerOrContext === 'object') { + super(providerOrContext); + + return; + } + + super({ + // eslint-disable-next-line @typescript-eslint/no-explicit-any + provider: providerOrContext as unknown as SupportedProviders, + registeredSubscriptions: { + logs: LogsSubscription, + newPendingTransactions: NewPendingTransactionsSubscription, + newHeads: NewHeadsSubscription, + syncing: SyncingSubscription, + pendingTransactions: NewPendingTransactionsSubscription, // the same as newPendingTransactions. just for support API like in version 1.x + newBlockHeaders: NewHeadsSubscription, // the same as newHeads. just for support API like in version 1.x + }, + }); } public async getProtocolVersion() { return rpcMethods.getProtocolVersion(this.requestManager); diff --git a/packages/web3/src/web3.ts b/packages/web3/src/web3.ts index 4405091cf14..baeb6126fa8 100644 --- a/packages/web3/src/web3.ts +++ b/packages/web3/src/web3.ts @@ -93,7 +93,7 @@ export class Web3 extends Web3Context { }; }; - public constructor(provider: SupportedProviders | string) { + public constructor(provider?: SupportedProviders | string) { const accountProvider = { create, privateKeyToAccount, diff --git a/packages/web3/test/integration/main_web3.test.ts b/packages/web3/test/integration/main_web3.test.ts index ee4e8117587..2d70aede0d0 100644 --- a/packages/web3/test/integration/main_web3.test.ts +++ b/packages/web3/test/integration/main_web3.test.ts @@ -84,6 +84,16 @@ describe('Web3 instance', () => { } }); + it('should be able to create web3 object without provider', () => { + expect(() => new Web3()).not.toThrow(); + }); + + it('should throw error when we make a request when provider not available', async () => { + web3 = new Web3(); + + await expect(web3.eth.getChainId()).rejects.toThrow('Provider not available'); + }); + describeIf(getSystemTestProvider().startsWith('http'))( 'Create Web3 class instance with http string providers', () => { @@ -97,7 +107,7 @@ describe('Web3 instance', () => { ? process.env.INFURA_GOERLI_HTTP.toString().includes('http') : false, )('should create instance with string of external http provider', async () => { - web3 = new Web3(process.env.INFURA_GOERLI_HTTP!); + web3 = new Web3(process.env.INFURA_GOERLI_HTTP); // eslint-disable-next-line jest/no-standalone-expect expect(web3).toBeInstanceOf(Web3); }); @@ -132,14 +142,14 @@ describe('Web3 instance', () => { ? process.env.INFURA_GOERLI_WS.toString().includes('ws') : false, )('should create instance with string of external ws provider', async () => { - web3 = new Web3(process.env.INFURA_GOERLI_WS!); + web3 = new Web3(process.env.INFURA_GOERLI_WS); // eslint-disable-next-line jest/no-standalone-expect expect(web3).toBeInstanceOf(Web3); }); }, ); describe('Web3 providers', () => { - it('should set the provider', async () => { + it('should set the provider with `.provider=`', async () => { web3 = new Web3('http://dummy.com'); web3.provider = clientUrl; @@ -151,7 +161,7 @@ describe('Web3 instance', () => { expect(response).toMatch(/0[xX][0-9a-fA-F]+/); }); - it('setProvider', async () => { + it('should set the provider with `.setProvider`', async () => { let newProvider: Web3BaseProvider; web3 = new Web3('http://dummy.com'); if (clientUrl.startsWith('http')) { @@ -165,6 +175,38 @@ describe('Web3 instance', () => { expect(web3.provider).toBe(newProvider); }); + it('should set the provider with `.setProvider` of empty initialized object', async () => { + web3 = new Web3(); + + web3.setProvider(getSystemTestProvider()); + + await expect(web3.eth.getChainId()).resolves.toBeDefined(); + }); + + it('should set the provider with `.provider=` of empty initialized object', async () => { + web3 = new Web3(); + + web3.provider = getSystemTestProvider(); + + await expect(web3.eth.getChainId()).resolves.toBeDefined(); + }); + + it('should unset the provider with `.setProvider`', async () => { + web3 = new Web3(getSystemTestProvider()); + await expect(web3.eth.getChainId()).resolves.toBeDefined(); + + web3.setProvider(undefined); + await expect(web3.eth.getChainId()).rejects.toThrow('Provider not available'); + }); + + it('should unset the provider with `.provider=`', async () => { + web3 = new Web3(getSystemTestProvider()); + await expect(web3.eth.getChainId()).resolves.toBeDefined(); + + web3.provider = undefined; + await expect(web3.eth.getChainId()).rejects.toThrow('Provider not available'); + }); + it('providers', async () => { const res = Web3.providers; From 6ea54d0ea815a3537c9809468320d629a347c21a Mon Sep 17 00:00:00 2001 From: Nazar Hussain Date: Tue, 21 Jun 2022 23:08:06 +0200 Subject: [PATCH 19/26] :art: Fix some merge issues --- packages/web3-common/src/web3_base_provider.ts | 2 -- packages/web3-eth-contract/src/types.ts | 2 +- 2 files changed, 1 insertion(+), 3 deletions(-) diff --git a/packages/web3-common/src/web3_base_provider.ts b/packages/web3-common/src/web3_base_provider.ts index 37a7e13a05d..1663115ccf6 100644 --- a/packages/web3-common/src/web3_base_provider.ts +++ b/packages/web3-common/src/web3_base_provider.ts @@ -54,7 +54,6 @@ export abstract class Web3BaseProvider | string; + readonly provider?: SupportedProviders | string; } export type TransactionReceipt = ReceiptInfo; From 4e35a8a7b3872594a753791c2d4116d095528c72 Mon Sep 17 00:00:00 2001 From: Nazar Hussain Date: Tue, 21 Jun 2022 23:18:35 +0200 Subject: [PATCH 20/26] :white_check_mark: Update unit tests for web3-core --- .../test/unit/__snapshots__/web3_context.test.ts.snap | 9 +-------- .../web3-core/test/unit/web3_request_manager.test.ts | 2 +- 2 files changed, 2 insertions(+), 9 deletions(-) diff --git a/packages/web3-core/test/unit/__snapshots__/web3_context.test.ts.snap b/packages/web3-core/test/unit/__snapshots__/web3_context.test.ts.snap index a492c52aeb1..0459563b9ce 100644 --- a/packages/web3-core/test/unit/__snapshots__/web3_context.test.ts.snap +++ b/packages/web3-core/test/unit/__snapshots__/web3_context.test.ts.snap @@ -24,10 +24,7 @@ Object { "transactionReceiptPollingInterval": undefined, "transactionTypeParser": undefined, }, - "provider": HttpProvider { - "clientUrl": "http://test/abc", - "httpProviderOptions": undefined, - }, + "provider": undefined, "providers": Object { "HttpProvider": [Function], "IpcProvider": [Function], @@ -41,10 +38,6 @@ Object { "_maxListeners": undefined, Symbol(kCapture): false, }, - "_provider": HttpProvider { - "clientUrl": "http://test/abc", - "httpProviderOptions": undefined, - }, }, "subscriptionManager": undefined, "wallet": undefined, diff --git a/packages/web3-core/test/unit/web3_request_manager.test.ts b/packages/web3-core/test/unit/web3_request_manager.test.ts index 3823d1b8cb0..15f2cdc59e5 100644 --- a/packages/web3-core/test/unit/web3_request_manager.test.ts +++ b/packages/web3-core/test/unit/web3_request_manager.test.ts @@ -233,7 +233,7 @@ describe('Web3RequestManager', () => { const manager = new Web3RequestManager(); expect(() => manager.setProvider(providerString)).toThrow( - `Can't autodetect provider for "pc://mydomain.com'"`, + `Can't autodetect provider for "pc://mydomain.com"`, ); }); }); From f72587ce11643253c35ffa5c13c6f4e898ff07a5 Mon Sep 17 00:00:00 2001 From: Nazar Hussain Date: Tue, 21 Jun 2022 23:23:22 +0200 Subject: [PATCH 21/26] :art: Add more integration tests for web3 --- packages/web3/src/web3.ts | 7 ++++--- packages/web3/test/integration/main_web3.test.ts | 13 +++++++++++-- 2 files changed, 15 insertions(+), 5 deletions(-) diff --git a/packages/web3/src/web3.ts b/packages/web3/src/web3.ts index baeb6126fa8..3385657731d 100644 --- a/packages/web3/src/web3.ts +++ b/packages/web3/src/web3.ts @@ -61,10 +61,11 @@ export class Web3 extends Web3Context { Personal, }; + public utils: typeof utils; + public eth: Web3Eth & { Iban: typeof Iban; ens: ENS; - utils: typeof utils; net: Net; personal: Personal; Contract: typeof Contract & { @@ -108,6 +109,8 @@ export class Web3 extends Web3Context { super({ provider, wallet, accountProvider }); + this.utils = utils; + // Have to use local alias to initiate contract context // eslint-disable-next-line @typescript-eslint/no-this-alias const self = this; @@ -146,8 +149,6 @@ export class Web3 extends Web3Context { net: self.use(Net), personal: self.use(Personal), - utils, - // Contract helper and module Contract: ContractBuilder, diff --git a/packages/web3/test/integration/main_web3.test.ts b/packages/web3/test/integration/main_web3.test.ts index 65b7eaed777..13d2e2a748c 100644 --- a/packages/web3/test/integration/main_web3.test.ts +++ b/packages/web3/test/integration/main_web3.test.ts @@ -75,12 +75,15 @@ describe('Web3 instance', () => { if (getSystemTestProvider().startsWith('ws')) { // make sure we try to close the connection after it is established if ( - web3.provider && + web3?.provider && (web3.provider as unknown as Web3BaseProvider).getStatus() === 'connecting' ) { await waitForOpenConnection(web3, currentAttempt); } - (web3.provider as unknown as Web3BaseProvider).disconnect(1000, ''); + + if (web3?.provider) { + (web3.provider as unknown as Web3BaseProvider).disconnect(1000, ''); + } } }); @@ -88,6 +91,12 @@ describe('Web3 instance', () => { expect(() => new Web3()).not.toThrow(); }); + it('should be able use functionality with web3 object not dependant on provider', () => { + web3 = new Web3(); + + expect(web3.utils.hexToNumber('0x5')).toBe(5); + }); + it('should throw error when we make a request when provider not available', async () => { web3 = new Web3(); From c0b14a398156545faa5ef293beab5a5b1f5b4b2b Mon Sep 17 00:00:00 2001 From: Nazar Hussain Date: Tue, 21 Jun 2022 23:36:23 +0200 Subject: [PATCH 22/26] :coffin: Fix dead code caused by merge --- .../web3-eth/test/unit/rpc_method_wrappers/estimate_gas.test.ts | 1 - .../web3-eth/test/unit/rpc_method_wrappers/get_proof.test.ts | 1 - 2 files changed, 2 deletions(-) diff --git a/packages/web3-eth/test/unit/rpc_method_wrappers/estimate_gas.test.ts b/packages/web3-eth/test/unit/rpc_method_wrappers/estimate_gas.test.ts index 83d492c529a..b6b4e20b6c1 100644 --- a/packages/web3-eth/test/unit/rpc_method_wrappers/estimate_gas.test.ts +++ b/packages/web3-eth/test/unit/rpc_method_wrappers/estimate_gas.test.ts @@ -23,7 +23,6 @@ import { Web3EthExecutionAPI } from '../../../src/web3_eth_execution_api'; import { estimateGas } from '../../../src/rpc_method_wrappers'; import { mockRpcResponse, testData } from './fixtures/estimate_gas'; import { formatTransaction } from '../../../src'; -import { STR_NUMBER_DATA_FORMAT } from '../../../src/constants'; jest.mock('../../../src/rpc_methods'); diff --git a/packages/web3-eth/test/unit/rpc_method_wrappers/get_proof.test.ts b/packages/web3-eth/test/unit/rpc_method_wrappers/get_proof.test.ts index eb7a48f85c5..70b6a8af15d 100644 --- a/packages/web3-eth/test/unit/rpc_method_wrappers/get_proof.test.ts +++ b/packages/web3-eth/test/unit/rpc_method_wrappers/get_proof.test.ts @@ -23,7 +23,6 @@ import { Web3EthExecutionAPI } from '../../../src/web3_eth_execution_api'; import { getProof } from '../../../src/rpc_method_wrappers'; import { mockRpcResponse, testData } from './fixtures/get_proof'; import { accountSchema } from '../../../src/schemas'; -import { STR_NUMBER_DATA_FORMAT } from '../../../src/constants'; jest.mock('../../../src/rpc_methods'); From 8379c187ae513a3a2c831408edee8f8cc72e780b Mon Sep 17 00:00:00 2001 From: Nazar Hussain Date: Wed, 22 Jun 2022 00:21:45 +0200 Subject: [PATCH 23/26] :bug: Update a provider init logic --- packages/web3-core/src/web3_context.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/web3-core/src/web3_context.ts b/packages/web3-core/src/web3_context.ts index fc21438b708..e52855b7d9d 100644 --- a/packages/web3-core/src/web3_context.ts +++ b/packages/web3-core/src/web3_context.ts @@ -108,7 +108,7 @@ export class Web3Context< // If "providerOrContext" is provided as "string" or an objects matching "SupportedProviders" interface if ( isNullish(providerOrContext) || - (typeof providerOrContext === 'string' && providerOrContext.trim() === '') || + (typeof providerOrContext === 'string' && providerOrContext.trim() !== '') || isSupportedProvider(providerOrContext as SupportedProviders) ) { this._requestManager = new Web3RequestManager( From ae0ef3d0df788ef28f541375629e002d58412760 Mon Sep 17 00:00:00 2001 From: Nazar Hussain Date: Wed, 22 Jun 2022 00:31:50 +0200 Subject: [PATCH 24/26] :art: Update test snapshots --- .../__snapshots__/web3_context.test.ts.snap | 38 ++++++++++++++++--- 1 file changed, 33 insertions(+), 5 deletions(-) diff --git a/packages/web3-core/test/unit/__snapshots__/web3_context.test.ts.snap b/packages/web3-core/test/unit/__snapshots__/web3_context.test.ts.snap index 0459563b9ce..01bf48da89a 100644 --- a/packages/web3-core/test/unit/__snapshots__/web3_context.test.ts.snap +++ b/packages/web3-core/test/unit/__snapshots__/web3_context.test.ts.snap @@ -24,22 +24,50 @@ Object { "transactionReceiptPollingInterval": undefined, "transactionTypeParser": undefined, }, - "provider": undefined, + "provider": HttpProvider { + "clientUrl": "http://test/abc", + "httpProviderOptions": undefined, + }, "providers": Object { "HttpProvider": [Function], "IpcProvider": [Function], "WebsocketProvider": [Function], }, - "registeredSubscriptions": undefined, + "registeredSubscriptions": Object {}, "requestManager": Web3RequestManager { "_emitter": EventEmitter { - "_events": Object {}, - "_eventsCount": 0, + "_events": Object { + "BEFORE_PROVIDER_CHANGE": [Function], + "PROVIDER_CHANGED": [Function], + }, + "_eventsCount": 2, "_maxListeners": undefined, Symbol(kCapture): false, }, + "_provider": HttpProvider { + "clientUrl": "http://test/abc", + "httpProviderOptions": undefined, + }, + }, + "subscriptionManager": Web3SubscriptionManager { + "_subscriptions": Map {}, + "registeredSubscriptions": Object {}, + "requestManager": Web3RequestManager { + "_emitter": EventEmitter { + "_events": Object { + "BEFORE_PROVIDER_CHANGE": [Function], + "PROVIDER_CHANGED": [Function], + }, + "_eventsCount": 2, + "_maxListeners": undefined, + Symbol(kCapture): false, + }, + "_provider": HttpProvider { + "clientUrl": "http://test/abc", + "httpProviderOptions": undefined, + }, + }, }, - "subscriptionManager": undefined, "wallet": undefined, } `; From 8832f3ee3cc366291d3a2c68a1ed69b51dc9ea9b Mon Sep 17 00:00:00 2001 From: Nazar Hussain Date: Wed, 22 Jun 2022 12:52:45 +0200 Subject: [PATCH 25/26] :art: Update the eth constructor logic to inject subscriptions --- packages/web3-eth/src/web3_eth.ts | 34 +++++++++++++++++-------------- 1 file changed, 19 insertions(+), 15 deletions(-) diff --git a/packages/web3-eth/src/web3_eth.ts b/packages/web3-eth/src/web3_eth.ts index 3982a254f51..0bb59953c82 100644 --- a/packages/web3-eth/src/web3_eth.ts +++ b/packages/web3-eth/src/web3_eth.ts @@ -58,6 +58,15 @@ type RegisteredSubscription = { syncing: typeof SyncingSubscription; }; +const registeredSubscriptions = { + logs: LogsSubscription, + newPendingTransactions: NewPendingTransactionsSubscription, + newHeads: NewHeadsSubscription, + syncing: SyncingSubscription, + pendingTransactions: NewPendingTransactionsSubscription, // the same as newPendingTransactions. just for support API like in version 1.x + newBlockHeaders: NewHeadsSubscription, // the same as newHeads. just for support API like in version 1.x +}; + export class Web3Eth extends Web3Context { public constructor( providerOrContext?: SupportedProviders | Web3ContextInitOptions | string, @@ -66,29 +75,24 @@ export class Web3Eth extends Web3Context) ) { - super(providerOrContext); + super({ + provider: providerOrContext as SupportedProviders, + registeredSubscriptions, + }); + return; } - if (typeof providerOrContext === 'object') { - super(providerOrContext); - + if ((providerOrContext as Web3ContextInitOptions).registeredSubscriptions) { + super(providerOrContext as Web3ContextInitOptions); return; } super({ - // eslint-disable-next-line @typescript-eslint/no-explicit-any - provider: providerOrContext as unknown as SupportedProviders, - registeredSubscriptions: { - logs: LogsSubscription, - newPendingTransactions: NewPendingTransactionsSubscription, - newHeads: NewHeadsSubscription, - syncing: SyncingSubscription, - pendingTransactions: NewPendingTransactionsSubscription, // the same as newPendingTransactions. just for support API like in version 1.x - newBlockHeaders: NewHeadsSubscription, // the same as newHeads. just for support API like in version 1.x - }, + ...(providerOrContext as Web3ContextInitOptions), + registeredSubscriptions, }); - } + } public async getProtocolVersion() { return rpcMethods.getProtocolVersion(this.requestManager); } From fa8e0a0696a59cb34357acf6427a301dfa3d378f Mon Sep 17 00:00:00 2001 From: Nazar Hussain Date: Wed, 22 Jun 2022 13:47:01 +0200 Subject: [PATCH 26/26] :white_check_mark: Add more tests for web3 instance --- packages/web3/test/integration/main_web3.test.ts | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/packages/web3/test/integration/main_web3.test.ts b/packages/web3/test/integration/main_web3.test.ts index 13d2e2a748c..9d44aa7aed6 100644 --- a/packages/web3/test/integration/main_web3.test.ts +++ b/packages/web3/test/integration/main_web3.test.ts @@ -91,12 +91,23 @@ describe('Web3 instance', () => { expect(() => new Web3()).not.toThrow(); }); - it('should be able use functionality with web3 object not dependant on provider', () => { + it('should be able use "utils" without provider', () => { web3 = new Web3(); expect(web3.utils.hexToNumber('0x5')).toBe(5); }); + it('should be able use "abi" without provider', () => { + web3 = new Web3(); + const validData = validEncodeParametersData[0]; + + const encodedParameters = web3.eth.abi.encodeParameters( + validData.input[0], + validData.input[1], + ); + expect(encodedParameters).toEqual(validData.output); + }); + it('should throw error when we make a request when provider not available', async () => { web3 = new Web3();