diff --git a/CHANGELOG.md b/CHANGELOG.md
index c007375e541..dcedf476330 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2120,7 +2120,7 @@ If there are any bugs, improvements, optimizations or any new feature proposal f
#### web3-eth
- Ensure provider.supportsSubscriptions exists before watching by subscription (#6440)
-- Fixed param sent to `checkRevertBeforeSending` in `sendSignedTransaction`
+- Fixed param sent to `checkRevertBeforeSending` in `sendSignedTransaction`
- Fixed `defaultTransactionBuilder` for value issue (#6509)
#### web3-eth-abi
@@ -2129,7 +2129,7 @@ If there are any bugs, improvements, optimizations or any new feature proposal f
#### web3-eth-accounts
-- Fixed `recover` function, `v` will be normalized to value 0,1 (#6344)
+- Fixed `recover` function, `v` will be normalized to value 0,1 (#6344)
#### web3-providers-http
@@ -2252,7 +2252,7 @@ If there are any bugs, improvements, optimizations or any new feature proposal f
#### web3-eth-contract
-- Will populate `data` for transactions in contract for metamask provider instead of `input` (#6534)
+- Will populate `data` for transactions in contract for metamask provider instead of `input` (#6534)
## [4.3.0]
@@ -2260,19 +2260,18 @@ If there are any bugs, improvements, optimizations or any new feature proposal f
#### web3-core
-- Web3config `contractDataInputFill` has been defaulted to `data`, instead of `input`. (#6622)
+- Web3config `contractDataInputFill` has been defaulted to `data`, instead of `input`. (#6622)
#### web3-eth-contracts
-- By default, contracts will fill `data` instead of `input` within method calls (#6622)
+- By default, contracts will fill `data` instead of `input` within method calls (#6622)
### Added
-
#### web3-utils
- `SocketProvider` now contains public function `getPendingRequestQueueSize`, `getSentRequestsQueueSize` and `clearQueues` (#6479)
-- Added `safeDisconnect` as a `SocketProvider` method to disconnect only when request queue size and send request queue size is 0 (#6479)
+- Added `safeDisconnect` as a `SocketProvider` method to disconnect only when request queue size and send request queue size is 0 (#6479)
- Add `isContractInitOptions` method (#6555)
#### web3
@@ -2305,7 +2304,7 @@ If there are any bugs, improvements, optimizations or any new feature proposal f
#### web3-eth-contract
-- Allow the `deploy` function to accept parameters, even when no ABI was provided to the `Contract`(#6635)
+- Allow the `deploy` function to accept parameters, even when no ABI was provided to the `Contract`(#6635)
#### web3
@@ -2324,8 +2323,8 @@ If there are any bugs, improvements, optimizations or any new feature proposal f
#### web3-eth-contract
-- Fix and error that happen when trying to get past events by calling `contract.getPastEvents` or `contract.events.allEvents()`, if there is no matching events. (#6647)
-- Fixed: The Contract is not using the context wallet passed if context was passed at constructor. (#6661)
+- Fix and error that happen when trying to get past events by calling `contract.getPastEvents` or `contract.events.allEvents()`, if there is no matching events. (#6647)
+- Fixed: The Contract is not using the context wallet passed if context was passed at constructor. (#6661)
#### web3-utils
@@ -2347,7 +2346,7 @@ If there are any bugs, improvements, optimizations or any new feature proposal f
- Adds missing exported type `AbiItem` from 1.x to v4 for compatabiltiy (#6678)
-### Changed
+### Changed
#### web3
@@ -2359,7 +2358,7 @@ If there are any bugs, improvements, optimizations or any new feature proposal f
#### web3
-- Added EIP-6963 utility function `requestEIP6963Providers` for multi provider discovery
+- Added EIP-6963 utility function `requestEIP6963Providers` for multi provider discovery
#### web3-eth
@@ -2393,17 +2392,17 @@ If there are any bugs, improvements, optimizations or any new feature proposal f
#### web3-eth-ens
-- Added function getText and getName in ENS and resolver classes (#6914)
+- Added function getText and getName in ENS and resolver classes (#6914)
### fixed
#### web3-validator
-- Multi-dimensional arrays(with a fix length) are now handled properly when parsing ABIs (#6798)
+- Multi-dimensional arrays(with a fix length) are now handled properly when parsing ABIs (#6798)
#### web3-utils
-- fixed erroneous parsing of big numbers in the `toNumber(...)` function (#6880)
+- fixed erroneous parsing of big numbers in the `toNumber(...)` function (#6880)
## [4.8.0]
@@ -2421,30 +2420,60 @@ If there are any bugs, improvements, optimizations or any new feature proposal f
#### web3-eth-contract
-- Fix an issue with smart contract function overloading (#6922)
+- Fix an issue with smart contract function overloading (#6922)
#### web3-utils
-- fixed toHex incorrectly hexing Uint8Arrays and Buffer (#6957)
-- fixed isUint8Array not returning true for Buffer (#6957)
-
+- fixed toHex incorrectly hexing Uint8Arrays and Buffer (#6957)
+- fixed isUint8Array not returning true for Buffer (#6957)
### Added
#### web3-eth-contract
-- Added a console warning in case of an ambiguous call to a solidity method with parameter overloading (#6942)
-- Added contract.deploy(...).decodeData(...) and contract.decodeMethodData(...) that decode data based on the ABI (#6950)
+- Added a console warning in case of an ambiguous call to a solidity method with parameter overloading (#6942)
+- Added contract.deploy(...).decodeData(...) and contract.decodeMethodData(...) that decode data based on the ABI (#6950)
#### web3-eth
-- method `getBlock` now includes properties of eip 4844, 4895, 4788 when returning block (#6933)
+- method `getBlock` now includes properties of eip 4844, 4895, 4788 when returning block (#6933)
- update type `withdrawalsSchema`, `blockSchema` and `blockHeaderSchema` schemas to include properties of eip 4844, 4895, 4788 (#6933)
-
#### web3-types
- Added `signature` to type `AbiFunctionFragment` (#6922)
- 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
+
diff --git a/docs/docs/guides/web3_config/index.md b/docs/docs/guides/web3_config/index.md
index ea061762968..f6d041b6b15 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/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
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-core/src/web3_config.ts b/packages/web3-core/src/web3_config.ts
index 772653cfdeb..3c335292c4a 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/CHANGELOG.md b/packages/web3-eth-contract/CHANGELOG.md
index 2eb9a5ca676..8aa7c126ebb 100644
--- a/packages/web3-eth-contract/CHANGELOG.md
+++ b/packages/web3-eth-contract/CHANGELOG.md
@@ -328,7 +328,6 @@ Documentation:
- Added `dataInputFill` as a ContractInitOption, allowing users to have the choice using property `data`, `input` or `both` for contract methods to be sent to the RPC provider. (#6355)
- Added to `Web3Config` property `contractDataInputFill` allowing users to have the choice using property `data`, `input` or `both` for contract methods to be sent to the RPC provider when creating contracts. (#6377)
-
## [4.1.1]
### Changed
@@ -345,24 +344,24 @@ Documentation:
### Fixed
-- Will populate `data` for transactions in contract for metamask provider instead of `input` (#6534)
+- Will populate `data` for transactions in contract for metamask provider instead of `input` (#6534)
## [4.1.4]
### Changed
-- By default, contracts will fill `data` instead of `input` within method calls (#6622)
+- By default, contracts will fill `data` instead of `input` within method calls (#6622)
## [4.2.0]
### Changed
-- Allow the `deploy` function to accept parameters, even when no ABI was provided to the `Contract`(#6635)
+- Allow the `deploy` function to accept parameters, even when no ABI was provided to the `Contract`(#6635)
### Fixed
-- Fix and error that happen when trying to get past events by calling `contract.getPastEvents` or `contract.events.allEvents()`, if there is no matching events. (#6647)
-- Fixed: The Contract is not using the context wallet passed if context was passed at constructor. (#6661)
+- Fix and error that happen when trying to get past events by calling `contract.getPastEvents` or `contract.events.allEvents()`, if there is no matching events. (#6647)
+- Fixed: The Contract is not using the context wallet passed if context was passed at constructor. (#6661)
## [4.3.0]
@@ -374,11 +373,15 @@ Documentation:
### Fixed
-- Fix an issue with smart contract function overloading (#6922)
+- Fix an issue with smart contract function overloading (#6922)
### Added
-- Added a console warning in case of an ambiguous call to a solidity method with parameter overloading (#6942)
-- Added contract.deploy(...).decodeData(...) and contract.decodeMethodData(...) that decode data based on the ABI (#6950)
+- Added a console warning in case of an ambiguous call to a solidity method with parameter overloading (#6942)
+- Added contract.deploy(...).decodeData(...) and contract.decodeMethodData(...) that decode data based on the ABI (#6950)
## [Unreleased]
+
+### Added
+
+- `defaultReturnFormat` was added to all methods that have `ReturnType` param. (#6947)
diff --git a/packages/web3-eth-contract/src/contract.ts b/packages/web3-eth-contract/src/contract.ts
index 7ebff70a136..c4be775b31f 100644
--- a/packages/web3-eth-contract/src/contract.ts
+++ b/packages/web3-eth-contract/src/contract.ts
@@ -163,13 +163,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
>;
/**
@@ -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,13 +593,17 @@ export class Contract
? contextOrReturnFormat
: isDataFormat(optionsOrContextOrReturnFormat)
? optionsOrContextOrReturnFormat
- : returnFormat ?? DEFAULT_RETURN_FORMAT;
+ : returnFormat ?? this.defaultReturnFormat;
const address =
typeof addressOrOptionsOrContext === 'string' ? addressOrOptionsOrContext : undefined;
this.config.contractDataInputFill =
(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);
}
@@ -872,7 +886,7 @@ export class Contract
},
estimateGas: async (
options?: PayableCallOptions,
- returnFormat: ReturnFormat = DEFAULT_RETURN_FORMAT as ReturnFormat,
+ returnFormat: ReturnFormat = this.defaultReturnFormat as ReturnFormat,
) => {
const modifiedOptions = { ...options };
return this._contractMethodEstimateGas({
@@ -887,7 +901,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,
+ ),
),
decodeData: (data: HexString) => ({
...decodeMethodParams(
@@ -979,7 +997,7 @@ export class Contract
? param1
: isDataFormat(param2)
? param2
- : param3 ?? DEFAULT_RETURN_FORMAT;
+ : param3 ?? this.defaultReturnFormat;
const abi =
eventName === 'allEvents' || eventName === ALL_EVENTS
@@ -1018,7 +1036,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(),
);
}
@@ -1028,7 +1047,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()
+ );
});
});
}
@@ -1036,7 +1058,10 @@ export class Contract
return decodedLogs;
}
- private _parseAndSetAddress(value?: Address, returnFormat: DataFormat = DEFAULT_RETURN_FORMAT) {
+ private _parseAndSetAddress(
+ value?: Address,
+ returnFormat: DataFormat = this.defaultReturnFormat,
+ ) {
this._address = value
? toChecksumAddress(format({ format: 'address' }, value, returnFormat))
: value;
@@ -1059,7 +1084,7 @@ export class Contract
private _parseAndSetJsonInterface(
abis: ContractAbi,
- returnFormat: DataFormat = DEFAULT_RETURN_FORMAT,
+ returnFormat: DataFormat = this.defaultReturnFormat,
) {
this._functions = {};
this._methods = {} as ContractMethodsInterface;
@@ -1068,7 +1093,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 = {
@@ -1084,7 +1111,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, [
@@ -1092,10 +1121,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,
@@ -1108,7 +1137,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] =
@@ -1184,7 +1214,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);
@@ -1200,9 +1233,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
@@ -1224,14 +1257,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 = DEFAULT_RETURN_FORMAT as ReturnFormat,
+ returnFormat: ReturnFormat = this
+ .defaultReturnFormat as unknown as ReturnFormat,
) =>
this._contractMethodEstimateGas({
abi: methodAbi,
@@ -1289,7 +1330,12 @@ export class Contract
},
});
try {
- const result = await call(this, tx, block, DEFAULT_RETURN_FORMAT);
+ const result = await call(
+ this,
+ tx,
+ block,
+ this.defaultReturnFormat as typeof DEFAULT_RETURN_FORMAT,
+ );
return decodeMethodReturn(abi, result);
} catch (error: unknown) {
if (error instanceof ContractExecutionError) {
@@ -1320,7 +1366,7 @@ export class Contract
});
try {
- return createAccessList(this, tx, block, 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
@@ -1350,7 +1396,7 @@ export class Contract
contractOptions: modifiedContractOptions,
});
- const transactionToSend = sendTransaction(this, tx, DEFAULT_RETURN_FORMAT, {
+ const transactionToSend = sendTransaction(this, tx, this.defaultReturnFormat, {
// TODO Should make this configurable by the user
checkRevertBeforeSending: false,
contractAbi: this._jsonInterface,
@@ -1380,10 +1426,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, {
transactionResolver: receipt => {
if (receipt.status === BigInt(0)) {
throw new Web3ContractError("code couldn't be stored", receipt);
@@ -1423,16 +1469,20 @@ 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);
}
// eslint-disable-next-line class-methods-use-this
private _createContractEvent(
abi: AbiEventFragment & { signature: HexString },
- returnFormat: DataFormat = 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,
@@ -1442,7 +1492,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,
},
);
@@ -1455,7 +1508,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-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',
+ );
+ }
});
});
});
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-ens/src/ens.ts b/packages/web3-eth-ens/src/ens.ts
index 88d6ae58c83..254a33bc842 100644
--- a/packages/web3-eth-ens/src/ens.ts
+++ b/packages/web3-eth-ens/src/ens.ts
@@ -16,13 +16,16 @@ 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';
import {
Address,
- DEFAULT_RETURN_FORMAT,
EthExecutionAPI,
FMT_NUMBER,
PayableCallOptions,
@@ -37,25 +40,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 +178,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 +248,7 @@ export class ENS extends Web3Context {
return this._detectedAddress;
}
const networkType = await getId(this, {
- ...DEFAULT_RETURN_FORMAT,
+ ...this.defaultReturnFormat,
number: FMT_NUMBER.HEX,
}); // get the network from provider
const addr = registryAddresses[networkIds[networkType]];
@@ -292,10 +294,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-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);
diff --git a/packages/web3-eth/CHANGELOG.md b/packages/web3-eth/CHANGELOG.md
index b4b937ce6ae..ba7ee38a443 100644
--- a/packages/web3-eth/CHANGELOG.md
+++ b/packages/web3-eth/CHANGELOG.md
@@ -200,7 +200,7 @@ Documentation:
### Fixed
- Ensure provider.supportsSubscriptions exists before watching by subscription (#6440)
-- Fixed param sent to `checkRevertBeforeSending` in `sendSignedTransaction`
+- Fixed param sent to `checkRevertBeforeSending` in `sendSignedTransaction`
- Fixed `defaultTransactionBuilder` for value issue (#6509)
### Added
@@ -227,9 +227,13 @@ Documentation:
## [4.6.0]
-### Added
+### Added
-- method `getBlock` now includes properties of eip 4844, 4895, 4788 when returning block (#6933)
+- method `getBlock` now includes properties of eip 4844, 4895, 4788 when returning block (#6933)
- update type `withdrawalsSchema`, `blockSchema` and `blockHeaderSchema` schemas to include properties of eip 4844, 4895, 4788 (#6933)
-## [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/src/rpc_method_wrappers.ts b/packages/web3-eth/src/rpc_method_wrappers.ts
index 1a2cac1ffd8..20e832be892 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,
+ );
}
/**
@@ -359,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' },
@@ -373,7 +417,9 @@ export async function getTransaction(
return isNullish(response)
? response
- : formatTransaction(response, returnFormat, { fillInputAndData: true });
+ : formatTransaction(response, returnFormat, {
+ 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);
@@ -715,7 +779,7 @@ 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)) {
@@ -747,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,
@@ -781,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)
@@ -818,7 +882,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 +921,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 +945,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 +975,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 +1019,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 +1046,11 @@ export async function createAccessList(
blockNumberFormatted,
)) as unknown as AccessListResult;
- return format(accessListResultSchema, response, returnFormat);
+ return format(
+ accessListResultSchema,
+ response,
+ returnFormat ?? web3Context.defaultReturnFormat,
+ );
}
/**
@@ -987,5 +1071,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..6edb2ec52c3 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,7 @@ export async function getRevertReason<
web3Context: Web3Context,
transaction: TransactionCall,
contractAbi?: ContractAbi,
- returnFormat: ReturnFormat = 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 13edd253330..0d459017b4a 100644
--- a/packages/web3-eth/src/utils/transaction_builder.ts
+++ b/packages/web3-eth/src/utils/transaction_builder.ts
@@ -29,7 +29,6 @@ import {
Web3NetAPI,
Numbers,
DataFormat,
- DEFAULT_RETURN_FORMAT,
FormatType,
ETH_DATA_FORMAT,
} from 'web3-types';
@@ -99,7 +98,7 @@ export const getTransactionFromOrToAttr = (
export const getTransactionNonce = async (
web3Context: Web3Context,
address?: Address,
- returnFormat: ReturnFormat = 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
@@ -133,7 +132,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..959a7d5eddc 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,7 @@ export class Web3Eth extends Web3Context(
- returnFormat: ReturnFormat = DEFAULT_RETURN_FORMAT as ReturnFormat,
+ returnFormat: ReturnFormat = this.defaultReturnFormat as ReturnFormat,
) {
return rpcMethodsWrappers.getHashRate(this, returnFormat);
}
@@ -237,7 +238,7 @@ export class Web3Eth extends Web3Context(
- returnFormat: ReturnFormat = DEFAULT_RETURN_FORMAT as ReturnFormat,
+ returnFormat: ReturnFormat = this.defaultReturnFormat as ReturnFormat,
) {
return rpcMethodsWrappers.getGasPrice(this, returnFormat);
}
@@ -256,7 +257,7 @@ export class Web3Eth extends Web3Context(returnFormat: ReturnFormat = DEFAULT_RETURN_FORMAT as ReturnFormat) {
+ >(returnFormat: ReturnFormat = this.defaultReturnFormat as ReturnFormat) {
return rpcMethodsWrappers.getMaxPriorityFeePerGas(this, returnFormat);
}
@@ -300,7 +301,10 @@ export class Web3Eth extends Web3Context();
+ gasPrice = await this.getGasPrice<{
+ number: FMT_NUMBER.BIGINT;
+ bytes: FMT_BYTES.HEX;
+ }>();
} catch (error) {
// do nothing
}
@@ -361,7 +365,7 @@ export class Web3Eth extends Web3Context(
- returnFormat: ReturnFormat = DEFAULT_RETURN_FORMAT as ReturnFormat,
+ returnFormat: ReturnFormat = this.defaultReturnFormat as ReturnFormat,
) {
return rpcMethodsWrappers.getBlockNumber(this, returnFormat);
}
@@ -385,7 +389,7 @@ export class Web3Eth extends Web3Context(
address: Address,
blockNumber: BlockNumberOrTag = this.defaultBlock,
- returnFormat: ReturnFormat = DEFAULT_RETURN_FORMAT as ReturnFormat,
+ returnFormat: ReturnFormat = this.defaultReturnFormat as ReturnFormat,
) {
return rpcMethodsWrappers.getBalance(this, address, blockNumber, returnFormat);
}
@@ -421,9 +425,15 @@ export class Web3Eth extends Web3Context(
address: Address,
blockNumber: BlockNumberOrTag = this.defaultBlock,
- returnFormat: ReturnFormat = DEFAULT_RETURN_FORMAT as ReturnFormat,
+ returnFormat: ReturnFormat = this.defaultReturnFormat as ReturnFormat,
) {
return rpcMethodsWrappers.getCode(this, address, blockNumber, returnFormat);
}
@@ -527,7 +537,7 @@ export class Web3Eth extends Web3Context(
block: HexString32Bytes | BlockNumberOrTag = this.defaultBlock,
hydrated = false,
- returnFormat: ReturnFormat = DEFAULT_RETURN_FORMAT as ReturnFormat,
+ returnFormat: ReturnFormat = this.defaultReturnFormat as ReturnFormat,
) {
return rpcMethodsWrappers.getBlock(this, block, hydrated, returnFormat);
}
@@ -552,7 +562,7 @@ export class Web3Eth extends Web3Context(
block: HexString32Bytes | BlockNumberOrTag = this.defaultBlock,
- returnFormat: ReturnFormat = DEFAULT_RETURN_FORMAT as ReturnFormat,
+ returnFormat: ReturnFormat = this.defaultReturnFormat as ReturnFormat,
) {
return rpcMethodsWrappers.getBlockTransactionCount(this, block, returnFormat);
}
@@ -575,7 +585,7 @@ export class Web3Eth extends Web3Context(
block: HexString32Bytes | BlockNumberOrTag = this.defaultBlock,
- returnFormat: ReturnFormat = DEFAULT_RETURN_FORMAT as ReturnFormat,
+ returnFormat: ReturnFormat = this.defaultReturnFormat as ReturnFormat,
) {
return rpcMethodsWrappers.getBlockUncleCount(this, block, returnFormat);
}
@@ -646,7 +656,7 @@ export class Web3Eth extends Web3Context(
block: HexString32Bytes | BlockNumberOrTag = this.defaultBlock,
uncleIndex: Numbers,
- returnFormat: ReturnFormat = DEFAULT_RETURN_FORMAT as ReturnFormat,
+ returnFormat: ReturnFormat = this.defaultReturnFormat as ReturnFormat,
) {
return rpcMethodsWrappers.getUncle(this, block, uncleIndex, returnFormat);
}
@@ -701,9 +711,13 @@ export class Web3Eth extends Web3Context(
transactionHash: Bytes,
- returnFormat: ReturnFormat = DEFAULT_RETURN_FORMAT as ReturnFormat,
+ returnFormat: ReturnFormat = this.defaultReturnFormat 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 +808,7 @@ export class Web3Eth extends Web3Context(returnFormat: ReturnFormat = DEFAULT_RETURN_FORMAT as ReturnFormat) {
+ >(returnFormat: ReturnFormat = this.defaultReturnFormat as ReturnFormat) {
return rpcMethodsWrappers.getPendingTransactions(this, returnFormat);
}
@@ -853,9 +867,14 @@ export class Web3Eth extends Web3Context(
block: HexString32Bytes | BlockNumberOrTag = this.defaultBlock,
transactionIndex: Numbers,
- returnFormat: ReturnFormat = DEFAULT_RETURN_FORMAT as ReturnFormat,
+ returnFormat: ReturnFormat = this.defaultReturnFormat as ReturnFormat,
) {
- return rpcMethodsWrappers.getTransactionFromBlock(this, block, transactionIndex, returnFormat);
+ return rpcMethodsWrappers.getTransactionFromBlock(
+ this,
+ block,
+ transactionIndex,
+ returnFormat,
+ );
}
/**
@@ -904,7 +923,10 @@ export class Web3Eth extends Web3Context(transactionHash: Bytes, returnFormat: ReturnFormat = DEFAULT_RETURN_FORMAT as ReturnFormat) {
+ >(
+ transactionHash: Bytes,
+ returnFormat: ReturnFormat = this.defaultReturnFormat as ReturnFormat,
+ ) {
const response = await rpcMethodsWrappers.getTransactionReceipt(
this,
transactionHash,
@@ -934,10 +956,12 @@ 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 as ReturnFormat,
) {
return rpcMethodsWrappers.getTransactionCount(this, address, blockNumber, returnFormat);
}
@@ -1054,7 +1078,7 @@ export class Web3Eth extends Web3Context(
transaction: Bytes,
- returnFormat: ReturnFormat = DEFAULT_RETURN_FORMAT as ReturnFormat,
+ returnFormat: ReturnFormat = this.defaultReturnFormat as ReturnFormat,
options?: SendTransactionOptions,
) {
return rpcMethodsWrappers.sendSignedTransaction(this, transaction, returnFormat, options);
@@ -1182,7 +1206,7 @@ export class Web3Eth extends Web3Context(
message: Bytes,
addressOrIndex: Address | number,
- returnFormat: ReturnFormat = DEFAULT_RETURN_FORMAT as ReturnFormat,
+ returnFormat: ReturnFormat = this.defaultReturnFormat as ReturnFormat,
) {
return rpcMethodsWrappers.sign(this, message, addressOrIndex, returnFormat);
}
@@ -1240,7 +1264,7 @@ export class Web3Eth extends Web3Context(
transaction: Transaction,
- returnFormat: ReturnFormat = DEFAULT_RETURN_FORMAT as ReturnFormat,
+ returnFormat: ReturnFormat = this.defaultReturnFormat as ReturnFormat,
) {
return rpcMethodsWrappers.signTransaction(this, transaction, returnFormat);
}
@@ -1259,7 +1283,7 @@ export class Web3Eth extends Web3Context(
transaction: TransactionCall,
blockNumber: BlockNumberOrTag = this.defaultBlock,
- returnFormat: ReturnFormat = DEFAULT_RETURN_FORMAT as ReturnFormat,
+ returnFormat: ReturnFormat = this.defaultReturnFormat as ReturnFormat,
) {
return rpcMethodsWrappers.call(this, transaction, blockNumber, returnFormat);
}
@@ -1293,7 +1317,7 @@ export class Web3Eth extends Web3Context(
transaction: Transaction,
blockNumber: BlockNumberOrTag = this.defaultBlock,
- returnFormat: ReturnFormat = DEFAULT_RETURN_FORMAT as ReturnFormat,
+ returnFormat: ReturnFormat = this.defaultReturnFormat as ReturnFormat,
) {
return rpcMethodsWrappers.estimateGas(this, transaction, blockNumber, returnFormat);
}
@@ -1344,7 +1368,7 @@ export class Web3Eth extends Web3Context(
filter: Filter,
- returnFormat: ReturnFormat = DEFAULT_RETURN_FORMAT as ReturnFormat,
+ returnFormat: ReturnFormat = this.defaultReturnFormat as ReturnFormat,
) {
return rpcMethodsWrappers.getLogs(this, filter, returnFormat);
}
@@ -1427,7 +1451,7 @@ export class Web3Eth extends Web3Context(
- returnFormat: ReturnFormat = DEFAULT_RETURN_FORMAT as ReturnFormat,
+ returnFormat: ReturnFormat = this.defaultReturnFormat as ReturnFormat,
) {
return rpcMethodsWrappers.getChainId(this, returnFormat);
}
@@ -1520,7 +1544,7 @@ export class Web3Eth extends Web3Context(
transaction: TransactionForAccessList,
blockNumber: BlockNumberOrTag = this.defaultBlock,
- returnFormat: ReturnFormat = DEFAULT_RETURN_FORMAT as ReturnFormat,
+ returnFormat: ReturnFormat = this.defaultReturnFormat as ReturnFormat,
) {
return rpcMethodsWrappers.createAccessList(this, transaction, blockNumber, returnFormat);
}
@@ -1653,7 +1677,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/integration/format.test.ts b/packages/web3-eth/test/integration/format.test.ts
new file mode 100644
index 00000000000..b9962c065ff
--- /dev/null
+++ b/packages/web3-eth/test/integration/format.test.ts
@@ -0,0 +1,112 @@
+/*
+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 } 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';
+
+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);
+ });
+
+ 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..eba6792a2f8 100644
--- a/packages/web3-eth/test/integration/rpc.test.ts
+++ b/packages/web3-eth/test/integration/rpc.test.ts
@@ -26,7 +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 { Web3Eth } from '../../src';
import {
@@ -37,16 +36,11 @@ 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';
describe('rpc', () => {
let web3Eth: Web3Eth;
@@ -86,11 +80,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 +110,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-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-net/src/net.ts b/packages/web3-net/src/net.ts
index eb84e567bb5..ac376e86c5a 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,7 @@ export class Net extends Web3Context {
* ```
*/
public async getId(
- returnFormat: ReturnFormat = DEFAULT_RETURN_FORMAT as ReturnFormat,
+ returnFormat: ReturnFormat = this.defaultReturnFormat as ReturnFormat,
) {
return rpcMethodsWrappers.getId(this, returnFormat);
}
@@ -71,7 +71,7 @@ export class Net extends Web3Context {
* ```
*/
public async getPeerCount(
- returnFormat: ReturnFormat = DEFAULT_RETURN_FORMAT as ReturnFormat,
+ returnFormat: ReturnFormat = this.defaultReturnFormat as ReturnFormat,
) {
return rpcMethodsWrappers.getPeerCount(this, returnFormat);
}
diff --git a/packages/web3-types/CHANGELOG.md b/packages/web3-types/CHANGELOG.md
index b3a8628c9a5..3f96fe9d53d 100644
--- a/packages/web3-types/CHANGELOG.md
+++ b/packages/web3-types/CHANGELOG.md
@@ -194,4 +194,4 @@ Documentation:
### 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
+- update type `Withdrawals`, `block` and `BlockHeaderOutput` to include properties of eip 4844, 4895, 4788 (#6933)
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/CHANGELOG.md b/packages/web3-utils/CHANGELOG.md
index 0d18cd22d3b..1ae402166d7 100644
--- a/packages/web3-utils/CHANGELOG.md
+++ b/packages/web3-utils/CHANGELOG.md
@@ -174,7 +174,7 @@ Documentation:
### Added
- `SocketProvider` now contains public function `getPendingRequestQueueSize`, `getSentRequestsQueueSize` and `clearQueues` (#6479)
-- Added `safeDisconnect` as a `SocketProvider` method to disconnect only when request queue size and send request queue size is 0 (#6479)
+- Added `safeDisconnect` as a `SocketProvider` method to disconnect only when request queue size and send request queue size is 0 (#6479)
- Add `isContractInitOptions` method (#6555)
### Fixed
@@ -203,13 +203,17 @@ Documentation:
### Fixed
-- fixed erroneous parsing of big numbers in the `toNumber(...)` function (#6880)
+- fixed erroneous parsing of big numbers in the `toNumber(...)` function (#6880)
## [4.2.3]
+### Changed
+
+- Method `format` was changed. Now it has default value `DEFAULT_RETURN_FORMAT` for `returnFormat` parameter (#6947)
+
### Fixed
-- fixed toHex incorrectly hexing Uint8Arrays and Buffer (#6957)
-- fixed isUint8Array not returning true for Buffer (#6957)
+- fixed toHex incorrectly hexing Uint8Arrays and Buffer (#6957)
+- fixed isUint8Array not returning true for Buffer (#6957)
## [Unreleased]
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);
}
}
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..5496a9efce1
--- /dev/null
+++ b/packages/web3/test/integration/web3.format.test.ts
@@ -0,0 +1,107 @@
+/*
+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 } from 'web3-types';
+import { numberToHex } from 'web3-utils';
+import { Web3, Contract, FMT_BYTES, FMT_NUMBER } from '../../src';
+
+import {
+ closeOpenConnection,
+ getSystemTestProvider,
+ createNewAccount,
+ createTempAccount,
+ mapFormatToType,
+} from '../shared_fixtures/system_tests_utils';
+import { BasicAbi, BasicBytecode } from '../shared_fixtures/build/Basic';
+
+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);
+ });
+
+ 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',
+};