From 90d1eb86a9ee102fd3a364e107a083f6f0cbc8ff Mon Sep 17 00:00:00 2001 From: Oleksii Kosynskyi Date: Thu, 28 Mar 2024 13:59:57 +0100 Subject: [PATCH 01/21] add default return format --- packages/web3-core/src/web3_config.ts | 20 +- .../__snapshots__/web3_context.test.ts.snap | 4 + .../web3-core/test/unit/web3_config.test.ts | 2 + .../web3-eth-accounts/test/config/setup.js | 2 +- packages/web3-eth-contract/src/contract.ts | 71 +++++-- packages/web3-eth-ens/src/ens.ts | 51 ++--- packages/web3-eth/src/rpc_method_wrappers.ts | 188 ++++++++++++++---- .../web3-eth/src/utils/get_revert_reason.ts | 10 +- .../web3-eth/src/utils/transaction_builder.ts | 7 +- packages/web3-eth/src/web3_eth.ts | 88 ++++++-- packages/web3-net/src/net.ts | 42 ++-- packages/web3-types/src/data_format_types.ts | 5 +- packages/web3-utils/src/formatter.ts | 11 +- packages/web3/src/web3.ts | 47 +++-- 14 files changed, 390 insertions(+), 158 deletions(-) diff --git a/packages/web3-core/src/web3_config.ts b/packages/web3-core/src/web3_config.ts index 772653cfdeb..d28eacc6bab 100644 --- a/packages/web3-core/src/web3_config.ts +++ b/packages/web3-core/src/web3_config.ts @@ -15,7 +15,14 @@ You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see . */ -import { Numbers, HexString, BlockNumberOrTag, Common } from 'web3-types'; +import { + Numbers, + HexString, + BlockNumberOrTag, + Common, + DEFAULT_RETURN_FORMAT, + DataFormat, +} from 'web3-types'; import { ConfigHardforkMismatchError, ConfigChainMismatchError } from 'web3-errors'; import { isNullish, toHex } from 'web3-utils'; import { TransactionTypeParser } from './types.js'; @@ -52,6 +59,7 @@ export interface Web3ConfigOptions { }; transactionBuilder?: TransactionBuilder; transactionTypeParser?: TransactionTypeParser; + defaultReturnFormat?: DataFormat; } type ConfigEvent = P extends unknown @@ -93,6 +101,7 @@ export abstract class Web3Config }, transactionBuilder: undefined, transactionTypeParser: undefined, + defaultReturnFormat: DEFAULT_RETURN_FORMAT, }; public constructor(options?: Partial) { @@ -348,6 +357,15 @@ export abstract class Web3Config this.config.maxListenersWarningThreshold = val; } + public get defaultReturnFormat() { + return this.config.defaultReturnFormat; + } + public set defaultReturnFormat(val) { + this._triggerConfigChange('defaultReturnFormat', val); + + this.config.defaultReturnFormat = val; + } + public get defaultNetworkId() { return this.config.defaultNetworkId; } 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 7e9121c85d2..e01ba14a467 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 @@ -13,6 +13,10 @@ exports[`Web3Context getContextObject should return correct context object 1`] = "defaultHardfork": "london", "defaultMaxPriorityFeePerGas": "0x9502f900", "defaultNetworkId": undefined, + "defaultReturnFormat": { + "bytes": "BYTES_HEX", + "number": "NUMBER_BIGINT", + }, "defaultTransactionType": "0x2", "enableExperimentalFeatures": { "useRpcCallSpecification": false, diff --git a/packages/web3-core/test/unit/web3_config.test.ts b/packages/web3-core/test/unit/web3_config.test.ts index 32a5fc17ddc..0391eec851a 100644 --- a/packages/web3-core/test/unit/web3_config.test.ts +++ b/packages/web3-core/test/unit/web3_config.test.ts @@ -16,6 +16,7 @@ along with web3.js. If not, see . */ import { toHex } from 'web3-utils'; +import { DEFAULT_RETURN_FORMAT } from 'web3-types'; import { Web3Config, Web3ConfigEvent } from '../../src/web3_config'; class MyConfigObject extends Web3Config {} @@ -44,6 +45,7 @@ const defaultConfig = { transactionConfirmationPollingInterval: undefined, defaultTransactionType: '0x2', defaultMaxPriorityFeePerGas: toHex(2500000000), + defaultReturnFormat: DEFAULT_RETURN_FORMAT, }; const setValue = { string: 'newValue', diff --git a/packages/web3-eth-accounts/test/config/setup.js b/packages/web3-eth-accounts/test/config/setup.js index b3c35155474..36be82ea918 100644 --- a/packages/web3-eth-accounts/test/config/setup.js +++ b/packages/web3-eth-accounts/test/config/setup.js @@ -23,6 +23,6 @@ require('jest-extended'); process.env.NODE_ENV = 'test'; -const jestTimeout = 10000; +const jestTimeout = 15000; jest.setTimeout(jestTimeout); diff --git a/packages/web3-eth-contract/src/contract.ts b/packages/web3-eth-contract/src/contract.ts index 54b7e4e792d..77756224993 100644 --- a/packages/web3-eth-contract/src/contract.ts +++ b/packages/web3-eth-contract/src/contract.ts @@ -157,13 +157,13 @@ export type ContractMethodsInterface = { } & { [key: string]: ContractBoundMethod }; export type ContractMethodSend = Web3PromiEvent< - FormatType, - SendTransactionEvents + FormatType, + SendTransactionEvents >; export type ContractDeploySend = Web3PromiEvent< // eslint-disable-next-line no-use-before-define Contract, - SendTransactionEvents + SendTransactionEvents >; /** @@ -526,7 +526,7 @@ export class Contract ? contextOrReturnFormat : isDataFormat(optionsOrContextOrReturnFormat) ? optionsOrContextOrReturnFormat - : returnFormat ?? DEFAULT_RETURN_FORMAT; + : returnFormat ?? this.defaultReturnFormat ?? DEFAULT_RETURN_FORMAT; const address = typeof addressOrOptionsOrContext === 'string' ? addressOrOptionsOrContext : undefined; this.config.contractDataInputFill = @@ -799,7 +799,8 @@ export class Contract }, estimateGas: async ( options?: PayableCallOptions, - returnFormat: ReturnFormat = DEFAULT_RETURN_FORMAT as ReturnFormat, + returnFormat: ReturnFormat = (this.defaultReturnFormat ?? + DEFAULT_RETURN_FORMAT) as ReturnFormat, ) => { const modifiedOptions = { ...options }; return this._contractMethodEstimateGas({ @@ -814,7 +815,11 @@ export class Contract encodeMethodABI( abi as AbiFunctionFragment, args as unknown[], - format({ format: 'bytes' }, deployData as Bytes, DEFAULT_RETURN_FORMAT), + format( + { format: 'bytes' }, + deployData as Bytes, + this.defaultReturnFormat as typeof DEFAULT_RETURN_FORMAT, + ), ), }; } @@ -898,7 +903,7 @@ export class Contract ? param1 : isDataFormat(param2) ? param2 - : param3 ?? DEFAULT_RETURN_FORMAT; + : param3 ?? (this.defaultReturnFormat as DataFormat); const abi = eventName === 'allEvents' || eventName === ALL_EVENTS @@ -959,7 +964,10 @@ export class Contract return decodedLogs; } - private _parseAndSetAddress(value?: Address, returnFormat: DataFormat = DEFAULT_RETURN_FORMAT) { + private _parseAndSetAddress( + value?: Address, + returnFormat: DataFormat = this.defaultReturnFormat ?? DEFAULT_RETURN_FORMAT, + ) { this._address = value ? toChecksumAddress(format({ format: 'address' }, value, returnFormat)) : value; @@ -967,7 +975,7 @@ export class Contract private _parseAndSetJsonInterface( abis: ContractAbi, - returnFormat: DataFormat = DEFAULT_RETURN_FORMAT, + returnFormat: DataFormat = this.defaultReturnFormat ?? DEFAULT_RETURN_FORMAT, ) { this._functions = {}; this._methods = {} as ContractMethodsInterface; @@ -1119,7 +1127,8 @@ export class Contract estimateGas: async ( options?: PayableCallOptions | NonPayableCallOptions, - returnFormat: ReturnFormat = DEFAULT_RETURN_FORMAT as ReturnFormat, + returnFormat: ReturnFormat = (this.defaultReturnFormat ?? + DEFAULT_RETURN_FORMAT) as unknown as ReturnFormat, ) => this._contractMethodEstimateGas({ abi: methodAbi, @@ -1176,7 +1185,12 @@ export class Contract }, }); try { - const result = await call(this, tx, block, DEFAULT_RETURN_FORMAT); + const result = await call( + this, + tx, + block, + (this.defaultReturnFormat ?? DEFAULT_RETURN_FORMAT) as typeof DEFAULT_RETURN_FORMAT, + ); return decodeMethodReturn(abi, result); } catch (error: unknown) { if (error instanceof ContractExecutionError) { @@ -1207,7 +1221,12 @@ export class Contract }); try { - return createAccessList(this, tx, block, DEFAULT_RETURN_FORMAT); + return createAccessList( + this, + tx, + block, + this.defaultReturnFormat ?? DEFAULT_RETURN_FORMAT, + ); } catch (error: unknown) { if (error instanceof ContractExecutionError) { // this will parse the error data by trying to decode the ABI error inputs according to EIP-838 @@ -1237,11 +1256,16 @@ export class Contract contractOptions: modifiedContractOptions, }); - const transactionToSend = sendTransaction(this, tx, DEFAULT_RETURN_FORMAT, { - // TODO Should make this configurable by the user - checkRevertBeforeSending: false, - contractAbi: this._jsonInterface, - }); + const transactionToSend = sendTransaction( + this, + tx, + this.defaultReturnFormat ?? DEFAULT_RETURN_FORMAT, + { + // TODO Should make this configurable by the user + checkRevertBeforeSending: false, + contractAbi: this._jsonInterface, + }, + ); // eslint-disable-next-line no-void void transactionToSend.on('error', (error: unknown) => { @@ -1267,10 +1291,10 @@ export class Contract const tx = getSendTxParams({ abi, params, - options: { ...options, dataInputFill: this.config.contractDataInputFill }, + options: { ...options, dataInputFill: this.contractDataInputFill }, contractOptions: modifiedContractOptions, }); - return sendTransaction(this, tx, DEFAULT_RETURN_FORMAT, { + return sendTransaction(this, tx, this.defaultReturnFormat ?? DEFAULT_RETURN_FORMAT, { transactionResolver: receipt => { if (receipt.status === BigInt(0)) { throw new Web3ContractError("code couldn't be stored", receipt); @@ -1310,13 +1334,18 @@ export class Contract options: { ...options, dataInputFill: this.config.contractDataInputFill }, contractOptions: contractOptions ?? this.options, }); - return estimateGas(this, tx, BlockTags.LATEST, returnFormat); + return estimateGas( + this, + tx, + BlockTags.LATEST, + returnFormat ?? this.defaultReturnFormat ?? DEFAULT_RETURN_FORMAT, + ); } // eslint-disable-next-line class-methods-use-this private _createContractEvent( abi: AbiEventFragment & { signature: HexString }, - returnFormat: DataFormat = DEFAULT_RETURN_FORMAT, + returnFormat: DataFormat = this.defaultReturnFormat ?? DEFAULT_RETURN_FORMAT, ): ContractBoundEvent { return (...params: unknown[]) => { const { topics, fromBlock } = encodeEventABI( diff --git a/packages/web3-eth-ens/src/ens.ts b/packages/web3-eth-ens/src/ens.ts index 88d6ae58c83..8729ee83018 100644 --- a/packages/web3-eth-ens/src/ens.ts +++ b/packages/web3-eth-ens/src/ens.ts @@ -16,7 +16,11 @@ along with web3.js. If not, see . */ import { Web3Context, Web3ContextObject } from 'web3-core'; -import { ENSNetworkNotSyncedError, ENSUnsupportedNetworkError, RevertInstructionError } from 'web3-errors'; +import { + ENSNetworkNotSyncedError, + ENSUnsupportedNetworkError, + RevertInstructionError, +} from 'web3-errors'; import { isSyncing } from 'web3-eth'; import { Contract } from 'web3-eth-contract'; import { getId } from 'web3-net'; @@ -37,25 +41,25 @@ import { Resolver } from './resolver.js'; /** * This class is designed to interact with the ENS system on the Ethereum blockchain. -* For using ENS package, first install Web3 package using: `npm i web3` or `yarn add web3` based on your package manager, after that ENS features can be used as mentioned in following snippet. -* ```ts -* -* import { Web3 } from 'web3'; -* -* const web3 = new Web3('https://127.0.0.1:4545'); -* -* console.log(await web3.eth.ens.getAddress('ethereum.eth')) -* ``` -* For using individual package install `web3-eth-ens` packages using: `npm i web3-eth-ens` or `yarn add web3-eth-ens`. This is more efficient approach for building lightweight applications. -* -* ```ts -*import { ENS } from 'web3-eth-ens'; -* -* const ens = new ENS(undefined,'https://127.0.0.1:4545'); -* -* console.log(await ens.getAddress('vitalik.eth')); -* ``` -*/ + * For using ENS package, first install Web3 package using: `npm i web3` or `yarn add web3` based on your package manager, after that ENS features can be used as mentioned in following snippet. + * ```ts + * + * import { Web3 } from 'web3'; + * + * const web3 = new Web3('https://127.0.0.1:4545'); + * + * console.log(await web3.eth.ens.getAddress('ethereum.eth')) + * ``` + * For using individual package install `web3-eth-ens` packages using: `npm i web3-eth-ens` or `yarn add web3-eth-ens`. This is more efficient approach for building lightweight applications. + * + * ```ts + *import { ENS } from 'web3-eth-ens'; + * + * const ens = new ENS(undefined,'https://127.0.0.1:4545'); + * + * console.log(await ens.getAddress('vitalik.eth')); + * ``` + */ export class ENS extends Web3Context { /** * The registryAddress property can be used to define a custom registry address when you are connected to an unknown chain. It defaults to the main registry address. @@ -175,7 +179,6 @@ export class ENS extends Web3Context { return this._resolver.getText(ENSName, key); } - /** * Resolves the name of an ENS node. * @param ENSName - The node to resolve @@ -246,7 +249,7 @@ export class ENS extends Web3Context { return this._detectedAddress; } const networkType = await getId(this, { - ...DEFAULT_RETURN_FORMAT, + ...(this.defaultReturnFormat ?? DEFAULT_RETURN_FORMAT), number: FMT_NUMBER.HEX, }); // get the network from provider const addr = registryAddresses[networkIds[networkType]]; @@ -292,10 +295,10 @@ export class ENS extends Web3Context { * const receipt = await ens.setAddress('web3js.eth','0xe2597eb05cf9a87eb1309e86750c903ec38e527e'); *``` */ - public async setAddress( + public async setAddress( name: string, address: Address, - txConfig: PayableCallOptions + txConfig: PayableCallOptions, ): Promise { return this._resolver.setAddress(name, address, txConfig); } diff --git a/packages/web3-eth/src/rpc_method_wrappers.ts b/packages/web3-eth/src/rpc_method_wrappers.ts index 1a2cac1ffd8..f514516960c 100644 --- a/packages/web3-eth/src/rpc_method_wrappers.ts +++ b/packages/web3-eth/src/rpc_method_wrappers.ts @@ -122,7 +122,11 @@ export async function getHashRate( ) { const response = await ethRpcMethods.getHashRate(web3Context.requestManager); - return format({ format: 'uint' }, response as Numbers, returnFormat); + return format( + { format: 'uint' }, + response as Numbers, + returnFormat ?? web3Context.defaultReturnFormat, + ); } /** @@ -135,7 +139,11 @@ export async function getGasPrice( ) { const response = await ethRpcMethods.getGasPrice(web3Context.requestManager); - return format({ format: 'uint' }, response as Numbers, returnFormat); + return format( + { format: 'uint' }, + response as Numbers, + returnFormat ?? web3Context.defaultReturnFormat, + ); } /** @@ -148,7 +156,11 @@ export async function getMaxPriorityFeePerGas( ) { const response = await ethRpcMethods.getMaxPriorityFeePerGas(web3Context.requestManager); - return format({ format: 'uint' }, response as Numbers, returnFormat); + return format( + { format: 'uint' }, + response as Numbers, + returnFormat ?? web3Context.defaultReturnFormat, + ); } /** * View additional documentations here: {@link Web3Eth.getBlockNumber} @@ -160,7 +172,11 @@ export async function getBlockNumber( ) { const response = await ethRpcMethods.getBlockNumber(web3Context.requestManager); - return format({ format: 'uint' }, response as Numbers, returnFormat); + return format( + { format: 'uint' }, + response as Numbers, + returnFormat ?? web3Context.defaultReturnFormat, + ); } /** @@ -181,7 +197,11 @@ export async function getBalance( address, blockNumberFormatted, ); - return format({ format: 'uint' }, response as Numbers, returnFormat); + return format( + { format: 'uint' }, + response as Numbers, + returnFormat ?? web3Context.defaultReturnFormat, + ); } /** @@ -205,7 +225,11 @@ export async function getStorageAt( storageSlotFormatted, blockNumberFormatted, ); - return format({ format: 'bytes' }, response as Bytes, returnFormat); + return format( + { format: 'bytes' }, + response as Bytes, + returnFormat ?? web3Context.defaultReturnFormat, + ); } /** @@ -226,7 +250,11 @@ export async function getCode( address, blockNumberFormatted, ); - return format({ format: 'bytes' }, response as Bytes, returnFormat); + return format( + { format: 'bytes' }, + response as Bytes, + returnFormat ?? web3Context.defaultReturnFormat, + ); } /** @@ -257,7 +285,11 @@ export async function getBlock( hydrated, ); } - return format(blockSchema, response as unknown as Block, returnFormat); + return format( + blockSchema, + response as unknown as Block, + returnFormat ?? web3Context.defaultReturnFormat, + ); } /** @@ -286,7 +318,11 @@ export async function getBlockTransactionCount( ); } - return format({ format: 'uint' }, response as Numbers, returnFormat); + return format( + { format: 'uint' }, + response as Numbers, + returnFormat ?? web3Context.defaultReturnFormat, + ); } /** @@ -315,7 +351,11 @@ export async function getBlockUncleCount( ); } - return format({ format: 'uint' }, response as Numbers, returnFormat); + return format( + { format: 'uint' }, + response as Numbers, + returnFormat ?? web3Context.defaultReturnFormat, + ); } /** @@ -349,7 +389,11 @@ export async function getUncle( ); } - return format(blockSchema, response as unknown as Block, returnFormat); + return format( + blockSchema, + response as unknown as Block, + returnFormat ?? web3Context.defaultReturnFormat, + ); } /** @@ -373,7 +417,9 @@ export async function getTransaction( return isNullish(response) ? response - : formatTransaction(response, returnFormat, { fillInputAndData: true }); + : formatTransaction(response, returnFormat ?? web3Context.defaultReturnFormat, { + fillInputAndData: true, + }); } /** @@ -387,9 +433,13 @@ export async function getPendingTransactions( const response = await ethRpcMethods.getPendingTransactions(web3Context.requestManager); return response.map(transaction => - formatTransaction(transaction as unknown as Transaction, returnFormat, { - fillInputAndData: true, - }), + formatTransaction( + transaction as unknown as Transaction, + returnFormat ?? web3Context.defaultReturnFormat, + { + fillInputAndData: true, + }, + ), ); } @@ -426,7 +476,9 @@ export async function getTransactionFromBlock( return isNullish(response) ? response - : formatTransaction(response, returnFormat, { fillInputAndData: true }); + : formatTransaction(response, returnFormat ?? web3Context.defaultReturnFormat, { + fillInputAndData: true, + }); } /** @@ -453,7 +505,7 @@ export async function getTransactionReceipt( : (format( transactionReceiptSchema, response as unknown as TransactionReceipt, - returnFormat, + returnFormat ?? web3Context.defaultReturnFormat, ) as TransactionReceipt); } @@ -476,7 +528,11 @@ export async function getTransactionCount( blockNumberFormatted, ); - return format({ format: 'uint' }, response as Numbers, returnFormat); + return format( + { format: 'uint' }, + response as Numbers, + returnFormat ?? web3Context.defaultReturnFormat, + ); } /** @@ -519,7 +575,7 @@ export function sendTransaction< }, ETH_DATA_FORMAT, ); - + try { transactionFormatted = await sendTxHelper.populateGasPrice({ transaction, @@ -548,7 +604,7 @@ export function sendTransaction< const transactionHashFormatted = format( { format: 'bytes32' }, transactionHash as Bytes, - returnFormat, + returnFormat ?? web3Context.defaultReturnFormat, ); sendTxHelper.emitSent(transactionFormatted); sendTxHelper.emitTransactionHash( @@ -558,11 +614,15 @@ export function sendTransaction< const transactionReceipt = await waitForTransactionReceipt( web3Context, transactionHash, - returnFormat, + returnFormat ?? web3Context.defaultReturnFormat, ); const transactionReceiptFormatted = sendTxHelper.getReceiptWithEvents( - format(transactionReceiptSchema, transactionReceipt, returnFormat), + format( + transactionReceiptSchema, + transactionReceipt, + returnFormat ?? web3Context.defaultReturnFormat, + ), ); sendTxHelper.emitReceipt(transactionReceiptFormatted); @@ -661,7 +721,7 @@ export function sendSignedTransaction< const transactionHashFormatted = format( { format: 'bytes32' }, transactionHash as Bytes, - returnFormat, + returnFormat ?? web3Context.defaultReturnFormat, ); sendTxHelper.emitTransactionHash( @@ -671,11 +731,15 @@ export function sendSignedTransaction< const transactionReceipt = await waitForTransactionReceipt( web3Context, transactionHash, - returnFormat, + returnFormat ?? web3Context.defaultReturnFormat, ); const transactionReceiptFormatted = sendTxHelper.getReceiptWithEvents( - format(transactionReceiptSchema, transactionReceipt, returnFormat), + format( + transactionReceiptSchema, + transactionReceipt, + returnFormat ?? web3Context.defaultReturnFormat, + ), ); sendTxHelper.emitReceipt(transactionReceiptFormatted); @@ -721,7 +785,11 @@ export async function sign( if (web3Context.wallet?.get(addressOrIndex)) { const wallet = web3Context.wallet.get(addressOrIndex) as Web3BaseWalletAccount; const signed = wallet.sign(messageFormatted); - return format(SignatureObjectSchema, signed, returnFormat); + return format( + SignatureObjectSchema, + signed, + returnFormat ?? web3Context.defaultReturnFormat, + ); } if (typeof addressOrIndex === 'number') { @@ -737,7 +805,11 @@ export async function sign( messageFormatted, ); - return format({ format: 'bytes' }, response as Bytes, returnFormat); + return format( + { format: 'bytes' }, + response as Bytes, + returnFormat ?? web3Context.defaultReturnFormat, + ); } /** @@ -756,18 +828,26 @@ export async function signTransaction( // Some clients only return the encoded signed transaction (e.g. Ganache) // while clients such as Geth return the desired SignedTransactionInfoAPI object return isString(response as HexStringBytes) - ? decodeSignedTransaction(response as HexStringBytes, returnFormat, { - fillInputAndData: true, - }) + ? decodeSignedTransaction( + response as HexStringBytes, + returnFormat ?? web3Context.defaultReturnFormat ?? DEFAULT_RETURN_FORMAT, + { + fillInputAndData: true, + }, + ) : { raw: format( { format: 'bytes' }, (response as SignedTransactionInfoAPI).raw, - returnFormat, + returnFormat ?? web3Context.defaultReturnFormat, + ), + tx: formatTransaction( + (response as SignedTransactionInfoAPI).tx, + returnFormat ?? web3Context.defaultReturnFormat, + { + fillInputAndData: true, + }, ), - tx: formatTransaction((response as SignedTransactionInfoAPI).tx, returnFormat, { - fillInputAndData: true, - }), }; } @@ -793,7 +873,11 @@ export async function call( blockNumberFormatted, ); - return format({ format: 'bytes' }, response as Bytes, returnFormat); + return format( + { format: 'bytes' }, + response as Bytes, + returnFormat ?? web3Context.defaultReturnFormat, + ); } // TODO - Investigate whether response is padded as 1.x docs suggest @@ -818,7 +902,11 @@ export async function estimateGas( blockNumberFormatted, ); - return format({ format: 'uint' }, response as Numbers, returnFormat); + return format( + { format: 'uint' }, + response as Numbers, + returnFormat ?? web3Context.defaultReturnFormat, + ); } // TODO - Add input formatting to filter @@ -853,7 +941,11 @@ export async function getLogs( return res; } - return format(logSchema, res as unknown as Log, returnFormat); + return format( + logSchema, + res as unknown as Log, + returnFormat ?? web3Context.defaultReturnFormat, + ); }); return result; @@ -873,7 +965,7 @@ export async function getChainId( { format: 'uint' }, // Response is number in hex formatted string response as unknown as number, - returnFormat, + returnFormat ?? web3Context.defaultReturnFormat, ); } @@ -903,7 +995,11 @@ export async function getProof( blockNumberFormatted, ); - return format(accountSchema, response as unknown as AccountObject, returnFormat); + return format( + accountSchema, + response as unknown as AccountObject, + returnFormat ?? web3Context.defaultReturnFormat, + ); } // TODO Throwing an error with Geth, but not Infura @@ -943,7 +1039,11 @@ export async function getFeeHistory( rewardPercentilesFormatted, ); - return format(feeHistorySchema, response as unknown as FeeHistory, returnFormat); + return format( + feeHistorySchema, + response as unknown as FeeHistory, + returnFormat ?? web3Context.defaultReturnFormat, + ); } /** @@ -966,7 +1066,11 @@ export async function createAccessList( blockNumberFormatted, )) as unknown as AccessListResult; - return format(accessListResultSchema, response, returnFormat); + return format( + accessListResultSchema, + response, + returnFormat ?? web3Context.defaultReturnFormat, + ); } /** @@ -987,5 +1091,5 @@ export async function signTypedData( useLegacy, ); - return format({ format: 'bytes' }, response, returnFormat); + return format({ format: 'bytes' }, response, returnFormat ?? web3Context.defaultReturnFormat); } diff --git a/packages/web3-eth/src/utils/get_revert_reason.ts b/packages/web3-eth/src/utils/get_revert_reason.ts index ae4fc32dbfa..b95491b4f1d 100644 --- a/packages/web3-eth/src/utils/get_revert_reason.ts +++ b/packages/web3-eth/src/utils/get_revert_reason.ts @@ -16,7 +16,12 @@ along with web3.js. If not, see . */ import { Web3Context } from 'web3-core'; -import { ContractExecutionError, Eip838ExecutionError, InvalidResponseError , MultipleErrors } from 'web3-errors'; +import { + ContractExecutionError, + Eip838ExecutionError, + InvalidResponseError, + MultipleErrors, +} from 'web3-errors'; import { decodeContractErrorData, isAbiErrorFragment } from 'web3-eth-abi'; import { AbiErrorFragment, @@ -80,7 +85,8 @@ export async function getRevertReason< web3Context: Web3Context, transaction: TransactionCall, contractAbi?: ContractAbi, - returnFormat: ReturnFormat = DEFAULT_RETURN_FORMAT as ReturnFormat, + returnFormat: ReturnFormat = (web3Context.defaultReturnFormat ?? + DEFAULT_RETURN_FORMAT) as ReturnFormat, ): Promise { try { await call(web3Context, transaction, web3Context.defaultBlock, returnFormat); diff --git a/packages/web3-eth/src/utils/transaction_builder.ts b/packages/web3-eth/src/utils/transaction_builder.ts index 13edd253330..ad3ff866d8a 100644 --- a/packages/web3-eth/src/utils/transaction_builder.ts +++ b/packages/web3-eth/src/utils/transaction_builder.ts @@ -29,9 +29,9 @@ import { Web3NetAPI, Numbers, DataFormat, - DEFAULT_RETURN_FORMAT, FormatType, ETH_DATA_FORMAT, + DEFAULT_RETURN_FORMAT, } from 'web3-types'; import { Web3Context } from 'web3-core'; import { privateKeyToAddress } from 'web3-eth-accounts'; @@ -99,7 +99,8 @@ export const getTransactionFromOrToAttr = ( export const getTransactionNonce = async ( web3Context: Web3Context, address?: Address, - returnFormat: ReturnFormat = DEFAULT_RETURN_FORMAT as ReturnFormat, + returnFormat: ReturnFormat = (web3Context.defaultReturnFormat ?? + DEFAULT_RETURN_FORMAT) as ReturnFormat, ) => { if (isNullish(address)) { // TODO if (web3.eth.accounts.wallet) use address from local wallet @@ -133,7 +134,7 @@ export async function defaultTransactionBuilder(option let populatedTransaction = format( transactionSchema, options.transaction, - DEFAULT_RETURN_FORMAT, + options.web3Context.defaultReturnFormat, ) as InternalTransaction; if (isNullish(populatedTransaction.from)) { diff --git a/packages/web3-eth/src/web3_eth.ts b/packages/web3-eth/src/web3_eth.ts index 3c1165b0e3c..2c025c702dc 100644 --- a/packages/web3-eth/src/web3_eth.ts +++ b/packages/web3-eth/src/web3_eth.ts @@ -201,7 +201,8 @@ export class Web3Eth extends Web3Context( - returnFormat: ReturnFormat = DEFAULT_RETURN_FORMAT as ReturnFormat, + returnFormat: ReturnFormat = (this.defaultReturnFormat ?? + DEFAULT_RETURN_FORMAT) as ReturnFormat, ) { return this.getHashRate(returnFormat); } @@ -219,7 +220,8 @@ export class Web3Eth extends Web3Context( - returnFormat: ReturnFormat = DEFAULT_RETURN_FORMAT as ReturnFormat, + returnFormat: ReturnFormat = (this.defaultReturnFormat ?? + DEFAULT_RETURN_FORMAT) as ReturnFormat, ) { return rpcMethodsWrappers.getHashRate(this, returnFormat); } @@ -237,7 +239,8 @@ export class Web3Eth extends Web3Context( - returnFormat: ReturnFormat = DEFAULT_RETURN_FORMAT as ReturnFormat, + returnFormat: ReturnFormat = (this.defaultReturnFormat ?? + DEFAULT_RETURN_FORMAT) as ReturnFormat, ) { return rpcMethodsWrappers.getGasPrice(this, returnFormat); } @@ -256,7 +259,10 @@ export class Web3Eth extends Web3Context(returnFormat: ReturnFormat = DEFAULT_RETURN_FORMAT as ReturnFormat) { + >( + returnFormat: ReturnFormat = (this.defaultReturnFormat ?? + DEFAULT_RETURN_FORMAT) as ReturnFormat, + ) { return rpcMethodsWrappers.getMaxPriorityFeePerGas(this, returnFormat); } @@ -300,7 +306,10 @@ export class Web3Eth extends Web3Context(); + gasPrice = await this.getGasPrice<{ + number: FMT_NUMBER.BIGINT; + bytes: FMT_BYTES.HEX; + }>(); } catch (error) { // do nothing } @@ -361,7 +370,8 @@ export class Web3Eth extends Web3Context( - returnFormat: ReturnFormat = DEFAULT_RETURN_FORMAT as ReturnFormat, + returnFormat: ReturnFormat = (this.defaultReturnFormat ?? + DEFAULT_RETURN_FORMAT) as ReturnFormat, ) { return rpcMethodsWrappers.getBlockNumber(this, returnFormat); } @@ -385,7 +395,8 @@ export class Web3Eth extends Web3Context( address: Address, blockNumber: BlockNumberOrTag = this.defaultBlock, - returnFormat: ReturnFormat = DEFAULT_RETURN_FORMAT as ReturnFormat, + returnFormat: ReturnFormat = (this.defaultReturnFormat ?? + DEFAULT_RETURN_FORMAT) as ReturnFormat, ) { return rpcMethodsWrappers.getBalance(this, address, blockNumber, returnFormat); } @@ -421,9 +432,16 @@ export class Web3Eth extends Web3Context( address: Address, blockNumber: BlockNumberOrTag = this.defaultBlock, - returnFormat: ReturnFormat = DEFAULT_RETURN_FORMAT as ReturnFormat, + returnFormat: ReturnFormat = (this.defaultReturnFormat ?? + DEFAULT_RETURN_FORMAT) as ReturnFormat, ) { return rpcMethodsWrappers.getCode(this, address, blockNumber, returnFormat); } @@ -527,7 +546,8 @@ export class Web3Eth extends Web3Context( block: HexString32Bytes | BlockNumberOrTag = this.defaultBlock, hydrated = false, - returnFormat: ReturnFormat = DEFAULT_RETURN_FORMAT as ReturnFormat, + returnFormat: ReturnFormat = (this.defaultReturnFormat ?? + DEFAULT_RETURN_FORMAT) as ReturnFormat, ) { return rpcMethodsWrappers.getBlock(this, block, hydrated, returnFormat); } @@ -552,7 +572,8 @@ export class Web3Eth extends Web3Context( block: HexString32Bytes | BlockNumberOrTag = this.defaultBlock, - returnFormat: ReturnFormat = DEFAULT_RETURN_FORMAT as ReturnFormat, + returnFormat: ReturnFormat = (this.defaultReturnFormat ?? + DEFAULT_RETURN_FORMAT) as ReturnFormat, ) { return rpcMethodsWrappers.getBlockTransactionCount(this, block, returnFormat); } @@ -575,7 +596,8 @@ export class Web3Eth extends Web3Context( block: HexString32Bytes | BlockNumberOrTag = this.defaultBlock, - returnFormat: ReturnFormat = DEFAULT_RETURN_FORMAT as ReturnFormat, + returnFormat: ReturnFormat = (this.defaultReturnFormat ?? + DEFAULT_RETURN_FORMAT) as ReturnFormat, ) { return rpcMethodsWrappers.getBlockUncleCount(this, block, returnFormat); } @@ -646,7 +668,8 @@ export class Web3Eth extends Web3Context( block: HexString32Bytes | BlockNumberOrTag = this.defaultBlock, uncleIndex: Numbers, - returnFormat: ReturnFormat = DEFAULT_RETURN_FORMAT as ReturnFormat, + returnFormat: ReturnFormat = (this.defaultReturnFormat ?? + DEFAULT_RETURN_FORMAT) as ReturnFormat, ) { return rpcMethodsWrappers.getUncle(this, block, uncleIndex, returnFormat); } @@ -701,9 +724,14 @@ export class Web3Eth extends Web3Context( transactionHash: Bytes, - returnFormat: ReturnFormat = DEFAULT_RETURN_FORMAT as ReturnFormat, + returnFormat: ReturnFormat = (this.defaultReturnFormat ?? + DEFAULT_RETURN_FORMAT) as ReturnFormat, ) { - const response = await rpcMethodsWrappers.getTransaction(this, transactionHash, returnFormat); + const response = await rpcMethodsWrappers.getTransaction( + this, + transactionHash, + returnFormat, + ); if (!response) throw new TransactionNotFound(); @@ -794,7 +822,10 @@ export class Web3Eth extends Web3Context(returnFormat: ReturnFormat = DEFAULT_RETURN_FORMAT as ReturnFormat) { + >( + returnFormat: ReturnFormat = (this.defaultReturnFormat ?? + DEFAULT_RETURN_FORMAT) as ReturnFormat, + ) { return rpcMethodsWrappers.getPendingTransactions(this, returnFormat); } @@ -853,9 +884,15 @@ export class Web3Eth extends Web3Context( block: HexString32Bytes | BlockNumberOrTag = this.defaultBlock, transactionIndex: Numbers, - returnFormat: ReturnFormat = DEFAULT_RETURN_FORMAT as ReturnFormat, + returnFormat: ReturnFormat = (this.defaultReturnFormat ?? + DEFAULT_RETURN_FORMAT) as ReturnFormat, ) { - return rpcMethodsWrappers.getTransactionFromBlock(this, block, transactionIndex, returnFormat); + return rpcMethodsWrappers.getTransactionFromBlock( + this, + block, + transactionIndex, + returnFormat, + ); } /** @@ -904,7 +941,11 @@ export class Web3Eth extends Web3Context(transactionHash: Bytes, returnFormat: ReturnFormat = DEFAULT_RETURN_FORMAT as ReturnFormat) { + >( + transactionHash: Bytes, + returnFormat: ReturnFormat = (this.defaultReturnFormat ?? + DEFAULT_RETURN_FORMAT) as ReturnFormat, + ) { const response = await rpcMethodsWrappers.getTransactionReceipt( this, transactionHash, @@ -934,10 +975,13 @@ export class Web3Eth extends Web3Context 1 * ``` */ - public async getTransactionCount( + public async getTransactionCount< + ReturnFormat extends DataFormat = typeof DEFAULT_RETURN_FORMAT, + >( address: Address, blockNumber: BlockNumberOrTag = this.defaultBlock, - returnFormat: ReturnFormat = DEFAULT_RETURN_FORMAT as ReturnFormat, + returnFormat: ReturnFormat = (this.defaultReturnFormat ?? + DEFAULT_RETURN_FORMAT) as ReturnFormat, ) { return rpcMethodsWrappers.getTransactionCount(this, address, blockNumber, returnFormat); } diff --git a/packages/web3-net/src/net.ts b/packages/web3-net/src/net.ts index eb84e567bb5..bf7a676dd1c 100644 --- a/packages/web3-net/src/net.ts +++ b/packages/web3-net/src/net.ts @@ -21,24 +21,24 @@ import * as rpcMethodsWrappers from './rpc_method_wrappers.js'; /** * Net class allows you to interact with an Ethereum node’s network properties. -* For using Net package, first install Web3 package using: `npm i web3` or `yarn add web3` based on your package manager, after that Net features can be used. -* ```ts -* -* import { Web3 } from 'web3'; -* const web3 = new Web3('https://mainnet.infura.io/v3/'); -* -* console.log(await web3.eth.net.getId()); -* -* ``` -* For using individual package install `web3-net` packages using: `npm i web3-net` or `yarn add web3-net`. -* -* ```ts -* import {Net} from 'web3-net'; -* -* const net = new Net('https://mainnet.infura.io/v3/'); -* console.log(await net.getId()); -* ``` -*/ + * For using Net package, first install Web3 package using: `npm i web3` or `yarn add web3` based on your package manager, after that Net features can be used. + * ```ts + * + * import { Web3 } from 'web3'; + * const web3 = new Web3('https://mainnet.infura.io/v3/'); + * + * console.log(await web3.eth.net.getId()); + * + * ``` + * For using individual package install `web3-net` packages using: `npm i web3-net` or `yarn add web3-net`. + * + * ```ts + * import {Net} from 'web3-net'; + * + * const net = new Net('https://mainnet.infura.io/v3/'); + * console.log(await net.getId()); + * ``` + */ export class Net extends Web3Context { /** * Gets the current network ID @@ -53,7 +53,8 @@ export class Net extends Web3Context { * ``` */ public async getId( - returnFormat: ReturnFormat = DEFAULT_RETURN_FORMAT as ReturnFormat, + returnFormat: ReturnFormat = (this.defaultReturnFormat ?? + DEFAULT_RETURN_FORMAT) as ReturnFormat, ) { return rpcMethodsWrappers.getId(this, returnFormat); } @@ -71,7 +72,8 @@ export class Net extends Web3Context { * ``` */ public async getPeerCount( - returnFormat: ReturnFormat = DEFAULT_RETURN_FORMAT as ReturnFormat, + returnFormat: ReturnFormat = (this.defaultReturnFormat ?? + DEFAULT_RETURN_FORMAT) as ReturnFormat, ) { return rpcMethodsWrappers.getPeerCount(this, returnFormat); } diff --git a/packages/web3-types/src/data_format_types.ts b/packages/web3-types/src/data_format_types.ts index f0ffe3bc8aa..46c1f5352b8 100644 --- a/packages/web3-types/src/data_format_types.ts +++ b/packages/web3-types/src/data_format_types.ts @@ -46,7 +46,10 @@ export type DataFormat = { readonly bytes: FMT_BYTES; }; -export const DEFAULT_RETURN_FORMAT = { number: FMT_NUMBER.BIGINT, bytes: FMT_BYTES.HEX } as const; +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 diff --git a/packages/web3-utils/src/formatter.ts b/packages/web3-utils/src/formatter.ts index 1901e1fde21..0a8ca3b723f 100644 --- a/packages/web3-utils/src/formatter.ts +++ b/packages/web3-utils/src/formatter.ts @@ -15,7 +15,14 @@ You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see . */ import { FormatterError } from 'web3-errors'; -import { Bytes, DataFormat, FMT_BYTES, FMT_NUMBER, FormatType } from 'web3-types'; +import { + Bytes, + DataFormat, + FMT_BYTES, + FMT_NUMBER, + FormatType, + DEFAULT_RETURN_FORMAT, +} from 'web3-types'; import { isNullish, isObject, JsonSchema, utils, ValidationSchemaInput } from 'web3-validator'; import { bytesToUint8Array, bytesToHex, numberToHex, toBigInt } from './converters.js'; import { mergeDeep } from './objects.js'; @@ -277,7 +284,7 @@ export const format = < >( schema: ValidationSchemaInput | JsonSchema, data: DataType, - returnFormat: ReturnType, + returnFormat: ReturnType = DEFAULT_RETURN_FORMAT as ReturnType, ): FormatType => { let dataToParse: Record | unknown[] | unknown; diff --git a/packages/web3/src/web3.ts b/packages/web3/src/web3.ts index 2953e67d364..0fda2c10521 100644 --- a/packages/web3/src/web3.ts +++ b/packages/web3/src/web3.ts @@ -20,7 +20,7 @@ import { Web3ContextInitOptions, Web3ContextObject, Web3SubscriptionConstructor, - isSupportedProvider + isSupportedProvider, } from 'web3-core'; import { Web3Eth, RegisteredSubscription, registeredSubscriptions } from 'web3-eth'; import Contract from 'web3-eth-contract'; @@ -37,7 +37,6 @@ import { EthExecutionAPI, SupportedProviders, DataFormat, - DEFAULT_RETURN_FORMAT } from 'web3-types'; import { InvalidMethodParamsError } from 'web3-errors'; import abi from './abi.js'; @@ -122,32 +121,38 @@ export class Web3< class ContractBuilder extends Contract { public constructor(jsonInterface: Abi); - public constructor(jsonInterface: Abi, + public constructor( + jsonInterface: Abi, addressOrOptionsOrContext?: Address | ContractInitOptions | Web3Context, - ); + ); public constructor( jsonInterface: Abi, addressOrOptionsOrContext?: Address | ContractInitOptions | Web3Context, optionsOrContextOrReturnFormat?: ContractInitOptions | Web3Context | DataFormat, ); - public constructor(jsonInterface: Abi, + public constructor( + jsonInterface: Abi, addressOrOptionsOrContext?: Address | ContractInitOptions, optionsOrContextOrReturnFormat?: ContractInitOptions, contextOrReturnFormat?: Web3Context | DataFormat, - ); - public constructor(jsonInterface: Abi, + ); + public constructor( + jsonInterface: Abi, addressOrOptionsOrContext?: Address | ContractInitOptions, optionsOrContextOrReturnFormat?: ContractInitOptions, contextOrReturnFormat?: Web3Context | DataFormat, - ); - public constructor(jsonInterface: Abi, + ); + public constructor( + jsonInterface: Abi, addressOrOptionsOrContext?: Address | ContractInitOptions, optionsOrContextOrReturnFormat?: ContractInitOptions, contextOrReturnFormat?: Web3Context | DataFormat, - returnFormat?: DataFormat - ) - { - if (isContractInitOptions(addressOrOptionsOrContext) && isContractInitOptions(optionsOrContextOrReturnFormat)) { + returnFormat?: DataFormat, + ) { + if ( + isContractInitOptions(addressOrOptionsOrContext) && + isContractInitOptions(optionsOrContextOrReturnFormat) + ) { throw new InvalidMethodParamsError( 'Should not provide options at both 2nd and 3rd parameters', ); @@ -155,22 +160,26 @@ export class Web3< let address: string | undefined; let options: object = {}; let context: Web3ContextObject; - let dataFormat: DataFormat = DEFAULT_RETURN_FORMAT; + let dataFormat: DataFormat | undefined; // add validation so its not a breaking change - if (!isNullish(addressOrOptionsOrContext) && typeof addressOrOptionsOrContext !== 'object' && typeof addressOrOptionsOrContext !== 'string') { + if ( + !isNullish(addressOrOptionsOrContext) && + typeof addressOrOptionsOrContext !== 'object' && + typeof addressOrOptionsOrContext !== 'string' + ) { throw new InvalidMethodParamsError(); } if (typeof addressOrOptionsOrContext === 'string') { address = addressOrOptionsOrContext; } - if (isContractInitOptions(addressOrOptionsOrContext)){ + if (isContractInitOptions(addressOrOptionsOrContext)) { options = addressOrOptionsOrContext as object; } else if (isContractInitOptions(optionsOrContextOrReturnFormat)) { options = optionsOrContextOrReturnFormat as object; } else { - options = {} + options = {}; } if (addressOrOptionsOrContext instanceof Web3Context) { @@ -183,7 +192,7 @@ export class Web3< context = self.getContextObject() as Web3ContextObject; } - if (returnFormat){ + if (returnFormat) { dataFormat = returnFormat; } else if (isDataFormat(optionsOrContextOrReturnFormat)) { dataFormat = optionsOrContextOrReturnFormat as DataFormat; @@ -191,7 +200,7 @@ export class Web3< dataFormat = contextOrReturnFormat; } - super(jsonInterface,address, options, context, dataFormat) + super(jsonInterface, address, options, context, dataFormat); super.subscribeToContextEvents(self); } } From 4c178000b5da143b6265e9f6498b876839844a15 Mon Sep 17 00:00:00 2001 From: Oleksii Kosynskyi Date: Thu, 28 Mar 2024 21:37:57 +0100 Subject: [PATCH 02/21] fix ens tests --- .../test/integration/ens.events.test.ts | 14 ++------------ .../web3-eth-ens/test/integration/ens.test.ts | 14 ++------------ .../test/integration/resolver.test.ts | 18 ++---------------- .../web3-eth-ens/test/integration/setup.js | 2 +- 4 files changed, 7 insertions(+), 41 deletions(-) diff --git a/packages/web3-eth-ens/test/integration/ens.events.test.ts b/packages/web3-eth-ens/test/integration/ens.events.test.ts index 8ad10d08bda..4e199597c24 100644 --- a/packages/web3-eth-ens/test/integration/ens.events.test.ts +++ b/packages/web3-eth-ens/test/integration/ens.events.test.ts @@ -18,9 +18,8 @@ along with web3.js. If not, see . /* eslint-disable @typescript-eslint/no-unused-vars */ import { Contract, PayableTxOptions } from 'web3-eth-contract'; import { sha3 } from 'web3-utils'; -import { getBlock } from 'web3-eth'; -import { Address, Bytes, DEFAULT_RETURN_FORMAT } from 'web3-types'; +import { Address, Bytes } from 'web3-types'; // eslint-disable-next-line import/no-extraneous-dependencies import { IpcProvider } from 'web3-providers-ipc'; import { ENS } from '../../src'; @@ -75,7 +74,7 @@ describeIf(isSocket)('ens events', () => { const acc2 = await createTempAccount(); accountOne = acc2.address; - sendOptions = { from: defaultAccount, gas: '10000000' }; + sendOptions = { from: defaultAccount, type: '0x1' }; const Registry = new Contract(ENSRegistryAbi, undefined, { provider: getSystemTestProvider(), @@ -120,15 +119,6 @@ describeIf(isSocket)('ens events', () => { else provider = new ENS.providers.HttpProvider(clientUrl); ens = new ENS(registry.options.address, provider); - - const block = await getBlock(ens, 'latest', false, DEFAULT_RETURN_FORMAT); - const gas = block.gasLimit.toString(); - - // Increase gas for contract calls - sendOptions = { - ...sendOptions, - gas, - }; }); afterAll(async () => { diff --git a/packages/web3-eth-ens/test/integration/ens.test.ts b/packages/web3-eth-ens/test/integration/ens.test.ts index 5683451b66f..bde73e72fc7 100644 --- a/packages/web3-eth-ens/test/integration/ens.test.ts +++ b/packages/web3-eth-ens/test/integration/ens.test.ts @@ -16,9 +16,8 @@ along with web3.js. If not, see . */ /* eslint-disable @typescript-eslint/no-unused-vars */ -import { getBlock } from 'web3-eth'; import { Contract, PayableTxOptions } from 'web3-eth-contract'; -import { Address, Bytes, DEFAULT_RETURN_FORMAT } from 'web3-types'; +import { Address, Bytes } from 'web3-types'; import { sha3, toChecksumAddress } from 'web3-utils'; // eslint-disable-next-line import/no-extraneous-dependencies import { IpcProvider } from 'web3-providers-ipc'; @@ -76,7 +75,7 @@ describe('ens', () => { const acc2 = await createTempAccount(); accountOne = acc2.address; - sendOptions = { from: defaultAccount, gas: '10000000' }; + sendOptions = { from: defaultAccount, type: '0x1' }; const Registry = new Contract(ENSRegistryAbi, undefined, { provider: getSystemTestProvider(), @@ -121,15 +120,6 @@ describe('ens', () => { else provider = new ENS.providers.HttpProvider(clientUrl); ens = new ENS(registry.options.address, provider); - - const block = await getBlock(ens, 'latest', false, DEFAULT_RETURN_FORMAT); - const gas = block.gasLimit.toString(); - - // Increase gas for contract calls - sendOptions = { - ...sendOptions, - gas, - }; }); afterAll(async () => { diff --git a/packages/web3-eth-ens/test/integration/resolver.test.ts b/packages/web3-eth-ens/test/integration/resolver.test.ts index 587ce2e7b29..f6b2e648991 100644 --- a/packages/web3-eth-ens/test/integration/resolver.test.ts +++ b/packages/web3-eth-ens/test/integration/resolver.test.ts @@ -15,12 +15,10 @@ You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see . */ -/* eslint-disable @typescript-eslint/no-unused-vars */ -import Web3Eth from 'web3-eth'; import { Contract, PayableTxOptions } from 'web3-eth-contract'; import { sha3 } from 'web3-utils'; -import { Address, Bytes, DEFAULT_RETURN_FORMAT } from 'web3-types'; +import { Address, Bytes } from 'web3-types'; // eslint-disable-next-line import/no-extraneous-dependencies import { IpcProvider } from 'web3-providers-ipc'; import { ENS } from '../../src'; @@ -59,8 +57,6 @@ describe('ens', () => { const node = namehash('resolver'); const label = sha3('resolver') as string; - let web3Eth: Web3Eth; - let ens: ENS; let defaultAccount: string; let accountOne: string; @@ -78,7 +74,7 @@ describe('ens', () => { const acc2 = await createTempAccount(); accountOne = acc2.address; - sendOptions = { from: defaultAccount, gas: '10000000' }; + sendOptions = { from: defaultAccount, type: '0x1' }; const Registry = new Contract(ENSRegistryAbi, undefined, { provider: getSystemTestProvider(), @@ -123,16 +119,6 @@ describe('ens', () => { else provider = new ENS.providers.HttpProvider(clientUrl); ens = new ENS(registry.options.address, provider); - - web3Eth = new Web3Eth(provider); - const block = await web3Eth.getBlock('latest', false, DEFAULT_RETURN_FORMAT); - const gas = block.gasLimit.toString(); - - // Increase gas for contract calls - sendOptions = { - ...sendOptions, - gas, - }; }); afterAll(async () => { diff --git a/packages/web3-eth-ens/test/integration/setup.js b/packages/web3-eth-ens/test/integration/setup.js index 5be1bccf7cc..59b1f904213 100644 --- a/packages/web3-eth-ens/test/integration/setup.js +++ b/packages/web3-eth-ens/test/integration/setup.js @@ -19,6 +19,6 @@ along with web3.js. If not, see . // eslint-disable-next-line @typescript-eslint/no-require-imports require('../config/setup'); -const jestTimeout = 15000; +const jestTimeout = 30000; jest.setTimeout(jestTimeout); From 50f18b508e3dd70591b5d28221017d44eb2ec673 Mon Sep 17 00:00:00 2001 From: Oleksii Kosynskyi Date: Mon, 1 Apr 2024 18:12:29 +0200 Subject: [PATCH 03/21] add format tests --- packages/web3-eth-contract/src/contract.ts | 16 ++- packages/web3-eth/src/web3_eth.ts | 39 ++++-- .../web3_eth_methods_with_parameters.ts | 1 + .../web3-eth/test/integration/format.test.ts | 116 ++++++++++++++++++ packages/web3-eth/test/integration/helper.ts | 14 +-- .../web3-eth/test/integration/rpc.test.ts | 33 +++-- .../web3/test/integration/web3.format.test.ts | 111 +++++++++++++++++ scripts/system_tests_utils.ts | 11 ++ 8 files changed, 292 insertions(+), 49 deletions(-) create mode 100644 packages/web3-eth/test/integration/format.test.ts create mode 100644 packages/web3/test/integration/web3.format.test.ts diff --git a/packages/web3-eth-contract/src/contract.ts b/packages/web3-eth-contract/src/contract.ts index c7f69a2d967..520b3d85a20 100644 --- a/packages/web3-eth-contract/src/contract.ts +++ b/packages/web3-eth-contract/src/contract.ts @@ -942,7 +942,8 @@ export class Contract if (Array.isArray(filter[key])) { return (filter[key] as Numbers[]).some( (v: Numbers) => - String(log.returnValues[key]).toUpperCase() === String(v).toUpperCase(), + String(log.returnValues[key]).toUpperCase() === + String(v).toUpperCase(), ); } @@ -1010,10 +1011,10 @@ export class Contract abi, ]); const abiFragment = this._overloadedMethodAbis.get(abi.name) ?? []; - const contractMethod = this._createContractMethod( - abiFragment, - errorsAbi, - ); + const contractMethod = this._createContractMethod< + typeof abiFragment, + AbiErrorFragment + >(abiFragment, errorsAbi); const exactContractMethod = this._createContractMethod< typeof abiFragment, @@ -1104,7 +1105,10 @@ export class Contract for (const _abi of arrayOfAbis) { try { abiParams = this._getAbiParams(_abi, params); - validator.validate(_abi.inputs as unknown as ValidationSchemaInput, abiParams); + validator.validate( + _abi.inputs as unknown as ValidationSchemaInput, + abiParams, + ); applicableMethodAbi.push(_abi); } catch (e) { errors.push(e as Web3ValidationErrorObject); diff --git a/packages/web3-eth/src/web3_eth.ts b/packages/web3-eth/src/web3_eth.ts index 2c025c702dc..dc6f978c9c7 100644 --- a/packages/web3-eth/src/web3_eth.ts +++ b/packages/web3-eth/src/web3_eth.ts @@ -1098,7 +1098,8 @@ export class Web3Eth extends Web3Context( transaction: Bytes, - returnFormat: ReturnFormat = DEFAULT_RETURN_FORMAT as ReturnFormat, + returnFormat: ReturnFormat = (this.defaultReturnFormat ?? + DEFAULT_RETURN_FORMAT) as ReturnFormat, options?: SendTransactionOptions, ) { return rpcMethodsWrappers.sendSignedTransaction(this, transaction, returnFormat, options); @@ -1226,7 +1228,8 @@ export class Web3Eth extends Web3Context( message: Bytes, addressOrIndex: Address | number, - returnFormat: ReturnFormat = DEFAULT_RETURN_FORMAT as ReturnFormat, + returnFormat: ReturnFormat = (this.defaultReturnFormat ?? + DEFAULT_RETURN_FORMAT) as ReturnFormat, ) { return rpcMethodsWrappers.sign(this, message, addressOrIndex, returnFormat); } @@ -1284,7 +1287,8 @@ export class Web3Eth extends Web3Context( transaction: Transaction, - returnFormat: ReturnFormat = DEFAULT_RETURN_FORMAT as ReturnFormat, + returnFormat: ReturnFormat = (this.defaultReturnFormat ?? + DEFAULT_RETURN_FORMAT) as ReturnFormat, ) { return rpcMethodsWrappers.signTransaction(this, transaction, returnFormat); } @@ -1303,7 +1307,8 @@ export class Web3Eth extends Web3Context( transaction: TransactionCall, blockNumber: BlockNumberOrTag = this.defaultBlock, - returnFormat: ReturnFormat = DEFAULT_RETURN_FORMAT as ReturnFormat, + returnFormat: ReturnFormat = (this.defaultReturnFormat ?? + DEFAULT_RETURN_FORMAT) as ReturnFormat, ) { return rpcMethodsWrappers.call(this, transaction, blockNumber, returnFormat); } @@ -1337,7 +1342,8 @@ export class Web3Eth extends Web3Context( transaction: Transaction, blockNumber: BlockNumberOrTag = this.defaultBlock, - returnFormat: ReturnFormat = DEFAULT_RETURN_FORMAT as ReturnFormat, + returnFormat: ReturnFormat = (this.defaultReturnFormat ?? + DEFAULT_RETURN_FORMAT) as ReturnFormat, ) { return rpcMethodsWrappers.estimateGas(this, transaction, blockNumber, returnFormat); } @@ -1388,7 +1394,8 @@ export class Web3Eth extends Web3Context( filter: Filter, - returnFormat: ReturnFormat = DEFAULT_RETURN_FORMAT as ReturnFormat, + returnFormat: ReturnFormat = (this.defaultReturnFormat ?? + DEFAULT_RETURN_FORMAT) as ReturnFormat, ) { return rpcMethodsWrappers.getLogs(this, filter, returnFormat); } @@ -1471,7 +1478,8 @@ export class Web3Eth extends Web3Context( - returnFormat: ReturnFormat = DEFAULT_RETURN_FORMAT as ReturnFormat, + returnFormat: ReturnFormat = (this.defaultReturnFormat ?? + DEFAULT_RETURN_FORMAT) as ReturnFormat, ) { return rpcMethodsWrappers.getChainId(this, returnFormat); } @@ -1564,7 +1572,8 @@ export class Web3Eth extends Web3Context( transaction: TransactionForAccessList, blockNumber: BlockNumberOrTag = this.defaultBlock, - returnFormat: ReturnFormat = DEFAULT_RETURN_FORMAT as ReturnFormat, + returnFormat: ReturnFormat = (this.defaultReturnFormat ?? + DEFAULT_RETURN_FORMAT) as ReturnFormat, ) { return rpcMethodsWrappers.createAccessList(this, transaction, blockNumber, returnFormat); } @@ -1697,7 +1708,8 @@ export class Web3Eth extends Web3Context( name: T, args?: ConstructorParameters[0], - returnFormat: ReturnType = DEFAULT_RETURN_FORMAT as ReturnType, + returnFormat: ReturnType = (this.defaultReturnFormat ?? + DEFAULT_RETURN_FORMAT) as ReturnType, ): Promise> { const subscription = await this.subscriptionManager?.subscribe(name, args, returnFormat); if ( diff --git a/packages/web3-eth/test/fixtures/web3_eth_methods_with_parameters.ts b/packages/web3-eth/test/fixtures/web3_eth_methods_with_parameters.ts index 17d9c204f21..dc16ed1bb2d 100644 --- a/packages/web3-eth/test/fixtures/web3_eth_methods_with_parameters.ts +++ b/packages/web3-eth/test/fixtures/web3_eth_methods_with_parameters.ts @@ -30,6 +30,7 @@ import { Uint256, TransactionWithSenderAPI, TransactionReceipt, + FMT_BYTES, } from 'web3-types'; import { transactionWithSender } from './rpc_methods_wrappers'; diff --git a/packages/web3-eth/test/integration/format.test.ts b/packages/web3-eth/test/integration/format.test.ts new file mode 100644 index 00000000000..647ea4351af --- /dev/null +++ b/packages/web3-eth/test/integration/format.test.ts @@ -0,0 +1,116 @@ +/* +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 { SupportedProviders, FMT_BYTES, FMT_NUMBER, DEFAULT_RETURN_FORMAT } from 'web3-types'; +// eslint-disable-next-line import/no-extraneous-dependencies +import { Contract } from 'web3-eth-contract'; +import { numberToHex } from 'web3-utils'; +// eslint-disable-next-line import/no-extraneous-dependencies +import { Web3Eth } from '../../src'; + +import { + closeOpenConnection, + getSystemTestProvider, + createNewAccount, + createTempAccount, + mapFormatToType, +} from '../fixtures/system_test_utils'; +import { BasicAbi, BasicBytecode } from '../shared_fixtures/build/Basic'; +import { describe } from 'node:test'; + +describe('format', () => { + let web3Eth: Web3Eth; + let clientUrl: string | SupportedProviders; + let contractDeployed: Contract; + let contract: Contract; + let deployOptions: Record; + let sendOptions: Record; + let tempAcc: { address: string; privateKey: string }; + beforeAll(async () => { + clientUrl = getSystemTestProvider(); + web3Eth = new Web3Eth({ + provider: clientUrl, + config: { + transactionPollingTimeout: 2000, + }, + }); + contract = new Contract(BasicAbi, undefined, { + provider: clientUrl, + }); + + deployOptions = { + data: BasicBytecode, + arguments: [10, 'string init value'], + }; + tempAcc = await createTempAccount(); + sendOptions = { from: tempAcc.address, gas: '1000000' }; + + contractDeployed = await contract.deploy(deployOptions).send(sendOptions); + }); + beforeEach(() => { + web3Eth.defaultReturnFormat = DEFAULT_RETURN_FORMAT; + }); + + afterAll(async () => { + await closeOpenConnection(web3Eth); + await closeOpenConnection(contract); + }); + + describe('methods', () => { + it.each(Object.values(FMT_NUMBER))('getBlockNumber', async format => { + web3Eth.defaultReturnFormat = { number: format as FMT_NUMBER, bytes: FMT_BYTES.HEX }; + const res = await web3Eth.getBlockNumber(); + expect(typeof res).toBe(mapFormatToType[format as string]); + expect(parseInt(String(res), 16)).toBeGreaterThan(0); + }); + + it.each(Object.values(FMT_NUMBER))('getGasPrice', async format => { + web3Eth.defaultReturnFormat = { number: format as FMT_NUMBER, bytes: FMT_BYTES.HEX }; + const res = await web3Eth.getGasPrice(); + expect(typeof res).toBe(mapFormatToType[format as string]); + expect(parseInt(String(res), 16)).toBeGreaterThan(0); + }); + + it.each(Object.values(FMT_NUMBER))('getBalance', async format => { + web3Eth.defaultReturnFormat = { number: format as FMT_NUMBER, bytes: FMT_BYTES.HEX }; + const value = '0xa'; + const newAccount = await createNewAccount(); + await web3Eth.sendTransaction({ + to: newAccount.address, + value, + from: tempAcc.address, + }); + const res = await web3Eth.getBalance(newAccount.address); + expect(typeof res).toBe(mapFormatToType[format as string]); + expect(numberToHex(res)).toBe(value); + }); + + it.each(Object.values(FMT_BYTES))('getCode', async format => { + web3Eth.defaultReturnFormat = { number: FMT_NUMBER.BIGINT, bytes: format }; + const code = await web3Eth.getCode(contractDeployed?.options?.address as string); + expect(code).toBeDefined(); + expect(typeof code).toBe(mapFormatToType[format as string]); + }); + + it.each(Object.values(FMT_NUMBER))('getChainId', async format => { + web3Eth.defaultReturnFormat = { number: format as FMT_NUMBER, bytes: FMT_BYTES.HEX }; + const res = await web3Eth.getChainId(); + expect(typeof res).toBe(mapFormatToType[format as string]); + expect(Number(res)).toBeGreaterThan(0); + }); + }); +}); diff --git a/packages/web3-eth/test/integration/helper.ts b/packages/web3-eth/test/integration/helper.ts index 46063294702..4a12b288055 100644 --- a/packages/web3-eth/test/integration/helper.ts +++ b/packages/web3-eth/test/integration/helper.ts @@ -14,13 +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 { - AbiEventFragment, - Block, - TransactionInfo, - TransactionReceipt, - FMT_NUMBER, -} from 'web3-types'; +import { AbiEventFragment, Block, TransactionInfo, TransactionReceipt } from 'web3-types'; // eslint-disable-next-line import/no-extraneous-dependencies import Web3 from 'web3'; import { BasicAbi } from '../shared_fixtures/build/Basic'; @@ -130,12 +124,6 @@ export const validateReceipt = (r: TransactionReceipt) => { expect(Number(r.gasUsed)).toBeGreaterThan(0); }; -export const mapFormatToType: { [key: string]: string } = { - [FMT_NUMBER.NUMBER]: 'number', - [FMT_NUMBER.HEX]: 'string', - [FMT_NUMBER.STR]: 'string', - [FMT_NUMBER.BIGINT]: 'bigint', -}; // eslint-disable-next-line @typescript-eslint/no-non-null-assertion export const eventAbi: AbiEventFragment = BasicAbi.find((e: any) => { return e.name === 'StringEvent' && (e as AbiEventFragment).type === 'event'; diff --git a/packages/web3-eth/test/integration/rpc.test.ts b/packages/web3-eth/test/integration/rpc.test.ts index d9ca6e5676b..d273d4cd261 100644 --- a/packages/web3-eth/test/integration/rpc.test.ts +++ b/packages/web3-eth/test/integration/rpc.test.ts @@ -37,16 +37,12 @@ import { itIf, createTempAccount, describeIf, - BACKEND + mapFormatToType, + BACKEND, } from '../fixtures/system_test_utils'; import { BasicAbi, BasicBytecode } from '../shared_fixtures/build/Basic'; -import { - eventAbi, - mapFormatToType, - sendFewTxes, - validateReceipt, - validateTransaction, -} from './helper'; +import { eventAbi, sendFewTxes, validateReceipt, validateTransaction } from './helper'; +import { describe } from 'node:test'; describe('rpc', () => { let web3Eth: Web3Eth; @@ -86,11 +82,14 @@ describe('rpc', () => { }); describe('methods', () => { - itIf(!['geth', 'hardhat'].includes(getSystemTestBackend()))('getProtocolVersion', async () => { - const version = await web3Eth.getProtocolVersion(); - // eslint-disable-next-line jest/no-standalone-expect - expect(parseInt(version, 16)).toBeGreaterThan(0); - }); + itIf(!['geth', 'hardhat'].includes(getSystemTestBackend()))( + 'getProtocolVersion', + async () => { + const version = await web3Eth.getProtocolVersion(); + // eslint-disable-next-line jest/no-standalone-expect + expect(parseInt(version, 16)).toBeGreaterThan(0); + }, + ); // TODO:in beta, test eth_syncing during sync mode with return obj having ( startingblock, currentBlock, heighestBlock ) it('isSyncing', async () => { @@ -113,20 +112,20 @@ describe('rpc', () => { expect(isMining).toBe(true); }); - describeIf(getSystemTestBackend() !== BACKEND.HARDHAT)('getHashRate', () => { + describeIf(getSystemTestBackend() !== BACKEND.HARDHAT)('getHashRate', () => { it.each(Object.values(FMT_NUMBER))('getHashRate', async format => { const hashRate = await web3Eth.getHashRate({ number: format as FMT_NUMBER, bytes: FMT_BYTES.HEX, }); // eslint-disable-next-line jest/no-standalone-expect - expect(typeof hashRate).toBe(mapFormatToType[format as string]); + expect(typeof hashRate).toBe(mapFormatToType[format as string]); }); - }) + }); it('getAccounts', async () => { // hardhat does not have support importrawkey, so we can't add new accounts rather just check the default 20 accounts - if (getSystemTestBackend() !== BACKEND.HARDHAT) { + if (getSystemTestBackend() !== BACKEND.HARDHAT) { const account = await createNewAccount({ unlock: true }); const accList = await web3Eth.getAccounts(); const accListLowerCase = accList.map((add: string) => add.toLowerCase()); diff --git a/packages/web3/test/integration/web3.format.test.ts b/packages/web3/test/integration/web3.format.test.ts new file mode 100644 index 00000000000..80303704529 --- /dev/null +++ b/packages/web3/test/integration/web3.format.test.ts @@ -0,0 +1,111 @@ +/* +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 { SupportedProviders, FMT_BYTES, FMT_NUMBER, DEFAULT_RETURN_FORMAT } from 'web3-types'; +import { numberToHex } from 'web3-utils'; +import { Web3, Contract } from '../../src'; + +import { + closeOpenConnection, + getSystemTestProvider, + createNewAccount, + createTempAccount, + mapFormatToType, +} from '../shared_fixtures/system_tests_utils'; +import { BasicAbi, BasicBytecode } from '../shared_fixtures/build/Basic'; +import { describe } from 'node:test'; + +describe('format', () => { + let web3: Web3; + let clientUrl: string | SupportedProviders; + let contractDeployed: Contract; + let contract: Contract; + let deployOptions: Record; + let sendOptions: Record; + let tempAcc: { address: string; privateKey: string }; + beforeAll(async () => { + clientUrl = getSystemTestProvider(); + web3 = new Web3({ + provider: clientUrl, + config: { + transactionPollingTimeout: 2000, + }, + }); + contract = new web3.eth.Contract(BasicAbi); + + deployOptions = { + data: BasicBytecode, + arguments: [10, 'string init value'], + }; + tempAcc = await createTempAccount(); + sendOptions = { from: tempAcc.address, gas: '1000000' }; + + contractDeployed = await contract.deploy(deployOptions).send(sendOptions); + }); + beforeEach(() => { + web3.defaultReturnFormat = DEFAULT_RETURN_FORMAT; + }); + + afterAll(async () => { + await closeOpenConnection(web3); + }); + + describe('methods', () => { + it.each(Object.values(FMT_NUMBER))('getBlockNumber', async format => { + web3.defaultReturnFormat = { number: format as FMT_NUMBER, bytes: FMT_BYTES.HEX }; + const res = await web3.eth.getBlockNumber(); + expect(typeof res).toBe(mapFormatToType[format as string]); + expect(parseInt(String(res), 16)).toBeGreaterThan(0); + }); + + it.each(Object.values(FMT_NUMBER))('getGasPrice', async format => { + web3.defaultReturnFormat = { number: format as FMT_NUMBER, bytes: FMT_BYTES.HEX }; + const res = await web3.eth.getGasPrice(); + expect(typeof res).toBe(mapFormatToType[format as string]); + expect(parseInt(String(res), 16)).toBeGreaterThan(0); + }); + + it.each(Object.values(FMT_NUMBER))('getBalance', async format => { + web3.defaultReturnFormat = { number: format as FMT_NUMBER, bytes: FMT_BYTES.HEX }; + const value = '0xa'; + const newAccount = await createNewAccount(); + await web3.eth.sendTransaction({ + to: newAccount.address, + value, + from: tempAcc.address, + }); + const res = await web3.eth.getBalance(newAccount.address); + expect(typeof res).toBe(mapFormatToType[format as string]); + expect(numberToHex(res)).toBe(value); + }); + + it.each(Object.values(FMT_BYTES))('getCode', async format => { + web3.defaultReturnFormat = { number: FMT_NUMBER.BIGINT, bytes: format }; + const code = await web3.eth.getCode(contractDeployed?.options?.address as string); + expect(code).toBeDefined(); + expect(typeof code).toBe(mapFormatToType[format as string]); + }); + + it.each(Object.values(FMT_NUMBER))('getChainId', async format => { + web3.defaultReturnFormat = { number: format as FMT_NUMBER, bytes: FMT_BYTES.HEX }; + + const res = await web3.eth.getChainId(); + expect(typeof res).toBe(mapFormatToType[format as string]); + expect(Number(res)).toBeGreaterThan(0); + }); + }); +}); diff --git a/scripts/system_tests_utils.ts b/scripts/system_tests_utils.ts index a502c44825e..da58fc19d91 100644 --- a/scripts/system_tests_utils.ts +++ b/scripts/system_tests_utils.ts @@ -48,6 +48,8 @@ import { SupportedProviders, Web3APISpec, Web3EthExecutionAPI, + FMT_NUMBER, + FMT_BYTES, } from 'web3-types'; // eslint-disable-next-line import/no-extraneous-dependencies import { Personal } from 'web3-eth-personal'; @@ -504,3 +506,12 @@ export const objectBigintToString = (obj: object): object => // eslint-disable-next-line @typescript-eslint/no-unsafe-return JSON.stringify(obj, (_, value) => (typeof value === 'bigint' ? value.toString() : value)), ); + +export const mapFormatToType: { [key: string]: string } = { + [FMT_NUMBER.NUMBER]: 'number', + [FMT_NUMBER.HEX]: 'string', + [FMT_NUMBER.STR]: 'string', + [FMT_NUMBER.BIGINT]: 'bigint', + [FMT_BYTES.HEX]: 'string', + [FMT_BYTES.UINT8ARRAY]: 'object', +}; From 95de1c7babfb58d975b76393e8115a8c11a9e3ee Mon Sep 17 00:00:00 2001 From: Oleksii Kosynskyi Date: Mon, 1 Apr 2024 18:13:54 +0200 Subject: [PATCH 04/21] lint fix --- .../web3-eth/test/integration/format.test.ts | 12 +++---- .../web3-eth/test/integration/rpc.test.ts | 32 +++++++++---------- .../web3/test/integration/web3.format.test.ts | 12 +++---- 3 files changed, 28 insertions(+), 28 deletions(-) diff --git a/packages/web3-eth/test/integration/format.test.ts b/packages/web3-eth/test/integration/format.test.ts index 647ea4351af..10761f1ae90 100644 --- a/packages/web3-eth/test/integration/format.test.ts +++ b/packages/web3-eth/test/integration/format.test.ts @@ -20,6 +20,7 @@ import { SupportedProviders, FMT_BYTES, FMT_NUMBER, DEFAULT_RETURN_FORMAT } from import { Contract } from 'web3-eth-contract'; import { numberToHex } from 'web3-utils'; // eslint-disable-next-line import/no-extraneous-dependencies +import { describe } from 'node:test'; import { Web3Eth } from '../../src'; import { @@ -30,7 +31,6 @@ import { mapFormatToType, } from '../fixtures/system_test_utils'; import { BasicAbi, BasicBytecode } from '../shared_fixtures/build/Basic'; -import { describe } from 'node:test'; describe('format', () => { let web3Eth: Web3Eth; @@ -71,21 +71,21 @@ describe('format', () => { }); describe('methods', () => { - it.each(Object.values(FMT_NUMBER))('getBlockNumber', async format => { + test.each(Object.values(FMT_NUMBER))('getBlockNumber', async format => { web3Eth.defaultReturnFormat = { number: format as FMT_NUMBER, bytes: FMT_BYTES.HEX }; const res = await web3Eth.getBlockNumber(); expect(typeof res).toBe(mapFormatToType[format as string]); expect(parseInt(String(res), 16)).toBeGreaterThan(0); }); - it.each(Object.values(FMT_NUMBER))('getGasPrice', async format => { + test.each(Object.values(FMT_NUMBER))('getGasPrice', async format => { web3Eth.defaultReturnFormat = { number: format as FMT_NUMBER, bytes: FMT_BYTES.HEX }; const res = await web3Eth.getGasPrice(); expect(typeof res).toBe(mapFormatToType[format as string]); expect(parseInt(String(res), 16)).toBeGreaterThan(0); }); - it.each(Object.values(FMT_NUMBER))('getBalance', async format => { + test.each(Object.values(FMT_NUMBER))('getBalance', async format => { web3Eth.defaultReturnFormat = { number: format as FMT_NUMBER, bytes: FMT_BYTES.HEX }; const value = '0xa'; const newAccount = await createNewAccount(); @@ -99,14 +99,14 @@ describe('format', () => { expect(numberToHex(res)).toBe(value); }); - it.each(Object.values(FMT_BYTES))('getCode', async format => { + test.each(Object.values(FMT_BYTES))('getCode', async format => { web3Eth.defaultReturnFormat = { number: FMT_NUMBER.BIGINT, bytes: format }; const code = await web3Eth.getCode(contractDeployed?.options?.address as string); expect(code).toBeDefined(); expect(typeof code).toBe(mapFormatToType[format as string]); }); - it.each(Object.values(FMT_NUMBER))('getChainId', async format => { + test.each(Object.values(FMT_NUMBER))('getChainId', async format => { web3Eth.defaultReturnFormat = { number: format as FMT_NUMBER, bytes: FMT_BYTES.HEX }; const res = await web3Eth.getChainId(); expect(typeof res).toBe(mapFormatToType[format as string]); diff --git a/packages/web3-eth/test/integration/rpc.test.ts b/packages/web3-eth/test/integration/rpc.test.ts index d273d4cd261..b9e989c22a3 100644 --- a/packages/web3-eth/test/integration/rpc.test.ts +++ b/packages/web3-eth/test/integration/rpc.test.ts @@ -27,6 +27,7 @@ import { import { Contract, decodeEventABI } from 'web3-eth-contract'; import { hexToNumber, hexToString, numberToHex, getStorageSlotNumForLongString } from 'web3-utils'; // eslint-disable-next-line import/no-extraneous-dependencies +import { describe } from 'node:test'; import { Web3Eth } from '../../src'; import { @@ -42,7 +43,6 @@ import { } from '../fixtures/system_test_utils'; import { BasicAbi, BasicBytecode } from '../shared_fixtures/build/Basic'; import { eventAbi, sendFewTxes, validateReceipt, validateTransaction } from './helper'; -import { describe } from 'node:test'; describe('rpc', () => { let web3Eth: Web3Eth; @@ -92,13 +92,13 @@ describe('rpc', () => { ); // TODO:in beta, test eth_syncing during sync mode with return obj having ( startingblock, currentBlock, heighestBlock ) - it('isSyncing', async () => { + test('isSyncing', async () => { const isSyncing = await web3Eth.isSyncing(); expect(isSyncing).toBe(false); }); // TODO: in future release, set coinbase account in node and match actual address here - it('getCoinbase', async () => { + test('getCoinbase', async () => { const coinbase = await web3Eth.getCoinbase(); expect(coinbase.startsWith('0x')).toBe(true); expect(coinbase).toHaveLength(42); @@ -113,7 +113,7 @@ describe('rpc', () => { }); describeIf(getSystemTestBackend() !== BACKEND.HARDHAT)('getHashRate', () => { - it.each(Object.values(FMT_NUMBER))('getHashRate', async format => { + test.each(Object.values(FMT_NUMBER))('getHashRate', async format => { const hashRate = await web3Eth.getHashRate({ number: format as FMT_NUMBER, bytes: FMT_BYTES.HEX, @@ -123,7 +123,7 @@ describe('rpc', () => { }); }); - it('getAccounts', async () => { + test('getAccounts', async () => { // hardhat does not have support importrawkey, so we can't add new accounts rather just check the default 20 accounts if (getSystemTestBackend() !== BACKEND.HARDHAT) { const account = await createNewAccount({ unlock: true }); @@ -138,7 +138,7 @@ describe('rpc', () => { } }); - it.each(Object.values(FMT_NUMBER))('getBlockNumber', async format => { + test.each(Object.values(FMT_NUMBER))('getBlockNumber', async format => { const res = await web3Eth.getBlockNumber({ number: format as FMT_NUMBER, bytes: FMT_BYTES.HEX, @@ -147,7 +147,7 @@ describe('rpc', () => { expect(parseInt(String(res), 16)).toBeGreaterThan(0); }); - it.each(Object.values(FMT_NUMBER))('getGasPrice', async format => { + test.each(Object.values(FMT_NUMBER))('getGasPrice', async format => { const res = await web3Eth.getGasPrice({ number: format as FMT_NUMBER, bytes: FMT_BYTES.HEX, @@ -156,7 +156,7 @@ describe('rpc', () => { expect(parseInt(String(res), 16)).toBeGreaterThan(0); }); - it.each(Object.values(FMT_NUMBER))('getBalance', async format => { + test.each(Object.values(FMT_NUMBER))('getBalance', async format => { const value = '0xa'; const newAccount = await createNewAccount(); await web3Eth.sendTransaction({ @@ -173,7 +173,7 @@ describe('rpc', () => { expect(numberToHex(res)).toBe(value); }); - it('getStorageAt', async () => { + test('getStorageAt', async () => { const numberData = 10; const stringData = 'str'; const boolData = true; @@ -247,7 +247,7 @@ describe('rpc', () => { expect(stringDataLong).toBe(str); }); - it.each(Object.values(FMT_NUMBER))('getCode', async format => { + test.each(Object.values(FMT_NUMBER))('getCode', async format => { const code = await web3Eth.getCode( contractDeployed?.options?.address as string, undefined, @@ -260,7 +260,7 @@ describe('rpc', () => { expect(BasicBytecode.slice(-100)).toBe(code.slice(-100)); }); - it('getTransaction', async () => { + test('getTransaction', async () => { const [receipt] = await sendFewTxes({ from: tempAcc.address, value: '0x1', @@ -276,7 +276,7 @@ describe('rpc', () => { validateTransaction(res as TransactionInfo); expect(res?.hash).toBe(receipt.transactionHash); }); - it('check get transaction fields', async () => { + test('check get transaction fields', async () => { const receipt0 = await web3Eth.sendTransaction({ from: tempAcc.address, value: '0x1', @@ -375,7 +375,7 @@ describe('rpc', () => { expect(res).toBeDefined(); }); - it('getTransactionReceipt', async () => { + test('getTransactionReceipt', async () => { const [receipt] = await sendFewTxes({ from: tempAcc.address, value: '0x1', @@ -390,7 +390,7 @@ describe('rpc', () => { expect(res?.transactionHash).toBe(receipt.transactionHash); }); - it('getChainId', async () => { + test('getChainId', async () => { const res = await web3Eth.getChainId({ number: FMT_NUMBER.NUMBER, bytes: FMT_BYTES.HEX, @@ -399,7 +399,7 @@ describe('rpc', () => { expect(Number(res)).toBeGreaterThan(0); }); - it('getNodeInfo', async () => { + test('getNodeInfo', async () => { const res = await web3Eth.getNodeInfo(); // TODO: in next release, it should also be validated expect(res).toBeDefined(); @@ -432,7 +432,7 @@ describe('rpc', () => { expect(res.storageProof[0].value).toBe(numberData); }); - it('getPastLogs', async () => { + test('getPastLogs', async () => { const listOfStrings = ['t1', 't2', 't3']; const resTx = []; for (const l of listOfStrings) { diff --git a/packages/web3/test/integration/web3.format.test.ts b/packages/web3/test/integration/web3.format.test.ts index 80303704529..cf21cffdca2 100644 --- a/packages/web3/test/integration/web3.format.test.ts +++ b/packages/web3/test/integration/web3.format.test.ts @@ -17,6 +17,7 @@ along with web3.js. If not, see . import { SupportedProviders, FMT_BYTES, FMT_NUMBER, DEFAULT_RETURN_FORMAT } from 'web3-types'; import { numberToHex } from 'web3-utils'; +import { describe } from 'node:test'; import { Web3, Contract } from '../../src'; import { @@ -27,7 +28,6 @@ import { mapFormatToType, } from '../shared_fixtures/system_tests_utils'; import { BasicAbi, BasicBytecode } from '../shared_fixtures/build/Basic'; -import { describe } from 'node:test'; describe('format', () => { let web3: Web3; @@ -65,21 +65,21 @@ describe('format', () => { }); describe('methods', () => { - it.each(Object.values(FMT_NUMBER))('getBlockNumber', async format => { + test.each(Object.values(FMT_NUMBER))('getBlockNumber', async format => { web3.defaultReturnFormat = { number: format as FMT_NUMBER, bytes: FMT_BYTES.HEX }; const res = await web3.eth.getBlockNumber(); expect(typeof res).toBe(mapFormatToType[format as string]); expect(parseInt(String(res), 16)).toBeGreaterThan(0); }); - it.each(Object.values(FMT_NUMBER))('getGasPrice', async format => { + test.each(Object.values(FMT_NUMBER))('getGasPrice', async format => { web3.defaultReturnFormat = { number: format as FMT_NUMBER, bytes: FMT_BYTES.HEX }; const res = await web3.eth.getGasPrice(); expect(typeof res).toBe(mapFormatToType[format as string]); expect(parseInt(String(res), 16)).toBeGreaterThan(0); }); - it.each(Object.values(FMT_NUMBER))('getBalance', async format => { + test.each(Object.values(FMT_NUMBER))('getBalance', async format => { web3.defaultReturnFormat = { number: format as FMT_NUMBER, bytes: FMT_BYTES.HEX }; const value = '0xa'; const newAccount = await createNewAccount(); @@ -93,14 +93,14 @@ describe('format', () => { expect(numberToHex(res)).toBe(value); }); - it.each(Object.values(FMT_BYTES))('getCode', async format => { + test.each(Object.values(FMT_BYTES))('getCode', async format => { web3.defaultReturnFormat = { number: FMT_NUMBER.BIGINT, bytes: format }; const code = await web3.eth.getCode(contractDeployed?.options?.address as string); expect(code).toBeDefined(); expect(typeof code).toBe(mapFormatToType[format as string]); }); - it.each(Object.values(FMT_NUMBER))('getChainId', async format => { + test.each(Object.values(FMT_NUMBER))('getChainId', async format => { web3.defaultReturnFormat = { number: format as FMT_NUMBER, bytes: FMT_BYTES.HEX }; const res = await web3.eth.getChainId(); From b4e4fe5eb85629b7a24d23c504eb425f7daa3176 Mon Sep 17 00:00:00 2001 From: Oleksii Kosynskyi Date: Tue, 2 Apr 2024 12:30:30 +0200 Subject: [PATCH 05/21] add types and docs --- docs/docs/guides/web3_config/index.md | 45 ++++++++++++++++++- packages/web3/src/types.ts | 2 +- .../web3/test/integration/web3.format.test.ts | 4 +- 3 files changed, 47 insertions(+), 4 deletions(-) diff --git a/docs/docs/guides/web3_config/index.md b/docs/docs/guides/web3_config/index.md index ea061762968..20d08b6dde4 100644 --- a/docs/docs/guides/web3_config/index.md +++ b/docs/docs/guides/web3_config/index.md @@ -27,6 +27,7 @@ There is list of configuration params that can be set for modifying behavior of - [defaultHardfork](/api/web3-core/class/Web3Config#defaultHardfork) - [defaultCommon](/api/web3-core/class/Web3Config#defaultCommon) - [defaultTransactionType](/api/web3-core/class/Web3Config#defaultTransactionType) +- [defaultReturnFormat](/api/web3-core/class/Web3Config#defaultReturnFormat) ## Global level Config @@ -198,4 +199,46 @@ console.log(web3.getContextObject().config) transactionPollingTimeout: 750000, ... */ -``` \ No newline at end of file +``` + + +### defaultReturnFormat +The `defaultReturnFormat` allows users to specify the format in which certain types of data should be returned by default. It is a configuration parameter that can be set at the global level and affects how data is returned across the entire library. +```ts +import { Web3, FMT_NUMBER, FMT_BYTES } from 'web3'; + +web3.defaultReturnFormat = { + number: FMT_NUMBER.BIGINT, + bytes: FMT_BYTES.HEX, +}; + +``` +:::info +The `defaultReturnFormat` can be configured both globally and at the package level: +```ts +import { Web3Eth, FMT_NUMBER, FMT_BYTES } from 'web3-eth'; + +const eth = new Web3Eth() +eth.defaultReturnFormat = { + number: FMT_NUMBER.BIGINT, + bytes: FMT_BYTES.HEX, +}; + +``` +::: +#### All available choices for numeric data: +```ts +export enum FMT_NUMBER { + NUMBER = 'NUMBER_NUMBER', + HEX = 'NUMBER_HEX', + STR = 'NUMBER_STR', + BIGINT = 'NUMBER_BIGINT', +} +``` +#### All available choices for bytes data: +```ts +export enum FMT_BYTES { + HEX = 'BYTES_HEX', + UINT8ARRAY = 'BYTES_UINT8ARRAY', +} +``` diff --git a/packages/web3/src/types.ts b/packages/web3/src/types.ts index fb14e6b2e1a..003135a97d9 100644 --- a/packages/web3/src/types.ts +++ b/packages/web3/src/types.ts @@ -41,7 +41,7 @@ import { ENS } from 'web3-eth-ens'; import { Net } from 'web3-net'; import { Iban } from 'web3-eth-iban'; import { Personal } from 'web3-eth-personal'; - +export { FMT_BYTES, FMT_NUMBER } from 'web3-types'; /** * The Ethereum interface for main web3 object. It provides extra methods in addition to `web3-eth` interface. * diff --git a/packages/web3/test/integration/web3.format.test.ts b/packages/web3/test/integration/web3.format.test.ts index cf21cffdca2..17b4da38275 100644 --- a/packages/web3/test/integration/web3.format.test.ts +++ b/packages/web3/test/integration/web3.format.test.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 { SupportedProviders, FMT_BYTES, FMT_NUMBER, DEFAULT_RETURN_FORMAT } from 'web3-types'; +import { SupportedProviders, DEFAULT_RETURN_FORMAT } from 'web3-types'; import { numberToHex } from 'web3-utils'; import { describe } from 'node:test'; -import { Web3, Contract } from '../../src'; +import { Web3, Contract, FMT_BYTES, FMT_NUMBER } from '../../src'; import { closeOpenConnection, From 33dec1a58523c9cb43148af0589a027fd074da92 Mon Sep 17 00:00:00 2001 From: Oleksii Kosynskyi Date: Tue, 2 Apr 2024 12:34:28 +0200 Subject: [PATCH 06/21] fix --- .../web3-eth/test/fixtures/web3_eth_methods_with_parameters.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/packages/web3-eth/test/fixtures/web3_eth_methods_with_parameters.ts b/packages/web3-eth/test/fixtures/web3_eth_methods_with_parameters.ts index dc16ed1bb2d..17d9c204f21 100644 --- a/packages/web3-eth/test/fixtures/web3_eth_methods_with_parameters.ts +++ b/packages/web3-eth/test/fixtures/web3_eth_methods_with_parameters.ts @@ -30,7 +30,6 @@ import { Uint256, TransactionWithSenderAPI, TransactionReceipt, - FMT_BYTES, } from 'web3-types'; import { transactionWithSender } from './rpc_methods_wrappers'; From 22362e890bf05bae14c425d9a65a4fb20d55cb63 Mon Sep 17 00:00:00 2001 From: Oleksii Kosynskyi Date: Tue, 2 Apr 2024 12:38:39 +0200 Subject: [PATCH 07/21] fix --- packages/web3/src/types.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/web3/src/types.ts b/packages/web3/src/types.ts index 003135a97d9..fb14e6b2e1a 100644 --- a/packages/web3/src/types.ts +++ b/packages/web3/src/types.ts @@ -41,7 +41,7 @@ import { ENS } from 'web3-eth-ens'; import { Net } from 'web3-net'; import { Iban } from 'web3-eth-iban'; import { Personal } from 'web3-eth-personal'; -export { FMT_BYTES, FMT_NUMBER } from 'web3-types'; + /** * The Ethereum interface for main web3 object. It provides extra methods in addition to `web3-eth` interface. * From 96f7cf6f75781a1a1ec3a88aa00fd4f6f0394034 Mon Sep 17 00:00:00 2001 From: Oleksii Kosynskyi Date: Tue, 2 Apr 2024 12:48:39 +0200 Subject: [PATCH 08/21] add changelog --- CHANGELOG.md | 32 ++++++++++++++++++++++++- packages/web3-core/CHANGELOG.md | 5 +++- packages/web3-eth-contract/CHANGELOG.md | 3 +++ packages/web3-eth-ens/CHANGELOG.md | 5 +++- packages/web3-eth/CHANGELOG.md | 5 +++- packages/web3-net/CHANGELOG.md | 5 +++- packages/web3-utils/src/formatter.ts | 11 ++------- 7 files changed, 52 insertions(+), 14 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 34609aba1c0..0892287cdd9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2405,4 +2405,34 @@ If there are any bugs, improvements, optimizations or any new feature proposal f - fixed erroneous parsing of big numbers in the `toNumber(...)` function (#6880) -## [Unreleased] \ No newline at end of file +## [Unreleased] +### Added + +#### web3-core + +- `defaultReturnFormat` was added to the configuration options. (#6947) + +#### web3-eth + +- `defaultReturnFormat` was added to all methods that have `ReturnType` param. (#6947) + +#### web3-eth-contract + +- `defaultReturnFormat` was added to all methods that have `ReturnType` param. (#6947) + +#### web3-eth-ens + +- `defaultReturnFormat` was added to all methods that have `ReturnType` param. (#6947) + +#### web3-net + +- `defaultReturnFormat` was added to all methods that have `ReturnType` param. (#6947) + +#### web3-types + +- Added `signature` to type `AbiFunctionFragment` (#6922) + +### Fixed + +#### web3-eth-contract + diff --git a/packages/web3-core/CHANGELOG.md b/packages/web3-core/CHANGELOG.md index 39d574bcd43..31f03f1aa62 100644 --- a/packages/web3-core/CHANGELOG.md +++ b/packages/web3-core/CHANGELOG.md @@ -207,4 +207,7 @@ Documentation: - Web3config `contractDataInputFill` has been defaulted to `data`, istead of `input`. (#6622) -## [Unreleased] \ No newline at end of file +## [Unreleased] + +### Added +- `defaultReturnFormat` was added to the configuration options. (#6947) diff --git a/packages/web3-eth-contract/CHANGELOG.md b/packages/web3-eth-contract/CHANGELOG.md index 9aae3aa558e..b3be7ba75a7 100644 --- a/packages/web3-eth-contract/CHANGELOG.md +++ b/packages/web3-eth-contract/CHANGELOG.md @@ -375,3 +375,6 @@ Documentation: ### Fixed - Fix an issue with smart contract function overloading (#6922) + +### Added +- `defaultReturnFormat` was added to all methods that have `ReturnType` param. (#6947) diff --git a/packages/web3-eth-ens/CHANGELOG.md b/packages/web3-eth-ens/CHANGELOG.md index c0212f7f121..c40b2727d5e 100644 --- a/packages/web3-eth-ens/CHANGELOG.md +++ b/packages/web3-eth-ens/CHANGELOG.md @@ -153,4 +153,7 @@ Documentation: - Added function getText and getName in ENS and resolver classes (#6914) -## [Unreleased] \ No newline at end of file +## [Unreleased] + +### Added +- `defaultReturnFormat` was added to all methods that have `ReturnType` param. (#6947) diff --git a/packages/web3-eth/CHANGELOG.md b/packages/web3-eth/CHANGELOG.md index 90ad4805704..deeea43fc55 100644 --- a/packages/web3-eth/CHANGELOG.md +++ b/packages/web3-eth/CHANGELOG.md @@ -225,4 +225,7 @@ Documentation: - Added `eth.getMaxPriorityFeePerGas` method (#6748) -## [Unreleased] \ No newline at end of file +## [Unreleased] + +### Added +- `defaultReturnFormat` was added to all methods that have `ReturnType` param. (#6947) diff --git a/packages/web3-net/CHANGELOG.md b/packages/web3-net/CHANGELOG.md index dd6227ecdd8..d60abde6313 100644 --- a/packages/web3-net/CHANGELOG.md +++ b/packages/web3-net/CHANGELOG.md @@ -141,4 +141,7 @@ Documentation: - Dependencies updated -## [Unreleased] \ No newline at end of file +## [Unreleased] + +### Added +- `defaultReturnFormat` was added to all methods that have `ReturnType` param. (#6947) diff --git a/packages/web3-utils/src/formatter.ts b/packages/web3-utils/src/formatter.ts index 0a8ca3b723f..1901e1fde21 100644 --- a/packages/web3-utils/src/formatter.ts +++ b/packages/web3-utils/src/formatter.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 { FormatterError } from 'web3-errors'; -import { - Bytes, - DataFormat, - FMT_BYTES, - FMT_NUMBER, - FormatType, - DEFAULT_RETURN_FORMAT, -} from 'web3-types'; +import { Bytes, DataFormat, FMT_BYTES, FMT_NUMBER, FormatType } from 'web3-types'; import { isNullish, isObject, JsonSchema, utils, ValidationSchemaInput } from 'web3-validator'; import { bytesToUint8Array, bytesToHex, numberToHex, toBigInt } from './converters.js'; import { mergeDeep } from './objects.js'; @@ -284,7 +277,7 @@ export const format = < >( schema: ValidationSchemaInput | JsonSchema, data: DataType, - returnFormat: ReturnType = DEFAULT_RETURN_FORMAT as ReturnType, + returnFormat: ReturnType, ): FormatType => { let dataToParse: Record | unknown[] | unknown; From b27ea84cd1c4562d812cecd65195b2767b6953e7 Mon Sep 17 00:00:00 2001 From: Oleksii Kosynskyi Date: Tue, 2 Apr 2024 12:51:22 +0200 Subject: [PATCH 09/21] add changelog --- CHANGELOG.md | 7 +++++++ packages/web3-utils/CHANGELOG.md | 5 ++++- packages/web3-utils/src/formatter.ts | 11 +++++++++-- 3 files changed, 20 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0892287cdd9..8db41aa4efc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2407,6 +2407,7 @@ If there are any bugs, improvements, optimizations or any new feature proposal f ## [Unreleased] ### Added +### Added #### web3-core @@ -2436,3 +2437,9 @@ If there are any bugs, improvements, optimizations or any new feature proposal f #### web3-eth-contract + +### Changed + +#### web3-utils + +- Method `format` was changed. Now it has default value `DEFAULT_RETURN_FORMAT` for `returnFormat` parameter (#6947) diff --git a/packages/web3-utils/CHANGELOG.md b/packages/web3-utils/CHANGELOG.md index f3a240fde97..8247bd787a0 100644 --- a/packages/web3-utils/CHANGELOG.md +++ b/packages/web3-utils/CHANGELOG.md @@ -205,4 +205,7 @@ Documentation: - fixed erroneous parsing of big numbers in the `toNumber(...)` function (#6880) -## [Unreleased] \ No newline at end of file +## [Unreleased] + +### Changed +- Method `format` was changed. Now it has default value `DEFAULT_RETURN_FORMAT` for `returnFormat` parameter (#6947) diff --git a/packages/web3-utils/src/formatter.ts b/packages/web3-utils/src/formatter.ts index 1901e1fde21..0a8ca3b723f 100644 --- a/packages/web3-utils/src/formatter.ts +++ b/packages/web3-utils/src/formatter.ts @@ -15,7 +15,14 @@ You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see . */ import { FormatterError } from 'web3-errors'; -import { Bytes, DataFormat, FMT_BYTES, FMT_NUMBER, FormatType } from 'web3-types'; +import { + Bytes, + DataFormat, + FMT_BYTES, + FMT_NUMBER, + FormatType, + DEFAULT_RETURN_FORMAT, +} from 'web3-types'; import { isNullish, isObject, JsonSchema, utils, ValidationSchemaInput } from 'web3-validator'; import { bytesToUint8Array, bytesToHex, numberToHex, toBigInt } from './converters.js'; import { mergeDeep } from './objects.js'; @@ -277,7 +284,7 @@ export const format = < >( schema: ValidationSchemaInput | JsonSchema, data: DataType, - returnFormat: ReturnType, + returnFormat: ReturnType = DEFAULT_RETURN_FORMAT as ReturnType, ): FormatType => { let dataToParse: Record | unknown[] | unknown; From e0733f4977ee0d3030f5476049531c40c295fde5 Mon Sep 17 00:00:00 2001 From: Oleksii Kosynskyi Date: Tue, 2 Apr 2024 14:32:00 +0200 Subject: [PATCH 10/21] fix tests --- packages/web3-eth/test/integration/format.test.ts | 3 --- packages/web3/test/integration/web3.format.test.ts | 3 --- 2 files changed, 6 deletions(-) diff --git a/packages/web3-eth/test/integration/format.test.ts b/packages/web3-eth/test/integration/format.test.ts index 10761f1ae90..6a881d08723 100644 --- a/packages/web3-eth/test/integration/format.test.ts +++ b/packages/web3-eth/test/integration/format.test.ts @@ -61,9 +61,6 @@ describe('format', () => { contractDeployed = await contract.deploy(deployOptions).send(sendOptions); }); - beforeEach(() => { - web3Eth.defaultReturnFormat = DEFAULT_RETURN_FORMAT; - }); afterAll(async () => { await closeOpenConnection(web3Eth); diff --git a/packages/web3/test/integration/web3.format.test.ts b/packages/web3/test/integration/web3.format.test.ts index 17b4da38275..f1c15aa5e1b 100644 --- a/packages/web3/test/integration/web3.format.test.ts +++ b/packages/web3/test/integration/web3.format.test.ts @@ -56,9 +56,6 @@ describe('format', () => { contractDeployed = await contract.deploy(deployOptions).send(sendOptions); }); - beforeEach(() => { - web3.defaultReturnFormat = DEFAULT_RETURN_FORMAT; - }); afterAll(async () => { await closeOpenConnection(web3); From f59e840ff5c8d8b6648f39c4b9508e1f5fa9a12d Mon Sep 17 00:00:00 2001 From: Oleksii Kosynskyi Date: Tue, 2 Apr 2024 14:43:31 +0200 Subject: [PATCH 11/21] fix --- packages/web3-eth/test/integration/format.test.ts | 2 +- packages/web3/test/integration/web3.format.test.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/web3-eth/test/integration/format.test.ts b/packages/web3-eth/test/integration/format.test.ts index 6a881d08723..304f1c6a64b 100644 --- a/packages/web3-eth/test/integration/format.test.ts +++ b/packages/web3-eth/test/integration/format.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 { SupportedProviders, FMT_BYTES, FMT_NUMBER, DEFAULT_RETURN_FORMAT } from 'web3-types'; +import { SupportedProviders, FMT_BYTES, FMT_NUMBER } from 'web3-types'; // eslint-disable-next-line import/no-extraneous-dependencies import { Contract } from 'web3-eth-contract'; import { numberToHex } from 'web3-utils'; diff --git a/packages/web3/test/integration/web3.format.test.ts b/packages/web3/test/integration/web3.format.test.ts index f1c15aa5e1b..3aa2564e2ec 100644 --- a/packages/web3/test/integration/web3.format.test.ts +++ b/packages/web3/test/integration/web3.format.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 { SupportedProviders, DEFAULT_RETURN_FORMAT } from 'web3-types'; +import { SupportedProviders } from 'web3-types'; import { numberToHex } from 'web3-utils'; import { describe } from 'node:test'; import { Web3, Contract, FMT_BYTES, FMT_NUMBER } from '../../src'; From f408e8b63399f7401073f11cbe0dae449e8b3a25 Mon Sep 17 00:00:00 2001 From: Oleksii Kosynskyi Date: Tue, 2 Apr 2024 15:02:34 +0200 Subject: [PATCH 12/21] fix --- packages/web3-eth/test/integration/format.test.ts | 1 - packages/web3/test/integration/web3.format.test.ts | 1 - 2 files changed, 2 deletions(-) diff --git a/packages/web3-eth/test/integration/format.test.ts b/packages/web3-eth/test/integration/format.test.ts index 304f1c6a64b..3ff73214f6e 100644 --- a/packages/web3-eth/test/integration/format.test.ts +++ b/packages/web3-eth/test/integration/format.test.ts @@ -20,7 +20,6 @@ import { SupportedProviders, FMT_BYTES, FMT_NUMBER } from 'web3-types'; import { Contract } from 'web3-eth-contract'; import { numberToHex } from 'web3-utils'; // eslint-disable-next-line import/no-extraneous-dependencies -import { describe } from 'node:test'; import { Web3Eth } from '../../src'; import { diff --git a/packages/web3/test/integration/web3.format.test.ts b/packages/web3/test/integration/web3.format.test.ts index 3aa2564e2ec..f8638133487 100644 --- a/packages/web3/test/integration/web3.format.test.ts +++ b/packages/web3/test/integration/web3.format.test.ts @@ -17,7 +17,6 @@ along with web3.js. If not, see . import { SupportedProviders } from 'web3-types'; import { numberToHex } from 'web3-utils'; -import { describe } from 'node:test'; import { Web3, Contract, FMT_BYTES, FMT_NUMBER } from '../../src'; import { From 38432e400bb85237a0e4c35a290ae35b4f7a7bce Mon Sep 17 00:00:00 2001 From: Oleksii Kosynskyi Date: Tue, 2 Apr 2024 15:04:23 +0200 Subject: [PATCH 13/21] fix --- packages/web3-eth/test/integration/format.test.ts | 10 +++++----- packages/web3/test/integration/web3.format.test.ts | 10 +++++----- 2 files changed, 10 insertions(+), 10 deletions(-) diff --git a/packages/web3-eth/test/integration/format.test.ts b/packages/web3-eth/test/integration/format.test.ts index 3ff73214f6e..b9962c065ff 100644 --- a/packages/web3-eth/test/integration/format.test.ts +++ b/packages/web3-eth/test/integration/format.test.ts @@ -67,21 +67,21 @@ describe('format', () => { }); describe('methods', () => { - test.each(Object.values(FMT_NUMBER))('getBlockNumber', async format => { + it.each(Object.values(FMT_NUMBER))('getBlockNumber', async format => { web3Eth.defaultReturnFormat = { number: format as FMT_NUMBER, bytes: FMT_BYTES.HEX }; const res = await web3Eth.getBlockNumber(); expect(typeof res).toBe(mapFormatToType[format as string]); expect(parseInt(String(res), 16)).toBeGreaterThan(0); }); - test.each(Object.values(FMT_NUMBER))('getGasPrice', async format => { + it.each(Object.values(FMT_NUMBER))('getGasPrice', async format => { web3Eth.defaultReturnFormat = { number: format as FMT_NUMBER, bytes: FMT_BYTES.HEX }; const res = await web3Eth.getGasPrice(); expect(typeof res).toBe(mapFormatToType[format as string]); expect(parseInt(String(res), 16)).toBeGreaterThan(0); }); - test.each(Object.values(FMT_NUMBER))('getBalance', async format => { + it.each(Object.values(FMT_NUMBER))('getBalance', async format => { web3Eth.defaultReturnFormat = { number: format as FMT_NUMBER, bytes: FMT_BYTES.HEX }; const value = '0xa'; const newAccount = await createNewAccount(); @@ -95,14 +95,14 @@ describe('format', () => { expect(numberToHex(res)).toBe(value); }); - test.each(Object.values(FMT_BYTES))('getCode', async format => { + it.each(Object.values(FMT_BYTES))('getCode', async format => { web3Eth.defaultReturnFormat = { number: FMT_NUMBER.BIGINT, bytes: format }; const code = await web3Eth.getCode(contractDeployed?.options?.address as string); expect(code).toBeDefined(); expect(typeof code).toBe(mapFormatToType[format as string]); }); - test.each(Object.values(FMT_NUMBER))('getChainId', async format => { + it.each(Object.values(FMT_NUMBER))('getChainId', async format => { web3Eth.defaultReturnFormat = { number: format as FMT_NUMBER, bytes: FMT_BYTES.HEX }; const res = await web3Eth.getChainId(); expect(typeof res).toBe(mapFormatToType[format as string]); diff --git a/packages/web3/test/integration/web3.format.test.ts b/packages/web3/test/integration/web3.format.test.ts index f8638133487..5496a9efce1 100644 --- a/packages/web3/test/integration/web3.format.test.ts +++ b/packages/web3/test/integration/web3.format.test.ts @@ -61,21 +61,21 @@ describe('format', () => { }); describe('methods', () => { - test.each(Object.values(FMT_NUMBER))('getBlockNumber', async format => { + it.each(Object.values(FMT_NUMBER))('getBlockNumber', async format => { web3.defaultReturnFormat = { number: format as FMT_NUMBER, bytes: FMT_BYTES.HEX }; const res = await web3.eth.getBlockNumber(); expect(typeof res).toBe(mapFormatToType[format as string]); expect(parseInt(String(res), 16)).toBeGreaterThan(0); }); - test.each(Object.values(FMT_NUMBER))('getGasPrice', async format => { + it.each(Object.values(FMT_NUMBER))('getGasPrice', async format => { web3.defaultReturnFormat = { number: format as FMT_NUMBER, bytes: FMT_BYTES.HEX }; const res = await web3.eth.getGasPrice(); expect(typeof res).toBe(mapFormatToType[format as string]); expect(parseInt(String(res), 16)).toBeGreaterThan(0); }); - test.each(Object.values(FMT_NUMBER))('getBalance', async format => { + it.each(Object.values(FMT_NUMBER))('getBalance', async format => { web3.defaultReturnFormat = { number: format as FMT_NUMBER, bytes: FMT_BYTES.HEX }; const value = '0xa'; const newAccount = await createNewAccount(); @@ -89,14 +89,14 @@ describe('format', () => { expect(numberToHex(res)).toBe(value); }); - test.each(Object.values(FMT_BYTES))('getCode', async format => { + it.each(Object.values(FMT_BYTES))('getCode', async format => { web3.defaultReturnFormat = { number: FMT_NUMBER.BIGINT, bytes: format }; const code = await web3.eth.getCode(contractDeployed?.options?.address as string); expect(code).toBeDefined(); expect(typeof code).toBe(mapFormatToType[format as string]); }); - test.each(Object.values(FMT_NUMBER))('getChainId', async format => { + it.each(Object.values(FMT_NUMBER))('getChainId', async format => { web3.defaultReturnFormat = { number: format as FMT_NUMBER, bytes: FMT_BYTES.HEX }; const res = await web3.eth.getChainId(); From ac7e138f271cae3fab433716a52bccd28895fa97 Mon Sep 17 00:00:00 2001 From: Oleksii Kosynskyi Date: Tue, 2 Apr 2024 15:14:13 +0200 Subject: [PATCH 14/21] fix --- .../web3-eth/test/integration/rpc.test.ts | 32 +++++++++---------- 1 file changed, 15 insertions(+), 17 deletions(-) diff --git a/packages/web3-eth/test/integration/rpc.test.ts b/packages/web3-eth/test/integration/rpc.test.ts index b9e989c22a3..eba6792a2f8 100644 --- a/packages/web3-eth/test/integration/rpc.test.ts +++ b/packages/web3-eth/test/integration/rpc.test.ts @@ -26,8 +26,6 @@ import { // eslint-disable-next-line import/no-extraneous-dependencies import { Contract, decodeEventABI } from 'web3-eth-contract'; import { hexToNumber, hexToString, numberToHex, getStorageSlotNumForLongString } from 'web3-utils'; -// eslint-disable-next-line import/no-extraneous-dependencies -import { describe } from 'node:test'; import { Web3Eth } from '../../src'; import { @@ -92,13 +90,13 @@ describe('rpc', () => { ); // TODO:in beta, test eth_syncing during sync mode with return obj having ( startingblock, currentBlock, heighestBlock ) - test('isSyncing', async () => { + it('isSyncing', async () => { const isSyncing = await web3Eth.isSyncing(); expect(isSyncing).toBe(false); }); // TODO: in future release, set coinbase account in node and match actual address here - test('getCoinbase', async () => { + it('getCoinbase', async () => { const coinbase = await web3Eth.getCoinbase(); expect(coinbase.startsWith('0x')).toBe(true); expect(coinbase).toHaveLength(42); @@ -113,7 +111,7 @@ describe('rpc', () => { }); describeIf(getSystemTestBackend() !== BACKEND.HARDHAT)('getHashRate', () => { - test.each(Object.values(FMT_NUMBER))('getHashRate', async format => { + it.each(Object.values(FMT_NUMBER))('getHashRate', async format => { const hashRate = await web3Eth.getHashRate({ number: format as FMT_NUMBER, bytes: FMT_BYTES.HEX, @@ -123,7 +121,7 @@ describe('rpc', () => { }); }); - test('getAccounts', async () => { + it('getAccounts', async () => { // hardhat does not have support importrawkey, so we can't add new accounts rather just check the default 20 accounts if (getSystemTestBackend() !== BACKEND.HARDHAT) { const account = await createNewAccount({ unlock: true }); @@ -138,7 +136,7 @@ describe('rpc', () => { } }); - test.each(Object.values(FMT_NUMBER))('getBlockNumber', async format => { + it.each(Object.values(FMT_NUMBER))('getBlockNumber', async format => { const res = await web3Eth.getBlockNumber({ number: format as FMT_NUMBER, bytes: FMT_BYTES.HEX, @@ -147,7 +145,7 @@ describe('rpc', () => { expect(parseInt(String(res), 16)).toBeGreaterThan(0); }); - test.each(Object.values(FMT_NUMBER))('getGasPrice', async format => { + it.each(Object.values(FMT_NUMBER))('getGasPrice', async format => { const res = await web3Eth.getGasPrice({ number: format as FMT_NUMBER, bytes: FMT_BYTES.HEX, @@ -156,7 +154,7 @@ describe('rpc', () => { expect(parseInt(String(res), 16)).toBeGreaterThan(0); }); - test.each(Object.values(FMT_NUMBER))('getBalance', async format => { + it.each(Object.values(FMT_NUMBER))('getBalance', async format => { const value = '0xa'; const newAccount = await createNewAccount(); await web3Eth.sendTransaction({ @@ -173,7 +171,7 @@ describe('rpc', () => { expect(numberToHex(res)).toBe(value); }); - test('getStorageAt', async () => { + it('getStorageAt', async () => { const numberData = 10; const stringData = 'str'; const boolData = true; @@ -247,7 +245,7 @@ describe('rpc', () => { expect(stringDataLong).toBe(str); }); - test.each(Object.values(FMT_NUMBER))('getCode', async format => { + it.each(Object.values(FMT_NUMBER))('getCode', async format => { const code = await web3Eth.getCode( contractDeployed?.options?.address as string, undefined, @@ -260,7 +258,7 @@ describe('rpc', () => { expect(BasicBytecode.slice(-100)).toBe(code.slice(-100)); }); - test('getTransaction', async () => { + it('getTransaction', async () => { const [receipt] = await sendFewTxes({ from: tempAcc.address, value: '0x1', @@ -276,7 +274,7 @@ describe('rpc', () => { validateTransaction(res as TransactionInfo); expect(res?.hash).toBe(receipt.transactionHash); }); - test('check get transaction fields', async () => { + it('check get transaction fields', async () => { const receipt0 = await web3Eth.sendTransaction({ from: tempAcc.address, value: '0x1', @@ -375,7 +373,7 @@ describe('rpc', () => { expect(res).toBeDefined(); }); - test('getTransactionReceipt', async () => { + it('getTransactionReceipt', async () => { const [receipt] = await sendFewTxes({ from: tempAcc.address, value: '0x1', @@ -390,7 +388,7 @@ describe('rpc', () => { expect(res?.transactionHash).toBe(receipt.transactionHash); }); - test('getChainId', async () => { + it('getChainId', async () => { const res = await web3Eth.getChainId({ number: FMT_NUMBER.NUMBER, bytes: FMT_BYTES.HEX, @@ -399,7 +397,7 @@ describe('rpc', () => { expect(Number(res)).toBeGreaterThan(0); }); - test('getNodeInfo', async () => { + it('getNodeInfo', async () => { const res = await web3Eth.getNodeInfo(); // TODO: in next release, it should also be validated expect(res).toBeDefined(); @@ -432,7 +430,7 @@ describe('rpc', () => { expect(res.storageProof[0].value).toBe(numberData); }); - test('getPastLogs', async () => { + it('getPastLogs', async () => { const listOfStrings = ['t1', 't2', 't3']; const resTx = []; for (const l of listOfStrings) { From 477c0b4f70fd39803bf45c697e485b6ffc2f6e0c Mon Sep 17 00:00:00 2001 From: Oleksii Kosynskyi Date: Wed, 3 Apr 2024 19:11:42 +0200 Subject: [PATCH 15/21] fix changelog --- CHANGELOG.md | 2 -- 1 file changed, 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8db41aa4efc..66db37b0b1d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2406,8 +2406,6 @@ If there are any bugs, improvements, optimizations or any new feature proposal f - fixed erroneous parsing of big numbers in the `toNumber(...)` function (#6880) ## [Unreleased] -### Added -### Added #### web3-core From 3caa777e893aadb9062094d37d35ebdae23b5403 Mon Sep 17 00:00:00 2001 From: Oleksii Kosynskyi Date: Mon, 8 Apr 2024 20:54:33 -0400 Subject: [PATCH 16/21] fix default --- packages/web3-core/src/web3_config.ts | 2 +- packages/web3-eth-contract/src/contract.ts | 135 ++++++++++-------- packages/web3-eth-ens/src/ens.ts | 3 +- packages/web3-eth/src/rpc_method_wrappers.ts | 50 ++----- .../web3-eth/src/utils/get_revert_reason.ts | 3 +- .../web3-eth/src/utils/transaction_builder.ts | 4 +- packages/web3-eth/src/web3_eth.ts | 85 ++++------- packages/web3-net/src/net.ts | 6 +- 8 files changed, 125 insertions(+), 163 deletions(-) diff --git a/packages/web3-core/src/web3_config.ts b/packages/web3-core/src/web3_config.ts index d28eacc6bab..3c335292c4a 100644 --- a/packages/web3-core/src/web3_config.ts +++ b/packages/web3-core/src/web3_config.ts @@ -59,7 +59,7 @@ export interface Web3ConfigOptions { }; transactionBuilder?: TransactionBuilder; transactionTypeParser?: TransactionTypeParser; - defaultReturnFormat?: DataFormat; + defaultReturnFormat: DataFormat; } type ConfigEvent = P extends unknown diff --git a/packages/web3-eth-contract/src/contract.ts b/packages/web3-eth-contract/src/contract.ts index 14c6df1e1e4..763a3a6eb6b 100644 --- a/packages/web3-eth-contract/src/contract.ts +++ b/packages/web3-eth-contract/src/contract.ts @@ -334,24 +334,24 @@ const contractSubscriptions = { * Decodes the given ABI-encoded data, revealing both the method name and the parameters used in the smart contract call. * This function reverses the encoding process happens at the method `encodeABI`. * It's particularly useful for debugging and understanding the interactions with and between smart contracts. - * + * * #### Parameters - * + * * - `data` **HexString**: The string of ABI-encoded data that needs to be decoded. This should include the method signature and the encoded parameters. - * + * * #### Returns - * + * * - **Object**: This object combines both the decoded parameters and the method name in a readable format. Specifically, the returned object contains: * - `__method__` **String**: The name of the contract method, reconstructed from the ABI. * - `__length__` **Number**: The number of parameters decoded. * - Additional properties representing each parameter by name, as well as their position and values. - * + * * #### Example - * + * * Given an ABI-encoded string from a transaction, you can decode this data to identify the method called and the parameters passed. * Here's a simplified example: - * - * + * + * * ```typescript * const GreeterAbi = [ * { @@ -368,11 +368,11 @@ const contractSubscriptions = { * }, * ]; * const contract = new Contract(GreeterAbi); // Initialize with your contract's ABI - * + * * // The ABI-encoded data string for "setGreeting('Hello World')" * const encodedData = * '0xa41368620000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000b48656c6c6f20576f726c64000000000000000000000000000000000000000000'; - * + * * try { * const decoded = contract.decodeMethodData(encodedData); * console.log(decoded.__method__); // Outputs: "setGreeting(string)" @@ -388,7 +388,7 @@ const contractSubscriptions = { * console.error(error); * } * ``` - * + * * ### createAccessList * This will create an access list a method execution will access when executed in the EVM. @@ -513,7 +513,11 @@ export class Contract ); public constructor( jsonInterface: Abi, - addressOrOptionsOrContext?: Address | ContractInitOptions | Web3ContractContext | Web3Context, + addressOrOptionsOrContext?: + | Address + | ContractInitOptions + | Web3ContractContext + | Web3Context, optionsOrContextOrReturnFormat?: | ContractInitOptions | Web3ContractContext @@ -539,14 +543,20 @@ export class Contract } let provider; - if (typeof addressOrOptionsOrContext === 'object' && 'provider' in addressOrOptionsOrContext) { + if ( + typeof addressOrOptionsOrContext === 'object' && + 'provider' in addressOrOptionsOrContext + ) { provider = addressOrOptionsOrContext.provider; } else if ( typeof optionsOrContextOrReturnFormat === 'object' && 'provider' in optionsOrContextOrReturnFormat ) { provider = optionsOrContextOrReturnFormat.provider; - } else if (typeof contextOrReturnFormat === 'object' && 'provider' in contextOrReturnFormat) { + } else if ( + typeof contextOrReturnFormat === 'object' && + 'provider' in contextOrReturnFormat + ) { provider = contextOrReturnFormat.provider; } else { provider = Contract.givenProvider; @@ -583,7 +593,7 @@ export class Contract ? contextOrReturnFormat : isDataFormat(optionsOrContextOrReturnFormat) ? optionsOrContextOrReturnFormat - : returnFormat ?? this.defaultReturnFormat ?? DEFAULT_RETURN_FORMAT; + : returnFormat ?? this.defaultReturnFormat; const address = typeof addressOrOptionsOrContext === 'string' ? addressOrOptionsOrContext : undefined; this.config.contractDataInputFill = @@ -872,8 +882,7 @@ export class Contract }, estimateGas: async ( options?: PayableCallOptions, - returnFormat: ReturnFormat = (this.defaultReturnFormat ?? - DEFAULT_RETURN_FORMAT) as ReturnFormat, + returnFormat: ReturnFormat = this.defaultReturnFormat as ReturnFormat, ) => { const modifiedOptions = { ...options }; return this._contractMethodEstimateGas({ @@ -984,7 +993,7 @@ export class Contract ? param1 : isDataFormat(param2) ? param2 - : param3 ?? (this.defaultReturnFormat as DataFormat); + : param3 ?? (this.defaultReturnFormat ); const abi = eventName === 'allEvents' || eventName === ALL_EVENTS @@ -1034,7 +1043,10 @@ export class Contract if (hashedIndexedString === String(log.returnValues[key])) return true; } - return String(log.returnValues[key]).toUpperCase() === String(filter[key]).toUpperCase(); + return ( + String(log.returnValues[key]).toUpperCase() === + String(filter[key]).toUpperCase() + ); }); }); } @@ -1044,7 +1056,7 @@ export class Contract private _parseAndSetAddress( value?: Address, - returnFormat: DataFormat = this.defaultReturnFormat ?? DEFAULT_RETURN_FORMAT, + returnFormat: DataFormat = this.defaultReturnFormat, ) { this._address = value ? toChecksumAddress(format({ format: 'address' }, value, returnFormat)) @@ -1068,7 +1080,7 @@ export class Contract private _parseAndSetJsonInterface( abis: ContractAbi, - returnFormat: DataFormat = this.defaultReturnFormat ?? DEFAULT_RETURN_FORMAT, + returnFormat: DataFormat = this.defaultReturnFormat, ) { this._functions = {}; this._methods = {} as ContractMethodsInterface; @@ -1077,7 +1089,9 @@ export class Contract let result: ContractAbi = []; const functionsAbi = abis.filter(abi => abi.type !== 'error'); - const errorsAbi = abis.filter(abi => isAbiErrorFragment(abi)) as unknown as AbiErrorFragment[]; + const errorsAbi = abis.filter(abi => + isAbiErrorFragment(abi), + ) as unknown as AbiErrorFragment[]; for (const a of functionsAbi) { const abi: Mutable = { @@ -1093,7 +1107,9 @@ export class Contract // make constant and payable backwards compatible abi.constant = - abi.stateMutability === 'view' ?? abi.stateMutability === 'pure' ?? abi.constant; + abi.stateMutability === 'view' ?? + abi.stateMutability === 'pure' ?? + abi.constant; abi.payable = abi.stateMutability === 'payable' ?? abi.payable; this._overloadedMethodAbis.set(abi.name, [ @@ -1117,7 +1133,8 @@ export class Contract }; // We don't know a particular type of the Abi method so can't type check - this._methods[abi.name as keyof ContractMethodsInterface] = contractMethod as never; + this._methods[abi.name as keyof ContractMethodsInterface] = + contractMethod as never; // We don't know a particular type of the Abi method so can't type check this._methods[methodName as keyof ContractMethodsInterface] = @@ -1212,9 +1229,9 @@ export class Contract } compatible methods: ${JSON.stringify( applicableMethodAbi.map( m => - `${(m as { methodNameWithInputs: string }).methodNameWithInputs} (signature: ${ - (m as { signature: string }).signature - })`, + `${ + (m as { methodNameWithInputs: string }).methodNameWithInputs + } (signature: ${(m as { signature: string }).signature})`, ), )} \n\tThe first one will be used: ${ (methodAbi as { methodNameWithInputs: string }).methodNameWithInputs @@ -1236,15 +1253,22 @@ export class Contract call: async ( options?: PayableCallOptions | NonPayableCallOptions, block?: BlockNumberOrTag, - ) => this._contractMethodCall(methodAbi, abiParams, internalErrorsAbis, options, block), + ) => + this._contractMethodCall( + methodAbi, + abiParams, + internalErrorsAbis, + options, + block, + ), send: (options?: PayableTxOptions | NonPayableTxOptions): ContractMethodSend => this._contractMethodSend(methodAbi, abiParams, internalErrorsAbis, options), estimateGas: async ( options?: PayableCallOptions | NonPayableCallOptions, - returnFormat: ReturnFormat = (this.defaultReturnFormat ?? - DEFAULT_RETURN_FORMAT) as unknown as ReturnFormat, + returnFormat: ReturnFormat = this + .defaultReturnFormat as unknown as ReturnFormat, ) => this._contractMethodEstimateGas({ abi: methodAbi, @@ -1306,7 +1330,7 @@ export class Contract this, tx, block, - (this.defaultReturnFormat ?? DEFAULT_RETURN_FORMAT) as typeof DEFAULT_RETURN_FORMAT, + this.defaultReturnFormat as typeof DEFAULT_RETURN_FORMAT, ); return decodeMethodReturn(abi, result); } catch (error: unknown) { @@ -1338,12 +1362,7 @@ export class Contract }); try { - return createAccessList( - this, - tx, - block, - this.defaultReturnFormat ?? DEFAULT_RETURN_FORMAT, - ); + return createAccessList(this, tx, block, this.defaultReturnFormat); } catch (error: unknown) { if (error instanceof ContractExecutionError) { // this will parse the error data by trying to decode the ABI error inputs according to EIP-838 @@ -1373,16 +1392,11 @@ export class Contract contractOptions: modifiedContractOptions, }); - const transactionToSend = sendTransaction( - this, - tx, - this.defaultReturnFormat ?? DEFAULT_RETURN_FORMAT, - { - // TODO Should make this configurable by the user - checkRevertBeforeSending: false, - contractAbi: this._jsonInterface, - }, - ); + const transactionToSend = sendTransaction(this, tx, this.defaultReturnFormat, { + // TODO Should make this configurable by the user + checkRevertBeforeSending: false, + contractAbi: this._jsonInterface, + }); // eslint-disable-next-line no-void void transactionToSend.on('error', (error: unknown) => { @@ -1411,7 +1425,7 @@ export class Contract options: { ...options, dataInputFill: this.contractDataInputFill }, contractOptions: modifiedContractOptions, }); - return sendTransaction(this, tx, this.defaultReturnFormat ?? DEFAULT_RETURN_FORMAT, { + return sendTransaction(this, tx, this.defaultReturnFormat, { transactionResolver: receipt => { if (receipt.status === BigInt(0)) { throw new Web3ContractError("code couldn't be stored", receipt); @@ -1451,21 +1465,20 @@ export class Contract options: { ...options, dataInputFill: this.config.contractDataInputFill }, contractOptions: contractOptions ?? this.options, }); - return estimateGas( - this, - tx, - BlockTags.LATEST, - returnFormat ?? this.defaultReturnFormat ?? DEFAULT_RETURN_FORMAT, - ); + return estimateGas(this, tx, BlockTags.LATEST, returnFormat ?? this.defaultReturnFormat); } // eslint-disable-next-line class-methods-use-this private _createContractEvent( abi: AbiEventFragment & { signature: HexString }, - returnFormat: DataFormat = this.defaultReturnFormat ?? DEFAULT_RETURN_FORMAT, + returnFormat: DataFormat = this.defaultReturnFormat, ): ContractBoundEvent { return (...params: unknown[]) => { - const { topics, fromBlock } = encodeEventABI(this.options, abi, params[0] as EventParameters); + const { topics, fromBlock } = encodeEventABI( + this.options, + abi, + params[0] as EventParameters, + ); const sub = new LogsSubscription( { address: this.options.address, @@ -1475,7 +1488,10 @@ export class Contract }, { // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment - subscriptionManager: this.subscriptionManager as Web3SubscriptionManager, + subscriptionManager: this.subscriptionManager as Web3SubscriptionManager< + unknown, + any + >, returnFormat, }, ); @@ -1488,7 +1504,10 @@ export class Contract } }) .catch((error: Error) => { - sub.emit('error', new SubscriptionError('Failed to get past events.', error)); + sub.emit( + 'error', + new SubscriptionError('Failed to get past events.', error), + ); }); } this.subscriptionManager?.addSubscription(sub).catch((error: Error) => { diff --git a/packages/web3-eth-ens/src/ens.ts b/packages/web3-eth-ens/src/ens.ts index 8729ee83018..254a33bc842 100644 --- a/packages/web3-eth-ens/src/ens.ts +++ b/packages/web3-eth-ens/src/ens.ts @@ -26,7 +26,6 @@ import { Contract } from 'web3-eth-contract'; import { getId } from 'web3-net'; import { Address, - DEFAULT_RETURN_FORMAT, EthExecutionAPI, FMT_NUMBER, PayableCallOptions, @@ -249,7 +248,7 @@ export class ENS extends Web3Context { return this._detectedAddress; } const networkType = await getId(this, { - ...(this.defaultReturnFormat ?? DEFAULT_RETURN_FORMAT), + ...this.defaultReturnFormat, number: FMT_NUMBER.HEX, }); // get the network from provider const addr = registryAddresses[networkIds[networkType]]; diff --git a/packages/web3-eth/src/rpc_method_wrappers.ts b/packages/web3-eth/src/rpc_method_wrappers.ts index f514516960c..20e832be892 100644 --- a/packages/web3-eth/src/rpc_method_wrappers.ts +++ b/packages/web3-eth/src/rpc_method_wrappers.ts @@ -403,7 +403,7 @@ export async function getUncle( export async function getTransaction( web3Context: Web3Context, transactionHash: Bytes, - returnFormat: ReturnFormat, + returnFormat: ReturnFormat = web3Context.defaultReturnFormat as ReturnFormat, ) { const transactionHashFormatted = format( { format: 'bytes32' }, @@ -417,7 +417,7 @@ export async function getTransaction( return isNullish(response) ? response - : formatTransaction(response, returnFormat ?? web3Context.defaultReturnFormat, { + : formatTransaction(response, returnFormat, { fillInputAndData: true, }); } @@ -779,17 +779,13 @@ export async function sign( web3Context: Web3Context, message: Bytes, addressOrIndex: Address | number, - returnFormat: ReturnFormat, + returnFormat: ReturnFormat = web3Context.defaultReturnFormat as ReturnFormat, ) { const messageFormatted = format({ format: 'bytes' }, message, DEFAULT_RETURN_FORMAT); if (web3Context.wallet?.get(addressOrIndex)) { const wallet = web3Context.wallet.get(addressOrIndex) as Web3BaseWalletAccount; const signed = wallet.sign(messageFormatted); - return format( - SignatureObjectSchema, - signed, - returnFormat ?? web3Context.defaultReturnFormat, - ); + return format(SignatureObjectSchema, signed, returnFormat); } if (typeof addressOrIndex === 'number') { @@ -805,11 +801,7 @@ export async function sign( messageFormatted, ); - return format( - { format: 'bytes' }, - response as Bytes, - returnFormat ?? web3Context.defaultReturnFormat, - ); + return format({ format: 'bytes' }, response as Bytes, returnFormat); } /** @@ -819,7 +811,7 @@ export async function sign( export async function signTransaction( web3Context: Web3Context, transaction: Transaction, - returnFormat: ReturnFormat, + returnFormat: ReturnFormat = web3Context.defaultReturnFormat as ReturnFormat, ) { const response = await ethRpcMethods.signTransaction( web3Context.requestManager, @@ -828,26 +820,18 @@ export async function signTransaction( // Some clients only return the encoded signed transaction (e.g. Ganache) // while clients such as Geth return the desired SignedTransactionInfoAPI object return isString(response as HexStringBytes) - ? decodeSignedTransaction( - response as HexStringBytes, - returnFormat ?? web3Context.defaultReturnFormat ?? DEFAULT_RETURN_FORMAT, - { - fillInputAndData: true, - }, - ) + ? decodeSignedTransaction(response as HexStringBytes, returnFormat, { + fillInputAndData: true, + }) : { raw: format( { format: 'bytes' }, (response as SignedTransactionInfoAPI).raw, - returnFormat ?? web3Context.defaultReturnFormat, - ), - tx: formatTransaction( - (response as SignedTransactionInfoAPI).tx, - returnFormat ?? web3Context.defaultReturnFormat, - { - fillInputAndData: true, - }, + returnFormat, ), + tx: formatTransaction((response as SignedTransactionInfoAPI).tx, returnFormat, { + fillInputAndData: true, + }), }; } @@ -861,7 +845,7 @@ export async function call( web3Context: Web3Context, transaction: TransactionCall, blockNumber: BlockNumberOrTag = web3Context.defaultBlock, - returnFormat: ReturnFormat, + returnFormat: ReturnFormat = web3Context.defaultReturnFormat as ReturnFormat, ) { const blockNumberFormatted = isBlockTag(blockNumber as string) ? (blockNumber as BlockTag) @@ -873,11 +857,7 @@ export async function call( blockNumberFormatted, ); - return format( - { format: 'bytes' }, - response as Bytes, - returnFormat ?? web3Context.defaultReturnFormat, - ); + return format({ format: 'bytes' }, response as Bytes, returnFormat); } // TODO - Investigate whether response is padded as 1.x docs suggest diff --git a/packages/web3-eth/src/utils/get_revert_reason.ts b/packages/web3-eth/src/utils/get_revert_reason.ts index b95491b4f1d..6edb2ec52c3 100644 --- a/packages/web3-eth/src/utils/get_revert_reason.ts +++ b/packages/web3-eth/src/utils/get_revert_reason.ts @@ -85,8 +85,7 @@ export async function getRevertReason< web3Context: Web3Context, transaction: TransactionCall, contractAbi?: ContractAbi, - returnFormat: ReturnFormat = (web3Context.defaultReturnFormat ?? - DEFAULT_RETURN_FORMAT) as ReturnFormat, + returnFormat: ReturnFormat = web3Context.defaultReturnFormat as ReturnFormat, ): Promise { try { await call(web3Context, transaction, web3Context.defaultBlock, returnFormat); diff --git a/packages/web3-eth/src/utils/transaction_builder.ts b/packages/web3-eth/src/utils/transaction_builder.ts index ad3ff866d8a..0d459017b4a 100644 --- a/packages/web3-eth/src/utils/transaction_builder.ts +++ b/packages/web3-eth/src/utils/transaction_builder.ts @@ -31,7 +31,6 @@ import { DataFormat, FormatType, ETH_DATA_FORMAT, - DEFAULT_RETURN_FORMAT, } from 'web3-types'; import { Web3Context } from 'web3-core'; import { privateKeyToAddress } from 'web3-eth-accounts'; @@ -99,8 +98,7 @@ export const getTransactionFromOrToAttr = ( export const getTransactionNonce = async ( web3Context: Web3Context, address?: Address, - returnFormat: ReturnFormat = (web3Context.defaultReturnFormat ?? - DEFAULT_RETURN_FORMAT) as ReturnFormat, + returnFormat: ReturnFormat = web3Context.defaultReturnFormat as ReturnFormat, ) => { if (isNullish(address)) { // TODO if (web3.eth.accounts.wallet) use address from local wallet diff --git a/packages/web3-eth/src/web3_eth.ts b/packages/web3-eth/src/web3_eth.ts index dc6f978c9c7..959a7d5eddc 100644 --- a/packages/web3-eth/src/web3_eth.ts +++ b/packages/web3-eth/src/web3_eth.ts @@ -220,8 +220,7 @@ export class Web3Eth extends Web3Context( - returnFormat: ReturnFormat = (this.defaultReturnFormat ?? - DEFAULT_RETURN_FORMAT) as ReturnFormat, + returnFormat: ReturnFormat = this.defaultReturnFormat as ReturnFormat, ) { return rpcMethodsWrappers.getHashRate(this, returnFormat); } @@ -239,8 +238,7 @@ export class Web3Eth extends Web3Context( - returnFormat: ReturnFormat = (this.defaultReturnFormat ?? - DEFAULT_RETURN_FORMAT) as ReturnFormat, + returnFormat: ReturnFormat = this.defaultReturnFormat as ReturnFormat, ) { return rpcMethodsWrappers.getGasPrice(this, returnFormat); } @@ -259,10 +257,7 @@ export class Web3Eth extends Web3Context( - returnFormat: ReturnFormat = (this.defaultReturnFormat ?? - DEFAULT_RETURN_FORMAT) as ReturnFormat, - ) { + >(returnFormat: ReturnFormat = this.defaultReturnFormat as ReturnFormat) { return rpcMethodsWrappers.getMaxPriorityFeePerGas(this, returnFormat); } @@ -370,8 +365,7 @@ export class Web3Eth extends Web3Context( - returnFormat: ReturnFormat = (this.defaultReturnFormat ?? - DEFAULT_RETURN_FORMAT) as ReturnFormat, + returnFormat: ReturnFormat = this.defaultReturnFormat as ReturnFormat, ) { return rpcMethodsWrappers.getBlockNumber(this, returnFormat); } @@ -395,8 +389,7 @@ export class Web3Eth extends Web3Context( address: Address, blockNumber: BlockNumberOrTag = this.defaultBlock, - returnFormat: ReturnFormat = (this.defaultReturnFormat ?? - DEFAULT_RETURN_FORMAT) as ReturnFormat, + returnFormat: ReturnFormat = this.defaultReturnFormat as ReturnFormat, ) { return rpcMethodsWrappers.getBalance(this, address, blockNumber, returnFormat); } @@ -432,8 +425,7 @@ export class Web3Eth extends Web3Context( address: Address, blockNumber: BlockNumberOrTag = this.defaultBlock, - returnFormat: ReturnFormat = (this.defaultReturnFormat ?? - DEFAULT_RETURN_FORMAT) as ReturnFormat, + returnFormat: ReturnFormat = this.defaultReturnFormat as ReturnFormat, ) { return rpcMethodsWrappers.getCode(this, address, blockNumber, returnFormat); } @@ -546,8 +537,7 @@ export class Web3Eth extends Web3Context( block: HexString32Bytes | BlockNumberOrTag = this.defaultBlock, hydrated = false, - returnFormat: ReturnFormat = (this.defaultReturnFormat ?? - DEFAULT_RETURN_FORMAT) as ReturnFormat, + returnFormat: ReturnFormat = this.defaultReturnFormat as ReturnFormat, ) { return rpcMethodsWrappers.getBlock(this, block, hydrated, returnFormat); } @@ -572,8 +562,7 @@ export class Web3Eth extends Web3Context( block: HexString32Bytes | BlockNumberOrTag = this.defaultBlock, - returnFormat: ReturnFormat = (this.defaultReturnFormat ?? - DEFAULT_RETURN_FORMAT) as ReturnFormat, + returnFormat: ReturnFormat = this.defaultReturnFormat as ReturnFormat, ) { return rpcMethodsWrappers.getBlockTransactionCount(this, block, returnFormat); } @@ -596,8 +585,7 @@ export class Web3Eth extends Web3Context( block: HexString32Bytes | BlockNumberOrTag = this.defaultBlock, - returnFormat: ReturnFormat = (this.defaultReturnFormat ?? - DEFAULT_RETURN_FORMAT) as ReturnFormat, + returnFormat: ReturnFormat = this.defaultReturnFormat as ReturnFormat, ) { return rpcMethodsWrappers.getBlockUncleCount(this, block, returnFormat); } @@ -668,8 +656,7 @@ export class Web3Eth extends Web3Context( block: HexString32Bytes | BlockNumberOrTag = this.defaultBlock, uncleIndex: Numbers, - returnFormat: ReturnFormat = (this.defaultReturnFormat ?? - DEFAULT_RETURN_FORMAT) as ReturnFormat, + returnFormat: ReturnFormat = this.defaultReturnFormat as ReturnFormat, ) { return rpcMethodsWrappers.getUncle(this, block, uncleIndex, returnFormat); } @@ -724,8 +711,7 @@ export class Web3Eth extends Web3Context( transactionHash: Bytes, - returnFormat: ReturnFormat = (this.defaultReturnFormat ?? - DEFAULT_RETURN_FORMAT) as ReturnFormat, + returnFormat: ReturnFormat = this.defaultReturnFormat as ReturnFormat, ) { const response = await rpcMethodsWrappers.getTransaction( this, @@ -822,10 +808,7 @@ export class Web3Eth extends Web3Context( - returnFormat: ReturnFormat = (this.defaultReturnFormat ?? - DEFAULT_RETURN_FORMAT) as ReturnFormat, - ) { + >(returnFormat: ReturnFormat = this.defaultReturnFormat as ReturnFormat) { return rpcMethodsWrappers.getPendingTransactions(this, returnFormat); } @@ -884,8 +867,7 @@ export class Web3Eth extends Web3Context( block: HexString32Bytes | BlockNumberOrTag = this.defaultBlock, transactionIndex: Numbers, - returnFormat: ReturnFormat = (this.defaultReturnFormat ?? - DEFAULT_RETURN_FORMAT) as ReturnFormat, + returnFormat: ReturnFormat = this.defaultReturnFormat as ReturnFormat, ) { return rpcMethodsWrappers.getTransactionFromBlock( this, @@ -943,8 +925,7 @@ export class Web3Eth extends Web3Context( transactionHash: Bytes, - returnFormat: ReturnFormat = (this.defaultReturnFormat ?? - DEFAULT_RETURN_FORMAT) as ReturnFormat, + returnFormat: ReturnFormat = this.defaultReturnFormat as ReturnFormat, ) { const response = await rpcMethodsWrappers.getTransactionReceipt( this, @@ -980,8 +961,7 @@ export class Web3Eth extends Web3Context( address: Address, blockNumber: BlockNumberOrTag = this.defaultBlock, - returnFormat: ReturnFormat = (this.defaultReturnFormat ?? - DEFAULT_RETURN_FORMAT) as ReturnFormat, + returnFormat: ReturnFormat = this.defaultReturnFormat as ReturnFormat, ) { return rpcMethodsWrappers.getTransactionCount(this, address, blockNumber, returnFormat); } @@ -1098,8 +1078,7 @@ export class Web3Eth extends Web3Context( transaction: Bytes, - returnFormat: ReturnFormat = (this.defaultReturnFormat ?? - DEFAULT_RETURN_FORMAT) as ReturnFormat, + returnFormat: ReturnFormat = this.defaultReturnFormat as ReturnFormat, options?: SendTransactionOptions, ) { return rpcMethodsWrappers.sendSignedTransaction(this, transaction, returnFormat, options); @@ -1228,8 +1206,7 @@ export class Web3Eth extends Web3Context( message: Bytes, addressOrIndex: Address | number, - returnFormat: ReturnFormat = (this.defaultReturnFormat ?? - DEFAULT_RETURN_FORMAT) as ReturnFormat, + returnFormat: ReturnFormat = this.defaultReturnFormat as ReturnFormat, ) { return rpcMethodsWrappers.sign(this, message, addressOrIndex, returnFormat); } @@ -1287,8 +1264,7 @@ export class Web3Eth extends Web3Context( transaction: Transaction, - returnFormat: ReturnFormat = (this.defaultReturnFormat ?? - DEFAULT_RETURN_FORMAT) as ReturnFormat, + returnFormat: ReturnFormat = this.defaultReturnFormat as ReturnFormat, ) { return rpcMethodsWrappers.signTransaction(this, transaction, returnFormat); } @@ -1307,8 +1283,7 @@ export class Web3Eth extends Web3Context( transaction: TransactionCall, blockNumber: BlockNumberOrTag = this.defaultBlock, - returnFormat: ReturnFormat = (this.defaultReturnFormat ?? - DEFAULT_RETURN_FORMAT) as ReturnFormat, + returnFormat: ReturnFormat = this.defaultReturnFormat as ReturnFormat, ) { return rpcMethodsWrappers.call(this, transaction, blockNumber, returnFormat); } @@ -1342,8 +1317,7 @@ export class Web3Eth extends Web3Context( transaction: Transaction, blockNumber: BlockNumberOrTag = this.defaultBlock, - returnFormat: ReturnFormat = (this.defaultReturnFormat ?? - DEFAULT_RETURN_FORMAT) as ReturnFormat, + returnFormat: ReturnFormat = this.defaultReturnFormat as ReturnFormat, ) { return rpcMethodsWrappers.estimateGas(this, transaction, blockNumber, returnFormat); } @@ -1394,8 +1368,7 @@ export class Web3Eth extends Web3Context( filter: Filter, - returnFormat: ReturnFormat = (this.defaultReturnFormat ?? - DEFAULT_RETURN_FORMAT) as ReturnFormat, + returnFormat: ReturnFormat = this.defaultReturnFormat as ReturnFormat, ) { return rpcMethodsWrappers.getLogs(this, filter, returnFormat); } @@ -1478,8 +1451,7 @@ export class Web3Eth extends Web3Context( - returnFormat: ReturnFormat = (this.defaultReturnFormat ?? - DEFAULT_RETURN_FORMAT) as ReturnFormat, + returnFormat: ReturnFormat = this.defaultReturnFormat as ReturnFormat, ) { return rpcMethodsWrappers.getChainId(this, returnFormat); } @@ -1572,8 +1544,7 @@ export class Web3Eth extends Web3Context( transaction: TransactionForAccessList, blockNumber: BlockNumberOrTag = this.defaultBlock, - returnFormat: ReturnFormat = (this.defaultReturnFormat ?? - DEFAULT_RETURN_FORMAT) as ReturnFormat, + returnFormat: ReturnFormat = this.defaultReturnFormat as ReturnFormat, ) { return rpcMethodsWrappers.createAccessList(this, transaction, blockNumber, returnFormat); } diff --git a/packages/web3-net/src/net.ts b/packages/web3-net/src/net.ts index bf7a676dd1c..ac376e86c5a 100644 --- a/packages/web3-net/src/net.ts +++ b/packages/web3-net/src/net.ts @@ -53,8 +53,7 @@ export class Net extends Web3Context { * ``` */ public async getId( - returnFormat: ReturnFormat = (this.defaultReturnFormat ?? - DEFAULT_RETURN_FORMAT) as ReturnFormat, + returnFormat: ReturnFormat = this.defaultReturnFormat as ReturnFormat, ) { return rpcMethodsWrappers.getId(this, returnFormat); } @@ -72,8 +71,7 @@ export class Net extends Web3Context { * ``` */ public async getPeerCount( - returnFormat: ReturnFormat = (this.defaultReturnFormat ?? - DEFAULT_RETURN_FORMAT) as ReturnFormat, + returnFormat: ReturnFormat = this.defaultReturnFormat as ReturnFormat, ) { return rpcMethodsWrappers.getPeerCount(this, returnFormat); } From f41ea1a88465c938256250efc5ff9d1ddaf988ba Mon Sep 17 00:00:00 2001 From: Oleksii Kosynskyi Date: Mon, 8 Apr 2024 21:24:50 -0400 Subject: [PATCH 17/21] add estimate gas test --- packages/web3-eth-contract/src/contract.ts | 6 +- .../test/integration/contract_deploy.test.ts | 57 ++++++++++++++----- 2 files changed, 49 insertions(+), 14 deletions(-) diff --git a/packages/web3-eth-contract/src/contract.ts b/packages/web3-eth-contract/src/contract.ts index 763a3a6eb6b..c4be775b31f 100644 --- a/packages/web3-eth-contract/src/contract.ts +++ b/packages/web3-eth-contract/src/contract.ts @@ -600,6 +600,10 @@ export class Contract (options as ContractInitOptions)?.dataInputFill ?? this.config.contractDataInputFill; this._parseAndSetJsonInterface(jsonInterface, returnDataFormat); + if (this.defaultReturnFormat !== returnDataFormat) { + this.defaultReturnFormat = returnDataFormat; + } + if (!isNullish(address)) { this._parseAndSetAddress(address, returnDataFormat); } @@ -993,7 +997,7 @@ export class Contract ? param1 : isDataFormat(param2) ? param2 - : param3 ?? (this.defaultReturnFormat ); + : param3 ?? this.defaultReturnFormat; const abi = eventName === 'allEvents' || eventName === ALL_EVENTS 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 1d7277fe881..b8036c123a3 100644 --- a/packages/web3-eth-contract/test/integration/contract_deploy.test.ts +++ b/packages/web3-eth-contract/test/integration/contract_deploy.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 { Web3Eth } from 'web3-eth'; +import { FMT_BYTES, FMT_NUMBER } from 'web3-types'; import { Contract } from '../../src'; import { sleep } from '../shared_fixtures/utils'; import { ERC721TokenAbi, ERC721TokenBytecode } from '../shared_fixtures/build/ERC721Token'; @@ -30,7 +31,8 @@ import { sendFewSampleTxs, closeOpenConnection, getSystemTestBackend, - BACKEND + BACKEND, + mapFormatToType, } from '../fixtures/system_test_utils'; describe('contract', () => { @@ -109,8 +111,33 @@ describe('contract', () => { from: acc.address, gas: '1000000', }); + expect(typeof estimatedGas).toBe('bigint'); expect(Number(estimatedGas)).toBeGreaterThan(0); }); + it.each(Object.values(FMT_NUMBER))( + 'should return estimated gas of contract constructor %p with correct type', + async format => { + const returnFormat = { number: format as FMT_NUMBER, bytes: FMT_BYTES.HEX }; + + const estimatedGas = await new Contract( + GreeterAbi, + { + provider: getSystemTestProvider(), + }, + returnFormat, + ) + .deploy({ + data: GreeterBytecode, + arguments: ['My Greeting'], + }) + .estimateGas({ + from: acc.address, + gas: '1000000', + }); + expect(typeof estimatedGas).toBe(mapFormatToType[format as string]); + expect(Number(estimatedGas)).toBeGreaterThan(0); + }, + ); it('should return estimated gas of contract constructor without arguments', async () => { const estimatedGas = await new Contract(ERC721TokenAbi, undefined, { provider: getSystemTestProvider(), @@ -256,7 +283,7 @@ describe('contract', () => { }); it('should fail with errors on "intrinsic gas too low" OOG', async () => { - if (getSystemTestBackend() !== BACKEND.HARDHAT){ + if (getSystemTestBackend() !== BACKEND.HARDHAT) { // eslint-disable-next-line jest/no-conditional-expect await expect( contract.deploy(deployOptions).send({ ...sendOptions, gas: '100' }), @@ -265,7 +292,9 @@ describe('contract', () => { // eslint-disable-next-line jest/no-conditional-expect await expect( contract.deploy(deployOptions).send({ ...sendOptions, gas: '100' }), - ).rejects.toThrow('Returned error: Transaction requires at least 109656 gas but got 100'); + ).rejects.toThrow( + 'Returned error: Transaction requires at least 109656 gas but got 100', + ); } }); @@ -283,7 +312,7 @@ describe('contract', () => { it('should fail with errors on revert', async () => { const revert = new Contract(DeployRevertAbi); revert.provider = getSystemTestProvider(); - if (getSystemTestBackend() !== BACKEND.HARDHAT){ + if (getSystemTestBackend() !== BACKEND.HARDHAT) { // eslint-disable-next-line jest/no-conditional-expect await expect( revert @@ -293,15 +322,17 @@ describe('contract', () => { .send(sendOptions), ).rejects.toThrow("code couldn't be stored"); } else { - // eslint-disable-next-line jest/no-conditional-expect - await expect( - revert - .deploy({ - data: DeployRevertBytecode, - }) - .send(sendOptions), - ).rejects.toThrow("Error happened while trying to execute a function inside a smart contract"); - } + // eslint-disable-next-line jest/no-conditional-expect + await expect( + revert + .deploy({ + data: DeployRevertBytecode, + }) + .send(sendOptions), + ).rejects.toThrow( + 'Error happened while trying to execute a function inside a smart contract', + ); + } }); }); }); From 581c04477f8e14b5d156f7d24bde589652c123da Mon Sep 17 00:00:00 2001 From: Oleksii Kosynskyi Date: Wed, 17 Apr 2024 14:51:33 -0400 Subject: [PATCH 18/21] add guide to upgrade from 1.x --- docs/docs/guides/web3_config/index.md | 8 ++++---- docs/docs/guides/web3_upgrade_guide/1.x/index.md | 3 +++ 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/docs/docs/guides/web3_config/index.md b/docs/docs/guides/web3_config/index.md index 20d08b6dde4..f6d041b6b15 100644 --- a/docs/docs/guides/web3_config/index.md +++ b/docs/docs/guides/web3_config/index.md @@ -229,10 +229,10 @@ eth.defaultReturnFormat = { #### All available choices for numeric data: ```ts export enum FMT_NUMBER { - NUMBER = 'NUMBER_NUMBER', - HEX = 'NUMBER_HEX', - STR = 'NUMBER_STR', - BIGINT = 'NUMBER_BIGINT', + NUMBER = 'NUMBER_NUMBER', + HEX = 'NUMBER_HEX', + STR = 'NUMBER_STR', + BIGINT = 'NUMBER_BIGINT', } ``` #### All available choices for bytes data: diff --git a/docs/docs/guides/web3_upgrade_guide/1.x/index.md b/docs/docs/guides/web3_upgrade_guide/1.x/index.md index 52530284ed2..b375a63974f 100644 --- a/docs/docs/guides/web3_upgrade_guide/1.x/index.md +++ b/docs/docs/guides/web3_upgrade_guide/1.x/index.md @@ -79,6 +79,9 @@ It will not have: - `givenProvider` default value is `undefined` instead of `null` - `currentProvider` default value is `undefined` instead of `null` (if web3 is instantiated without a provider) +:::warning +In version 4.x, all numbers return as BigInt instead of string or number, which constitutes a breaking change for users accustomed to handling numbers as string or number in their code. For instance, web3.eth.getBalance will now return BigInt instead of string or number. If you wish to retain numbers as number or string, you can refer to [this guide](/guides/web3_config/#defaultreturnformat) on how to set returning types in web3js 4.x. +::: ### Web3 BatchRequest ```ts From 9ef542a3ebf5009e63d80075bfeb6d7c3296b2c9 Mon Sep 17 00:00:00 2001 From: Oleksii Kosynskyi Date: Thu, 18 Apr 2024 10:33:25 -0400 Subject: [PATCH 19/21] fix change log --- CHANGELOG.md | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index f908197a639..dcedf476330 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2445,3 +2445,35 @@ If there are any bugs, improvements, optimizations or any new feature proposal f - update type `Withdrawals`, `block` and `BlockHeaderOutput` to include properties of eip 4844, 4895, 4788 (#6933) ## [Unreleased] + +### Added + +#### web3-core + +- `defaultReturnFormat` was added to the configuration options. (#6947) + +#### web3-eth + +- `defaultReturnFormat` was added to all methods that have `ReturnType` param. (#6947) + +#### web3-eth-contract + +- `defaultReturnFormat` was added to all methods that have `ReturnType` param. (#6947) + +#### web3-eth-ens + +- `defaultReturnFormat` was added to all methods that have `ReturnType` param. (#6947) + +#### web3-net + +- `defaultReturnFormat` was added to all methods that have `ReturnType` param. (#6947) + +#### web3-types + +- Added `signature` to type `AbiFunctionFragment` (#6922) +- update type `Withdrawals`, `block` and `BlockHeaderOutput` to include properties of eip 4844, 4895, 4788 (#6933) + +### Fixed + +#### web3-validator + From 72aee9d4a508390e09959168b739b2c9ca52393e Mon Sep 17 00:00:00 2001 From: Oleksii Kosynskyi Date: Thu, 18 Apr 2024 10:40:11 -0400 Subject: [PATCH 20/21] remove changelogs --- CHANGELOG.md | 2 -- packages/web3-types/CHANGELOG.md | 5 ----- packages/web3-validator/CHANGELOG.md | 4 ---- 3 files changed, 11 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index dcedf476330..3729ce98065 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2470,8 +2470,6 @@ If there are any bugs, improvements, optimizations or any new feature proposal f #### web3-types -- Added `signature` to type `AbiFunctionFragment` (#6922) -- update type `Withdrawals`, `block` and `BlockHeaderOutput` to include properties of eip 4844, 4895, 4788 (#6933) ### Fixed diff --git a/packages/web3-types/CHANGELOG.md b/packages/web3-types/CHANGELOG.md index b3a8628c9a5..b7cc8d9808d 100644 --- a/packages/web3-types/CHANGELOG.md +++ b/packages/web3-types/CHANGELOG.md @@ -190,8 +190,3 @@ Documentation: - Type `FeeData` to be filled by `await web3.eth.calculateFeeData()` to be used with EIP-1559 transactions (#6795) ## [Unreleased] - -### Added - -- Added `signature` to type `AbiFunctionFragment` (#6922) -- update type `Withdrawals`, `block` and `BlockHeaderOutput` to include properties of eip 4844, 4895, 4788 (#6933) \ No newline at end of file diff --git a/packages/web3-validator/CHANGELOG.md b/packages/web3-validator/CHANGELOG.md index 07ba353112d..77d60beadc0 100644 --- a/packages/web3-validator/CHANGELOG.md +++ b/packages/web3-validator/CHANGELOG.md @@ -169,7 +169,3 @@ Documentation: - Multi-dimensional arrays(with a fix length) are now handled properly when parsing ABIs (#6798) ## [Unreleased] - -### Fixed - -- Nodejs Buffer is not recognized as valid bytes value From 5913c9ec9412dced925c017cbe56c9d699897d95 Mon Sep 17 00:00:00 2001 From: Oleksii Kosynskyi Date: Thu, 18 Apr 2024 10:43:43 -0400 Subject: [PATCH 21/21] fix --- CHANGELOG.md | 2 ++ packages/web3-types/CHANGELOG.md | 5 +++++ packages/web3-validator/CHANGELOG.md | 4 ++++ 3 files changed, 11 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3729ce98065..dcedf476330 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2470,6 +2470,8 @@ If there are any bugs, improvements, optimizations or any new feature proposal f #### web3-types +- Added `signature` to type `AbiFunctionFragment` (#6922) +- update type `Withdrawals`, `block` and `BlockHeaderOutput` to include properties of eip 4844, 4895, 4788 (#6933) ### Fixed diff --git a/packages/web3-types/CHANGELOG.md b/packages/web3-types/CHANGELOG.md index b7cc8d9808d..3f96fe9d53d 100644 --- a/packages/web3-types/CHANGELOG.md +++ b/packages/web3-types/CHANGELOG.md @@ -190,3 +190,8 @@ Documentation: - Type `FeeData` to be filled by `await web3.eth.calculateFeeData()` to be used with EIP-1559 transactions (#6795) ## [Unreleased] + +### Added + +- Added `signature` to type `AbiFunctionFragment` (#6922) +- update type `Withdrawals`, `block` and `BlockHeaderOutput` to include properties of eip 4844, 4895, 4788 (#6933) diff --git a/packages/web3-validator/CHANGELOG.md b/packages/web3-validator/CHANGELOG.md index 77d60beadc0..07ba353112d 100644 --- a/packages/web3-validator/CHANGELOG.md +++ b/packages/web3-validator/CHANGELOG.md @@ -169,3 +169,7 @@ Documentation: - Multi-dimensional arrays(with a fix length) are now handled properly when parsing ABIs (#6798) ## [Unreleased] + +### Fixed + +- Nodejs Buffer is not recognized as valid bytes value