From 0d3760571acd342a33f65b91349dbaa0c1672da3 Mon Sep 17 00:00:00 2001 From: luu-alex <98a.lexluu@gmail.com> Date: Thu, 29 Aug 2024 03:47:01 +0800 Subject: [PATCH 1/5] format all files and fix formatter so it runs on commit --- .husky/pre-commit | 4 + fixtures/contracts/Basic.sol | 40 +- fixtures/contracts/GreeterWithOverloading.sol | 12 +- package.json | 3 +- packages/web3-core/CHANGELOG.md | 6 +- packages/web3-core/src/utils.ts | 11 +- packages/web3-core/src/web3_config.ts | 7 +- packages/web3-core/src/web3_context.ts | 21 +- packages/web3-errors/CHANGELOG.md | 8 +- packages/web3-errors/src/error_codes.ts | 1 - .../web3-errors/src/errors/response_errors.ts | 11 +- .../web3-errors/src/errors/schema_errors.ts | 1 - .../web3-errors/src/errors/utils_errors.ts | 1 - packages/web3-errors/src/index.ts | 2 +- packages/web3-errors/test/unit/errors.test.ts | 7 +- packages/web3-eth-abi/CHANGELOG.md | 2 +- packages/web3-eth-abi/src/api/errors_api.ts | 2 +- packages/web3-eth-abi/src/api/events_api.ts | 2 +- .../web3-eth-abi/src/api/functions_api.ts | 2 +- packages/web3-eth-abi/src/api/logs_api.ts | 2 +- .../web3-eth-abi/src/api/parameters_api.ts | 3 +- .../src/coders/base/numbersLimits.ts | 4 +- packages/web3-eth-accounts/CHANGELOG.md | 11 +- packages/web3-eth-accounts/src/account.ts | 2 +- .../src/common/chains/goerli.ts | 137 +- .../src/common/chains/mainnet.ts | 152 +- .../src/common/chains/sepolia.ts | 138 +- .../web3-eth-accounts/src/common/eips/1153.ts | 39 +- .../web3-eth-accounts/src/common/eips/1559.ts | 45 +- .../web3-eth-accounts/src/common/eips/2315.ts | 43 +- .../web3-eth-accounts/src/common/eips/2537.ts | 81 +- .../web3-eth-accounts/src/common/eips/2565.ts | 31 +- .../web3-eth-accounts/src/common/eips/2718.ts | 21 +- .../web3-eth-accounts/src/common/eips/2929.ts | 165 +- .../web3-eth-accounts/src/common/eips/2930.ts | 37 +- .../web3-eth-accounts/src/common/eips/3074.ts | 43 +- .../web3-eth-accounts/src/common/eips/3198.ts | 31 +- .../web3-eth-accounts/src/common/eips/3529.ts | 45 +- .../web3-eth-accounts/src/common/eips/3540.ts | 25 +- .../web3-eth-accounts/src/common/eips/3541.ts | 23 +- .../web3-eth-accounts/src/common/eips/3554.ts | 33 +- .../web3-eth-accounts/src/common/eips/3607.ts | 25 +- .../web3-eth-accounts/src/common/eips/3651.ts | 25 +- .../web3-eth-accounts/src/common/eips/3670.ts | 25 +- .../web3-eth-accounts/src/common/eips/3675.ts | 25 +- .../web3-eth-accounts/src/common/eips/3855.ts | 33 +- .../web3-eth-accounts/src/common/eips/3860.ts | 41 +- .../web3-eth-accounts/src/common/eips/4345.ts | 33 +- .../web3-eth-accounts/src/common/eips/4399.ts | 25 +- .../web3-eth-accounts/src/common/eips/4844.ts | 107 +- .../web3-eth-accounts/src/common/eips/4895.ts | 25 +- .../web3-eth-accounts/src/common/eips/5133.ts | 33 +- .../src/common/hardforks/arrowGlacier.ts | 21 +- .../src/common/hardforks/berlin.ts | 13 +- .../src/common/hardforks/byzantium.ts | 109 +- .../src/common/hardforks/chainstart.ts | 685 ++++--- .../src/common/hardforks/constantinople.ts | 109 +- .../src/common/hardforks/dao.ts | 19 +- .../src/common/hardforks/grayGlacier.ts | 21 +- .../src/common/hardforks/homestead.ts | 27 +- .../src/common/hardforks/istanbul.ts | 171 +- .../src/common/hardforks/london.ts | 13 +- .../src/common/hardforks/merge.ts | 21 +- .../common/hardforks/mergeForkIdTransition.ts | 13 +- .../src/common/hardforks/muirGlacier.ts | 29 +- .../src/common/hardforks/petersburg.ts | 64 +- .../src/common/hardforks/shanghai.ts | 14 +- .../src/common/hardforks/sharding.ts | 13 +- .../src/common/hardforks/spuriousDragon.ts | 36 +- .../src/common/hardforks/tangerineWhistle.ts | 83 +- packages/web3-eth-accounts/src/wallet.ts | 12 +- .../test/fixtures/account.ts | 32 +- .../test/unit/account_dom.test.ts | 14 +- packages/web3-eth-contract/CHANGELOG.md | 6 +- .../src/contract-deployer-method-class.ts | 56 +- packages/web3-eth-contract/src/contract.ts | 84 +- packages/web3-eth-contract/src/encoding.ts | 1 - packages/web3-eth-contract/src/utils.ts | 61 +- .../test/fixtures/AbiItem.ts | 162 +- .../contract_transaction_middleware.ts | 17 +- .../web3-eth-contract/test/fixtures/create.ts | 227 ++- .../test/fixtures/create2.ts | 101 +- .../integration/contract_accesslist.test.ts | 2 +- .../test/integration/contract_deploy.test.ts | 2 +- .../test/integration/contract_methods.test.ts | 11 +- .../local_account/contract_deploy.test.ts | 27 +- .../contract_overloaded_methods.test.ts | 5 +- .../test/unit/contract.test.ts | 20 +- .../test/unit/contract_typing.test.ts | 4 +- .../test/unit/function_overloading.test.ts | 10 +- .../web3-eth-contract/test/unit/utils.test.ts | 161 +- packages/web3-eth-ens/CHANGELOG.md | 4 +- packages/web3-eth-ens/src/ens.ts | 4 +- packages/web3-eth-ens/src/resolver.ts | 33 +- .../web3-eth-ens/test/integration/setup.js | 1 - packages/web3-eth-ens/test/unit/ens.test.ts | 6 +- .../web3-eth-ens/test/unit/resolver.test.ts | 67 +- packages/web3-eth-iban/CHANGELOG.md | 2 +- packages/web3-eth-personal/CHANGELOG.md | 2 +- packages/web3-eth-personal/src/personal.ts | 38 +- .../test/integration/personal.test.ts | 2 +- packages/web3-eth/CHANGELOG.md | 4 +- packages/web3-eth/src/rpc_method_wrappers.ts | 28 +- packages/web3-eth/src/schemas.ts | 20 +- packages/web3-eth/src/types.ts | 16 +- .../src/utils/detect_transaction_type.ts | 6 +- .../utils/prepare_transaction_for_signing.ts | 2 +- .../src/utils/reject_if_block_timeout.ts | 35 +- packages/web3-eth/src/utils/send_tx_helper.ts | 13 +- .../src/utils/watch_transaction_by_polling.ts | 2 +- packages/web3-eth/src/web3_eth.ts | 13 +- packages/web3-eth/test/e2e/e2e_utils.ts | 15 +- packages/web3-eth/test/e2e/setup.js | 1 - .../test/fixtures/transactions_data.ts | 194 +- .../integration/block/rpc.getBlock.test.ts | 2 +- .../rpc.getBlockTransactionCount.test.ts | 2 +- .../block/rpc.getBlockUncleCount.test.ts | 2 +- .../integration/block/rpc.getUncle.test.ts | 2 +- .../test/integration/defaults.test.ts | 1764 ++++++++--------- .../defaults.transactionBlockTimeout.test.ts | 15 +- .../integration/get_revert_reason.test.ts | 6 +- .../web3-eth/test/integration/nonce.test.ts | 14 +- .../integration/watch_transaction.test.ts | 11 +- .../web3_eth/createAccessList.test.ts | 2 +- .../integration/web3_eth/estimate_gas.test.ts | 2 +- .../web3_eth/getFeeHistory.test.ts | 2 +- .../web3_eth/send_signed_transaction.test.ts | 2 +- .../test/integration/web3_eth/sign.test.ts | 2 +- .../web3_eth/sign_transaction.test.ts | 2 +- .../integration/web3_eth/submit_work.test.ts | 23 +- .../unit/default_transaction_builder.test.ts | 1 - .../test/unit/detect_transaction_type.test.ts | 1 - .../prepare_transaction_for_signing.test.ts | 7 +- .../rpc_method_wrappers/fixtures/get_block.ts | 2 +- .../rpc_method_wrappers/get_block.test.ts | 11 +- .../send_transaction_middleware.test.ts | 108 +- .../web3-eth/test/unit/send_tx_helper.test.ts | 15 +- .../unit/utils/get_transaction_type.test.ts | 42 +- .../wait_for_transaction_receipt.test.ts | 2 +- .../watch_transaction_by_subscription.test.ts | 74 +- .../unit/web3_eth_calculate_fee_data.test.ts | 6 +- .../web3_eth_methods_no_parameters.test.ts | 4 +- .../web3_eth_methods_with_parameters.test.ts | 8 +- packages/web3-net/CHANGELOG.md | 2 +- .../test/fixtures/rpc_method_wrappers.ts | 2 +- .../test/integration/web3_net.test.ts | 4 +- .../test/unit/rpc_method_wrappers.test.ts | 1 - packages/web3-providers-http/CHANGELOG.md | 4 +- packages/web3-providers-http/src/index.ts | 4 +- packages/web3-providers-ipc/CHANGELOG.md | 2 +- packages/web3-providers-ws/CHANGELOG.md | 2 +- .../integration/geth_fault_tolerance.test.ts | 84 +- .../web_socket_provider_integration.test.ts | 13 +- .../test/unit/__mocks__/isomorphic-ws.ts | 7 +- .../test/unit/check_implementation.test.ts | 6 +- packages/web3-rpc-methods/CHANGELOG.md | 2 +- .../get_uncle_by_block_number.test.ts | 14 +- .../personal_rpc_methods/eth_personal.test.ts | 83 +- packages/web3-rpc-providers/CHANGELOG.md | 8 +- packages/web3-rpc-providers/README.md | 1 - packages/web3-rpc-providers/src/errors.ts | 7 +- packages/web3-rpc-providers/src/index.ts | 2 +- packages/web3-rpc-providers/src/types.ts | 46 +- .../web3-rpc-providers/src/web3_provider.ts | 311 +-- .../src/web3_provider_quicknode.ts | 186 +- .../test/unit/constructor.test.ts | 339 ++-- .../test/unit/request.test.ts | 201 +- packages/web3-types/CHANGELOG.md | 5 +- .../web3-types/src/apis/eth_execution_api.ts | 5 +- packages/web3-types/src/eth_abi_types.ts | 22 +- packages/web3-types/src/web3_base_provider.ts | 2 - packages/web3-utils/src/formatter.ts | 29 +- .../web3-utils/test/unit/formatter.test.ts | 12 +- packages/web3-validator/CHANGELOG.md | 8 +- packages/web3-validator/src/utils.ts | 81 +- .../web3-validator/src/validation/bytes.ts | 4 +- packages/web3-validator/src/validator.ts | 17 +- .../test/fixtures/abi_to_json_schema.ts | 904 ++++----- .../test/fixtures/validation.ts | 1 - .../test/unit/web3_validator.test.ts | 14 +- packages/web3/CHANGELOG.md | 59 +- packages/web3/README.md | 30 +- packages/web3/src/accounts.ts | 10 +- packages/web3/src/providers.exports.ts | 2 +- packages/web3/src/web3_eip6963.ts | 108 +- .../web3/test/cjs_black_box/.eslintrc.cjs | 2 +- .../test/web3-eth-contract/erc20.test.ts | 2 +- packages/web3/test/config/jest.config.js | 2 +- packages/web3/test/e2e/setup.js | 1 - .../test/web3-eth-contract/erc20.test.ts | 2 +- .../test/fixtures/transaction_middleware.ts | 17 +- .../integration/contract-middleware.test.ts | 37 +- .../external-providers/hardhat.test.ts | 5 +- packages/web3/test/integration/setup.js | 1 - .../web3/test/integration/web3.config.test.ts | 34 +- .../test/integration/web3RPCProviders.test.ts | 85 +- packages/web3/test/integration/ws.test.ts | 20 +- .../nodejs_test/long_connection_ws.js | 84 +- packages/web3/test/stress/setup.js | 1 - .../test/unit/contract-middleware.test.ts | 10 +- packages/web3/test/unit/web3.config.test.ts | 278 +-- packages/web3/test/unit/web3.test.ts | 4 +- packages/web3/test/unit/web3eip6963.test.ts | 148 +- scripts/system_tests_utils.ts | 46 +- templates/.prettierignore.tmpl | 1 + templates/cypress.config.js | 2 +- tools/web3-plugin-example/CHANGELOG.md | 4 +- .../src/custom_rpc_methods.ts | 6 +- .../src/request_manager_middleware.ts | 17 +- .../src/transaction_middleware.ts | 17 +- .../src/transaction_middleware_plugin.ts | 7 +- .../contract_transaction_middleware.test.ts | 43 +- .../test/unit/fixtures/transactions_data.ts | 194 +- .../test/unit/transaction_middleware.test.ts | 40 +- 214 files changed, 5351 insertions(+), 5172 deletions(-) create mode 100755 .husky/pre-commit diff --git a/.husky/pre-commit b/.husky/pre-commit new file mode 100755 index 00000000000..2f53ba1badd --- /dev/null +++ b/.husky/pre-commit @@ -0,0 +1,4 @@ +#!/usr/bin/env sh +. "$(dirname -- "$0")/_/husky.sh" + +yarn format diff --git a/fixtures/contracts/Basic.sol b/fixtures/contracts/Basic.sol index 89b3a1c8a65..e31573d026b 100644 --- a/fixtures/contracts/Basic.sol +++ b/fixtures/contracts/Basic.sol @@ -10,7 +10,11 @@ contract Basic { event StringEvent(string str); event MultiValueEvent(string str, uint256 val, bool flag); event MultiValueIndexedEvent(string str, uint256 indexed val, bool indexed flag); - event MultiValueIndexedEventWithStringIndexed(string indexed str, uint256 indexed val, bool indexed flag); + event MultiValueIndexedEventWithStringIndexed( + string indexed str, + uint256 indexed val, + bool indexed flag + ); constructor(uint256 _val, string memory _stringValue) { intValue = _val; @@ -29,11 +33,23 @@ contract Basic { return boolValue; } - function getValues() public view returns (uint256, string memory, bool) { + function getValues() + public + view + returns ( + uint256, + string memory, + bool + ) + { return (intValue, stringValue, boolValue); } - function setValues(uint256 _value, string memory _stringValue, bool _boolValue) public { + function setValues( + uint256 _value, + string memory _stringValue, + bool _boolValue + ) public { intValue = _value; stringValue = _stringValue; boolValue = _boolValue; @@ -51,11 +67,19 @@ contract Basic { revert('REVERTED WITH REVERT'); } - function firesMultiValueEvent(string memory str, uint256 val, bool flag) public { + function firesMultiValueEvent( + string memory str, + uint256 val, + bool flag + ) public { emit MultiValueEvent(str, val, flag); } - function firesMultiValueIndexedEvent(string memory str, uint256 val, bool flag) public { + function firesMultiValueIndexedEvent( + string memory str, + uint256 val, + bool flag + ) public { emit MultiValueIndexedEvent(str, val, flag); } @@ -63,7 +87,11 @@ contract Basic { emit StringEvent(_str); } - function firesMultiValueIndexedEventWithStringIndexed(string calldata str, uint256 val, bool flag) public { + function firesMultiValueIndexedEventWithStringIndexed( + string calldata str, + uint256 val, + bool flag + ) public { emit MultiValueIndexedEventWithStringIndexed(str, val, flag); } } diff --git a/fixtures/contracts/GreeterWithOverloading.sol b/fixtures/contracts/GreeterWithOverloading.sol index 384709287b2..4caf4e31df4 100644 --- a/fixtures/contracts/GreeterWithOverloading.sol +++ b/fixtures/contracts/GreeterWithOverloading.sol @@ -25,13 +25,16 @@ contract GreeterWithOverloading { return (true, greeting); } - // function overlading with additional parameter - function setGreeting(string memory _greeting, bool _raiseEvents) public returns (bool, string memory) { - if(_raiseEvents) { + // function overlading with additional parameter + function setGreeting(string memory _greeting, bool _raiseEvents) + public + returns (bool, string memory) + { + if (_raiseEvents) { emit GREETING_CHANGING(greeting, _greeting); } greeting = _greeting; - if(_raiseEvents) { + if (_raiseEvents) { emit GREETING_CHANGED(greeting); } return (true, greeting); @@ -41,4 +44,3 @@ contract GreeterWithOverloading { counter = counter + 1; } } - \ No newline at end of file diff --git a/package.json b/package.json index 1a3d5b6a5d5..02f2757993d 100644 --- a/package.json +++ b/package.json @@ -97,7 +97,8 @@ "husky:uninstall": "husky uninstall", "postinstall": "yarn build", "compile:contracts": "node ./scripts/compile_contracts.js && yarn format && yarn lint:fix", - "publish:canary": "lerna publish --canary --dist-tag dev --preid dev.$(git rev-parse --short HEAD) --exact --graph-type all --force-publish \"*\" --no-verify-access --yes" + "publish:canary": "lerna publish --canary --dist-tag dev --preid dev.$(git rev-parse --short HEAD) --exact --graph-type all --force-publish \"*\" --no-verify-access --yes", + "prepare": "husky install" }, "devDependencies": { "@cypress/webpack-preprocessor": "^5.12.0", diff --git a/packages/web3-core/CHANGELOG.md b/packages/web3-core/CHANGELOG.md index 2864dbd4d8d..18e3e0bf08a 100644 --- a/packages/web3-core/CHANGELOG.md +++ b/packages/web3-core/CHANGELOG.md @@ -195,7 +195,7 @@ Documentation: ### Fixed -- Fix `Web3Config` to properly update within other web3 packages when `setConfig` is used (#6555) +- Fix `Web3Config` to properly update within other web3 packages when `setConfig` is used (#6555) ### Added @@ -205,7 +205,7 @@ Documentation: ### Changed -- Web3config `contractDataInputFill` has been defaulted to `data`, istead of `input`. (#6622) +- Web3config `contractDataInputFill` has been defaulted to `data`, istead of `input`. (#6622) ## [4.4.0] @@ -233,4 +233,4 @@ Documentation: - `setConfig()` fix for `setMaxListenerWarningThreshold` fix (#5079) -## [Unreleased] \ No newline at end of file +## [Unreleased] diff --git a/packages/web3-core/src/utils.ts b/packages/web3-core/src/utils.ts index 34c5162c488..32b052a7706 100644 --- a/packages/web3-core/src/utils.ts +++ b/packages/web3-core/src/utils.ts @@ -33,10 +33,11 @@ export const isWeb3Provider = ( export const isMetaMaskProvider = ( provider: SupportedProviders, ): provider is MetaMaskProvider => - typeof provider !== 'string' && -'request' in provider && -provider.request.constructor.name === 'AsyncFunction' && 'isMetaMask' in provider && provider.isMetaMask; - + typeof provider !== 'string' && + 'request' in provider && + provider.request.constructor.name === 'AsyncFunction' && + 'isMetaMask' in provider && + provider.isMetaMask; export const isLegacyRequestProvider = ( provider: SupportedProviders, @@ -62,7 +63,7 @@ export const isLegacySendAsyncProvider = ( export const isSupportedProvider = ( provider: SupportedProviders, -): provider is SupportedProviders => +): provider is SupportedProviders => provider && (isWeb3Provider(provider) || isEIP1193Provider(provider) || diff --git a/packages/web3-core/src/web3_config.ts b/packages/web3-core/src/web3_config.ts index e647e05a9d5..f617756ad12 100644 --- a/packages/web3-core/src/web3_config.ts +++ b/packages/web3-core/src/web3_config.ts @@ -115,10 +115,11 @@ export abstract class Web3Config for (const key of keys) { this._triggerConfigChange(key, options[key]); - if(!isNullish(options[key]) && + if ( + !isNullish(options[key]) && typeof options[key] === 'number' && - key === 'maxListenersWarningThreshold' ) - { + key === 'maxListenersWarningThreshold' + ) { // additionally set in event emitter this.setMaxListenerWarningThreshold(Number(options[key])); } diff --git a/packages/web3-core/src/web3_context.ts b/packages/web3-core/src/web3_context.ts index 867f10f2350..207c4a64574 100644 --- a/packages/web3-core/src/web3_context.ts +++ b/packages/web3-core/src/web3_context.ts @@ -18,8 +18,15 @@ along with web3.js. If not, see . import { ExistingPluginNamespaceError } from 'web3-errors'; import { EthExecutionAPI, - HexString, Numbers, SupportedProviders, Transaction, Web3AccountProvider, Web3APISpec, Web3BaseProvider, Web3BaseWallet, - Web3BaseWalletAccount + HexString, + Numbers, + SupportedProviders, + Transaction, + Web3AccountProvider, + Web3APISpec, + Web3BaseProvider, + Web3BaseWallet, + Web3BaseWalletAccount, } from 'web3-types'; import { isNullish } from 'web3-utils'; import { BaseTransaction, TransactionFactory } from 'web3-eth-accounts'; @@ -130,7 +137,7 @@ export class Web3Context< registeredSubscriptions, accountProvider, wallet, - requestManagerMiddleware + requestManagerMiddleware, } = providerOrContext as Web3ContextInitOptions; this.setConfig(config ?? {}); @@ -140,7 +147,7 @@ export class Web3Context< new Web3RequestManager( provider, config?.enableExperimentalFeatures?.useSubscriptionWhenCheckingBlockTimeout, - requestManagerMiddleware + requestManagerMiddleware, ); if (subscriptionManager) { @@ -221,7 +228,7 @@ export class Web3Context< // @ts-expect-error No index signature with a parameter of type 'string' was found on type 'Web3Context' this[ContextRef.name] = newContextChild; - + return newContextChild; } @@ -359,10 +366,10 @@ export class Web3Context< return true; } - public setRequestManagerMiddleware(requestManagerMiddleware: RequestManagerMiddleware){ + public setRequestManagerMiddleware(requestManagerMiddleware: RequestManagerMiddleware) { this.requestManager.setMiddleware(requestManagerMiddleware); } - + /** * Will return the {@link Web3BatchRequest} constructor. */ diff --git a/packages/web3-errors/CHANGELOG.md b/packages/web3-errors/CHANGELOG.md index 47cb02f3cd3..2bcd592fb2d 100644 --- a/packages/web3-errors/CHANGELOG.md +++ b/packages/web3-errors/CHANGELOG.md @@ -170,18 +170,18 @@ Documentation: ### Added -- Added `InvalidIntegerError` error for fromWei and toWei (#7052) +- Added `InvalidIntegerError` error for fromWei and toWei (#7052) ## [1.2.1] ### Fixed -- Fixed the undefined data in `Eip838ExecutionError` constructor (#6905) +- Fixed the undefined data in `Eip838ExecutionError` constructor (#6905) ## [1.3.0] ### Added -- Added optional `statusCode` property of response in ResponseError. +- Added optional `statusCode` property of response in ResponseError. -## [Unreleased] \ No newline at end of file +## [Unreleased] diff --git a/packages/web3-errors/src/error_codes.ts b/packages/web3-errors/src/error_codes.ts index 16c95ad81cb..9950b6a0231 100644 --- a/packages/web3-errors/src/error_codes.ts +++ b/packages/web3-errors/src/error_codes.ts @@ -160,7 +160,6 @@ export const ERR_INVALID_INTEGER = 1015; // Validation error codes export const ERR_VALIDATION = 1100; - // Core error codes export const ERR_CORE_HARDFORK_MISMATCH = 1101; export const ERR_CORE_CHAIN_MISMATCH = 1102; diff --git a/packages/web3-errors/src/errors/response_errors.ts b/packages/web3-errors/src/errors/response_errors.ts index 214bf6652f6..401001973aa 100644 --- a/packages/web3-errors/src/errors/response_errors.ts +++ b/packages/web3-errors/src/errors/response_errors.ts @@ -51,7 +51,7 @@ export class ResponseError extends B response: JsonRpcResponse, message?: string, request?: JsonRpcPayload, - statusCode?: number + statusCode?: number, ) { super( message ?? @@ -85,7 +85,12 @@ export class ResponseError extends B } public toJSON() { - return { ...super.toJSON(), data: this.data, request: this.request, statusCode: this.statusCode }; + return { + ...super.toJSON(), + data: this.data, + request: this.request, + statusCode: this.statusCode, + }; } } @@ -111,4 +116,4 @@ export class InvalidResponseError ex this.cause = errorOrErrors as Error | undefined; } } -} \ No newline at end of file +} diff --git a/packages/web3-errors/src/errors/schema_errors.ts b/packages/web3-errors/src/errors/schema_errors.ts index 4d61684c616..142b970896b 100644 --- a/packages/web3-errors/src/errors/schema_errors.ts +++ b/packages/web3-errors/src/errors/schema_errors.ts @@ -28,5 +28,4 @@ export class SchemaFormatError extends BaseWeb3Error { public toJSON() { return { ...super.toJSON(), type: this.type }; } - } diff --git a/packages/web3-errors/src/errors/utils_errors.ts b/packages/web3-errors/src/errors/utils_errors.ts index ca213958b9a..3c96b847109 100644 --- a/packages/web3-errors/src/errors/utils_errors.ts +++ b/packages/web3-errors/src/errors/utils_errors.ts @@ -81,7 +81,6 @@ export class InvalidIntegerError extends InvalidValueError { public constructor(value: unknown) { super(value, 'not a valid unit. Must be a positive integer'); - } } diff --git a/packages/web3-errors/src/index.ts b/packages/web3-errors/src/index.ts index 2e4ef7abca6..fefa397d7f3 100644 --- a/packages/web3-errors/src/index.ts +++ b/packages/web3-errors/src/index.ts @@ -30,4 +30,4 @@ export * from './errors/response_errors.js'; export * from './errors/core_errors.js'; export * from './errors/rpc_errors.js'; export * from './errors/rpc_error_messages.js'; -export * from './errors/schema_errors.js'; \ No newline at end of file +export * from './errors/schema_errors.js'; diff --git a/packages/web3-errors/test/unit/errors.test.ts b/packages/web3-errors/test/unit/errors.test.ts index 0731f4dff37..a2d7cc2ecd6 100644 --- a/packages/web3-errors/test/unit/errors.test.ts +++ b/packages/web3-errors/test/unit/errors.test.ts @@ -329,7 +329,7 @@ describe('errors', () => { } as JsonRpcError).toJSON(), ).toMatchSnapshot(); }); - it('should return correctly when data is undefined', () => { + it('should return correctly when data is undefined', () => { expect( new contractErrors.Eip838ExecutionError({ data: undefined, @@ -391,10 +391,7 @@ describe('errors', () => { describe('SchemaFormatError', () => { it('should have valid json structure', () => { - expect( - new schemaErrors.SchemaFormatError("unsupported" - ).toJSON(), - ).toMatchSnapshot(); + expect(new schemaErrors.SchemaFormatError('unsupported').toJSON()).toMatchSnapshot(); }); }); }); diff --git a/packages/web3-eth-abi/CHANGELOG.md b/packages/web3-eth-abi/CHANGELOG.md index 6d04047ddef..8410c9d9f95 100644 --- a/packages/web3-eth-abi/CHANGELOG.md +++ b/packages/web3-eth-abi/CHANGELOG.md @@ -182,4 +182,4 @@ Documentation: - fix encodedata in EIP-712 (#7095) -## [Unreleased] \ No newline at end of file +## [Unreleased] diff --git a/packages/web3-eth-abi/src/api/errors_api.ts b/packages/web3-eth-abi/src/api/errors_api.ts index 69933f5eb6e..895ea02b2d5 100644 --- a/packages/web3-eth-abi/src/api/errors_api.ts +++ b/packages/web3-eth-abi/src/api/errors_api.ts @@ -16,7 +16,7 @@ along with web3.js. If not, see . */ /** - * + * * @module ABI */ diff --git a/packages/web3-eth-abi/src/api/events_api.ts b/packages/web3-eth-abi/src/api/events_api.ts index 67bb1791432..82d116e6967 100644 --- a/packages/web3-eth-abi/src/api/events_api.ts +++ b/packages/web3-eth-abi/src/api/events_api.ts @@ -16,7 +16,7 @@ along with web3.js. If not, see . */ /** - * + * * @module ABI */ diff --git a/packages/web3-eth-abi/src/api/functions_api.ts b/packages/web3-eth-abi/src/api/functions_api.ts index 776cb084940..7504f352275 100644 --- a/packages/web3-eth-abi/src/api/functions_api.ts +++ b/packages/web3-eth-abi/src/api/functions_api.ts @@ -16,7 +16,7 @@ along with web3.js. If not, see . */ /** - * + * * @module ABI */ import { AbiError } from 'web3-errors'; diff --git a/packages/web3-eth-abi/src/api/logs_api.ts b/packages/web3-eth-abi/src/api/logs_api.ts index f7ebd012d57..678ec6d7129 100644 --- a/packages/web3-eth-abi/src/api/logs_api.ts +++ b/packages/web3-eth-abi/src/api/logs_api.ts @@ -16,7 +16,7 @@ along with web3.js. If not, see . */ /** - * + * * @module ABI */ diff --git a/packages/web3-eth-abi/src/api/parameters_api.ts b/packages/web3-eth-abi/src/api/parameters_api.ts index d9cbd106673..f81a32e9db3 100644 --- a/packages/web3-eth-abi/src/api/parameters_api.ts +++ b/packages/web3-eth-abi/src/api/parameters_api.ts @@ -16,7 +16,7 @@ along with web3.js. If not, see . */ /** - * + * * @module ABI */ @@ -27,7 +27,6 @@ import { encodeParameters } from '../coders/encode.js'; export { encodeParameters, inferTypesAndEncodeParameters } from '../coders/encode.js'; - /** * Encodes a parameter based on its type to its ABI representation. * @param abi - The type of the parameter. See the [Solidity documentation](https://docs.soliditylang.org/en/develop/types.html) for a list of types. diff --git a/packages/web3-eth-abi/src/coders/base/numbersLimits.ts b/packages/web3-eth-abi/src/coders/base/numbersLimits.ts index 29f11462843..4376d9a1a90 100644 --- a/packages/web3-eth-abi/src/coders/base/numbersLimits.ts +++ b/packages/web3-eth-abi/src/coders/base/numbersLimits.ts @@ -15,9 +15,9 @@ You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see . */ -/* +/* * this variable contains the precalculated limits for all the numbers for uint and int types -*/ + */ export const numberLimits = new Map(); let base = BigInt(256); // 2 ^ 8 = 256 diff --git a/packages/web3-eth-accounts/CHANGELOG.md b/packages/web3-eth-accounts/CHANGELOG.md index 5a9768477e5..dc08d0cc692 100644 --- a/packages/web3-eth-accounts/CHANGELOG.md +++ b/packages/web3-eth-accounts/CHANGELOG.md @@ -136,7 +136,6 @@ Documentation: - Fixed "The `r` and `s` returned by `sign` to does not always consist of 64 characters" (#6411) - ## [4.1.0] ### Added @@ -147,7 +146,7 @@ Documentation: ### Fixed -- Fixed `recover` function, `v` will be normalized to value 0,1 (#6344) +- Fixed `recover` function, `v` will be normalized to value 0,1 (#6344) ## [4.1.1] @@ -166,7 +165,7 @@ Documentation: ### Changed -- baseTransaction method updated (#7095) +- baseTransaction method updated (#7095) ## [4.2.0] @@ -175,11 +174,13 @@ Documentation: - Added public function `signMessageWithPrivateKey` (#7174) ### Fixed -- Fix `TransactionFactory.registerTransactionType` not working, if there is a version mistatch between `web3-eth` and `web3-eth-accounts` by saving `extraTxTypes` at `globals`. (#7197) + +- Fix `TransactionFactory.registerTransactionType` not working, if there is a version mistatch between `web3-eth` and `web3-eth-accounts` by saving `extraTxTypes` at `globals`. (#7197) ## [4.2.1] ### Fixed -- Revert `TransactionFactory.registerTransactionType` if there is a version mistatch between `web3-eth` and `web3-eth-accounts` and fix nextjs problem. (#7216) + +- Revert `TransactionFactory.registerTransactionType` if there is a version mistatch between `web3-eth` and `web3-eth-accounts` and fix nextjs problem. (#7216) ## [Unreleased] diff --git a/packages/web3-eth-accounts/src/account.ts b/packages/web3-eth-accounts/src/account.ts index ac8e0adcfc6..e928a95f53f 100644 --- a/packages/web3-eth-accounts/src/account.ts +++ b/packages/web3-eth-accounts/src/account.ts @@ -172,7 +172,7 @@ export const hashMessage = (message: string): string => { /** * Takes a hash of a message and a private key, signs the message using the SECP256k1 elliptic curve algorithm, and returns the signature components. - * @param hash - The hash of the message to be signed, represented as a hexadecimal string. + * @param hash - The hash of the message to be signed, represented as a hexadecimal string. * @param privateKey - The private key used to sign the message, represented as a byte array. * @returns - The signature Object containing the message, messageHash, signature r, s, v */ diff --git a/packages/web3-eth-accounts/src/common/chains/goerli.ts b/packages/web3-eth-accounts/src/common/chains/goerli.ts index d09be79d2cc..f49b1f0bc8c 100644 --- a/packages/web3-eth-accounts/src/common/chains/goerli.ts +++ b/packages/web3-eth-accounts/src/common/chains/goerli.ts @@ -1,97 +1,98 @@ export default { - "name": "goerli", - "chainId": 5, - "networkId": 5, - "defaultHardfork": "merge", - "consensus": { - "type": "poa", - "algorithm": "clique", - "clique": { - "period": 15, - "epoch": 30000 - } + name: 'goerli', + chainId: 5, + networkId: 5, + defaultHardfork: 'merge', + consensus: { + type: 'poa', + algorithm: 'clique', + clique: { + period: 15, + epoch: 30000, + }, }, - "comment": "Cross-client PoA test network", - "url": "https://github.com/goerli/testnet", - "genesis": { - "timestamp": "0x5c51a607", - "gasLimit": 10485760, - "difficulty": 1, - "nonce": "0x0000000000000000", - "extraData": "0x22466c6578692069732061207468696e6722202d204166726900000000000000e0a2bd4258d2768837baa26a28fe71dc079f84c70000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" + comment: 'Cross-client PoA test network', + url: 'https://github.com/goerli/testnet', + genesis: { + timestamp: '0x5c51a607', + gasLimit: 10485760, + difficulty: 1, + nonce: '0x0000000000000000', + extraData: + '0x22466c6578692069732061207468696e6722202d204166726900000000000000e0a2bd4258d2768837baa26a28fe71dc079f84c70000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000', }, - "hardforks": [ + hardforks: [ { - "name": "chainstart", - "block": 0, - "forkHash": "0xa3f5ab08" + name: 'chainstart', + block: 0, + forkHash: '0xa3f5ab08', }, { - "name": "homestead", - "block": 0, - "forkHash": "0xa3f5ab08" + name: 'homestead', + block: 0, + forkHash: '0xa3f5ab08', }, { - "name": "tangerineWhistle", - "block": 0, - "forkHash": "0xa3f5ab08" + name: 'tangerineWhistle', + block: 0, + forkHash: '0xa3f5ab08', }, { - "name": "spuriousDragon", - "block": 0, - "forkHash": "0xa3f5ab08" + name: 'spuriousDragon', + block: 0, + forkHash: '0xa3f5ab08', }, { - "name": "byzantium", - "block": 0, - "forkHash": "0xa3f5ab08" + name: 'byzantium', + block: 0, + forkHash: '0xa3f5ab08', }, { - "name": "constantinople", - "block": 0, - "forkHash": "0xa3f5ab08" + name: 'constantinople', + block: 0, + forkHash: '0xa3f5ab08', }, { - "name": "petersburg", - "block": 0, - "forkHash": "0xa3f5ab08" + name: 'petersburg', + block: 0, + forkHash: '0xa3f5ab08', }, { - "name": "istanbul", - "block": 1561651, - "forkHash": "0xc25efa5c" + name: 'istanbul', + block: 1561651, + forkHash: '0xc25efa5c', }, { - "name": "berlin", - "block": 4460644, - "forkHash": "0x757a1c47" + name: 'berlin', + block: 4460644, + forkHash: '0x757a1c47', }, { - "name": "london", - "block": 5062605, - "forkHash": "0xb8c6299d" + name: 'london', + block: 5062605, + forkHash: '0xb8c6299d', }, { - "//_comment": "The forkHash will remain same as mergeForkIdTransition is post merge, terminal block: https://goerli.etherscan.io/block/7382818", - "name": "merge", - "ttd": "10790000", - "block": 7382819, - "forkHash": "0xb8c6299d" + '//_comment': + 'The forkHash will remain same as mergeForkIdTransition is post merge, terminal block: https://goerli.etherscan.io/block/7382818', + name: 'merge', + ttd: '10790000', + block: 7382819, + forkHash: '0xb8c6299d', }, { - "name": "mergeForkIdTransition", - "block": null, - "forkHash": null + name: 'mergeForkIdTransition', + block: null, + forkHash: null, }, { - "name": "shanghai", - "block": null, - "forkHash": null - } + name: 'shanghai', + block: null, + forkHash: null, + }, + ], + bootstrapNodes: [], + dnsNetworks: [ + 'enrtree://AKA3AM6LPBYEUDMVNU3BSVQJ5AD45Y7YPOHJLEF6W26QOE4VTUDPE@all.goerli.ethdisco.net', ], - "bootstrapNodes": [], - "dnsNetworks": [ - "enrtree://AKA3AM6LPBYEUDMVNU3BSVQJ5AD45Y7YPOHJLEF6W26QOE4VTUDPE@all.goerli.ethdisco.net" - ] -} - ; \ No newline at end of file +}; diff --git a/packages/web3-eth-accounts/src/common/chains/mainnet.ts b/packages/web3-eth-accounts/src/common/chains/mainnet.ts index d18bc733a94..356d6472568 100644 --- a/packages/web3-eth-accounts/src/common/chains/mainnet.ts +++ b/packages/web3-eth-accounts/src/common/chains/mainnet.ts @@ -1,113 +1,113 @@ export default { - "name": "mainnet", - "chainId": 1, - "networkId": 1, - "defaultHardfork": "merge", - "consensus": { - "type": "pow", - "algorithm": "ethash", - "ethash": {} + name: 'mainnet', + chainId: 1, + networkId: 1, + defaultHardfork: 'merge', + consensus: { + type: 'pow', + algorithm: 'ethash', + ethash: {}, }, - "comment": "The Ethereum main chain", - "url": "https://ethstats.net/", - "genesis": { - "gasLimit": 5000, - "difficulty": 17179869184, - "nonce": "0x0000000000000042", - "extraData": "0x11bbe8db4e347b4e8c937c1c8370e4b5ed33adb3db69cbdb7a38e1e50b1b82fa" + comment: 'The Ethereum main chain', + url: 'https://ethstats.net/', + genesis: { + gasLimit: 5000, + difficulty: 17179869184, + nonce: '0x0000000000000042', + extraData: '0x11bbe8db4e347b4e8c937c1c8370e4b5ed33adb3db69cbdb7a38e1e50b1b82fa', }, - "hardforks": [ + hardforks: [ { - "name": "chainstart", - "block": 0, - "forkHash": "0xfc64ec04" + name: 'chainstart', + block: 0, + forkHash: '0xfc64ec04', }, { - "name": "homestead", - "block": 1150000, - "forkHash": "0x97c2c34c" + name: 'homestead', + block: 1150000, + forkHash: '0x97c2c34c', }, { - "name": "dao", - "block": 1920000, - "forkHash": "0x91d1f948" + name: 'dao', + block: 1920000, + forkHash: '0x91d1f948', }, { - "name": "tangerineWhistle", - "block": 2463000, - "forkHash": "0x7a64da13" + name: 'tangerineWhistle', + block: 2463000, + forkHash: '0x7a64da13', }, { - "name": "spuriousDragon", - "block": 2675000, - "forkHash": "0x3edd5b10" + name: 'spuriousDragon', + block: 2675000, + forkHash: '0x3edd5b10', }, { - "name": "byzantium", - "block": 4370000, - "forkHash": "0xa00bc324" + name: 'byzantium', + block: 4370000, + forkHash: '0xa00bc324', }, { - "name": "constantinople", - "block": 7280000, - "forkHash": "0x668db0af" + name: 'constantinople', + block: 7280000, + forkHash: '0x668db0af', }, { - "name": "petersburg", - "block": 7280000, - "forkHash": "0x668db0af" + name: 'petersburg', + block: 7280000, + forkHash: '0x668db0af', }, { - "name": "istanbul", - "block": 9069000, - "forkHash": "0x879d6e30" + name: 'istanbul', + block: 9069000, + forkHash: '0x879d6e30', }, { - "name": "muirGlacier", - "block": 9200000, - "forkHash": "0xe029e991" + name: 'muirGlacier', + block: 9200000, + forkHash: '0xe029e991', }, { - "name": "berlin", - "block": 12244000, - "forkHash": "0x0eb440f6" + name: 'berlin', + block: 12244000, + forkHash: '0x0eb440f6', }, { - "name": "london", - "block": 12965000, - "forkHash": "0xb715077d" + name: 'london', + block: 12965000, + forkHash: '0xb715077d', }, { - "name": "arrowGlacier", - "block": 13773000, - "forkHash": "0x20c327fc" + name: 'arrowGlacier', + block: 13773000, + forkHash: '0x20c327fc', }, { - "name": "grayGlacier", - "block": 15050000, - "forkHash": "0xf0afd0e3" + name: 'grayGlacier', + block: 15050000, + forkHash: '0xf0afd0e3', }, { - "//_comment": "The forkHash will remain same as mergeForkIdTransition is post merge, terminal block: https://etherscan.io/block/15537393", - "name": "merge", - "ttd": "58750000000000000000000", - "block": 15537394, - "forkHash": "0xf0afd0e3" + '//_comment': + 'The forkHash will remain same as mergeForkIdTransition is post merge, terminal block: https://etherscan.io/block/15537393', + name: 'merge', + ttd: '58750000000000000000000', + block: 15537394, + forkHash: '0xf0afd0e3', }, { - "name": "mergeForkIdTransition", - "block": null, - "forkHash": null + name: 'mergeForkIdTransition', + block: null, + forkHash: null, }, { - "name": "shanghai", - "block": null, - "forkHash": null - } + name: 'shanghai', + block: null, + forkHash: null, + }, + ], + bootstrapNodes: [], + dnsNetworks: [ + 'enrtree://AKA3AM6LPBYEUDMVNU3BSVQJ5AD45Y7YPOHJLEF6W26QOE4VTUDPE@all.mainnet.ethdisco.net', ], - "bootstrapNodes": [], - "dnsNetworks": [ - "enrtree://AKA3AM6LPBYEUDMVNU3BSVQJ5AD45Y7YPOHJLEF6W26QOE4VTUDPE@all.mainnet.ethdisco.net" - ] -} - ; \ No newline at end of file +}; diff --git a/packages/web3-eth-accounts/src/common/chains/sepolia.ts b/packages/web3-eth-accounts/src/common/chains/sepolia.ts index 1de20e440ee..f861601d06d 100644 --- a/packages/web3-eth-accounts/src/common/chains/sepolia.ts +++ b/packages/web3-eth-accounts/src/common/chains/sepolia.ts @@ -1,100 +1,100 @@ export default { - "name": "sepolia", - "chainId": 11155111, - "networkId": 11155111, - "defaultHardfork": "merge", - "consensus": { - "type": "pow", - "algorithm": "ethash", - "ethash": {} + name: 'sepolia', + chainId: 11155111, + networkId: 11155111, + defaultHardfork: 'merge', + consensus: { + type: 'pow', + algorithm: 'ethash', + ethash: {}, }, - "comment": "PoW test network to replace Ropsten", - "url": "https://github.com/ethereum/go-ethereum/pull/23730", - "genesis": { - "timestamp": "0x6159af19", - "gasLimit": 30000000, - "difficulty": 131072, - "nonce": "0x0000000000000000", - "extraData": "0x5365706f6c69612c20417468656e732c204174746963612c2047726565636521" + comment: 'PoW test network to replace Ropsten', + url: 'https://github.com/ethereum/go-ethereum/pull/23730', + genesis: { + timestamp: '0x6159af19', + gasLimit: 30000000, + difficulty: 131072, + nonce: '0x0000000000000000', + extraData: '0x5365706f6c69612c20417468656e732c204174746963612c2047726565636521', }, - "hardforks": [ + hardforks: [ { - "name": "chainstart", - "block": 0, - "forkHash": "0xfe3366e7" + name: 'chainstart', + block: 0, + forkHash: '0xfe3366e7', }, { - "name": "homestead", - "block": 0, - "forkHash": "0xfe3366e7" + name: 'homestead', + block: 0, + forkHash: '0xfe3366e7', }, { - "name": "tangerineWhistle", - "block": 0, - "forkHash": "0xfe3366e7" + name: 'tangerineWhistle', + block: 0, + forkHash: '0xfe3366e7', }, { - "name": "spuriousDragon", - "block": 0, - "forkHash": "0xfe3366e7" + name: 'spuriousDragon', + block: 0, + forkHash: '0xfe3366e7', }, { - "name": "byzantium", - "block": 0, - "forkHash": "0xfe3366e7" + name: 'byzantium', + block: 0, + forkHash: '0xfe3366e7', }, { - "name": "constantinople", - "block": 0, - "forkHash": "0xfe3366e7" + name: 'constantinople', + block: 0, + forkHash: '0xfe3366e7', }, { - "name": "petersburg", - "block": 0, - "forkHash": "0xfe3366e7" + name: 'petersburg', + block: 0, + forkHash: '0xfe3366e7', }, { - "name": "istanbul", - "block": 0, - "forkHash": "0xfe3366e7" + name: 'istanbul', + block: 0, + forkHash: '0xfe3366e7', }, { - "name": "muirGlacier", - "block": 0, - "forkHash": "0xfe3366e7" + name: 'muirGlacier', + block: 0, + forkHash: '0xfe3366e7', }, { - "name": "berlin", - "block": 0, - "forkHash": "0xfe3366e7" + name: 'berlin', + block: 0, + forkHash: '0xfe3366e7', }, { - "name": "london", - "block": 0, - "forkHash": "0xfe3366e7" + name: 'london', + block: 0, + forkHash: '0xfe3366e7', }, { - "//_comment": "The forkHash will remain same as mergeForkIdTransition is post merge, terminal block: https://sepolia.etherscan.io/block/1450408", - "name": "merge", - "ttd": "17000000000000000", - "block": 1450409, - "forkHash": "0xfe3366e7" + '//_comment': + 'The forkHash will remain same as mergeForkIdTransition is post merge, terminal block: https://sepolia.etherscan.io/block/1450408', + name: 'merge', + ttd: '17000000000000000', + block: 1450409, + forkHash: '0xfe3366e7', }, { - "name": "mergeForkIdTransition", - "block": 1735371, - "forkHash": "0xb96cbd13" + name: 'mergeForkIdTransition', + block: 1735371, + forkHash: '0xb96cbd13', }, { - "name": "shanghai", - "block": null, - "timestamp": "1677557088", - "forkHash": "0xf7f9bc08" - } + name: 'shanghai', + block: null, + timestamp: '1677557088', + forkHash: '0xf7f9bc08', + }, + ], + bootstrapNodes: [], + dnsNetworks: [ + 'enrtree://AKA3AM6LPBYEUDMVNU3BSVQJ5AD45Y7YPOHJLEF6W26QOE4VTUDPE@all.sepolia.ethdisco.net', ], - "bootstrapNodes": [], - "dnsNetworks": [ - "enrtree://AKA3AM6LPBYEUDMVNU3BSVQJ5AD45Y7YPOHJLEF6W26QOE4VTUDPE@all.sepolia.ethdisco.net" - ] -} - ; \ No newline at end of file +}; diff --git a/packages/web3-eth-accounts/src/common/eips/1153.ts b/packages/web3-eth-accounts/src/common/eips/1153.ts index a7440d29d19..ee2a9dbc9e9 100644 --- a/packages/web3-eth-accounts/src/common/eips/1153.ts +++ b/packages/web3-eth-accounts/src/common/eips/1153.ts @@ -1,23 +1,22 @@ export default { - "name": "EIP-1153", - "number": 1153, - "comment": "Transient Storage", - "url": "https://eips.ethereum.org/EIPS/eip-1153", - "status": "Review", - "minimumHardfork": "chainstart", - "requiredEIPs": [], - "gasConfig": {}, - "gasPrices": { - "tstore": { - "v": 100, - "d": "Base fee of the TSTORE opcode" + name: 'EIP-1153', + number: 1153, + comment: 'Transient Storage', + url: 'https://eips.ethereum.org/EIPS/eip-1153', + status: 'Review', + minimumHardfork: 'chainstart', + requiredEIPs: [], + gasConfig: {}, + gasPrices: { + tstore: { + v: 100, + d: 'Base fee of the TSTORE opcode', + }, + tload: { + v: 100, + d: 'Base fee of the TLOAD opcode', }, - "tload": { - "v": 100, - "d": "Base fee of the TLOAD opcode" - } }, - "vm": {}, - "pow": {} -} - ; \ No newline at end of file + vm: {}, + pow: {}, +}; diff --git a/packages/web3-eth-accounts/src/common/eips/1559.ts b/packages/web3-eth-accounts/src/common/eips/1559.ts index ef3f04422e9..3a070138543 100644 --- a/packages/web3-eth-accounts/src/common/eips/1559.ts +++ b/packages/web3-eth-accounts/src/common/eips/1559.ts @@ -1,27 +1,26 @@ export default { - "name": "EIP-1559", - "number": 1559, - "comment": "Fee market change for ETH 1.0 chain", - "url": "https://eips.ethereum.org/EIPS/eip-1559", - "status": "Final", - "minimumHardfork": "berlin", - "requiredEIPs": [2930], - "gasConfig": { - "baseFeeMaxChangeDenominator": { - "v": 8, - "d": "Maximum base fee change denominator" + name: 'EIP-1559', + number: 1559, + comment: 'Fee market change for ETH 1.0 chain', + url: 'https://eips.ethereum.org/EIPS/eip-1559', + status: 'Final', + minimumHardfork: 'berlin', + requiredEIPs: [2930], + gasConfig: { + baseFeeMaxChangeDenominator: { + v: 8, + d: 'Maximum base fee change denominator', }, - "elasticityMultiplier": { - "v": 2, - "d": "Maximum block gas target elasticity" + elasticityMultiplier: { + v: 2, + d: 'Maximum block gas target elasticity', + }, + initialBaseFee: { + v: 1000000000, + d: 'Initial base fee on first EIP1559 block', }, - "initialBaseFee": { - "v": 1000000000, - "d": "Initial base fee on first EIP1559 block" - } }, - "gasPrices": {}, - "vm": {}, - "pow": {} -} - ; \ No newline at end of file + gasPrices: {}, + vm: {}, + pow: {}, +}; diff --git a/packages/web3-eth-accounts/src/common/eips/2315.ts b/packages/web3-eth-accounts/src/common/eips/2315.ts index d29efa3049d..11ed6b5c2fe 100644 --- a/packages/web3-eth-accounts/src/common/eips/2315.ts +++ b/packages/web3-eth-accounts/src/common/eips/2315.ts @@ -1,26 +1,25 @@ export default { - "name": "EIP-2315", - "number": 2315, - "comment": "Simple subroutines for the EVM", - "url": "https://eips.ethereum.org/EIPS/eip-2315", - "status": "Draft", - "minimumHardfork": "istanbul", - "gasConfig": {}, - "gasPrices": { - "beginsub": { - "v": 2, - "d": "Base fee of the BEGINSUB opcode" + name: 'EIP-2315', + number: 2315, + comment: 'Simple subroutines for the EVM', + url: 'https://eips.ethereum.org/EIPS/eip-2315', + status: 'Draft', + minimumHardfork: 'istanbul', + gasConfig: {}, + gasPrices: { + beginsub: { + v: 2, + d: 'Base fee of the BEGINSUB opcode', }, - "returnsub": { - "v": 5, - "d": "Base fee of the RETURNSUB opcode" + returnsub: { + v: 5, + d: 'Base fee of the RETURNSUB opcode', + }, + jumpsub: { + v: 10, + d: 'Base fee of the JUMPSUB opcode', }, - "jumpsub": { - "v": 10, - "d": "Base fee of the JUMPSUB opcode" - } }, - "vm": {}, - "pow": {} -} - ; \ No newline at end of file + vm: {}, + pow: {}, +}; diff --git a/packages/web3-eth-accounts/src/common/eips/2537.ts b/packages/web3-eth-accounts/src/common/eips/2537.ts index 14fa62abdb1..b8cc037a717 100644 --- a/packages/web3-eth-accounts/src/common/eips/2537.ts +++ b/packages/web3-eth-accounts/src/common/eips/2537.ts @@ -1,46 +1,46 @@ export default { - "name": "EIP-2537", - "number": 2537, - "comment": "BLS12-381 precompiles", - "url": "https://eips.ethereum.org/EIPS/eip-2537", - "status": "Draft", - "minimumHardfork": "chainstart", - "gasConfig": {}, - "gasPrices": { - "Bls12381G1AddGas": { - "v": 600, - "d": "Gas cost of a single BLS12-381 G1 addition precompile-call" + name: 'EIP-2537', + number: 2537, + comment: 'BLS12-381 precompiles', + url: 'https://eips.ethereum.org/EIPS/eip-2537', + status: 'Draft', + minimumHardfork: 'chainstart', + gasConfig: {}, + gasPrices: { + Bls12381G1AddGas: { + v: 600, + d: 'Gas cost of a single BLS12-381 G1 addition precompile-call', }, - "Bls12381G1MulGas": { - "v": 12000, - "d": "Gas cost of a single BLS12-381 G1 multiplication precompile-call" + Bls12381G1MulGas: { + v: 12000, + d: 'Gas cost of a single BLS12-381 G1 multiplication precompile-call', }, - "Bls12381G2AddGas": { - "v": 4500, - "d": "Gas cost of a single BLS12-381 G2 addition precompile-call" + Bls12381G2AddGas: { + v: 4500, + d: 'Gas cost of a single BLS12-381 G2 addition precompile-call', }, - "Bls12381G2MulGas": { - "v": 55000, - "d": "Gas cost of a single BLS12-381 G2 multiplication precompile-call" + Bls12381G2MulGas: { + v: 55000, + d: 'Gas cost of a single BLS12-381 G2 multiplication precompile-call', }, - "Bls12381PairingBaseGas": { - "v": 115000, - "d": "Base gas cost of BLS12-381 pairing check" + Bls12381PairingBaseGas: { + v: 115000, + d: 'Base gas cost of BLS12-381 pairing check', }, - "Bls12381PairingPerPairGas": { - "v": 23000, - "d": "Per-pair gas cost of BLS12-381 pairing check" + Bls12381PairingPerPairGas: { + v: 23000, + d: 'Per-pair gas cost of BLS12-381 pairing check', }, - "Bls12381MapG1Gas": { - "v": 5500, - "d": "Gas cost of BLS12-381 map field element to G1" + Bls12381MapG1Gas: { + v: 5500, + d: 'Gas cost of BLS12-381 map field element to G1', }, - "Bls12381MapG2Gas": { - "v": 110000, - "d": "Gas cost of BLS12-381 map field element to G2" + Bls12381MapG2Gas: { + v: 110000, + d: 'Gas cost of BLS12-381 map field element to G2', }, - "Bls12381MultiExpGasDiscount": { - "v": [ + Bls12381MultiExpGasDiscount: { + v: [ [1, 1200], [2, 888], [3, 764], @@ -168,12 +168,11 @@ export default { [125, 176], [126, 176], [127, 175], - [128, 174] + [128, 174], ], - "d": "Discount gas costs of calls to the MultiExp precompiles with `k` (point, scalar) pair" - } + d: 'Discount gas costs of calls to the MultiExp precompiles with `k` (point, scalar) pair', + }, }, - "vm": {}, - "pow": {} -} - ; \ No newline at end of file + vm: {}, + pow: {}, +}; diff --git a/packages/web3-eth-accounts/src/common/eips/2565.ts b/packages/web3-eth-accounts/src/common/eips/2565.ts index 1c1743e9a16..27d223b2ec5 100644 --- a/packages/web3-eth-accounts/src/common/eips/2565.ts +++ b/packages/web3-eth-accounts/src/common/eips/2565.ts @@ -1,18 +1,17 @@ export default { - "name": "EIP-2565", - "number": 2565, - "comment": "ModExp gas cost", - "url": "https://eips.ethereum.org/EIPS/eip-2565", - "status": "Final", - "minimumHardfork": "byzantium", - "gasConfig": {}, - "gasPrices": { - "modexpGquaddivisor": { - "v": 3, - "d": "Gquaddivisor from modexp precompile for gas calculation" - } + name: 'EIP-2565', + number: 2565, + comment: 'ModExp gas cost', + url: 'https://eips.ethereum.org/EIPS/eip-2565', + status: 'Final', + minimumHardfork: 'byzantium', + gasConfig: {}, + gasPrices: { + modexpGquaddivisor: { + v: 3, + d: 'Gquaddivisor from modexp precompile for gas calculation', + }, }, - "vm": {}, - "pow": {} -} - ; \ No newline at end of file + vm: {}, + pow: {}, +}; diff --git a/packages/web3-eth-accounts/src/common/eips/2718.ts b/packages/web3-eth-accounts/src/common/eips/2718.ts index f8815c6d7b1..fe59a38fd85 100644 --- a/packages/web3-eth-accounts/src/common/eips/2718.ts +++ b/packages/web3-eth-accounts/src/common/eips/2718.ts @@ -1,12 +1,11 @@ export default { - "name": "EIP-2718", - "comment": "Typed Transaction Envelope", - "url": "https://eips.ethereum.org/EIPS/eip-2718", - "status": "Final", - "minimumHardfork": "chainstart", - "gasConfig": {}, - "gasPrices": {}, - "vm": {}, - "pow": {} -} - ; \ No newline at end of file + name: 'EIP-2718', + comment: 'Typed Transaction Envelope', + url: 'https://eips.ethereum.org/EIPS/eip-2718', + status: 'Final', + minimumHardfork: 'chainstart', + gasConfig: {}, + gasPrices: {}, + vm: {}, + pow: {}, +}; diff --git a/packages/web3-eth-accounts/src/common/eips/2929.ts b/packages/web3-eth-accounts/src/common/eips/2929.ts index f52dc217d3f..cbd9dc3103b 100644 --- a/packages/web3-eth-accounts/src/common/eips/2929.ts +++ b/packages/web3-eth-accounts/src/common/eips/2929.ts @@ -1,85 +1,84 @@ export default { - "name": "EIP-2929", - "comment": "Gas cost increases for state access opcodes", - "url": "https://eips.ethereum.org/EIPS/eip-2929", - "status": "Final", - "minimumHardfork": "chainstart", - "gasConfig": {}, - "gasPrices": { - "coldsload": { - "v": 2100, - "d": "Gas cost of the first read of storage from a given location (per transaction)" - }, - "coldaccountaccess": { - "v": 2600, - "d": "Gas cost of the first read of a given address (per transaction)" - }, - "warmstorageread": { - "v": 100, - "d": "Gas cost of reading storage locations which have already loaded 'cold'" - }, - "sstoreCleanGasEIP2200": { - "v": 2900, - "d": "Once per SSTORE operation from clean non-zero to something else" - }, - "sstoreNoopGasEIP2200": { - "v": 100, - "d": "Once per SSTORE operation if the value doesn't change" - }, - "sstoreDirtyGasEIP2200": { - "v": 100, - "d": "Once per SSTORE operation if a dirty value is changed" - }, - "sstoreInitRefundEIP2200": { - "v": 19900, - "d": "Once per SSTORE operation for resetting to the original zero value" - }, - "sstoreCleanRefundEIP2200": { - "v": 4900, - "d": "Once per SSTORE operation for resetting to the original non-zero value" - }, - "call": { - "v": 0, - "d": "Base fee of the CALL opcode" - }, - "callcode": { - "v": 0, - "d": "Base fee of the CALLCODE opcode" - }, - "delegatecall": { - "v": 0, - "d": "Base fee of the DELEGATECALL opcode" - }, - "staticcall": { - "v": 0, - "d": "Base fee of the STATICCALL opcode" - }, - "balance": { - "v": 0, - "d": "Base fee of the BALANCE opcode" - }, - "extcodesize": { - "v": 0, - "d": "Base fee of the EXTCODESIZE opcode" - }, - "extcodecopy": { - "v": 0, - "d": "Base fee of the EXTCODECOPY opcode" - }, - "extcodehash": { - "v": 0, - "d": "Base fee of the EXTCODEHASH opcode" - }, - "sload": { - "v": 0, - "d": "Base fee of the SLOAD opcode" - }, - "sstore": { - "v": 0, - "d": "Base fee of the SSTORE opcode" - } + name: 'EIP-2929', + comment: 'Gas cost increases for state access opcodes', + url: 'https://eips.ethereum.org/EIPS/eip-2929', + status: 'Final', + minimumHardfork: 'chainstart', + gasConfig: {}, + gasPrices: { + coldsload: { + v: 2100, + d: 'Gas cost of the first read of storage from a given location (per transaction)', + }, + coldaccountaccess: { + v: 2600, + d: 'Gas cost of the first read of a given address (per transaction)', + }, + warmstorageread: { + v: 100, + d: "Gas cost of reading storage locations which have already loaded 'cold'", + }, + sstoreCleanGasEIP2200: { + v: 2900, + d: 'Once per SSTORE operation from clean non-zero to something else', + }, + sstoreNoopGasEIP2200: { + v: 100, + d: "Once per SSTORE operation if the value doesn't change", + }, + sstoreDirtyGasEIP2200: { + v: 100, + d: 'Once per SSTORE operation if a dirty value is changed', + }, + sstoreInitRefundEIP2200: { + v: 19900, + d: 'Once per SSTORE operation for resetting to the original zero value', + }, + sstoreCleanRefundEIP2200: { + v: 4900, + d: 'Once per SSTORE operation for resetting to the original non-zero value', + }, + call: { + v: 0, + d: 'Base fee of the CALL opcode', + }, + callcode: { + v: 0, + d: 'Base fee of the CALLCODE opcode', + }, + delegatecall: { + v: 0, + d: 'Base fee of the DELEGATECALL opcode', + }, + staticcall: { + v: 0, + d: 'Base fee of the STATICCALL opcode', + }, + balance: { + v: 0, + d: 'Base fee of the BALANCE opcode', + }, + extcodesize: { + v: 0, + d: 'Base fee of the EXTCODESIZE opcode', + }, + extcodecopy: { + v: 0, + d: 'Base fee of the EXTCODECOPY opcode', + }, + extcodehash: { + v: 0, + d: 'Base fee of the EXTCODEHASH opcode', + }, + sload: { + v: 0, + d: 'Base fee of the SLOAD opcode', + }, + sstore: { + v: 0, + d: 'Base fee of the SSTORE opcode', + }, }, - "vm": {}, - "pow": {} -} - ; \ No newline at end of file + vm: {}, + pow: {}, +}; diff --git a/packages/web3-eth-accounts/src/common/eips/2930.ts b/packages/web3-eth-accounts/src/common/eips/2930.ts index 52500d0c94a..0ea09e49d40 100644 --- a/packages/web3-eth-accounts/src/common/eips/2930.ts +++ b/packages/web3-eth-accounts/src/common/eips/2930.ts @@ -1,22 +1,21 @@ export default { - "name": "EIP-2930", - "comment": "Optional access lists", - "url": "https://eips.ethereum.org/EIPS/eip-2930", - "status": "Final", - "minimumHardfork": "istanbul", - "requiredEIPs": [2718, 2929], - "gasConfig": {}, - "gasPrices": { - "accessListStorageKeyCost": { - "v": 1900, - "d": "Gas cost per storage key in an Access List transaction" + name: 'EIP-2930', + comment: 'Optional access lists', + url: 'https://eips.ethereum.org/EIPS/eip-2930', + status: 'Final', + minimumHardfork: 'istanbul', + requiredEIPs: [2718, 2929], + gasConfig: {}, + gasPrices: { + accessListStorageKeyCost: { + v: 1900, + d: 'Gas cost per storage key in an Access List transaction', + }, + accessListAddressCost: { + v: 2400, + d: 'Gas cost per storage key in an Access List transaction', }, - "accessListAddressCost": { - "v": 2400, - "d": "Gas cost per storage key in an Access List transaction" - } }, - "vm": {}, - "pow": {} -} - ; \ No newline at end of file + vm: {}, + pow: {}, +}; diff --git a/packages/web3-eth-accounts/src/common/eips/3074.ts b/packages/web3-eth-accounts/src/common/eips/3074.ts index 538b0569819..92cfc955aa9 100644 --- a/packages/web3-eth-accounts/src/common/eips/3074.ts +++ b/packages/web3-eth-accounts/src/common/eips/3074.ts @@ -1,26 +1,25 @@ export default { - "name": "EIP-3074", - "number": 3074, - "comment": "AUTH and AUTHCALL opcodes", - "url": "https://eips.ethereum.org/EIPS/eip-3074", - "status": "Review", - "minimumHardfork": "london", - "gasConfig": {}, - "gasPrices": { - "auth": { - "v": 3100, - "d": "Gas cost of the AUTH opcode" + name: 'EIP-3074', + number: 3074, + comment: 'AUTH and AUTHCALL opcodes', + url: 'https://eips.ethereum.org/EIPS/eip-3074', + status: 'Review', + minimumHardfork: 'london', + gasConfig: {}, + gasPrices: { + auth: { + v: 3100, + d: 'Gas cost of the AUTH opcode', }, - "authcall": { - "v": 0, - "d": "Gas cost of the AUTHCALL opcode" + authcall: { + v: 0, + d: 'Gas cost of the AUTHCALL opcode', + }, + authcallValueTransfer: { + v: 6700, + d: 'Paid for CALL when the value transfer is non-zero', }, - "authcallValueTransfer": { - "v": 6700, - "d": "Paid for CALL when the value transfer is non-zero" - } }, - "vm": {}, - "pow": {} -} - ; \ No newline at end of file + vm: {}, + pow: {}, +}; diff --git a/packages/web3-eth-accounts/src/common/eips/3198.ts b/packages/web3-eth-accounts/src/common/eips/3198.ts index d949d976359..73c55d3ac49 100644 --- a/packages/web3-eth-accounts/src/common/eips/3198.ts +++ b/packages/web3-eth-accounts/src/common/eips/3198.ts @@ -1,18 +1,17 @@ export default { - "name": "EIP-3198", - "number": 3198, - "comment": "BASEFEE opcode", - "url": "https://eips.ethereum.org/EIPS/eip-3198", - "status": "Final", - "minimumHardfork": "london", - "gasConfig": {}, - "gasPrices": { - "basefee": { - "v": 2, - "d": "Gas cost of the BASEFEE opcode" - } + name: 'EIP-3198', + number: 3198, + comment: 'BASEFEE opcode', + url: 'https://eips.ethereum.org/EIPS/eip-3198', + status: 'Final', + minimumHardfork: 'london', + gasConfig: {}, + gasPrices: { + basefee: { + v: 2, + d: 'Gas cost of the BASEFEE opcode', + }, }, - "vm": {}, - "pow": {} -} - ; \ No newline at end of file + vm: {}, + pow: {}, +}; diff --git a/packages/web3-eth-accounts/src/common/eips/3529.ts b/packages/web3-eth-accounts/src/common/eips/3529.ts index 2e8b0e39888..9e935b4ab07 100644 --- a/packages/web3-eth-accounts/src/common/eips/3529.ts +++ b/packages/web3-eth-accounts/src/common/eips/3529.ts @@ -1,27 +1,26 @@ export default { - "name": "EIP-3529", - "comment": "Reduction in refunds", - "url": "https://eips.ethereum.org/EIPS/eip-3529", - "status": "Final", - "minimumHardfork": "berlin", - "requiredEIPs": [2929], - "gasConfig": { - "maxRefundQuotient": { - "v": 5, - "d": "Maximum refund quotient; max tx refund is min(tx.gasUsed/maxRefundQuotient, tx.gasRefund)" - } + name: 'EIP-3529', + comment: 'Reduction in refunds', + url: 'https://eips.ethereum.org/EIPS/eip-3529', + status: 'Final', + minimumHardfork: 'berlin', + requiredEIPs: [2929], + gasConfig: { + maxRefundQuotient: { + v: 5, + d: 'Maximum refund quotient; max tx refund is min(tx.gasUsed/maxRefundQuotient, tx.gasRefund)', + }, }, - "gasPrices": { - "selfdestructRefund": { - "v": 0, - "d": "Refunded following a selfdestruct operation" + gasPrices: { + selfdestructRefund: { + v: 0, + d: 'Refunded following a selfdestruct operation', + }, + sstoreClearRefundEIP2200: { + v: 4800, + d: 'Once per SSTORE operation for clearing an originally existing storage slot', }, - "sstoreClearRefundEIP2200": { - "v": 4800, - "d": "Once per SSTORE operation for clearing an originally existing storage slot" - } }, - "vm": {}, - "pow": {} -} - ; \ No newline at end of file + vm: {}, + pow: {}, +}; diff --git a/packages/web3-eth-accounts/src/common/eips/3540.ts b/packages/web3-eth-accounts/src/common/eips/3540.ts index 39fdb91ee43..498e6ac3094 100644 --- a/packages/web3-eth-accounts/src/common/eips/3540.ts +++ b/packages/web3-eth-accounts/src/common/eips/3540.ts @@ -1,14 +1,13 @@ export default { - "name": "EIP-3540", - "number": 3540, - "comment": "EVM Object Format (EOF) v1", - "url": "https://eips.ethereum.org/EIPS/eip-3540", - "status": "Review", - "minimumHardfork": "london", - "requiredEIPs": [3541], - "gasConfig": {}, - "gasPrices": {}, - "vm": {}, - "pow": {} -} - ; \ No newline at end of file + name: 'EIP-3540', + number: 3540, + comment: 'EVM Object Format (EOF) v1', + url: 'https://eips.ethereum.org/EIPS/eip-3540', + status: 'Review', + minimumHardfork: 'london', + requiredEIPs: [3541], + gasConfig: {}, + gasPrices: {}, + vm: {}, + pow: {}, +}; diff --git a/packages/web3-eth-accounts/src/common/eips/3541.ts b/packages/web3-eth-accounts/src/common/eips/3541.ts index b3e7a0ce823..372b886834f 100644 --- a/packages/web3-eth-accounts/src/common/eips/3541.ts +++ b/packages/web3-eth-accounts/src/common/eips/3541.ts @@ -1,13 +1,12 @@ export default { - "name": "EIP-3541", - "comment": "Reject new contracts starting with the 0xEF byte", - "url": "https://eips.ethereum.org/EIPS/eip-3541", - "status": "Final", - "minimumHardfork": "berlin", - "requiredEIPs": [], - "gasConfig": {}, - "gasPrices": {}, - "vm": {}, - "pow": {} -} - ; \ No newline at end of file + name: 'EIP-3541', + comment: 'Reject new contracts starting with the 0xEF byte', + url: 'https://eips.ethereum.org/EIPS/eip-3541', + status: 'Final', + minimumHardfork: 'berlin', + requiredEIPs: [], + gasConfig: {}, + gasPrices: {}, + vm: {}, + pow: {}, +}; diff --git a/packages/web3-eth-accounts/src/common/eips/3554.ts b/packages/web3-eth-accounts/src/common/eips/3554.ts index 36a9d16ecf2..6f8c04a2ec4 100644 --- a/packages/web3-eth-accounts/src/common/eips/3554.ts +++ b/packages/web3-eth-accounts/src/common/eips/3554.ts @@ -1,18 +1,17 @@ export default { - "name": "EIP-3554", - "comment": "Reduction in refunds", - "url": "Difficulty Bomb Delay to December 1st 2021", - "status": "Final", - "minimumHardfork": "muirGlacier", - "requiredEIPs": [], - "gasConfig": {}, - "gasPrices": {}, - "vm": {}, - "pow": { - "difficultyBombDelay": { - "v": 9500000, - "d": "the amount of blocks to delay the difficulty bomb with" - } - } -} - ; \ No newline at end of file + name: 'EIP-3554', + comment: 'Reduction in refunds', + url: 'Difficulty Bomb Delay to December 1st 2021', + status: 'Final', + minimumHardfork: 'muirGlacier', + requiredEIPs: [], + gasConfig: {}, + gasPrices: {}, + vm: {}, + pow: { + difficultyBombDelay: { + v: 9500000, + d: 'the amount of blocks to delay the difficulty bomb with', + }, + }, +}; diff --git a/packages/web3-eth-accounts/src/common/eips/3607.ts b/packages/web3-eth-accounts/src/common/eips/3607.ts index 6c122728e68..90607ec697f 100644 --- a/packages/web3-eth-accounts/src/common/eips/3607.ts +++ b/packages/web3-eth-accounts/src/common/eips/3607.ts @@ -1,14 +1,13 @@ export default { - "name": "EIP-3607", - "number": 3607, - "comment": "Reject transactions from senders with deployed code", - "url": "https://eips.ethereum.org/EIPS/eip-3607", - "status": "Final", - "minimumHardfork": "chainstart", - "requiredEIPs": [], - "gasConfig": {}, - "gasPrices": {}, - "vm": {}, - "pow": {} -} - ; \ No newline at end of file + name: 'EIP-3607', + number: 3607, + comment: 'Reject transactions from senders with deployed code', + url: 'https://eips.ethereum.org/EIPS/eip-3607', + status: 'Final', + minimumHardfork: 'chainstart', + requiredEIPs: [], + gasConfig: {}, + gasPrices: {}, + vm: {}, + pow: {}, +}; diff --git a/packages/web3-eth-accounts/src/common/eips/3651.ts b/packages/web3-eth-accounts/src/common/eips/3651.ts index c6ebe81da92..65855ca18fb 100644 --- a/packages/web3-eth-accounts/src/common/eips/3651.ts +++ b/packages/web3-eth-accounts/src/common/eips/3651.ts @@ -1,14 +1,13 @@ export default { - "name": "EIP-3651", - "number": 3198, - "comment": "Warm COINBASE", - "url": "https://eips.ethereum.org/EIPS/eip-3651", - "status": "Review", - "minimumHardfork": "london", - "requiredEIPs": [2929], - "gasConfig": {}, - "gasPrices": {}, - "vm": {}, - "pow": {} -} - ; \ No newline at end of file + name: 'EIP-3651', + number: 3198, + comment: 'Warm COINBASE', + url: 'https://eips.ethereum.org/EIPS/eip-3651', + status: 'Review', + minimumHardfork: 'london', + requiredEIPs: [2929], + gasConfig: {}, + gasPrices: {}, + vm: {}, + pow: {}, +}; diff --git a/packages/web3-eth-accounts/src/common/eips/3670.ts b/packages/web3-eth-accounts/src/common/eips/3670.ts index 5b36d99b71f..6edc09bb2bf 100644 --- a/packages/web3-eth-accounts/src/common/eips/3670.ts +++ b/packages/web3-eth-accounts/src/common/eips/3670.ts @@ -1,14 +1,13 @@ export default { - "name": "EIP-3670", - "number": 3670, - "comment": "EOF - Code Validation", - "url": "https://eips.ethereum.org/EIPS/eip-3670", - "status": "Review", - "minimumHardfork": "london", - "requiredEIPs": [3540], - "gasConfig": {}, - "gasPrices": {}, - "vm": {}, - "pow": {} -} - ; \ No newline at end of file + name: 'EIP-3670', + number: 3670, + comment: 'EOF - Code Validation', + url: 'https://eips.ethereum.org/EIPS/eip-3670', + status: 'Review', + minimumHardfork: 'london', + requiredEIPs: [3540], + gasConfig: {}, + gasPrices: {}, + vm: {}, + pow: {}, +}; diff --git a/packages/web3-eth-accounts/src/common/eips/3675.ts b/packages/web3-eth-accounts/src/common/eips/3675.ts index a80350300c7..74d89ebb1f7 100644 --- a/packages/web3-eth-accounts/src/common/eips/3675.ts +++ b/packages/web3-eth-accounts/src/common/eips/3675.ts @@ -1,14 +1,13 @@ export default { - "name": "EIP-3675", - "number": 3675, - "comment": "Upgrade consensus to Proof-of-Stake", - "url": "https://eips.ethereum.org/EIPS/eip-3675", - "status": "Final", - "minimumHardfork": "london", - "requiredEIPs": [], - "gasConfig": {}, - "gasPrices": {}, - "vm": {}, - "pow": {} -} - ; \ No newline at end of file + name: 'EIP-3675', + number: 3675, + comment: 'Upgrade consensus to Proof-of-Stake', + url: 'https://eips.ethereum.org/EIPS/eip-3675', + status: 'Final', + minimumHardfork: 'london', + requiredEIPs: [], + gasConfig: {}, + gasPrices: {}, + vm: {}, + pow: {}, +}; diff --git a/packages/web3-eth-accounts/src/common/eips/3855.ts b/packages/web3-eth-accounts/src/common/eips/3855.ts index 2f5ac0641a5..b1733b4dd9a 100644 --- a/packages/web3-eth-accounts/src/common/eips/3855.ts +++ b/packages/web3-eth-accounts/src/common/eips/3855.ts @@ -1,19 +1,18 @@ export default { - "name": "EIP-3855", - "number": 3855, - "comment": "PUSH0 instruction", - "url": "https://eips.ethereum.org/EIPS/eip-3855", - "status": "Review", - "minimumHardfork": "chainstart", - "requiredEIPs": [], - "gasConfig": {}, - "gasPrices": { - "push0": { - "v": 2, - "d": "Base fee of the PUSH0 opcode" - } + name: 'EIP-3855', + number: 3855, + comment: 'PUSH0 instruction', + url: 'https://eips.ethereum.org/EIPS/eip-3855', + status: 'Review', + minimumHardfork: 'chainstart', + requiredEIPs: [], + gasConfig: {}, + gasPrices: { + push0: { + v: 2, + d: 'Base fee of the PUSH0 opcode', + }, }, - "vm": {}, - "pow": {} -} - ; \ No newline at end of file + vm: {}, + pow: {}, +}; diff --git a/packages/web3-eth-accounts/src/common/eips/3860.ts b/packages/web3-eth-accounts/src/common/eips/3860.ts index 0e1aeb999db..8206e041e18 100644 --- a/packages/web3-eth-accounts/src/common/eips/3860.ts +++ b/packages/web3-eth-accounts/src/common/eips/3860.ts @@ -1,24 +1,23 @@ export default { - "name": "EIP-3860", - "number": 3860, - "comment": "Limit and meter initcode", - "url": "https://eips.ethereum.org/EIPS/eip-3860", - "status": "Review", - "minimumHardfork": "spuriousDragon", - "requiredEIPs": [], - "gasConfig": {}, - "gasPrices": { - "initCodeWordCost": { - "v": 2, - "d": "Gas to pay for each word (32 bytes) of initcode when creating a contract" - } + name: 'EIP-3860', + number: 3860, + comment: 'Limit and meter initcode', + url: 'https://eips.ethereum.org/EIPS/eip-3860', + status: 'Review', + minimumHardfork: 'spuriousDragon', + requiredEIPs: [], + gasConfig: {}, + gasPrices: { + initCodeWordCost: { + v: 2, + d: 'Gas to pay for each word (32 bytes) of initcode when creating a contract', + }, }, - "vm": { - "maxInitCodeSize": { - "v": 49152, - "d": "Maximum length of initialization code when creating a contract" - } + vm: { + maxInitCodeSize: { + v: 49152, + d: 'Maximum length of initialization code when creating a contract', + }, }, - "pow": {} -} - ; \ No newline at end of file + pow: {}, +}; diff --git a/packages/web3-eth-accounts/src/common/eips/4345.ts b/packages/web3-eth-accounts/src/common/eips/4345.ts index 0e571b327c2..2977bf1b194 100644 --- a/packages/web3-eth-accounts/src/common/eips/4345.ts +++ b/packages/web3-eth-accounts/src/common/eips/4345.ts @@ -1,18 +1,17 @@ export default { - "name": "EIP-4345", - "number": 4345, - "comment": "Difficulty Bomb Delay to June 2022", - "url": "https://eips.ethereum.org/EIPS/eip-4345", - "status": "Final", - "minimumHardfork": "london", - "gasConfig": {}, - "gasPrices": {}, - "vm": {}, - "pow": { - "difficultyBombDelay": { - "v": 10700000, - "d": "the amount of blocks to delay the difficulty bomb with" - } - } -} - ; \ No newline at end of file + name: 'EIP-4345', + number: 4345, + comment: 'Difficulty Bomb Delay to June 2022', + url: 'https://eips.ethereum.org/EIPS/eip-4345', + status: 'Final', + minimumHardfork: 'london', + gasConfig: {}, + gasPrices: {}, + vm: {}, + pow: { + difficultyBombDelay: { + v: 10700000, + d: 'the amount of blocks to delay the difficulty bomb with', + }, + }, +}; diff --git a/packages/web3-eth-accounts/src/common/eips/4399.ts b/packages/web3-eth-accounts/src/common/eips/4399.ts index ed948d629de..c06bb9f8db3 100644 --- a/packages/web3-eth-accounts/src/common/eips/4399.ts +++ b/packages/web3-eth-accounts/src/common/eips/4399.ts @@ -1,14 +1,13 @@ export default { - "name": "EIP-4399", - "number": 4399, - "comment": "Supplant DIFFICULTY opcode with PREVRANDAO", - "url": "https://eips.ethereum.org/EIPS/eip-4399", - "status": "Review", - "minimumHardfork": "london", - "requiredEIPs": [], - "gasConfig": {}, - "gasPrices": {}, - "vm": {}, - "pow": {} -} - ; \ No newline at end of file + name: 'EIP-4399', + number: 4399, + comment: 'Supplant DIFFICULTY opcode with PREVRANDAO', + url: 'https://eips.ethereum.org/EIPS/eip-4399', + status: 'Review', + minimumHardfork: 'london', + requiredEIPs: [], + gasConfig: {}, + gasPrices: {}, + vm: {}, + pow: {}, +}; diff --git a/packages/web3-eth-accounts/src/common/eips/4844.ts b/packages/web3-eth-accounts/src/common/eips/4844.ts index 2795067c841..8d4944761fd 100644 --- a/packages/web3-eth-accounts/src/common/eips/4844.ts +++ b/packages/web3-eth-accounts/src/common/eips/4844.ts @@ -1,58 +1,57 @@ export default { - "name": "EIP-4844", - "number": 4844, - "comment": "Shard Blob Transactions", - "url": "https://eips.ethereum.org/EIPS/eip-4844", - "status": "Draft", - "minimumHardfork": "merge", - "requiredEIPs": [1559, 2718, 2930, 4895], - "gasConfig": { - "dataGasPerBlob": { - "v": 131072, - "d": "The base fee for data gas per blob" - }, - "targetDataGasPerBlock": { - "v": 262144, - "d": "The target data gas consumed per block" - }, - "maxDataGasPerBlock": { - "v": 524288, - "d": "The max data gas allowable per block" - }, - "dataGasPriceUpdateFraction": { - "v": 2225652, - "d": "The denominator used in the exponential when calculating a data gas price" - } + name: 'EIP-4844', + number: 4844, + comment: 'Shard Blob Transactions', + url: 'https://eips.ethereum.org/EIPS/eip-4844', + status: 'Draft', + minimumHardfork: 'merge', + requiredEIPs: [1559, 2718, 2930, 4895], + gasConfig: { + dataGasPerBlob: { + v: 131072, + d: 'The base fee for data gas per blob', + }, + targetDataGasPerBlock: { + v: 262144, + d: 'The target data gas consumed per block', + }, + maxDataGasPerBlock: { + v: 524288, + d: 'The max data gas allowable per block', + }, + dataGasPriceUpdateFraction: { + v: 2225652, + d: 'The denominator used in the exponential when calculating a data gas price', + }, }, - "gasPrices": { - "simpleGasPerBlob": { - "v": 12000, - "d": "The basic gas fee for each blob" - }, - "minDataGasPrice": { - "v": 1, - "d": "The minimum fee per data gas" - }, - "kzgPointEvaluationGasPrecompilePrice": { - "v": 50000, - "d": "The fee associated with the point evaluation precompile" - }, - "datahash": { - "v": 3, - "d": "Base fee of the DATAHASH opcode" - } + gasPrices: { + simpleGasPerBlob: { + v: 12000, + d: 'The basic gas fee for each blob', + }, + minDataGasPrice: { + v: 1, + d: 'The minimum fee per data gas', + }, + kzgPointEvaluationGasPrecompilePrice: { + v: 50000, + d: 'The fee associated with the point evaluation precompile', + }, + datahash: { + v: 3, + d: 'Base fee of the DATAHASH opcode', + }, }, - "sharding": { - "blobCommitmentVersionKzg": { - "v": 1, - "d": "The number indicated a versioned hash is a KZG commitment" - }, - "fieldElementsPerBlob": { - "v": 4096, - "d": "The number of field elements allowed per blob" - } + sharding: { + blobCommitmentVersionKzg: { + v: 1, + d: 'The number indicated a versioned hash is a KZG commitment', + }, + fieldElementsPerBlob: { + v: 4096, + d: 'The number of field elements allowed per blob', + }, }, - "vm": {}, - "pow": {} -} - ; \ No newline at end of file + vm: {}, + pow: {}, +}; diff --git a/packages/web3-eth-accounts/src/common/eips/4895.ts b/packages/web3-eth-accounts/src/common/eips/4895.ts index f70f2ec3b35..63bef6b9fce 100644 --- a/packages/web3-eth-accounts/src/common/eips/4895.ts +++ b/packages/web3-eth-accounts/src/common/eips/4895.ts @@ -1,14 +1,13 @@ export default { - "name": "EIP-4895", - "number": 4895, - "comment": "Beacon chain push withdrawals as operations", - "url": "https://eips.ethereum.org/EIPS/eip-4895", - "status": "Review", - "minimumHardfork": "merge", - "requiredEIPs": [], - "gasConfig": {}, - "gasPrices": {}, - "vm": {}, - "pow": {} -} - ; \ No newline at end of file + name: 'EIP-4895', + number: 4895, + comment: 'Beacon chain push withdrawals as operations', + url: 'https://eips.ethereum.org/EIPS/eip-4895', + status: 'Review', + minimumHardfork: 'merge', + requiredEIPs: [], + gasConfig: {}, + gasPrices: {}, + vm: {}, + pow: {}, +}; diff --git a/packages/web3-eth-accounts/src/common/eips/5133.ts b/packages/web3-eth-accounts/src/common/eips/5133.ts index de3b55c9721..c6041029b9b 100644 --- a/packages/web3-eth-accounts/src/common/eips/5133.ts +++ b/packages/web3-eth-accounts/src/common/eips/5133.ts @@ -1,18 +1,17 @@ export default { - "name": "EIP-5133", - "number": 5133, - "comment": "Delaying Difficulty Bomb to mid-September 2022", - "url": "https://eips.ethereum.org/EIPS/eip-5133", - "status": "Draft", - "minimumHardfork": "grayGlacier", - "gasConfig": {}, - "gasPrices": {}, - "vm": {}, - "pow": { - "difficultyBombDelay": { - "v": 11400000, - "d": "the amount of blocks to delay the difficulty bomb with" - } - } -} - ; \ No newline at end of file + name: 'EIP-5133', + number: 5133, + comment: 'Delaying Difficulty Bomb to mid-September 2022', + url: 'https://eips.ethereum.org/EIPS/eip-5133', + status: 'Draft', + minimumHardfork: 'grayGlacier', + gasConfig: {}, + gasPrices: {}, + vm: {}, + pow: { + difficultyBombDelay: { + v: 11400000, + d: 'the amount of blocks to delay the difficulty bomb with', + }, + }, +}; diff --git a/packages/web3-eth-accounts/src/common/hardforks/arrowGlacier.ts b/packages/web3-eth-accounts/src/common/hardforks/arrowGlacier.ts index e38f1782855..901ceaddb6a 100644 --- a/packages/web3-eth-accounts/src/common/hardforks/arrowGlacier.ts +++ b/packages/web3-eth-accounts/src/common/hardforks/arrowGlacier.ts @@ -1,12 +1,11 @@ export default { - "name": "arrowGlacier", - "comment": "HF to delay the difficulty bomb", - "url": "https://github.com/ethereum/execution-specs/blob/master/network-upgrades/mainnet-upgrades/arrow-glacier.md", - "status": "Final", - "eips": [4345], - "gasConfig": {}, - "gasPrices": {}, - "vm": {}, - "pow": {} -} - ; \ No newline at end of file + name: 'arrowGlacier', + comment: 'HF to delay the difficulty bomb', + url: 'https://github.com/ethereum/execution-specs/blob/master/network-upgrades/mainnet-upgrades/arrow-glacier.md', + status: 'Final', + eips: [4345], + gasConfig: {}, + gasPrices: {}, + vm: {}, + pow: {}, +}; diff --git a/packages/web3-eth-accounts/src/common/hardforks/berlin.ts b/packages/web3-eth-accounts/src/common/hardforks/berlin.ts index df30229fb2e..d76c7629520 100644 --- a/packages/web3-eth-accounts/src/common/hardforks/berlin.ts +++ b/packages/web3-eth-accounts/src/common/hardforks/berlin.ts @@ -1,8 +1,7 @@ export default { - "name": "berlin", - "comment": "HF targeted for July 2020 following the Muir Glacier HF", - "url": "https://eips.ethereum.org/EIPS/eip-2070", - "status": "Final", - "eips": [2565, 2929, 2718, 2930] -} - ; \ No newline at end of file + name: 'berlin', + comment: 'HF targeted for July 2020 following the Muir Glacier HF', + url: 'https://eips.ethereum.org/EIPS/eip-2070', + status: 'Final', + eips: [2565, 2929, 2718, 2930], +}; diff --git a/packages/web3-eth-accounts/src/common/hardforks/byzantium.ts b/packages/web3-eth-accounts/src/common/hardforks/byzantium.ts index 2c358c8f6ff..eb9a00a07c4 100644 --- a/packages/web3-eth-accounts/src/common/hardforks/byzantium.ts +++ b/packages/web3-eth-accounts/src/common/hardforks/byzantium.ts @@ -1,57 +1,56 @@ export default { - "name": "byzantium", - "comment": "Hardfork with new precompiles, instructions and other protocol changes", - "url": "https://eips.ethereum.org/EIPS/eip-609", - "status": "Final", - "gasConfig": {}, - "gasPrices": { - "modexpGquaddivisor": { - "v": 20, - "d": "Gquaddivisor from modexp precompile for gas calculation" - }, - "ecAdd": { - "v": 500, - "d": "Gas costs for curve addition precompile" - }, - "ecMul": { - "v": 40000, - "d": "Gas costs for curve multiplication precompile" - }, - "ecPairing": { - "v": 100000, - "d": "Base gas costs for curve pairing precompile" - }, - "ecPairingWord": { - "v": 80000, - "d": "Gas costs regarding curve pairing precompile input length" - }, - "revert": { - "v": 0, - "d": "Base fee of the REVERT opcode" - }, - "staticcall": { - "v": 700, - "d": "Base fee of the STATICCALL opcode" - }, - "returndatasize": { - "v": 2, - "d": "Base fee of the RETURNDATASIZE opcode" - }, - "returndatacopy": { - "v": 3, - "d": "Base fee of the RETURNDATACOPY opcode" - } + name: 'byzantium', + comment: 'Hardfork with new precompiles, instructions and other protocol changes', + url: 'https://eips.ethereum.org/EIPS/eip-609', + status: 'Final', + gasConfig: {}, + gasPrices: { + modexpGquaddivisor: { + v: 20, + d: 'Gquaddivisor from modexp precompile for gas calculation', + }, + ecAdd: { + v: 500, + d: 'Gas costs for curve addition precompile', + }, + ecMul: { + v: 40000, + d: 'Gas costs for curve multiplication precompile', + }, + ecPairing: { + v: 100000, + d: 'Base gas costs for curve pairing precompile', + }, + ecPairingWord: { + v: 80000, + d: 'Gas costs regarding curve pairing precompile input length', + }, + revert: { + v: 0, + d: 'Base fee of the REVERT opcode', + }, + staticcall: { + v: 700, + d: 'Base fee of the STATICCALL opcode', + }, + returndatasize: { + v: 2, + d: 'Base fee of the RETURNDATASIZE opcode', + }, + returndatacopy: { + v: 3, + d: 'Base fee of the RETURNDATACOPY opcode', + }, + }, + vm: {}, + pow: { + minerReward: { + v: '3000000000000000000', + d: 'the amount a miner get rewarded for mining a block', + }, + difficultyBombDelay: { + v: 3000000, + d: 'the amount of blocks to delay the difficulty bomb with', + }, }, - "vm": {}, - "pow": { - "minerReward": { - "v": "3000000000000000000", - "d": "the amount a miner get rewarded for mining a block" - }, - "difficultyBombDelay": { - "v": 3000000, - "d": "the amount of blocks to delay the difficulty bomb with" - } - } -} - ; \ No newline at end of file +}; diff --git a/packages/web3-eth-accounts/src/common/hardforks/chainstart.ts b/packages/web3-eth-accounts/src/common/hardforks/chainstart.ts index 32f5630b5ff..030366fcc78 100644 --- a/packages/web3-eth-accounts/src/common/hardforks/chainstart.ts +++ b/packages/web3-eth-accounts/src/common/hardforks/chainstart.ts @@ -1,439 +1,438 @@ export default { - "name": "chainstart", - "comment": "Start of the Ethereum main chain", - "url": "", - "status": "", - "gasConfig": { - "minGasLimit": { - "v": 5000, - "d": "Minimum the gas limit may ever be" - }, - "gasLimitBoundDivisor": { - "v": 1024, - "d": "The bound divisor of the gas limit, used in update calculations" - }, - "maxRefundQuotient": { - "v": 2, - "d": "Maximum refund quotient; max tx refund is min(tx.gasUsed/maxRefundQuotient, tx.gasRefund)" - } + name: 'chainstart', + comment: 'Start of the Ethereum main chain', + url: '', + status: '', + gasConfig: { + minGasLimit: { + v: 5000, + d: 'Minimum the gas limit may ever be', + }, + gasLimitBoundDivisor: { + v: 1024, + d: 'The bound divisor of the gas limit, used in update calculations', + }, + maxRefundQuotient: { + v: 2, + d: 'Maximum refund quotient; max tx refund is min(tx.gasUsed/maxRefundQuotient, tx.gasRefund)', + }, }, - "gasPrices": { - "base": { - "v": 2, - "d": "Gas base cost, used e.g. for ChainID opcode (Istanbul)" + gasPrices: { + base: { + v: 2, + d: 'Gas base cost, used e.g. for ChainID opcode (Istanbul)', + }, + tierStep: { + v: [0, 2, 3, 5, 8, 10, 20], + d: 'Once per operation, for a selection of them', }, - "tierStep": { - "v": [0, 2, 3, 5, 8, 10, 20], - "d": "Once per operation, for a selection of them" + exp: { + v: 10, + d: 'Base fee of the EXP opcode', }, - "exp": { - "v": 10, - "d": "Base fee of the EXP opcode" + expByte: { + v: 10, + d: 'Times ceil(log256(exponent)) for the EXP instruction', }, - "expByte": { - "v": 10, - "d": "Times ceil(log256(exponent)) for the EXP instruction" + sha3: { + v: 30, + d: 'Base fee of the SHA3 opcode', }, - "sha3": { - "v": 30, - "d": "Base fee of the SHA3 opcode" + sha3Word: { + v: 6, + d: "Once per word of the SHA3 operation's data", }, - "sha3Word": { - "v": 6, - "d": "Once per word of the SHA3 operation's data" + sload: { + v: 50, + d: 'Base fee of the SLOAD opcode', }, - "sload": { - "v": 50, - "d": "Base fee of the SLOAD opcode" + sstoreSet: { + v: 20000, + d: 'Once per SSTORE operation if the zeroness changes from zero', }, - "sstoreSet": { - "v": 20000, - "d": "Once per SSTORE operation if the zeroness changes from zero" + sstoreReset: { + v: 5000, + d: 'Once per SSTORE operation if the zeroness does not change from zero', }, - "sstoreReset": { - "v": 5000, - "d": "Once per SSTORE operation if the zeroness does not change from zero" + sstoreRefund: { + v: 15000, + d: 'Once per SSTORE operation if the zeroness changes to zero', }, - "sstoreRefund": { - "v": 15000, - "d": "Once per SSTORE operation if the zeroness changes to zero" + jumpdest: { + v: 1, + d: 'Base fee of the JUMPDEST opcode', }, - "jumpdest": { - "v": 1, - "d": "Base fee of the JUMPDEST opcode" + log: { + v: 375, + d: 'Base fee of the LOG opcode', }, - "log": { - "v": 375, - "d": "Base fee of the LOG opcode" + logData: { + v: 8, + d: "Per byte in a LOG* operation's data", }, - "logData": { - "v": 8, - "d": "Per byte in a LOG* operation's data" + logTopic: { + v: 375, + d: 'Multiplied by the * of the LOG*, per LOG transaction. e.g. LOG0 incurs 0 * c_txLogTopicGas, LOG4 incurs 4 * c_txLogTopicGas', }, - "logTopic": { - "v": 375, - "d": "Multiplied by the * of the LOG*, per LOG transaction. e.g. LOG0 incurs 0 * c_txLogTopicGas, LOG4 incurs 4 * c_txLogTopicGas" + create: { + v: 32000, + d: 'Base fee of the CREATE opcode', }, - "create": { - "v": 32000, - "d": "Base fee of the CREATE opcode" + call: { + v: 40, + d: 'Base fee of the CALL opcode', }, - "call": { - "v": 40, - "d": "Base fee of the CALL opcode" + callStipend: { + v: 2300, + d: 'Free gas given at beginning of call', }, - "callStipend": { - "v": 2300, - "d": "Free gas given at beginning of call" + callValueTransfer: { + v: 9000, + d: 'Paid for CALL when the value transfor is non-zero', }, - "callValueTransfer": { - "v": 9000, - "d": "Paid for CALL when the value transfor is non-zero" + callNewAccount: { + v: 25000, + d: "Paid for CALL when the destination address didn't exist prior", }, - "callNewAccount": { - "v": 25000, - "d": "Paid for CALL when the destination address didn't exist prior" + selfdestructRefund: { + v: 24000, + d: 'Refunded following a selfdestruct operation', }, - "selfdestructRefund": { - "v": 24000, - "d": "Refunded following a selfdestruct operation" + memory: { + v: 3, + d: 'Times the address of the (highest referenced byte in memory + 1). NOTE: referencing happens on read, write and in instructions such as RETURN and CALL', }, - "memory": { - "v": 3, - "d": "Times the address of the (highest referenced byte in memory + 1). NOTE: referencing happens on read, write and in instructions such as RETURN and CALL" + quadCoeffDiv: { + v: 512, + d: 'Divisor for the quadratic particle of the memory cost equation', }, - "quadCoeffDiv": { - "v": 512, - "d": "Divisor for the quadratic particle of the memory cost equation" + createData: { + v: 200, + d: '', }, - "createData": { - "v": 200, - "d": "" + tx: { + v: 21000, + d: 'Per transaction. NOTE: Not payable on data of calls between transactions', }, - "tx": { - "v": 21000, - "d": "Per transaction. NOTE: Not payable on data of calls between transactions" + txCreation: { + v: 32000, + d: 'The cost of creating a contract via tx', }, - "txCreation": { - "v": 32000, - "d": "The cost of creating a contract via tx" + txDataZero: { + v: 4, + d: 'Per byte of data attached to a transaction that equals zero. NOTE: Not payable on data of calls between transactions', }, - "txDataZero": { - "v": 4, - "d": "Per byte of data attached to a transaction that equals zero. NOTE: Not payable on data of calls between transactions" + txDataNonZero: { + v: 68, + d: 'Per byte of data attached to a transaction that is not equal to zero. NOTE: Not payable on data of calls between transactions', }, - "txDataNonZero": { - "v": 68, - "d": "Per byte of data attached to a transaction that is not equal to zero. NOTE: Not payable on data of calls between transactions" + copy: { + v: 3, + d: 'Multiplied by the number of 32-byte words that are copied (round up) for any *COPY operation and added', }, - "copy": { - "v": 3, - "d": "Multiplied by the number of 32-byte words that are copied (round up) for any *COPY operation and added" + ecRecover: { + v: 3000, + d: '', }, - "ecRecover": { - "v": 3000, - "d": "" + sha256: { + v: 60, + d: '', }, - "sha256": { - "v": 60, - "d": "" + sha256Word: { + v: 12, + d: '', }, - "sha256Word": { - "v": 12, - "d": "" + ripemd160: { + v: 600, + d: '', }, - "ripemd160": { - "v": 600, - "d": "" + ripemd160Word: { + v: 120, + d: '', }, - "ripemd160Word": { - "v": 120, - "d": "" + identity: { + v: 15, + d: '', }, - "identity": { - "v": 15, - "d": "" + identityWord: { + v: 3, + d: '', }, - "identityWord": { - "v": 3, - "d": "" + stop: { + v: 0, + d: 'Base fee of the STOP opcode', }, - "stop": { - "v": 0, - "d": "Base fee of the STOP opcode" + add: { + v: 3, + d: 'Base fee of the ADD opcode', }, - "add": { - "v": 3, - "d": "Base fee of the ADD opcode" + mul: { + v: 5, + d: 'Base fee of the MUL opcode', }, - "mul": { - "v": 5, - "d": "Base fee of the MUL opcode" + sub: { + v: 3, + d: 'Base fee of the SUB opcode', }, - "sub": { - "v": 3, - "d": "Base fee of the SUB opcode" + div: { + v: 5, + d: 'Base fee of the DIV opcode', }, - "div": { - "v": 5, - "d": "Base fee of the DIV opcode" + sdiv: { + v: 5, + d: 'Base fee of the SDIV opcode', }, - "sdiv": { - "v": 5, - "d": "Base fee of the SDIV opcode" + mod: { + v: 5, + d: 'Base fee of the MOD opcode', }, - "mod": { - "v": 5, - "d": "Base fee of the MOD opcode" + smod: { + v: 5, + d: 'Base fee of the SMOD opcode', }, - "smod": { - "v": 5, - "d": "Base fee of the SMOD opcode" + addmod: { + v: 8, + d: 'Base fee of the ADDMOD opcode', }, - "addmod": { - "v": 8, - "d": "Base fee of the ADDMOD opcode" + mulmod: { + v: 8, + d: 'Base fee of the MULMOD opcode', }, - "mulmod": { - "v": 8, - "d": "Base fee of the MULMOD opcode" + signextend: { + v: 5, + d: 'Base fee of the SIGNEXTEND opcode', }, - "signextend": { - "v": 5, - "d": "Base fee of the SIGNEXTEND opcode" + lt: { + v: 3, + d: 'Base fee of the LT opcode', }, - "lt": { - "v": 3, - "d": "Base fee of the LT opcode" + gt: { + v: 3, + d: 'Base fee of the GT opcode', }, - "gt": { - "v": 3, - "d": "Base fee of the GT opcode" + slt: { + v: 3, + d: 'Base fee of the SLT opcode', }, - "slt": { - "v": 3, - "d": "Base fee of the SLT opcode" + sgt: { + v: 3, + d: 'Base fee of the SGT opcode', }, - "sgt": { - "v": 3, - "d": "Base fee of the SGT opcode" + eq: { + v: 3, + d: 'Base fee of the EQ opcode', }, - "eq": { - "v": 3, - "d": "Base fee of the EQ opcode" + iszero: { + v: 3, + d: 'Base fee of the ISZERO opcode', }, - "iszero": { - "v": 3, - "d": "Base fee of the ISZERO opcode" + and: { + v: 3, + d: 'Base fee of the AND opcode', }, - "and": { - "v": 3, - "d": "Base fee of the AND opcode" + or: { + v: 3, + d: 'Base fee of the OR opcode', }, - "or": { - "v": 3, - "d": "Base fee of the OR opcode" + xor: { + v: 3, + d: 'Base fee of the XOR opcode', }, - "xor": { - "v": 3, - "d": "Base fee of the XOR opcode" + not: { + v: 3, + d: 'Base fee of the NOT opcode', }, - "not": { - "v": 3, - "d": "Base fee of the NOT opcode" + byte: { + v: 3, + d: 'Base fee of the BYTE opcode', }, - "byte": { - "v": 3, - "d": "Base fee of the BYTE opcode" + address: { + v: 2, + d: 'Base fee of the ADDRESS opcode', }, - "address": { - "v": 2, - "d": "Base fee of the ADDRESS opcode" + balance: { + v: 20, + d: 'Base fee of the BALANCE opcode', }, - "balance": { - "v": 20, - "d": "Base fee of the BALANCE opcode" + origin: { + v: 2, + d: 'Base fee of the ORIGIN opcode', }, - "origin": { - "v": 2, - "d": "Base fee of the ORIGIN opcode" + caller: { + v: 2, + d: 'Base fee of the CALLER opcode', }, - "caller": { - "v": 2, - "d": "Base fee of the CALLER opcode" + callvalue: { + v: 2, + d: 'Base fee of the CALLVALUE opcode', }, - "callvalue": { - "v": 2, - "d": "Base fee of the CALLVALUE opcode" + calldataload: { + v: 3, + d: 'Base fee of the CALLDATALOAD opcode', }, - "calldataload": { - "v": 3, - "d": "Base fee of the CALLDATALOAD opcode" + calldatasize: { + v: 2, + d: 'Base fee of the CALLDATASIZE opcode', }, - "calldatasize": { - "v": 2, - "d": "Base fee of the CALLDATASIZE opcode" + calldatacopy: { + v: 3, + d: 'Base fee of the CALLDATACOPY opcode', }, - "calldatacopy": { - "v": 3, - "d": "Base fee of the CALLDATACOPY opcode" + codesize: { + v: 2, + d: 'Base fee of the CODESIZE opcode', }, - "codesize": { - "v": 2, - "d": "Base fee of the CODESIZE opcode" + codecopy: { + v: 3, + d: 'Base fee of the CODECOPY opcode', }, - "codecopy": { - "v": 3, - "d": "Base fee of the CODECOPY opcode" + gasprice: { + v: 2, + d: 'Base fee of the GASPRICE opcode', }, - "gasprice": { - "v": 2, - "d": "Base fee of the GASPRICE opcode" + extcodesize: { + v: 20, + d: 'Base fee of the EXTCODESIZE opcode', }, - "extcodesize": { - "v": 20, - "d": "Base fee of the EXTCODESIZE opcode" + extcodecopy: { + v: 20, + d: 'Base fee of the EXTCODECOPY opcode', }, - "extcodecopy": { - "v": 20, - "d": "Base fee of the EXTCODECOPY opcode" + blockhash: { + v: 20, + d: 'Base fee of the BLOCKHASH opcode', }, - "blockhash": { - "v": 20, - "d": "Base fee of the BLOCKHASH opcode" + coinbase: { + v: 2, + d: 'Base fee of the COINBASE opcode', }, - "coinbase": { - "v": 2, - "d": "Base fee of the COINBASE opcode" + timestamp: { + v: 2, + d: 'Base fee of the TIMESTAMP opcode', }, - "timestamp": { - "v": 2, - "d": "Base fee of the TIMESTAMP opcode" + number: { + v: 2, + d: 'Base fee of the NUMBER opcode', }, - "number": { - "v": 2, - "d": "Base fee of the NUMBER opcode" + difficulty: { + v: 2, + d: 'Base fee of the DIFFICULTY opcode', }, - "difficulty": { - "v": 2, - "d": "Base fee of the DIFFICULTY opcode" + gaslimit: { + v: 2, + d: 'Base fee of the GASLIMIT opcode', }, - "gaslimit": { - "v": 2, - "d": "Base fee of the GASLIMIT opcode" + pop: { + v: 2, + d: 'Base fee of the POP opcode', }, - "pop": { - "v": 2, - "d": "Base fee of the POP opcode" + mload: { + v: 3, + d: 'Base fee of the MLOAD opcode', }, - "mload": { - "v": 3, - "d": "Base fee of the MLOAD opcode" + mstore: { + v: 3, + d: 'Base fee of the MSTORE opcode', }, - "mstore": { - "v": 3, - "d": "Base fee of the MSTORE opcode" + mstore8: { + v: 3, + d: 'Base fee of the MSTORE8 opcode', }, - "mstore8": { - "v": 3, - "d": "Base fee of the MSTORE8 opcode" + sstore: { + v: 0, + d: 'Base fee of the SSTORE opcode', }, - "sstore": { - "v": 0, - "d": "Base fee of the SSTORE opcode" + jump: { + v: 8, + d: 'Base fee of the JUMP opcode', }, - "jump": { - "v": 8, - "d": "Base fee of the JUMP opcode" + jumpi: { + v: 10, + d: 'Base fee of the JUMPI opcode', }, - "jumpi": { - "v": 10, - "d": "Base fee of the JUMPI opcode" + pc: { + v: 2, + d: 'Base fee of the PC opcode', }, - "pc": { - "v": 2, - "d": "Base fee of the PC opcode" + msize: { + v: 2, + d: 'Base fee of the MSIZE opcode', }, - "msize": { - "v": 2, - "d": "Base fee of the MSIZE opcode" + gas: { + v: 2, + d: 'Base fee of the GAS opcode', }, - "gas": { - "v": 2, - "d": "Base fee of the GAS opcode" + push: { + v: 3, + d: 'Base fee of the PUSH opcode', }, - "push": { - "v": 3, - "d": "Base fee of the PUSH opcode" + dup: { + v: 3, + d: 'Base fee of the DUP opcode', }, - "dup": { - "v": 3, - "d": "Base fee of the DUP opcode" + swap: { + v: 3, + d: 'Base fee of the SWAP opcode', }, - "swap": { - "v": 3, - "d": "Base fee of the SWAP opcode" + callcode: { + v: 40, + d: 'Base fee of the CALLCODE opcode', }, - "callcode": { - "v": 40, - "d": "Base fee of the CALLCODE opcode" + return: { + v: 0, + d: 'Base fee of the RETURN opcode', }, - "return": { - "v": 0, - "d": "Base fee of the RETURN opcode" + invalid: { + v: 0, + d: 'Base fee of the INVALID opcode', }, - "invalid": { - "v": 0, - "d": "Base fee of the INVALID opcode" + selfdestruct: { + v: 0, + d: 'Base fee of the SELFDESTRUCT opcode', }, - "selfdestruct": { - "v": 0, - "d": "Base fee of the SELFDESTRUCT opcode" - } }, - "vm": { - "stackLimit": { - "v": 1024, - "d": "Maximum size of VM stack allowed" - }, - "callCreateDepth": { - "v": 1024, - "d": "Maximum depth of call/create stack" - }, - "maxExtraDataSize": { - "v": 32, - "d": "Maximum size extra data may be after Genesis" - } + vm: { + stackLimit: { + v: 1024, + d: 'Maximum size of VM stack allowed', + }, + callCreateDepth: { + v: 1024, + d: 'Maximum depth of call/create stack', + }, + maxExtraDataSize: { + v: 32, + d: 'Maximum size extra data may be after Genesis', + }, + }, + pow: { + minimumDifficulty: { + v: 131072, + d: 'The minimum that the difficulty may ever be', + }, + difficultyBoundDivisor: { + v: 2048, + d: 'The bound divisor of the difficulty, used in the update calculations', + }, + durationLimit: { + v: 13, + d: 'The decision boundary on the blocktime duration used to determine whether difficulty should go up or not', + }, + epochDuration: { + v: 30000, + d: 'Duration between proof-of-work epochs', + }, + timebombPeriod: { + v: 100000, + d: 'Exponential difficulty timebomb period', + }, + minerReward: { + v: '5000000000000000000', + d: 'the amount a miner get rewarded for mining a block', + }, + difficultyBombDelay: { + v: 0, + d: 'the amount of blocks to delay the difficulty bomb with', + }, }, - "pow": { - "minimumDifficulty": { - "v": 131072, - "d": "The minimum that the difficulty may ever be" - }, - "difficultyBoundDivisor": { - "v": 2048, - "d": "The bound divisor of the difficulty, used in the update calculations" - }, - "durationLimit": { - "v": 13, - "d": "The decision boundary on the blocktime duration used to determine whether difficulty should go up or not" - }, - "epochDuration": { - "v": 30000, - "d": "Duration between proof-of-work epochs" - }, - "timebombPeriod": { - "v": 100000, - "d": "Exponential difficulty timebomb period" - }, - "minerReward": { - "v": "5000000000000000000", - "d": "the amount a miner get rewarded for mining a block" - }, - "difficultyBombDelay": { - "v": 0, - "d": "the amount of blocks to delay the difficulty bomb with" - } - } -} - ; \ No newline at end of file +}; diff --git a/packages/web3-eth-accounts/src/common/hardforks/constantinople.ts b/packages/web3-eth-accounts/src/common/hardforks/constantinople.ts index dd576fe1575..5401a1d7b58 100644 --- a/packages/web3-eth-accounts/src/common/hardforks/constantinople.ts +++ b/packages/web3-eth-accounts/src/common/hardforks/constantinople.ts @@ -1,69 +1,68 @@ export default { - "name": "constantinople", - "comment": "Postponed hardfork including EIP-1283 (SSTORE gas metering changes)", - "url": "https://eips.ethereum.org/EIPS/eip-1013", - "status": "Final", - "gasConfig": {}, - "gasPrices": { - "netSstoreNoopGas": { - "v": 200, - "d": "Once per SSTORE operation if the value doesn't change" + name: 'constantinople', + comment: 'Postponed hardfork including EIP-1283 (SSTORE gas metering changes)', + url: 'https://eips.ethereum.org/EIPS/eip-1013', + status: 'Final', + gasConfig: {}, + gasPrices: { + netSstoreNoopGas: { + v: 200, + d: "Once per SSTORE operation if the value doesn't change", }, - "netSstoreInitGas": { - "v": 20000, - "d": "Once per SSTORE operation from clean zero" + netSstoreInitGas: { + v: 20000, + d: 'Once per SSTORE operation from clean zero', }, - "netSstoreCleanGas": { - "v": 5000, - "d": "Once per SSTORE operation from clean non-zero" + netSstoreCleanGas: { + v: 5000, + d: 'Once per SSTORE operation from clean non-zero', }, - "netSstoreDirtyGas": { - "v": 200, - "d": "Once per SSTORE operation from dirty" + netSstoreDirtyGas: { + v: 200, + d: 'Once per SSTORE operation from dirty', }, - "netSstoreClearRefund": { - "v": 15000, - "d": "Once per SSTORE operation for clearing an originally existing storage slot" + netSstoreClearRefund: { + v: 15000, + d: 'Once per SSTORE operation for clearing an originally existing storage slot', }, - "netSstoreResetRefund": { - "v": 4800, - "d": "Once per SSTORE operation for resetting to the original non-zero value" + netSstoreResetRefund: { + v: 4800, + d: 'Once per SSTORE operation for resetting to the original non-zero value', }, - "netSstoreResetClearRefund": { - "v": 19800, - "d": "Once per SSTORE operation for resetting to the original zero value" + netSstoreResetClearRefund: { + v: 19800, + d: 'Once per SSTORE operation for resetting to the original zero value', }, - "shl": { - "v": 3, - "d": "Base fee of the SHL opcode" + shl: { + v: 3, + d: 'Base fee of the SHL opcode', }, - "shr": { - "v": 3, - "d": "Base fee of the SHR opcode" + shr: { + v: 3, + d: 'Base fee of the SHR opcode', }, - "sar": { - "v": 3, - "d": "Base fee of the SAR opcode" + sar: { + v: 3, + d: 'Base fee of the SAR opcode', }, - "extcodehash": { - "v": 400, - "d": "Base fee of the EXTCODEHASH opcode" + extcodehash: { + v: 400, + d: 'Base fee of the EXTCODEHASH opcode', + }, + create2: { + v: 32000, + d: 'Base fee of the CREATE2 opcode', }, - "create2": { - "v": 32000, - "d": "Base fee of the CREATE2 opcode" - } }, - "vm": {}, - "pow": { - "minerReward": { - "v": "2000000000000000000", - "d": "The amount a miner gets rewarded for mining a block" + vm: {}, + pow: { + minerReward: { + v: '2000000000000000000', + d: 'The amount a miner gets rewarded for mining a block', + }, + difficultyBombDelay: { + v: 5000000, + d: 'the amount of blocks to delay the difficulty bomb with', }, - "difficultyBombDelay": { - "v": 5000000, - "d": "the amount of blocks to delay the difficulty bomb with" - } - } -} - ; \ No newline at end of file + }, +}; diff --git a/packages/web3-eth-accounts/src/common/hardforks/dao.ts b/packages/web3-eth-accounts/src/common/hardforks/dao.ts index a565ec89a42..601858bce47 100644 --- a/packages/web3-eth-accounts/src/common/hardforks/dao.ts +++ b/packages/web3-eth-accounts/src/common/hardforks/dao.ts @@ -1,11 +1,10 @@ export default { - "name": "dao", - "comment": "DAO rescue hardfork", - "url": "https://eips.ethereum.org/EIPS/eip-779", - "status": "Final", - "gasConfig": {}, - "gasPrices": {}, - "vm": {}, - "pow": {} -} - ; \ No newline at end of file + name: 'dao', + comment: 'DAO rescue hardfork', + url: 'https://eips.ethereum.org/EIPS/eip-779', + status: 'Final', + gasConfig: {}, + gasPrices: {}, + vm: {}, + pow: {}, +}; diff --git a/packages/web3-eth-accounts/src/common/hardforks/grayGlacier.ts b/packages/web3-eth-accounts/src/common/hardforks/grayGlacier.ts index 3c67d73e7af..51490fed3e1 100644 --- a/packages/web3-eth-accounts/src/common/hardforks/grayGlacier.ts +++ b/packages/web3-eth-accounts/src/common/hardforks/grayGlacier.ts @@ -1,12 +1,11 @@ export default { - "name": "grayGlacier", - "comment": "Delaying the difficulty bomb to Mid September 2022", - "url": "https://github.com/ethereum/execution-specs/blob/master/network-upgrades/mainnet-upgrades/gray-glacier.md", - "status": "Draft", - "eips": [5133], - "gasConfig": {}, - "gasPrices": {}, - "vm": {}, - "pow": {} -} - ; \ No newline at end of file + name: 'grayGlacier', + comment: 'Delaying the difficulty bomb to Mid September 2022', + url: 'https://github.com/ethereum/execution-specs/blob/master/network-upgrades/mainnet-upgrades/gray-glacier.md', + status: 'Draft', + eips: [5133], + gasConfig: {}, + gasPrices: {}, + vm: {}, + pow: {}, +}; diff --git a/packages/web3-eth-accounts/src/common/hardforks/homestead.ts b/packages/web3-eth-accounts/src/common/hardforks/homestead.ts index e6521fc46ab..6cdbdec928f 100644 --- a/packages/web3-eth-accounts/src/common/hardforks/homestead.ts +++ b/packages/web3-eth-accounts/src/common/hardforks/homestead.ts @@ -1,16 +1,15 @@ export default { - "name": "homestead", - "comment": "Homestead hardfork with protocol and network changes", - "url": "https://eips.ethereum.org/EIPS/eip-606", - "status": "Final", - "gasConfig": {}, - "gasPrices": { - "delegatecall": { - "v": 40, - "d": "Base fee of the DELEGATECALL opcode" - } + name: 'homestead', + comment: 'Homestead hardfork with protocol and network changes', + url: 'https://eips.ethereum.org/EIPS/eip-606', + status: 'Final', + gasConfig: {}, + gasPrices: { + delegatecall: { + v: 40, + d: 'Base fee of the DELEGATECALL opcode', + }, }, - "vm": {}, - "pow": {} -} - ; \ No newline at end of file + vm: {}, + pow: {}, +}; diff --git a/packages/web3-eth-accounts/src/common/hardforks/istanbul.ts b/packages/web3-eth-accounts/src/common/hardforks/istanbul.ts index 96f3a66c598..33fb5b7fd92 100644 --- a/packages/web3-eth-accounts/src/common/hardforks/istanbul.ts +++ b/packages/web3-eth-accounts/src/common/hardforks/istanbul.ts @@ -1,88 +1,87 @@ export default { - "name": "istanbul", - "comment": "HF targeted for December 2019 following the Constantinople/Petersburg HF", - "url": "https://eips.ethereum.org/EIPS/eip-1679", - "status": "Final", - "gasConfig": {}, - "gasPrices": { - "blake2Round": { - "v": 1, - "d": "Gas cost per round for the Blake2 F precompile" - }, - "ecAdd": { - "v": 150, - "d": "Gas costs for curve addition precompile" - }, - "ecMul": { - "v": 6000, - "d": "Gas costs for curve multiplication precompile" - }, - "ecPairing": { - "v": 45000, - "d": "Base gas costs for curve pairing precompile" - }, - "ecPairingWord": { - "v": 34000, - "d": "Gas costs regarding curve pairing precompile input length" - }, - "txDataNonZero": { - "v": 16, - "d": "Per byte of data attached to a transaction that is not equal to zero. NOTE: Not payable on data of calls between transactions" - }, - "sstoreSentryGasEIP2200": { - "v": 2300, - "d": "Minimum gas required to be present for an SSTORE call, not consumed" - }, - "sstoreNoopGasEIP2200": { - "v": 800, - "d": "Once per SSTORE operation if the value doesn't change" - }, - "sstoreDirtyGasEIP2200": { - "v": 800, - "d": "Once per SSTORE operation if a dirty value is changed" - }, - "sstoreInitGasEIP2200": { - "v": 20000, - "d": "Once per SSTORE operation from clean zero to non-zero" - }, - "sstoreInitRefundEIP2200": { - "v": 19200, - "d": "Once per SSTORE operation for resetting to the original zero value" - }, - "sstoreCleanGasEIP2200": { - "v": 5000, - "d": "Once per SSTORE operation from clean non-zero to something else" - }, - "sstoreCleanRefundEIP2200": { - "v": 4200, - "d": "Once per SSTORE operation for resetting to the original non-zero value" - }, - "sstoreClearRefundEIP2200": { - "v": 15000, - "d": "Once per SSTORE operation for clearing an originally existing storage slot" - }, - "balance": { - "v": 700, - "d": "Base fee of the BALANCE opcode" - }, - "extcodehash": { - "v": 700, - "d": "Base fee of the EXTCODEHASH opcode" - }, - "chainid": { - "v": 2, - "d": "Base fee of the CHAINID opcode" - }, - "selfbalance": { - "v": 5, - "d": "Base fee of the SELFBALANCE opcode" - }, - "sload": { - "v": 800, - "d": "Base fee of the SLOAD opcode" - } + name: 'istanbul', + comment: 'HF targeted for December 2019 following the Constantinople/Petersburg HF', + url: 'https://eips.ethereum.org/EIPS/eip-1679', + status: 'Final', + gasConfig: {}, + gasPrices: { + blake2Round: { + v: 1, + d: 'Gas cost per round for the Blake2 F precompile', + }, + ecAdd: { + v: 150, + d: 'Gas costs for curve addition precompile', + }, + ecMul: { + v: 6000, + d: 'Gas costs for curve multiplication precompile', + }, + ecPairing: { + v: 45000, + d: 'Base gas costs for curve pairing precompile', + }, + ecPairingWord: { + v: 34000, + d: 'Gas costs regarding curve pairing precompile input length', + }, + txDataNonZero: { + v: 16, + d: 'Per byte of data attached to a transaction that is not equal to zero. NOTE: Not payable on data of calls between transactions', + }, + sstoreSentryGasEIP2200: { + v: 2300, + d: 'Minimum gas required to be present for an SSTORE call, not consumed', + }, + sstoreNoopGasEIP2200: { + v: 800, + d: "Once per SSTORE operation if the value doesn't change", + }, + sstoreDirtyGasEIP2200: { + v: 800, + d: 'Once per SSTORE operation if a dirty value is changed', + }, + sstoreInitGasEIP2200: { + v: 20000, + d: 'Once per SSTORE operation from clean zero to non-zero', + }, + sstoreInitRefundEIP2200: { + v: 19200, + d: 'Once per SSTORE operation for resetting to the original zero value', + }, + sstoreCleanGasEIP2200: { + v: 5000, + d: 'Once per SSTORE operation from clean non-zero to something else', + }, + sstoreCleanRefundEIP2200: { + v: 4200, + d: 'Once per SSTORE operation for resetting to the original non-zero value', + }, + sstoreClearRefundEIP2200: { + v: 15000, + d: 'Once per SSTORE operation for clearing an originally existing storage slot', + }, + balance: { + v: 700, + d: 'Base fee of the BALANCE opcode', + }, + extcodehash: { + v: 700, + d: 'Base fee of the EXTCODEHASH opcode', + }, + chainid: { + v: 2, + d: 'Base fee of the CHAINID opcode', + }, + selfbalance: { + v: 5, + d: 'Base fee of the SELFBALANCE opcode', + }, + sload: { + v: 800, + d: 'Base fee of the SLOAD opcode', + }, }, - "vm": {}, - "pow": {} -} - ; \ No newline at end of file + vm: {}, + pow: {}, +}; diff --git a/packages/web3-eth-accounts/src/common/hardforks/london.ts b/packages/web3-eth-accounts/src/common/hardforks/london.ts index 6d0ec4a4468..6b55207e434 100644 --- a/packages/web3-eth-accounts/src/common/hardforks/london.ts +++ b/packages/web3-eth-accounts/src/common/hardforks/london.ts @@ -1,8 +1,7 @@ export default { - "name": "london", - "comment": "HF targeted for July 2021 following the Berlin fork", - "url": "https://github.com/ethereum/eth1.0-specs/blob/master/network-upgrades/mainnet-upgrades/london.md", - "status": "Final", - "eips": [1559, 3198, 3529, 3541] -} - ; \ No newline at end of file + name: 'london', + comment: 'HF targeted for July 2021 following the Berlin fork', + url: 'https://github.com/ethereum/eth1.0-specs/blob/master/network-upgrades/mainnet-upgrades/london.md', + status: 'Final', + eips: [1559, 3198, 3529, 3541], +}; diff --git a/packages/web3-eth-accounts/src/common/hardforks/merge.ts b/packages/web3-eth-accounts/src/common/hardforks/merge.ts index db48aa32509..f574f678656 100644 --- a/packages/web3-eth-accounts/src/common/hardforks/merge.ts +++ b/packages/web3-eth-accounts/src/common/hardforks/merge.ts @@ -1,13 +1,12 @@ export default { - "name": "merge", - "comment": "Hardfork to upgrade the consensus mechanism to Proof-of-Stake", - "url": "https://github.com/ethereum/execution-specs/blob/master/network-upgrades/mainnet-upgrades/merge.md", - "status": "Final", - "consensus": { - "type": "pos", - "algorithm": "casper", - "casper": {} + name: 'merge', + comment: 'Hardfork to upgrade the consensus mechanism to Proof-of-Stake', + url: 'https://github.com/ethereum/execution-specs/blob/master/network-upgrades/mainnet-upgrades/merge.md', + status: 'Final', + consensus: { + type: 'pos', + algorithm: 'casper', + casper: {}, }, - "eips": [3675, 4399] -} - ; \ No newline at end of file + eips: [3675, 4399], +}; diff --git a/packages/web3-eth-accounts/src/common/hardforks/mergeForkIdTransition.ts b/packages/web3-eth-accounts/src/common/hardforks/mergeForkIdTransition.ts index f4df67bd2d2..08d6a2b9dcf 100644 --- a/packages/web3-eth-accounts/src/common/hardforks/mergeForkIdTransition.ts +++ b/packages/web3-eth-accounts/src/common/hardforks/mergeForkIdTransition.ts @@ -1,8 +1,7 @@ export default { - "name": "mergeForkIdTransition", - "comment": "Pre-merge hardfork to fork off non-upgraded clients", - "url": "https://eips.ethereum.org/EIPS/eip-3675", - "status": "Draft", - "eips": [] -} - ; \ No newline at end of file + name: 'mergeForkIdTransition', + comment: 'Pre-merge hardfork to fork off non-upgraded clients', + url: 'https://eips.ethereum.org/EIPS/eip-3675', + status: 'Draft', + eips: [], +}; diff --git a/packages/web3-eth-accounts/src/common/hardforks/muirGlacier.ts b/packages/web3-eth-accounts/src/common/hardforks/muirGlacier.ts index a7d02c6147e..8b3469e329a 100644 --- a/packages/web3-eth-accounts/src/common/hardforks/muirGlacier.ts +++ b/packages/web3-eth-accounts/src/common/hardforks/muirGlacier.ts @@ -1,16 +1,15 @@ export default { - "name": "muirGlacier", - "comment": "HF to delay the difficulty bomb", - "url": "https://eips.ethereum.org/EIPS/eip-2384", - "status": "Final", - "gasConfig": {}, - "gasPrices": {}, - "vm": {}, - "pow": { - "difficultyBombDelay": { - "v": 9000000, - "d": "the amount of blocks to delay the difficulty bomb with" - } - } -} - ; \ No newline at end of file + name: 'muirGlacier', + comment: 'HF to delay the difficulty bomb', + url: 'https://eips.ethereum.org/EIPS/eip-2384', + status: 'Final', + gasConfig: {}, + gasPrices: {}, + vm: {}, + pow: { + difficultyBombDelay: { + v: 9000000, + d: 'the amount of blocks to delay the difficulty bomb with', + }, + }, +}; diff --git a/packages/web3-eth-accounts/src/common/hardforks/petersburg.ts b/packages/web3-eth-accounts/src/common/hardforks/petersburg.ts index cca4005f893..fd392f6a9ed 100644 --- a/packages/web3-eth-accounts/src/common/hardforks/petersburg.ts +++ b/packages/web3-eth-accounts/src/common/hardforks/petersburg.ts @@ -1,40 +1,40 @@ export default { - "name": "petersburg", - "comment": "Aka constantinopleFix, removes EIP-1283, activate together with or after constantinople", - "url": "https://eips.ethereum.org/EIPS/eip-1716", - "status": "Final", - "gasConfig": {}, - "gasPrices": { - "netSstoreNoopGas": { - "v": null, - "d": "Removed along EIP-1283" + name: 'petersburg', + comment: + 'Aka constantinopleFix, removes EIP-1283, activate together with or after constantinople', + url: 'https://eips.ethereum.org/EIPS/eip-1716', + status: 'Final', + gasConfig: {}, + gasPrices: { + netSstoreNoopGas: { + v: null, + d: 'Removed along EIP-1283', }, - "netSstoreInitGas": { - "v": null, - "d": "Removed along EIP-1283" + netSstoreInitGas: { + v: null, + d: 'Removed along EIP-1283', }, - "netSstoreCleanGas": { - "v": null, - "d": "Removed along EIP-1283" + netSstoreCleanGas: { + v: null, + d: 'Removed along EIP-1283', }, - "netSstoreDirtyGas": { - "v": null, - "d": "Removed along EIP-1283" + netSstoreDirtyGas: { + v: null, + d: 'Removed along EIP-1283', }, - "netSstoreClearRefund": { - "v": null, - "d": "Removed along EIP-1283" + netSstoreClearRefund: { + v: null, + d: 'Removed along EIP-1283', }, - "netSstoreResetRefund": { - "v": null, - "d": "Removed along EIP-1283" + netSstoreResetRefund: { + v: null, + d: 'Removed along EIP-1283', + }, + netSstoreResetClearRefund: { + v: null, + d: 'Removed along EIP-1283', }, - "netSstoreResetClearRefund": { - "v": null, - "d": "Removed along EIP-1283" - } }, - "vm": {}, - "pow": {} -} - ; \ No newline at end of file + vm: {}, + pow: {}, +}; diff --git a/packages/web3-eth-accounts/src/common/hardforks/shanghai.ts b/packages/web3-eth-accounts/src/common/hardforks/shanghai.ts index 736e331a89e..3854e3aa65d 100644 --- a/packages/web3-eth-accounts/src/common/hardforks/shanghai.ts +++ b/packages/web3-eth-accounts/src/common/hardforks/shanghai.ts @@ -1,8 +1,8 @@ export default { - "name": "shanghai", - "comment": "Next feature hardfork after the merge hardfork having withdrawals, warm coinbase, push0, limit/meter initcode", - "url": "https://github.com/ethereum/execution-specs/blob/master/network-upgrades/mainnet-upgrades/shanghai.md", - "status": "Final", - "eips": [3651, 3855, 3860, 4895] -} - ; \ No newline at end of file + name: 'shanghai', + comment: + 'Next feature hardfork after the merge hardfork having withdrawals, warm coinbase, push0, limit/meter initcode', + url: 'https://github.com/ethereum/execution-specs/blob/master/network-upgrades/mainnet-upgrades/shanghai.md', + status: 'Final', + eips: [3651, 3855, 3860, 4895], +}; diff --git a/packages/web3-eth-accounts/src/common/hardforks/sharding.ts b/packages/web3-eth-accounts/src/common/hardforks/sharding.ts index e164e5f84d7..53d668b562f 100644 --- a/packages/web3-eth-accounts/src/common/hardforks/sharding.ts +++ b/packages/web3-eth-accounts/src/common/hardforks/sharding.ts @@ -1,8 +1,7 @@ export default { - "name": "shardingFork", - "comment": "Internal hardfork to test proto-danksharding (do not use in production)", - "url": "https://eips.ethereum.org/EIPS/eip-4844", - "status": "Experimental", - "eips": [4844] -} - ; \ No newline at end of file + name: 'shardingFork', + comment: 'Internal hardfork to test proto-danksharding (do not use in production)', + url: 'https://eips.ethereum.org/EIPS/eip-4844', + status: 'Experimental', + eips: [4844], +}; diff --git a/packages/web3-eth-accounts/src/common/hardforks/spuriousDragon.ts b/packages/web3-eth-accounts/src/common/hardforks/spuriousDragon.ts index e1ed0eda36c..2ed301b1a41 100644 --- a/packages/web3-eth-accounts/src/common/hardforks/spuriousDragon.ts +++ b/packages/web3-eth-accounts/src/common/hardforks/spuriousDragon.ts @@ -1,21 +1,21 @@ export default { - "name": "spuriousDragon", - "comment": "HF with EIPs for simple replay attack protection, EXP cost increase, state trie clearing, contract code size limit", - "url": "https://eips.ethereum.org/EIPS/eip-607", - "status": "Final", - "gasConfig": {}, - "gasPrices": { - "expByte": { - "v": 50, - "d": "Times ceil(log256(exponent)) for the EXP instruction" - } + name: 'spuriousDragon', + comment: + 'HF with EIPs for simple replay attack protection, EXP cost increase, state trie clearing, contract code size limit', + url: 'https://eips.ethereum.org/EIPS/eip-607', + status: 'Final', + gasConfig: {}, + gasPrices: { + expByte: { + v: 50, + d: 'Times ceil(log256(exponent)) for the EXP instruction', + }, }, - "vm": { - "maxCodeSize": { - "v": 24576, - "d": "Maximum length of contract code" - } + vm: { + maxCodeSize: { + v: 24576, + d: 'Maximum length of contract code', + }, }, - "pow": {} -} - ; \ No newline at end of file + pow: {}, +}; diff --git a/packages/web3-eth-accounts/src/common/hardforks/tangerineWhistle.ts b/packages/web3-eth-accounts/src/common/hardforks/tangerineWhistle.ts index ffb2bf43594..ccfc1044ccd 100644 --- a/packages/web3-eth-accounts/src/common/hardforks/tangerineWhistle.ts +++ b/packages/web3-eth-accounts/src/common/hardforks/tangerineWhistle.ts @@ -1,44 +1,43 @@ export default { - "name": "tangerineWhistle", - "comment": "Hardfork with gas cost changes for IO-heavy operations", - "url": "https://eips.ethereum.org/EIPS/eip-608", - "status": "Final", - "gasConfig": {}, - "gasPrices": { - "sload": { - "v": 200, - "d": "Once per SLOAD operation" - }, - "call": { - "v": 700, - "d": "Once per CALL operation & message call transaction" - }, - "extcodesize": { - "v": 700, - "d": "Base fee of the EXTCODESIZE opcode" - }, - "extcodecopy": { - "v": 700, - "d": "Base fee of the EXTCODECOPY opcode" - }, - "balance": { - "v": 400, - "d": "Base fee of the BALANCE opcode" - }, - "delegatecall": { - "v": 700, - "d": "Base fee of the DELEGATECALL opcode" - }, - "callcode": { - "v": 700, - "d": "Base fee of the CALLCODE opcode" - }, - "selfdestruct": { - "v": 5000, - "d": "Base fee of the SELFDESTRUCT opcode" - } + name: 'tangerineWhistle', + comment: 'Hardfork with gas cost changes for IO-heavy operations', + url: 'https://eips.ethereum.org/EIPS/eip-608', + status: 'Final', + gasConfig: {}, + gasPrices: { + sload: { + v: 200, + d: 'Once per SLOAD operation', + }, + call: { + v: 700, + d: 'Once per CALL operation & message call transaction', + }, + extcodesize: { + v: 700, + d: 'Base fee of the EXTCODESIZE opcode', + }, + extcodecopy: { + v: 700, + d: 'Base fee of the EXTCODECOPY opcode', + }, + balance: { + v: 400, + d: 'Base fee of the BALANCE opcode', + }, + delegatecall: { + v: 700, + d: 'Base fee of the DELEGATECALL opcode', + }, + callcode: { + v: 700, + d: 'Base fee of the CALLCODE opcode', + }, + selfdestruct: { + v: 5000, + d: 'Base fee of the SELFDESTRUCT opcode', + }, }, - "vm": {}, - "pow": {} -} - ; \ No newline at end of file + vm: {}, + pow: {}, +}; diff --git a/packages/web3-eth-accounts/src/wallet.ts b/packages/web3-eth-accounts/src/wallet.ts index 1e189fe4cbc..d69f6e5ddc6 100644 --- a/packages/web3-eth-accounts/src/wallet.ts +++ b/packages/web3-eth-accounts/src/wallet.ts @@ -26,18 +26,18 @@ type BrowserError = { code: number; name: string }; * These accounts can be used when using web3.eth.sendTransaction() or web3.eth.contract.methods.contractfunction().send(); * * For using Wallet functionality, install Web3 package using `npm i web3` or `yarn add web3`. - * After that, Wallet functionality will be available as mentioned below. - * + * After that, Wallet functionality will be available as mentioned below. + * * ```ts * import { Web3 } from 'web3'; * const web3 = new Web3('http://127.0.0.1:7545'); - * + * * const wallet = await web3.eth.accounts.wallet.create(2); - * + * * const signature = wallet.at(0).sign("Test Data"); // use wallet - * + * * // fund account before sending following transaction ... - * + * * const receipt = await web3.eth.sendTransaction({ // internally sign transaction using wallet * from: wallet.at(0).address, * to: "0xdAC17F958D2ee523a2206206994597C13D831ec7", diff --git a/packages/web3-eth-accounts/test/fixtures/account.ts b/packages/web3-eth-accounts/test/fixtures/account.ts index 104b5688e97..08c6a19ef54 100644 --- a/packages/web3-eth-accounts/test/fixtures/account.ts +++ b/packages/web3-eth-accounts/test/fixtures/account.ts @@ -222,27 +222,29 @@ export const invalidPrivateKeytoAccountData: [ ]; export const validPrivateKeyToPublicKeyData: [ - Bytes, boolean, string // private key, isCompressed, public key + Bytes, + boolean, + string, // private key, isCompressed, public key ][] = [ [ - "0x1e046a882bb38236b646c9f135cf90ad90a140810f439875f2a6dd8e50fa261f", // test string to uncompressed publickey + '0x1e046a882bb38236b646c9f135cf90ad90a140810f439875f2a6dd8e50fa261f', // test string to uncompressed publickey false, - "0x42beb65f179720abaa3ec9a70a539629cbbc5ec65bb57e7fc78977796837e537662dd17042e6449dc843c281067a4d6d8d1a1775a13c41901670d5de7ee6503a", + '0x42beb65f179720abaa3ec9a70a539629cbbc5ec65bb57e7fc78977796837e537662dd17042e6449dc843c281067a4d6d8d1a1775a13c41901670d5de7ee6503a', ], [ - "0x1e046a882bb38236b646c9f135cf90ad90a140810f439875f2a6dd8e50fa261f", // test string to compressed publickey + '0x1e046a882bb38236b646c9f135cf90ad90a140810f439875f2a6dd8e50fa261f', // test string to compressed publickey true, - "0x42beb65f179720abaa3ec9a70a539629cbbc5ec65bb57e7fc78977796837e537", + '0x42beb65f179720abaa3ec9a70a539629cbbc5ec65bb57e7fc78977796837e537', ], [ - hexToBytes("0xd933beabed94a9f23917576596b2bc64ffeacfe5ded09a99c0feee8369bd295d"), // test uint8array to uncompressed publickey + hexToBytes('0xd933beabed94a9f23917576596b2bc64ffeacfe5ded09a99c0feee8369bd295d'), // test uint8array to uncompressed publickey false, - "0x7891db4ed2d26584b0fa87329c40b398c940c08e7dbeb8e3dad83f34dba284c933fb14b1edd8893fa89af3823fd827ee59044033ca068803030afc294de5f390", + '0x7891db4ed2d26584b0fa87329c40b398c940c08e7dbeb8e3dad83f34dba284c933fb14b1edd8893fa89af3823fd827ee59044033ca068803030afc294de5f390', ], [ - hexToBytes("0xd933beabed94a9f23917576596b2bc64ffeacfe5ded09a99c0feee8369bd295d"), // test uint8array to compressed publickey + hexToBytes('0xd933beabed94a9f23917576596b2bc64ffeacfe5ded09a99c0feee8369bd295d'), // test uint8array to compressed publickey true, - "0x7891db4ed2d26584b0fa87329c40b398c940c08e7dbeb8e3dad83f34dba284c9", + '0x7891db4ed2d26584b0fa87329c40b398c940c08e7dbeb8e3dad83f34dba284c9', ], ]; @@ -407,9 +409,15 @@ export const invalidEncryptData: [ ]; export const validRecover: [string, string][] = [ - [ "I hereby confirm that I am the sole beneficial owner of the assets involved in the business relationship with Fiat24. \nI hereby undertake to inform Fiat24 proactively of any changes to the information contained herein.", "0xec4f73260ac14882e65995a09359896a0ae8f16bd0d28b0d9171655b4e85271e07cda040be059fdcbf52709e3c993eb50a89ce33f41617dc090dc80a583e3c4f00",], // v < 27 - ["test", "0xefb42c22baa0143b322e93b24b0903a0ef47a64b716fbb77debbea55a93dec3e4417aff7dce845723240916c6e34cf17c674828b3addfb0afad966334df5b6311b"] // v >= 27 -] + [ + 'I hereby confirm that I am the sole beneficial owner of the assets involved in the business relationship with Fiat24. \nI hereby undertake to inform Fiat24 proactively of any changes to the information contained herein.', + '0xec4f73260ac14882e65995a09359896a0ae8f16bd0d28b0d9171655b4e85271e07cda040be059fdcbf52709e3c993eb50a89ce33f41617dc090dc80a583e3c4f00', + ], // v < 27 + [ + 'test', + '0xefb42c22baa0143b322e93b24b0903a0ef47a64b716fbb77debbea55a93dec3e4417aff7dce845723240916c6e34cf17c674828b3addfb0afad966334df5b6311b', + ], // v >= 27 +]; export const invalidKeyStore: [[any, string]][] = [ [ diff --git a/packages/web3-eth-accounts/test/unit/account_dom.test.ts b/packages/web3-eth-accounts/test/unit/account_dom.test.ts index 587996a721c..799fc4f2f8e 100644 --- a/packages/web3-eth-accounts/test/unit/account_dom.test.ts +++ b/packages/web3-eth-accounts/test/unit/account_dom.test.ts @@ -98,9 +98,9 @@ describe('accounts', () => { describe('privateKeyToAccount', () => { describe('valid cases', () => { it.each(validPrivateKeytoAccountData)('%s', (input, output) => { - expect(JSON.stringify(privateKeyToAccount(input.address, input.ignoreLength))).toEqual( - JSON.stringify(output), - ); + expect( + JSON.stringify(privateKeyToAccount(input.address, input.ignoreLength)), + ).toEqual(JSON.stringify(output)); }); }); @@ -213,13 +213,17 @@ describe('accounts', () => { // make sure decrypt does not throw invalid password error const result = await decrypt(keystore, input[1]); - expect(JSON.stringify(result)).toEqual(JSON.stringify(privateKeyToAccount(input[3]))); + expect(JSON.stringify(result)).toEqual( + JSON.stringify(privateKeyToAccount(input[3])), + ); const keystoreString = JSON.stringify(keystore); const stringResult = await decrypt(keystoreString, input[1], true); - expect(JSON.stringify(stringResult)).toEqual(JSON.stringify(privateKeyToAccount(input[3]))); + expect(JSON.stringify(stringResult)).toEqual( + JSON.stringify(privateKeyToAccount(input[3])), + ); }); }); diff --git a/packages/web3-eth-contract/CHANGELOG.md b/packages/web3-eth-contract/CHANGELOG.md index 0d8310b9832..318816b7941 100644 --- a/packages/web3-eth-contract/CHANGELOG.md +++ b/packages/web3-eth-contract/CHANGELOG.md @@ -397,11 +397,11 @@ Documentation: ### Added -- Added `populateTransaction` to the `contract.deploy(...)` properties. (#7197) +- Added `populateTransaction` to the `contract.deploy(...)` properties. (#7197) ### Changed - The returnred properties of `contract.deploy(...)` are structured with a newly created class named `DeployerMethodClass`. (#7197) -- Add a missed accepted type for the `abi` parameter, at `dataInputEncodeMethodHelper` and `getSendTxParams`. (#7197) +- Add a missed accepted type for the `abi` parameter, at `dataInputEncodeMethodHelper` and `getSendTxParams`. (#7197) -## [Unreleased] \ No newline at end of file +## [Unreleased] diff --git a/packages/web3-eth-contract/src/contract-deployer-method-class.ts b/packages/web3-eth-contract/src/contract-deployer-method-class.ts index d57f7ae05b2..33018541390 100644 --- a/packages/web3-eth-contract/src/contract-deployer-method-class.ts +++ b/packages/web3-eth-contract/src/contract-deployer-method-class.ts @@ -15,14 +15,8 @@ You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see . */ -import { - Web3ContractError, -} from 'web3-errors'; -import { - sendTransaction, - SendTransactionEvents, - SendTransactionOptions, -} from 'web3-eth'; +import { Web3ContractError } from 'web3-errors'; +import { sendTransaction, SendTransactionEvents, SendTransactionOptions } from 'web3-eth'; import { AbiConstructorFragment, AbiFunctionFragment, @@ -37,24 +31,12 @@ import { TransactionReceipt, TransactionCall, } from 'web3-types'; -import { - format, -} from 'web3-utils'; -import { - isNullish, -} from 'web3-validator'; +import { format } from 'web3-utils'; +import { isNullish } from 'web3-validator'; import { Web3PromiEvent } from 'web3-core'; -import { - decodeMethodParams, - encodeMethodABI, -} from './encoding.js'; -import { - NonPayableTxOptions, - PayableTxOptions, -} from './types.js'; -import { - getSendTxParams, -} from './utils.js'; +import { decodeMethodParams, encodeMethodABI } from './encoding.js'; +import { NonPayableTxOptions, PayableTxOptions } from './types.js'; +import { getSendTxParams } from './utils.js'; // eslint-disable-next-line import/no-cycle import { Contract } from './contract.js'; @@ -68,15 +50,12 @@ export type ContractDeploySend = Web3PromiEvent< * This class is only supposed to be used for the return of `new Contract(...).deploy(...)` method. */ export class DeployerMethodClass { - protected readonly args: never[] | ContractConstructorArgs; protected readonly constructorAbi: AbiConstructorFragment; protected readonly contractOptions: ContractOptions; protected readonly deployData?: string; - protected _contractMethodDeploySend( - tx: TransactionCall, - ) { + protected _contractMethodDeploySend(tx: TransactionCall) { // eslint-disable-next-line no-use-before-define const returnTxOptions: SendTransactionOptions> = { transactionResolver: (receipt: TransactionReceipt) => { @@ -90,7 +69,7 @@ export class DeployerMethodClass { newContract.options.address = receipt.contractAddress; return newContract; }, - + contractAbi: this.parent.options.jsonInterface, // TODO Should make this configurable by the user checkRevertBeforeSending: false, @@ -124,8 +103,7 @@ export class DeployerMethodClass { } | undefined, ) { - - const { args, abi, contractOptions, deployData} = this.calculateDeployParams(); + const { args, abi, contractOptions, deployData } = this.calculateDeployParams(); this.args = args; this.constructorAbi = abi; @@ -141,9 +119,7 @@ export class DeployerMethodClass { return this._contractMethodDeploySend(tx); } - public populateTransaction( - txOptions?: PayableTxOptions | NonPayableTxOptions, - ) { + public populateTransaction(txOptions?: PayableTxOptions | NonPayableTxOptions) { const modifiedContractOptions = { ...this.contractOptions, from: this.contractOptions.from ?? this.parent.defaultAccount ?? undefined, @@ -202,7 +178,7 @@ export class DeployerMethodClass { }; const deployData = _input ?? _data; - return { args, abi, contractOptions, deployData} + return { args, abi, contractOptions, deployData }; } public async estimateGas( @@ -233,8 +209,12 @@ export class DeployerMethodClass { public decodeData(data: HexString) { return { - ...decodeMethodParams(this.constructorAbi, data.replace(this.deployData as string, ''), false), + ...decodeMethodParams( + this.constructorAbi, + data.replace(this.deployData as string, ''), + false, + ), __method__: this.constructorAbi.type, }; } -}; +} diff --git a/packages/web3-eth-contract/src/contract.ts b/packages/web3-eth-contract/src/contract.ts index 906cd3c8794..5566d0840bf 100644 --- a/packages/web3-eth-contract/src/contract.ts +++ b/packages/web3-eth-contract/src/contract.ts @@ -209,8 +209,6 @@ const contractSubscriptions = { newBlockHeaders: NewHeadsSubscription, }; - - /** * The `web3.eth.Contract` makes it easy to interact with smart contracts on the ethereum blockchain. * For using contract package, first install Web3 package using: `npm i web3` or `yarn add web3` based on your package manager, after that contracts features can be used as mentioned in following snippet. @@ -511,7 +509,11 @@ export class Contract ); public constructor( jsonInterface: Abi, - addressOrOptionsOrContext?: Address | ContractInitOptions | Web3ContractContext | Web3Context, + addressOrOptionsOrContext?: + | Address + | ContractInitOptions + | Web3ContractContext + | Web3Context, optionsOrContextOrReturnFormat?: | ContractInitOptions | Web3ContractContext @@ -537,14 +539,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; @@ -960,7 +968,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(), ); } @@ -970,7 +979,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() + ); }); }); } @@ -1013,7 +1025,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 = { @@ -1029,7 +1043,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, [ @@ -1037,10 +1053,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, @@ -1053,7 +1069,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] = @@ -1129,7 +1146,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); @@ -1145,9 +1165,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 @@ -1169,7 +1189,14 @@ 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), @@ -1198,7 +1225,8 @@ export class Contract }, estimateGas: async ( options?: PayableCallOptions | NonPayableCallOptions, - returnFormat: ReturnFormat = this.defaultReturnFormat as unknown as ReturnFormat, + returnFormat: ReturnFormat = this + .defaultReturnFormat as unknown as ReturnFormat, ) => this.contractMethodEstimateGas({ abi: methodAbi, @@ -1381,7 +1409,11 @@ export class Contract 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, @@ -1391,7 +1423,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, }, ); @@ -1404,7 +1439,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/src/encoding.ts b/packages/web3-eth-contract/src/encoding.ts index f57a9d7b4c5..48531277518 100644 --- a/packages/web3-eth-contract/src/encoding.ts +++ b/packages/web3-eth-contract/src/encoding.ts @@ -137,7 +137,6 @@ export const encodeMethodABI = ( params = inferTypesAndEncodeParameters(args).replace('0x', ''); } - if (isAbiConstructorFragment(abi)) { if (!deployData) throw new Web3ContractError( diff --git a/packages/web3-eth-contract/src/utils.ts b/packages/web3-eth-contract/src/utils.ts index fc475a5a813..5ef2de6d594 100644 --- a/packages/web3-eth-contract/src/utils.ts +++ b/packages/web3-eth-contract/src/utils.ts @@ -16,7 +16,12 @@ along with web3.js. If not, see . */ import { RLP } from '@ethereumjs/rlp'; -import { InvalidAddressError, InvalidMethodParamsError, InvalidNumberError, Web3ContractError } from 'web3-errors'; +import { + InvalidAddressError, + InvalidMethodParamsError, + InvalidNumberError, + Web3ContractError, +} from 'web3-errors'; import { TransactionForAccessList, AbiFunctionFragment, @@ -30,7 +35,14 @@ import { Numbers, AbiConstructorFragment, } from 'web3-types'; -import { isNullish, mergeDeep, isContractInitOptions, keccak256, toChecksumAddress, hexToNumber } from 'web3-utils'; +import { + isNullish, + mergeDeep, + isContractInitOptions, + keccak256, + toChecksumAddress, + hexToNumber, +} from 'web3-utils'; import { isAddress, isHexString } from 'web3-validator'; import { encodeMethodABI } from './encoding.js'; import { Web3ContractContext } from './types.js'; @@ -215,41 +227,38 @@ export const getCreateAccessListParams = ({ return txParams; }; - export const createContractAddress = (from: Address, nonce: Numbers): Address => { - if(!isAddress(from)) - throw new InvalidAddressError(`Invalid address given ${from}`); + if (!isAddress(from)) throw new InvalidAddressError(`Invalid address given ${from}`); let nonceValue = nonce; - if(typeof nonce === "string" && isHexString(nonce)) - nonceValue = hexToNumber(nonce); - else if(typeof nonce === "string" && !isHexString(nonce)) - throw new InvalidNumberError("Invalid nonce value format"); + if (typeof nonce === 'string' && isHexString(nonce)) nonceValue = hexToNumber(nonce); + else if (typeof nonce === 'string' && !isHexString(nonce)) + throw new InvalidNumberError('Invalid nonce value format'); - const rlpEncoded = RLP.encode( - [from, nonceValue] - ); - const result = keccak256(rlpEncoded); + const rlpEncoded = RLP.encode([from, nonceValue]); + const result = keccak256(rlpEncoded); - const contractAddress = '0x'.concat(result.substring(26)); + const contractAddress = '0x'.concat(result.substring(26)); - return toChecksumAddress(contractAddress); -} + return toChecksumAddress(contractAddress); +}; -export const create2ContractAddress = (from: Address, salt: HexString, initCode: HexString): Address => { - if(!isAddress(from)) - throw new InvalidAddressError(`Invalid address given ${from}`); +export const create2ContractAddress = ( + from: Address, + salt: HexString, + initCode: HexString, +): Address => { + if (!isAddress(from)) throw new InvalidAddressError(`Invalid address given ${from}`); - if(!isHexString(salt)) - throw new InvalidMethodParamsError(`Invalid salt value ${salt}`); + if (!isHexString(salt)) throw new InvalidMethodParamsError(`Invalid salt value ${salt}`); - if(!isHexString(initCode)) - throw new InvalidMethodParamsError(`Invalid initCode value ${initCode}`); + if (!isHexString(initCode)) + throw new InvalidMethodParamsError(`Invalid initCode value ${initCode}`); const initCodeHash = keccak256(initCode); const initCodeHashPadded = initCodeHash.padStart(64, '0'); // Pad to 32 bytes (64 hex characters) const create2Params = ['0xff', from, salt, initCodeHashPadded].map(x => x.replace(/0x/, '')); - const create2Address = `0x${ create2Params.join('')}`; + const create2Address = `0x${create2Params.join('')}`; - return toChecksumAddress(`0x${ keccak256(create2Address).slice(26)}`); // Slice to get the last 20 bytes (40 hex characters) & checksum - } \ No newline at end of file + return toChecksumAddress(`0x${keccak256(create2Address).slice(26)}`); // Slice to get the last 20 bytes (40 hex characters) & checksum +}; diff --git a/packages/web3-eth-contract/test/fixtures/AbiItem.ts b/packages/web3-eth-contract/test/fixtures/AbiItem.ts index bcc94ce4b02..7b112ef2e80 100644 --- a/packages/web3-eth-contract/test/fixtures/AbiItem.ts +++ b/packages/web3-eth-contract/test/fixtures/AbiItem.ts @@ -16,84 +16,84 @@ along with web3.js. If not, see . */ export const Abi = { - anonymous: false, - constant: true, - inputs: [ - { - name: 'testMe', - type: 'uint256[3]' - }, - { - name: 'inputA', - type: 'tuple', - components: [ - { - name: 'a', - type: 'uint8' - }, - { - name: 'b', - type: 'uint8' - } - ] - }, - { - name: 'inputB', - type: 'tuple[]', - components: [ - { - name: 'a1', - type: 'uint256' - }, - { - name: 'a2', - type: 'uint256' - } - ] - }, - { - name: 'inputC', - type: 'uint8', - indexed: false - } - ], - name: "testName", - outputs: [ - { - name: "test", - type: "uint256" - }, - { - name: 'outputA', - type: 'tuple', - components: [ - { - name: 'a', - type: 'uint8' - }, - { - name: 'b', - type: 'uint8' - } - ] - }, - { - name: 'outputB', - type: 'tuple[]', - components: [ - { - name: 'a1', - type: 'uint256' - }, - { - name: 'a2', - type: 'uint256' - } - ] - } - ], - payable: false, - stateMutability: "pure", - type: "function", - gas: 175875 -} \ No newline at end of file + anonymous: false, + constant: true, + inputs: [ + { + name: 'testMe', + type: 'uint256[3]', + }, + { + name: 'inputA', + type: 'tuple', + components: [ + { + name: 'a', + type: 'uint8', + }, + { + name: 'b', + type: 'uint8', + }, + ], + }, + { + name: 'inputB', + type: 'tuple[]', + components: [ + { + name: 'a1', + type: 'uint256', + }, + { + name: 'a2', + type: 'uint256', + }, + ], + }, + { + name: 'inputC', + type: 'uint8', + indexed: false, + }, + ], + name: 'testName', + outputs: [ + { + name: 'test', + type: 'uint256', + }, + { + name: 'outputA', + type: 'tuple', + components: [ + { + name: 'a', + type: 'uint8', + }, + { + name: 'b', + type: 'uint8', + }, + ], + }, + { + name: 'outputB', + type: 'tuple[]', + components: [ + { + name: 'a1', + type: 'uint256', + }, + { + name: 'a2', + type: 'uint256', + }, + ], + }, + ], + payable: false, + stateMutability: 'pure', + type: 'function', + gas: 175875, +}; diff --git a/packages/web3-eth-contract/test/fixtures/contract_transaction_middleware.ts b/packages/web3-eth-contract/test/fixtures/contract_transaction_middleware.ts index 9a1ab0f20cf..0a3d1819809 100644 --- a/packages/web3-eth-contract/test/fixtures/contract_transaction_middleware.ts +++ b/packages/web3-eth-contract/test/fixtures/contract_transaction_middleware.ts @@ -15,24 +15,21 @@ You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see . */ -import { TransactionMiddleware, TransactionMiddlewareData } from "web3-eth"; +import { TransactionMiddleware, TransactionMiddlewareData } from 'web3-eth'; -// Sample Transaction Middleware +// Sample Transaction Middleware export class ContractTransactionMiddleware implements TransactionMiddleware { - // eslint-disable-next-line class-methods-use-this - public async processTransaction(transaction: TransactionMiddlewareData, - _options?: { [key: string]: unknown } | undefined): - - Promise { - + public async processTransaction( + transaction: TransactionMiddlewareData, + _options?: { [key: string]: unknown } | undefined, + ): Promise { // eslint-disable-next-line prefer-const let txObj = { ...transaction }; - // Add your logic here for transaction modification + // Add your logic here for transaction modification txObj.data = '0x123'; return Promise.resolve(txObj); } - } diff --git a/packages/web3-eth-contract/test/fixtures/create.ts b/packages/web3-eth-contract/test/fixtures/create.ts index 0297828e5f1..4262b53e68d 100644 --- a/packages/web3-eth-contract/test/fixtures/create.ts +++ b/packages/web3-eth-contract/test/fixtures/create.ts @@ -15,120 +15,119 @@ You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see . */ -import { Numbers } from "web3-types"; +import { Numbers } from 'web3-types'; export interface CreateTestData { - address: string; - input: { - from: string; - nonce: Numbers; - }; - } - + address: string; + input: { + from: string; + nonce: Numbers; + }; +} + export const testData: CreateTestData[] = [ - { - address: '0x0C1B54fb6fdf63DEe15e65CAdBA8F2e028E26Bd0', - - input: { - from: '0xe2597eb05cf9a87eb1309e86750c903ec38e527e', - nonce: 0, - } - }, - { - address: '0x0C1B54fb6fdf63DEe15e65CAdBA8F2e028E26Bd0', - - input: { - from: '0xe2597eb05cf9a87eb1309e86750c903ec38e527e', - nonce: BigInt(0), - } - }, - { - address: '0x0C1B54fb6fdf63DEe15e65CAdBA8F2e028E26Bd0', - - input: { - from: '0xe2597eb05cf9a87eb1309e86750c903ec38e527e', - nonce: "0x0", - } - }, - { - address: '0x3474627D4F63A678266BC17171D87f8570936622', - - input: { - from: '0xb2682160c482eb985ec9f3e364eec0a904c44c23', - nonce: 10, - } - }, - - { - address: '0x3474627D4F63A678266BC17171D87f8570936622', - - input: { - from: '0xb2682160c482eb985ec9f3e364eec0a904c44c23', - nonce: "0xa", - } - }, - - { - address: '0x3474627D4F63A678266BC17171D87f8570936622', - - input: { - from: '0xb2682160c482eb985ec9f3e364eec0a904c44c23', - nonce: "0x0a", - } - }, - - { - address: '0x271300790813f82638A8A6A8a86d65df6dF33c17', - - input: { - from: '0x8ba1f109551bd432803012645ac136ddd64dba72', - nonce: "0x200", - } - }, - - { - address: '0x271300790813f82638A8A6A8a86d65df6dF33c17', - - input: { - from: '0x8ba1f109551bd432803012645ac136ddd64dba72', - nonce: "0x0200", - } - }, - - { - address: '0x995C25706C407a1F1E84b3777775e3e619764933', - - input: { - from: '0x8ba1f109551bd432803012645ac136ddd64dba72', - nonce: "0x1d", - } - }, - - { - address: '0x995C25706C407a1F1E84b3777775e3e619764933', - - input: { - from: '0x8ba1f109551bd432803012645ac136ddd64dba72', - nonce: "0x001d", - } - }, - - { - address: '0x995C25706C407a1F1E84b3777775e3e619764933', - - input: { - from: '0x8ba1f109551bd432803012645ac136ddd64dba72', - nonce: 29, - } - }, - - - { - address: '0x0CcCC7507aEDf9FEaF8C8D731421746e16b4d39D', - - input: { - from: '0xc6af6e1a78a6752c7f8cd63877eb789a2adb776c', - nonce: 0 - } - }, -]; \ No newline at end of file + { + address: '0x0C1B54fb6fdf63DEe15e65CAdBA8F2e028E26Bd0', + + input: { + from: '0xe2597eb05cf9a87eb1309e86750c903ec38e527e', + nonce: 0, + }, + }, + { + address: '0x0C1B54fb6fdf63DEe15e65CAdBA8F2e028E26Bd0', + + input: { + from: '0xe2597eb05cf9a87eb1309e86750c903ec38e527e', + nonce: BigInt(0), + }, + }, + { + address: '0x0C1B54fb6fdf63DEe15e65CAdBA8F2e028E26Bd0', + + input: { + from: '0xe2597eb05cf9a87eb1309e86750c903ec38e527e', + nonce: '0x0', + }, + }, + { + address: '0x3474627D4F63A678266BC17171D87f8570936622', + + input: { + from: '0xb2682160c482eb985ec9f3e364eec0a904c44c23', + nonce: 10, + }, + }, + + { + address: '0x3474627D4F63A678266BC17171D87f8570936622', + + input: { + from: '0xb2682160c482eb985ec9f3e364eec0a904c44c23', + nonce: '0xa', + }, + }, + + { + address: '0x3474627D4F63A678266BC17171D87f8570936622', + + input: { + from: '0xb2682160c482eb985ec9f3e364eec0a904c44c23', + nonce: '0x0a', + }, + }, + + { + address: '0x271300790813f82638A8A6A8a86d65df6dF33c17', + + input: { + from: '0x8ba1f109551bd432803012645ac136ddd64dba72', + nonce: '0x200', + }, + }, + + { + address: '0x271300790813f82638A8A6A8a86d65df6dF33c17', + + input: { + from: '0x8ba1f109551bd432803012645ac136ddd64dba72', + nonce: '0x0200', + }, + }, + + { + address: '0x995C25706C407a1F1E84b3777775e3e619764933', + + input: { + from: '0x8ba1f109551bd432803012645ac136ddd64dba72', + nonce: '0x1d', + }, + }, + + { + address: '0x995C25706C407a1F1E84b3777775e3e619764933', + + input: { + from: '0x8ba1f109551bd432803012645ac136ddd64dba72', + nonce: '0x001d', + }, + }, + + { + address: '0x995C25706C407a1F1E84b3777775e3e619764933', + + input: { + from: '0x8ba1f109551bd432803012645ac136ddd64dba72', + nonce: 29, + }, + }, + + { + address: '0x0CcCC7507aEDf9FEaF8C8D731421746e16b4d39D', + + input: { + from: '0xc6af6e1a78a6752c7f8cd63877eb789a2adb776c', + nonce: 0, + }, + }, +]; diff --git a/packages/web3-eth-contract/test/fixtures/create2.ts b/packages/web3-eth-contract/test/fixtures/create2.ts index 2cceb34f1bc..95bbb616983 100644 --- a/packages/web3-eth-contract/test/fixtures/create2.ts +++ b/packages/web3-eth-contract/test/fixtures/create2.ts @@ -15,56 +15,57 @@ You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see . */ -import { Address, HexString } from "web3-types"; +import { Address, HexString } from 'web3-types'; export interface Create2TestData { - address: Address; - salt: HexString; - init_code: HexString; - result: Address; - } + address: Address; + salt: HexString; + init_code: HexString; + result: Address; +} - export const create2TestData: Create2TestData[] = [ - { - address: "0x0000000000000000000000000000000000000000", - salt: "0x0000000000000000000000000000000000000000000000000000000000000000", - init_code: "0x00", - result: "0x4D1A2e2bB4F88F0250f26Ffff098B0b30B26BF38" - }, - { - address: "0xdeadbeef00000000000000000000000000000000", - salt: "0x0000000000000000000000000000000000000000000000000000000000000000", - init_code: "0x00", - result: "0xB928f69Bb1D91Cd65274e3c79d8986362984fDA3" - }, - { - address: "0xdeadbeef00000000000000000000000000000000", - salt: "0x000000000000000000000000feed000000000000000000000000000000000000", - init_code: "0x00", - result: "0xD04116cDd17beBE565EB2422F2497E06cC1C9833" - }, - { - address: "0x0000000000000000000000000000000000000000", - salt: "0x0000000000000000000000000000000000000000000000000000000000000000", - init_code: "0xdeadbeef", - result: "0x70f2b2914A2a4b783FaEFb75f459A580616Fcb5e" - }, - { - address: "0x00000000000000000000000000000000deadbeef", - salt: "0x00000000000000000000000000000000000000000000000000000000cafebabe", - init_code: "0xdeadbeef", - result: "0x60f3f640a8508fC6a86d45DF051962668E1e8AC7" - }, - { - address: "0x00000000000000000000000000000000deadbeef", - salt: "0x00000000000000000000000000000000000000000000000000000000cafebabe", - init_code: "0xdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef", - result: "0x1d8bfDC5D46DC4f61D6b6115972536eBE6A8854C" - }, - { - address: "0x0000000000000000000000000000000000000000", - salt: "0x0000000000000000000000000000000000000000000000000000000000000000", - init_code: "0x", - result: "0xE33C0C7F7df4809055C3ebA6c09CFe4BaF1BD9e0" - } - ]; \ No newline at end of file +export const create2TestData: Create2TestData[] = [ + { + address: '0x0000000000000000000000000000000000000000', + salt: '0x0000000000000000000000000000000000000000000000000000000000000000', + init_code: '0x00', + result: '0x4D1A2e2bB4F88F0250f26Ffff098B0b30B26BF38', + }, + { + address: '0xdeadbeef00000000000000000000000000000000', + salt: '0x0000000000000000000000000000000000000000000000000000000000000000', + init_code: '0x00', + result: '0xB928f69Bb1D91Cd65274e3c79d8986362984fDA3', + }, + { + address: '0xdeadbeef00000000000000000000000000000000', + salt: '0x000000000000000000000000feed000000000000000000000000000000000000', + init_code: '0x00', + result: '0xD04116cDd17beBE565EB2422F2497E06cC1C9833', + }, + { + address: '0x0000000000000000000000000000000000000000', + salt: '0x0000000000000000000000000000000000000000000000000000000000000000', + init_code: '0xdeadbeef', + result: '0x70f2b2914A2a4b783FaEFb75f459A580616Fcb5e', + }, + { + address: '0x00000000000000000000000000000000deadbeef', + salt: '0x00000000000000000000000000000000000000000000000000000000cafebabe', + init_code: '0xdeadbeef', + result: '0x60f3f640a8508fC6a86d45DF051962668E1e8AC7', + }, + { + address: '0x00000000000000000000000000000000deadbeef', + salt: '0x00000000000000000000000000000000000000000000000000000000cafebabe', + init_code: + '0xdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef', + result: '0x1d8bfDC5D46DC4f61D6b6115972536eBE6A8854C', + }, + { + address: '0x0000000000000000000000000000000000000000', + salt: '0x0000000000000000000000000000000000000000000000000000000000000000', + init_code: '0x', + result: '0xE33C0C7F7df4809055C3ebA6c09CFe4BaF1BD9e0', + }, +]; diff --git a/packages/web3-eth-contract/test/integration/contract_accesslist.test.ts b/packages/web3-eth-contract/test/integration/contract_accesslist.test.ts index 23934b05016..3173f452c33 100644 --- a/packages/web3-eth-contract/test/integration/contract_accesslist.test.ts +++ b/packages/web3-eth-contract/test/integration/contract_accesslist.test.ts @@ -22,7 +22,7 @@ import { createTempAccount, describeIf, getSystemTestBackend, - BACKEND + BACKEND, } from '../fixtures/system_test_utils'; describe('contract', () => { 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 2ff87f07177..b54ed63b41d 100644 --- a/packages/web3-eth-contract/test/integration/contract_deploy.test.ts +++ b/packages/web3-eth-contract/test/integration/contract_deploy.test.ts @@ -64,7 +64,7 @@ describe('contract', () => { // get contract address before deployment const address = createContractAddress(sendOptions.from as string, nonce); - + const deployedContract = await contract.deploy(deployOptions).send(sendOptions); expect(deployedContract).toBeDefined(); diff --git a/packages/web3-eth-contract/test/integration/contract_methods.test.ts b/packages/web3-eth-contract/test/integration/contract_methods.test.ts index 7cede74d7d1..46a1490c119 100644 --- a/packages/web3-eth-contract/test/integration/contract_methods.test.ts +++ b/packages/web3-eth-contract/test/integration/contract_methods.test.ts @@ -17,7 +17,12 @@ along with web3.js. If not, see . import { ContractExecutionError } from 'web3-errors'; import { Contract } from '../../src'; import { BasicAbi, BasicBytecode } from '../shared_fixtures/build/Basic'; -import { getSystemTestProvider, createTempAccount, getSystemTestBackend, BACKEND} from '../fixtures/system_test_utils'; +import { + getSystemTestProvider, + createTempAccount, + getSystemTestBackend, + BACKEND, +} from '../fixtures/system_test_utils'; describe('contract', () => { let contract: Contract; @@ -154,8 +159,8 @@ describe('contract', () => { await expect( contractDeployed.methods.reverts().send(sendOptions), ).rejects.toMatchObject({ - "name": "ContractExecutionError", - "receipt": undefined, + name: 'ContractExecutionError', + receipt: undefined, }); } else { // eslint-disable-next-line jest/no-conditional-expect diff --git a/packages/web3-eth-contract/test/integration/local_account/contract_deploy.test.ts b/packages/web3-eth-contract/test/integration/local_account/contract_deploy.test.ts index 7938636d8cb..821101ca225 100644 --- a/packages/web3-eth-contract/test/integration/local_account/contract_deploy.test.ts +++ b/packages/web3-eth-contract/test/integration/local_account/contract_deploy.test.ts @@ -117,22 +117,21 @@ describe('contract', () => { it('should emit the "confirmation" event', async () => { const confirmationHandler = jest.fn(); - const promievent = contract - .deploy(deployOptions) - .send(sendOptions); - const receiptPromise = new Promise((resolve) => { - // eslint-disable-next-line @typescript-eslint/no-floating-promises - promievent - .on('receipt', () => { - resolve() - }) - }) + const promievent = contract.deploy(deployOptions).send(sendOptions); + const receiptPromise = new Promise(resolve => { + // eslint-disable-next-line @typescript-eslint/no-floating-promises + promievent.on('receipt', () => { + resolve(); + }); + }); - const confirmationPRomise = new Promise((resolve) => { + const confirmationPRomise = new Promise(resolve => { // eslint-disable-next-line @typescript-eslint/no-floating-promises - promievent - .on('confirmation', () => {confirmationHandler(); resolve();}) - }) + promievent.on('confirmation', () => { + confirmationHandler(); + resolve(); + }); + }); await promievent; await receiptPromise; diff --git a/packages/web3-eth-contract/test/integration/local_account/contract_overloaded_methods.test.ts b/packages/web3-eth-contract/test/integration/local_account/contract_overloaded_methods.test.ts index 35ca056cbab..96985cda3a7 100644 --- a/packages/web3-eth-contract/test/integration/local_account/contract_overloaded_methods.test.ts +++ b/packages/web3-eth-contract/test/integration/local_account/contract_overloaded_methods.test.ts @@ -102,10 +102,7 @@ describe('contract ERC721 overloaded functions', () => { }); it('transferFrom with 3 invalid arguments', () => { - expect(() => - contractDeployed.methods - .safeTransferFrom(1, 2, 3), - ).toThrow('Web3 validator'); + expect(() => contractDeployed.methods.safeTransferFrom(1, 2, 3)).toThrow('Web3 validator'); }); it('transferFrom with 2 arguments', () => { diff --git a/packages/web3-eth-contract/test/unit/contract.test.ts b/packages/web3-eth-contract/test/unit/contract.test.ts index 6ae5f055904..a87a3455c2b 100644 --- a/packages/web3-eth-contract/test/unit/contract.test.ts +++ b/packages/web3-eth-contract/test/unit/contract.test.ts @@ -41,7 +41,7 @@ import { AllGetPastEventsData, getLogsData, getPastEventsData } from '../fixture import { erc721Abi } from '../fixtures/erc721'; import { ERC20TokenAbi } from '../shared_fixtures/build/ERC20Token'; import { processAsync } from '../shared_fixtures/utils'; -import { ContractTransactionMiddleware } from "../fixtures/contract_transaction_middleware"; +import { ContractTransactionMiddleware } from '../fixtures/contract_transaction_middleware'; jest.mock('web3-eth', () => { const allAutoMocked = jest.createMockFromModule('web3-eth'); @@ -149,7 +149,7 @@ describe('Contract', () => { }); it('should set the provider, from options, upon instantiation', () => { - const provider = "http://127.0.0.1:4545"; + const provider = 'http://127.0.0.1:4545'; const contract = new Contract([], '', { provider, }); @@ -161,7 +161,7 @@ describe('Contract', () => { }); it('should set the provider, from context, upon instantiation', () => { - const provider = "http://127.0.0.1:4545"; + const provider = 'http://127.0.0.1:4545'; const contract = new Contract( [], '', @@ -285,13 +285,12 @@ describe('Contract', () => { it('should pass middleware to sendTransaction when middleware is there and deploy().send() is called', async () => { const contract = new Contract(GreeterAbi); const middleware = new ContractTransactionMiddleware(); - contract.setTransactionMiddleware(middleware) + contract.setTransactionMiddleware(middleware); // eslint-disable-next-line @typescript-eslint/no-unused-vars const sendTransactionSpy = jest .spyOn(eth, 'sendTransaction') .mockImplementation((_objInstance, _tx, _dataFormat, _options, _middleware) => { - expect(_middleware).toBeDefined(); const newContract = contract.clone(); newContract.options.address = deployedAddr; @@ -306,12 +305,11 @@ describe('Contract', () => { arguments: ['My Greeting'], }) .send(sendOptions); - + sendTransactionSpy.mockClear(); }); it('should pass middleware to sendTransaction when middleware is there and contract.method.send() is called', async () => { - const contract = new Contract(GreeterAbi, '0x12264916b10Ae90076dDa6dE756EE1395BB69ec2'); const middleware = new ContractTransactionMiddleware(); contract.setTransactionMiddleware(middleware); @@ -319,17 +317,15 @@ describe('Contract', () => { const spyTx = jest .spyOn(eth, 'sendTransaction') .mockImplementation((_objInstance, _tx, _dataformat, _options, _middleware) => { - expect(_middleware).toBeDefined(); // eslint-disable-next-line @typescript-eslint/no-unsafe-return, @typescript-eslint/no-empty-function return { status: '0x1', on: () => {} } as any; - }); const receipt = await contract.methods.setGreeting('Hello').send({ from: '0x12364916b10Ae90076dDa6dE756EE1395BB69ec2', - gas: '1000000' + gas: '1000000', }); expect(receipt.status).toBe('0x1'); @@ -816,7 +812,7 @@ describe('Contract', () => { { gas: '0x97254' }, ); contract.maxListenersWarningThreshold = 1000; - + const clonnedContract = contract.clone(); expect(stringify(contract)).toStrictEqual(stringify(clonnedContract)); @@ -826,7 +822,7 @@ describe('Contract', () => { it('should clone new contract', () => { const contract = new Contract(sampleStorageContractABI); contract.maxListenersWarningThreshold = 1000; - + const clonnedContract = contract.clone(); expect(stringify(contract)).toStrictEqual(stringify(clonnedContract)); }); diff --git a/packages/web3-eth-contract/test/unit/contract_typing.test.ts b/packages/web3-eth-contract/test/unit/contract_typing.test.ts index e0bc6b9afcb..79f66bdca29 100644 --- a/packages/web3-eth-contract/test/unit/contract_typing.test.ts +++ b/packages/web3-eth-contract/test/unit/contract_typing.test.ts @@ -25,7 +25,6 @@ import { erc721Abi, Erc721Interface } from '../fixtures/erc721'; import { NonPayableMethodObject, PayableMethodObject } from '../../src'; describe('contract typing', () => { - describe('no abi type', () => { const defaultContractInstance = new Contract([]); // when using new web3.eth.Contract generic is any[] instead of never @@ -41,8 +40,7 @@ describe('contract typing', () => { expectTypeOf>().toBe(), expectTypeOf>().toBe(), ]); - - }) + }); describe('custom abi', () => { const abi = [ { diff --git a/packages/web3-eth-contract/test/unit/function_overloading.test.ts b/packages/web3-eth-contract/test/unit/function_overloading.test.ts index 6533aea84e2..146ae703f84 100644 --- a/packages/web3-eth-contract/test/unit/function_overloading.test.ts +++ b/packages/web3-eth-contract/test/unit/function_overloading.test.ts @@ -218,7 +218,9 @@ describe('test Params Overloading', () => { it('should call the first one when the signature is not passed but also show a warning', async () => { const originalWarn = console.warn; console.warn = function (message: string) { - expect(message).toMatch('Multiple methods found that is compatible with the given inputs.'); + expect(message).toMatch( + 'Multiple methods found that is compatible with the given inputs.', + ); }; const abi = contract.methods['funcWithParamsOverloading_pure']( '0x12eca7a3959a42973ef4452e44948650be8b8610', @@ -258,7 +260,8 @@ describe('test Params Overloading', () => { }); it('uint8', async () => { - const abi = contract.methods['funcWithParamsOverloading_pure(uint8)']('0x12').encodeABI(); + const abi = + contract.methods['funcWithParamsOverloading_pure(uint8)']('0x12').encodeABI(); expect(abi.substring(0, 10)).toBe('0xf2f11ccd'); }); }); @@ -279,7 +282,8 @@ describe('test Params Overloading', () => { }); it('uint8', async () => { - const abi = contract.methods['funcWithParamsOverloading_view(uint8)']('0x12').encodeABI(); + const abi = + contract.methods['funcWithParamsOverloading_view(uint8)']('0x12').encodeABI(); expect(abi.substring(0, 10)).toBe('0xda202a6f'); }); diff --git a/packages/web3-eth-contract/test/unit/utils.test.ts b/packages/web3-eth-contract/test/unit/utils.test.ts index 3b0b69a2bfc..d2cef819183 100644 --- a/packages/web3-eth-contract/test/unit/utils.test.ts +++ b/packages/web3-eth-contract/test/unit/utils.test.ts @@ -15,80 +15,99 @@ You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see . */ -import { InvalidAddressError, InvalidNumberError } from "web3-errors"; -import { Address, Numbers } from "web3-types"; +import { InvalidAddressError, InvalidNumberError } from 'web3-errors'; +import { Address, Numbers } from 'web3-types'; import { CreateTestData, testData } from '../fixtures/create'; -import { create2ContractAddress, createContractAddress } from "../../src/utils"; -import { create2TestData } from "../fixtures/create2"; - +import { create2ContractAddress, createContractAddress } from '../../src/utils'; +import { create2TestData } from '../fixtures/create2'; describe('createContractAddress', () => { - - it.each(testData)('creates correct contract address for input: %o', (testCase: CreateTestData) => { - const { address, input } = testCase; - const result = createContractAddress(input.from , input.nonce ); - expect(result).toBe(address); - }); - - it('should throw InvalidAddressError for invalid address', () => { - expect(() => createContractAddress('invalid_address', 1)).toThrow(InvalidAddressError); - }); - - it('should throw Error for invalid nonce', () => { - expect(() => createContractAddress('0xe2597eb05cf9a87eb1309e86750c903ec38e527e', "")).toThrow(InvalidNumberError); - }); - - it('should handle different nonce types correctly', () => { - const from: Address = '0x6ac7ea33f8831ea9dcc53393aaa88b25a785dbf0'; - const testCases: [Numbers, string][] = [ - [1, '0x343c43A37D37dfF08AE8C4A11544c718AbB4fCF8'], - ['0x2', '0xf778B86FA74E846c4f0a1fBd1335FE81c00a0C91'], - [BigInt(3), '0xffFd933A0bC612844eaF0C6Fe3E5b8E9B6C1d19c'], - ]; - - testCases.forEach(([nonce, expectedAddress]) => { - const result = createContractAddress(from, nonce); - expect(result).toBe(expectedAddress); - }); - }); - - it('should create different addresses for different nonces', () => { - const from: Address = '0x6ac7ea33f8831ea9dcc53393aaa88b25a785dbf0'; - const address1 = createContractAddress(from, 0); - const address2 = createContractAddress(from, 1); - - expect(address1).not.toBe(address2); - }); - - it('should create different addresses for different sender addresses', () => { - const from1: Address = '0x6ac7ea33f8831ea9dcc53393aaa88b25a785dbf0'; - const from2: Address = '0x1234567890123456789012345678901234567890'; - const nonce: Numbers = 0; - - const address1 = createContractAddress(from1, nonce); - const address2 = createContractAddress(from2, nonce); - - expect(address1).not.toBe(address2); - }); + it.each(testData)( + 'creates correct contract address for input: %o', + (testCase: CreateTestData) => { + const { address, input } = testCase; + const result = createContractAddress(input.from, input.nonce); + expect(result).toBe(address); + }, + ); + + it('should throw InvalidAddressError for invalid address', () => { + expect(() => createContractAddress('invalid_address', 1)).toThrow(InvalidAddressError); + }); + + it('should throw Error for invalid nonce', () => { + expect(() => + createContractAddress('0xe2597eb05cf9a87eb1309e86750c903ec38e527e', ''), + ).toThrow(InvalidNumberError); + }); + + it('should handle different nonce types correctly', () => { + const from: Address = '0x6ac7ea33f8831ea9dcc53393aaa88b25a785dbf0'; + const testCases: [Numbers, string][] = [ + [1, '0x343c43A37D37dfF08AE8C4A11544c718AbB4fCF8'], + ['0x2', '0xf778B86FA74E846c4f0a1fBd1335FE81c00a0C91'], + [BigInt(3), '0xffFd933A0bC612844eaF0C6Fe3E5b8E9B6C1d19c'], + ]; + + testCases.forEach(([nonce, expectedAddress]) => { + const result = createContractAddress(from, nonce); + expect(result).toBe(expectedAddress); + }); + }); + + it('should create different addresses for different nonces', () => { + const from: Address = '0x6ac7ea33f8831ea9dcc53393aaa88b25a785dbf0'; + const address1 = createContractAddress(from, 0); + const address2 = createContractAddress(from, 1); + + expect(address1).not.toBe(address2); + }); + + it('should create different addresses for different sender addresses', () => { + const from1: Address = '0x6ac7ea33f8831ea9dcc53393aaa88b25a785dbf0'; + const from2: Address = '0x1234567890123456789012345678901234567890'; + const nonce: Numbers = 0; + + const address1 = createContractAddress(from1, nonce); + const address2 = createContractAddress(from2, nonce); + + expect(address1).not.toBe(address2); + }); }); describe('create2ContractAddress', () => { - - it.each(create2TestData)('creates correct contract address for input: %o', (testCase) => { - const result = create2ContractAddress(testCase.address, testCase.salt, testCase.init_code); - expect(result).toBe(testCase.result); - }); - - it('should throw an InvalidAddressError if the from address is invalid', () => { - expect(() => create2ContractAddress('0xinvalidaddress', create2TestData[0].salt, create2TestData[0].init_code)).toThrow('Invalid address given 0xinvalidaddress'); - }); - - it('should throw an InvalidMethodParamsError if the salt is invalid', () => { - expect(() => create2ContractAddress(create2TestData[0].address, '0xinvalidsalt', create2TestData[0].init_code)).toThrow('Invalid salt value 0xinvalidsalt'); - }); - - it('should throw an InvalidMethodParamsError if the initCode is invalid', () => { - expect(() => create2ContractAddress(create2TestData[0].address, create2TestData[0].salt, '0xinvalidcode')).toThrow('Invalid initCode value 0xinvalidcode'); - }); - -}); \ No newline at end of file + it.each(create2TestData)('creates correct contract address for input: %o', testCase => { + const result = create2ContractAddress(testCase.address, testCase.salt, testCase.init_code); + expect(result).toBe(testCase.result); + }); + + it('should throw an InvalidAddressError if the from address is invalid', () => { + expect(() => + create2ContractAddress( + '0xinvalidaddress', + create2TestData[0].salt, + create2TestData[0].init_code, + ), + ).toThrow('Invalid address given 0xinvalidaddress'); + }); + + it('should throw an InvalidMethodParamsError if the salt is invalid', () => { + expect(() => + create2ContractAddress( + create2TestData[0].address, + '0xinvalidsalt', + create2TestData[0].init_code, + ), + ).toThrow('Invalid salt value 0xinvalidsalt'); + }); + + it('should throw an InvalidMethodParamsError if the initCode is invalid', () => { + expect(() => + create2ContractAddress( + create2TestData[0].address, + create2TestData[0].salt, + '0xinvalidcode', + ), + ).toThrow('Invalid initCode value 0xinvalidcode'); + }); +}); diff --git a/packages/web3-eth-ens/CHANGELOG.md b/packages/web3-eth-ens/CHANGELOG.md index 2eb11d79a13..73454c83b59 100644 --- a/packages/web3-eth-ens/CHANGELOG.md +++ b/packages/web3-eth-ens/CHANGELOG.md @@ -151,7 +151,7 @@ Documentation: ### Add -- Added function getText and getName in ENS and resolver classes (#6914) +- Added function getText and getName in ENS and resolver classes (#6914) ## [4.3.0] @@ -170,4 +170,4 @@ Documentation: - `getName` reverse resolution -## [Unreleased] \ No newline at end of file +## [Unreleased] diff --git a/packages/web3-eth-ens/src/ens.ts b/packages/web3-eth-ens/src/ens.ts index 8f3e1806127..2a74d0f3051 100644 --- a/packages/web3-eth-ens/src/ens.ts +++ b/packages/web3-eth-ens/src/ens.ts @@ -176,8 +176,8 @@ export class ENS extends Web3Context { * @returns - The value content stored in the resolver for the specified key */ public async getText(ENSNameOrAddr: string | Address, key: string): Promise { - if(isAddress(ENSNameOrAddr)) - return this._resolver.getText(await(this._resolver.getName(ENSNameOrAddr,false)), key); + if (isAddress(ENSNameOrAddr)) + return this._resolver.getText(await this._resolver.getName(ENSNameOrAddr, false), key); return this._resolver.getText(ENSNameOrAddr, key); } diff --git a/packages/web3-eth-ens/src/resolver.ts b/packages/web3-eth-ens/src/resolver.ts index cb345055d95..d0b4f5f20ea 100644 --- a/packages/web3-eth-ens/src/resolver.ts +++ b/packages/web3-eth-ens/src/resolver.ts @@ -25,7 +25,6 @@ import { interfaceIds, methodsInInterface } from './config.js'; import { Registry } from './registry.js'; import { namehash } from './utils.js'; - // Default public resolver // https://github.com/ensdomains/resolvers/blob/master/contracts/PublicResolver.sol @@ -105,42 +104,28 @@ export class Resolver { return resolverContract.methods.contenthash(namehash(ENSName)).call(); } - public async setAddress( - ENSName: string, - address: Address, - txConfig: PayableCallOptions, - ) { + public async setAddress(ENSName: string, address: Address, txConfig: PayableCallOptions) { const resolverContract = await this.getResolverContractAdapter(ENSName); await this.checkInterfaceSupport(resolverContract, methodsInInterface.setAddr); - return resolverContract.methods - .setAddr(namehash(ENSName), address) - .send(txConfig); + return resolverContract.methods.setAddr(namehash(ENSName), address).send(txConfig); } - public async getText( - ENSName: string, - key: string, - ) { + public async getText(ENSName: string, key: string) { const resolverContract = await this.getResolverContractAdapter(ENSName); await this.checkInterfaceSupport(resolverContract, methodsInInterface.text); - return resolverContract.methods - .text(namehash(ENSName), key).call() + return resolverContract.methods.text(namehash(ENSName), key).call(); } - public async getName( - address: string, - checkInterfaceSupport = true - ) { + public async getName(address: string, checkInterfaceSupport = true) { const reverseName = `${address.toLowerCase().substring(2)}.addr.reverse`; const resolverContract = await this.getResolverContractAdapter(reverseName); - - if(checkInterfaceSupport) + + if (checkInterfaceSupport) await this.checkInterfaceSupport(resolverContract, methodsInInterface.name); - - return resolverContract.methods - .name(namehash(reverseName)).call() + + return resolverContract.methods.name(namehash(reverseName)).call(); } } diff --git a/packages/web3-eth-ens/test/integration/setup.js b/packages/web3-eth-ens/test/integration/setup.js index c480060944a..d527ad558d3 100644 --- a/packages/web3-eth-ens/test/integration/setup.js +++ b/packages/web3-eth-ens/test/integration/setup.js @@ -18,4 +18,3 @@ along with web3.js. If not, see . // Have to use `require` because of Jest issue https://jestjs.io/docs/ecmascript-modules // eslint-disable-next-line @typescript-eslint/no-require-imports require('../config/setup'); - diff --git a/packages/web3-eth-ens/test/unit/ens.test.ts b/packages/web3-eth-ens/test/unit/ens.test.ts index 1c860d72c38..82932a2ff5b 100644 --- a/packages/web3-eth-ens/test/unit/ens.test.ts +++ b/packages/web3-eth-ens/test/unit/ens.test.ts @@ -120,11 +120,7 @@ describe('ens', () => { const sendOptions = { from: mockAddress }; await ens.setAddress(ENS_NAME, mockAddress, sendOptions); - expect(setAddressMock).toHaveBeenCalledWith( - ENS_NAME, - mockAddress, - sendOptions, - ); + expect(setAddressMock).toHaveBeenCalledWith(ENS_NAME, mockAddress, sendOptions); }); it('getAddress', async () => { // eslint-disable-next-line @typescript-eslint/no-empty-function diff --git a/packages/web3-eth-ens/test/unit/resolver.test.ts b/packages/web3-eth-ens/test/unit/resolver.test.ts index da189e5a45d..e3753dfe4e7 100644 --- a/packages/web3-eth-ens/test/unit/resolver.test.ts +++ b/packages/web3-eth-ens/test/unit/resolver.test.ts @@ -219,27 +219,27 @@ describe('resolver', () => { call: async () => Promise.resolve(true), } as unknown as NonPayableMethodObject); - const textMock = jest.spyOn(contract.methods, 'text').mockReturnValue({ - call: jest.fn(), - } as unknown as NonPayableMethodObject); + const textMock = jest.spyOn(contract.methods, 'text').mockReturnValue({ + call: jest.fn(), + } as unknown as NonPayableMethodObject); - jest.spyOn(registry, 'getResolver').mockImplementation(async () => { - return new Promise(resolve => { - resolve(contract); - }); + jest.spyOn(registry, 'getResolver').mockImplementation(async () => { + return new Promise(resolve => { + resolve(contract); }); - - await resolver.getText(ENS_NAME, "key"); - expect(supportsInterfaceMock).toHaveBeenCalledWith( - interfaceIds[methodsInInterface.text], - ); - expect(textMock).toHaveBeenCalledWith(namehash(ENS_NAME), "key"); - }) -}) + }); + + await resolver.getText(ENS_NAME, 'key'); + expect(supportsInterfaceMock).toHaveBeenCalledWith( + interfaceIds[methodsInInterface.text], + ); + expect(textMock).toHaveBeenCalledWith(namehash(ENS_NAME), 'key'); + }); + }); describe('name', () => { it('getName', async () => { - const address = "0x314159265dd8dbb310642f98f50c066173c1259b"; + const address = '0x314159265dd8dbb310642f98f50c066173c1259b'; const supportsInterfaceMock = jest .spyOn(contract.methods, 'supportsInterface') @@ -247,26 +247,25 @@ describe('resolver', () => { call: async () => Promise.resolve(true), } as unknown as NonPayableMethodObject); - const nameMock = jest.spyOn(contract.methods, 'name').mockReturnValue({ - call: jest.fn(), - } as unknown as NonPayableMethodObject); + const nameMock = jest.spyOn(contract.methods, 'name').mockReturnValue({ + call: jest.fn(), + } as unknown as NonPayableMethodObject); - jest.spyOn(registry, 'getResolver').mockImplementation(async () => { - return new Promise(resolve => { - resolve(contract); - }); + jest.spyOn(registry, 'getResolver').mockImplementation(async () => { + return new Promise(resolve => { + resolve(contract); }); - - await resolver.getName(address); - expect(supportsInterfaceMock).toHaveBeenCalledWith( - interfaceIds[methodsInInterface.name], - ); - - const reverseName = `${address.toLowerCase().substring(2)}.addr.reverse`; - expect(nameMock).toHaveBeenCalledWith(namehash(reverseName)); - }) - }) - + }); + + await resolver.getName(address); + expect(supportsInterfaceMock).toHaveBeenCalledWith( + interfaceIds[methodsInInterface.name], + ); + + const reverseName = `${address.toLowerCase().substring(2)}.addr.reverse`; + expect(nameMock).toHaveBeenCalledWith(namehash(reverseName)); + }); + }); describe('supportsInterface', () => { it('check supportsInterface for non strict hex id', async () => { diff --git a/packages/web3-eth-iban/CHANGELOG.md b/packages/web3-eth-iban/CHANGELOG.md index 797f4ffe29f..5904a58763d 100644 --- a/packages/web3-eth-iban/CHANGELOG.md +++ b/packages/web3-eth-iban/CHANGELOG.md @@ -125,4 +125,4 @@ Documentation: - Dependencies updated -## [Unreleased] \ No newline at end of file +## [Unreleased] diff --git a/packages/web3-eth-personal/CHANGELOG.md b/packages/web3-eth-personal/CHANGELOG.md index aba75cae036..33f479b4ef5 100644 --- a/packages/web3-eth-personal/CHANGELOG.md +++ b/packages/web3-eth-personal/CHANGELOG.md @@ -147,4 +147,4 @@ Documentation: - Dependencies updated -## [Unreleased] \ No newline at end of file +## [Unreleased] diff --git a/packages/web3-eth-personal/src/personal.ts b/packages/web3-eth-personal/src/personal.ts index 14bee669d6f..db8d2656703 100644 --- a/packages/web3-eth-personal/src/personal.ts +++ b/packages/web3-eth-personal/src/personal.ts @@ -21,25 +21,25 @@ import { Address, EthPersonalAPI, HexString, Transaction } from 'web3-types'; import * as rpcWrappers from './rpc_method_wrappers.js'; /** -* Eth Personal allows you to interact with the Ethereum node’s accounts. -* For using Eth Personal package, first install Web3 package using: `npm i web3` or `yarn add web3` based on your package manager. -* ```ts -* -*import { Web3 } from 'web3'; -* const web3 = new Web3('http://127.0.0.1:7545'); -* -* console.log(await web3.eth.personal.getAccounts()); -* -* ``` -* For using individual package install `web3-eth-personal` packages using: `npm i web3-eth-personal` or `yarn add web3-eth-personal`. -* -* ```ts -* import {Personal} from 'web3-eth-personal'; -* -* const personal = new Personal('http://127.0.0.1:7545'); -* console.log(await personal.getAccounts()); -* ``` -*/ + * Eth Personal allows you to interact with the Ethereum node’s accounts. + * For using Eth Personal package, first install Web3 package using: `npm i web3` or `yarn add web3` based on your package manager. + * ```ts + * + *import { Web3 } from 'web3'; + * const web3 = new Web3('http://127.0.0.1:7545'); + * + * console.log(await web3.eth.personal.getAccounts()); + * + * ``` + * For using individual package install `web3-eth-personal` packages using: `npm i web3-eth-personal` or `yarn add web3-eth-personal`. + * + * ```ts + * import {Personal} from 'web3-eth-personal'; + * + * const personal = new Personal('http://127.0.0.1:7545'); + * console.log(await personal.getAccounts()); + * ``` + */ export class Personal extends Web3Context { /** *Returns a list of accounts the node controls by using the provider and calling the RPC method personal_listAccounts. Using `web3.eth.accounts.create()` will not add accounts into this list. For that use `web3.eth.personal.newAccount()`. diff --git a/packages/web3-eth-personal/test/integration/personal.test.ts b/packages/web3-eth-personal/test/integration/personal.test.ts index d650bdc6e8b..27c0e33c2f7 100644 --- a/packages/web3-eth-personal/test/integration/personal.test.ts +++ b/packages/web3-eth-personal/test/integration/personal.test.ts @@ -27,7 +27,7 @@ import { getSystemTestProvider, itIf, describeIf, - BACKEND + BACKEND, } from '../fixtures/system_test_utils'; // hardhat does not support personal diff --git a/packages/web3-eth/CHANGELOG.md b/packages/web3-eth/CHANGELOG.md index 6be4b4b5797..9005985b2b2 100644 --- a/packages/web3-eth/CHANGELOG.md +++ b/packages/web3-eth/CHANGELOG.md @@ -254,7 +254,7 @@ Documentation: - `sendTransaction` in `rpc_method_wrappers` accepts optional param of `TransactionMiddleware` (#7088) - WebEth has `setTransactionMiddleware` and `getTransactionMiddleware` for automatically passing to `sentTransaction` (#7088) -- `TransactionMiddleware` and `TransactionMiddleware` data types are exported (#7088) +- `TransactionMiddleware` and `TransactionMiddleware` data types are exported (#7088) ## [4.8.1] @@ -269,4 +269,4 @@ Documentation: - Adds transaction property to be an empty list rather than undefined when no transactions are included in the block (#7151) - Change method `getTransactionReceipt` to not be casted as `TransactionReceipt` to give proper return type (#7159) -## [Unreleased] \ No newline at end of file +## [Unreleased] diff --git a/packages/web3-eth/src/rpc_method_wrappers.ts b/packages/web3-eth/src/rpc_method_wrappers.ts index 02fb9fbb173..e5ffe9baf64 100644 --- a/packages/web3-eth/src/rpc_method_wrappers.ts +++ b/packages/web3-eth/src/rpc_method_wrappers.ts @@ -296,10 +296,10 @@ export async function getBlock( const result = { ...res, transactions: res.transactions ?? [], - } + }; return result; } - + return res; } @@ -508,26 +508,30 @@ export async function getTransactionReceipt( ); let response; try { - response = await ethRpcMethods.getTransactionReceipt( + response = await ethRpcMethods.getTransactionReceipt( web3Context.requestManager, transactionHashFormatted, ); } catch (error) { // geth indexing error, we poll until transactions stopped indexing - if (typeof error === 'object' && !isNullish(error) && 'message' in error && (error as { message: string }).message === 'transaction indexing is in progress') { - console.warn('Transaction indexing is in progress.') + if ( + typeof error === 'object' && + !isNullish(error) && + 'message' in error && + (error as { message: string }).message === 'transaction indexing is in progress' + ) { + console.warn('Transaction indexing is in progress.'); } else { throw error; } - } return isNullish(response) ? response - : (format( + : format( transactionReceiptSchema, response as unknown as TransactionReceipt, returnFormat ?? web3Context.defaultReturnFormat, - )); + ); } /** @@ -572,7 +576,7 @@ export function sendTransaction< | TransactionWithFromAndToLocalWalletIndex, returnFormat: ReturnFormat, options: SendTransactionOptions = { checkRevertBeforeSending: true }, - transactionMiddleware?: TransactionMiddleware + transactionMiddleware?: TransactionMiddleware, ): Web3PromiEvent> { const promiEvent = new Web3PromiEvent>( (resolve, reject) => { @@ -585,9 +589,9 @@ export function sendTransaction< returnFormat, }); - let transaction = {...transactionObj}; - - if(!isNullish(transactionMiddleware)){ + let transaction = { ...transactionObj }; + + if (!isNullish(transactionMiddleware)) { transaction = await transactionMiddleware.processTransaction(transaction); } diff --git a/packages/web3-eth/src/schemas.ts b/packages/web3-eth/src/schemas.ts index 244e1260b53..e27140cdcf3 100644 --- a/packages/web3-eth/src/schemas.ts +++ b/packages/web3-eth/src/schemas.ts @@ -257,10 +257,10 @@ export const withdrawalsSchema = { export const blockSchema = { type: 'object', properties: { - baseFeePerGas: { + baseFeePerGas: { format: 'uint', }, - blobGasUsed: { + blobGasUsed: { format: 'uint', }, difficulty: { @@ -345,13 +345,13 @@ export const blockSchema = { format: 'bytes32', }, }, - withdrawals: { + withdrawals: { type: 'array', items: { ...withdrawalsSchema, }, }, - withdrawalsRoot: { + withdrawalsRoot: { format: 'bytes32', }, }, @@ -360,16 +360,16 @@ export const blockSchema = { export const blockHeaderSchema = { type: 'object', properties: { - author: { + author: { format: 'bytes32', }, - excessDataGas: { + excessDataGas: { format: 'uint', }, - baseFeePerGas: { + baseFeePerGas: { format: 'uint', }, - blobGasUsed: { + blobGasUsed: { format: 'uint', }, difficulty: { @@ -444,13 +444,13 @@ export const blockHeaderSchema = { format: 'bytes32', }, }, - withdrawals: { + withdrawals: { type: 'array', items: { ...withdrawalsSchema, }, }, - withdrawalsRoot: { + withdrawalsRoot: { format: 'bytes32', }, }, diff --git a/packages/web3-eth/src/types.ts b/packages/web3-eth/src/types.ts index 9ed49badb39..9f9de0ec14a 100644 --- a/packages/web3-eth/src/types.ts +++ b/packages/web3-eth/src/types.ts @@ -92,16 +92,16 @@ export interface RevertReasonWithCustomError extends RevertReason { customErrorArguments: Record; } -export type TransactionMiddlewareData = Transaction -| TransactionWithFromLocalWalletIndex -| TransactionWithToLocalWalletIndex -| TransactionWithFromAndToLocalWalletIndex; +export type TransactionMiddlewareData = + | Transaction + | TransactionWithFromLocalWalletIndex + | TransactionWithToLocalWalletIndex + | TransactionWithFromAndToLocalWalletIndex; -export interface TransactionMiddleware{ +export interface TransactionMiddleware { // for transaction processing before signing processTransaction( - transaction: TransactionMiddlewareData, + transaction: TransactionMiddlewareData, options?: { [key: string]: unknown }, ): Promise; - -} \ No newline at end of file +} diff --git a/packages/web3-eth/src/utils/detect_transaction_type.ts b/packages/web3-eth/src/utils/detect_transaction_type.ts index ec5539b375a..171a7597f3d 100644 --- a/packages/web3-eth/src/utils/detect_transaction_type.ts +++ b/packages/web3-eth/src/utils/detect_transaction_type.ts @@ -75,9 +75,7 @@ const validateTxTypeAndHandleErrors = ( } }; -export const defaultTransactionTypeParser: TransactionTypeParser = ( - transaction -) => { +export const defaultTransactionTypeParser: TransactionTypeParser = transaction => { const tx = transaction as unknown as Transaction; if (!isNullish(tx.type)) { let txSchema; @@ -139,7 +137,7 @@ export const detectTransactionType = ( web3Context?: Web3Context, ) => (web3Context?.transactionTypeParser ?? defaultTransactionTypeParser)( - transaction as unknown as Record + transaction as unknown as Record, ); export const detectRawTransactionType = (transaction: Uint8Array) => diff --git a/packages/web3-eth/src/utils/prepare_transaction_for_signing.ts b/packages/web3-eth/src/utils/prepare_transaction_for_signing.ts index fe761ada1f6..5213e66c778 100644 --- a/packages/web3-eth/src/utils/prepare_transaction_for_signing.ts +++ b/packages/web3-eth/src/utils/prepare_transaction_for_signing.ts @@ -141,7 +141,7 @@ export const prepareTransactionForSigning = async ( validateTransactionForSigning( formattedTransaction as unknown as FormatType, ); - + return TransactionFactory.fromTxData( getEthereumjsTxDataFromTransaction(formattedTransaction), getEthereumjsTransactionOptions(formattedTransaction, web3Context), diff --git a/packages/web3-eth/src/utils/reject_if_block_timeout.ts b/packages/web3-eth/src/utils/reject_if_block_timeout.ts index 2019ce3380d..e3563ca2a1a 100644 --- a/packages/web3-eth/src/utils/reject_if_block_timeout.ts +++ b/packages/web3-eth/src/utils/reject_if_block_timeout.ts @@ -34,25 +34,24 @@ function resolveByPolling( transactionHash?: Bytes, ): [Promise, ResourceCleaner] { const pollingInterval = web3Context.transactionPollingInterval; - const [intervalId, promiseToError] = - rejectIfConditionAtInterval(async () => { - let lastBlockNumber; - try { - lastBlockNumber = await getBlockNumber(web3Context, NUMBER_DATA_FORMAT); - } catch (error) { - console.warn('An error happen while trying to get the block number', error); - return undefined; - } - const numberOfBlocks = lastBlockNumber - starterBlockNumber; - if (numberOfBlocks >= web3Context.transactionBlockTimeout) { - return new TransactionBlockTimeoutError({ - starterBlockNumber, - numberOfBlocks, - transactionHash, - }); - } + const [intervalId, promiseToError] = rejectIfConditionAtInterval(async () => { + let lastBlockNumber; + try { + lastBlockNumber = await getBlockNumber(web3Context, NUMBER_DATA_FORMAT); + } catch (error) { + console.warn('An error happen while trying to get the block number', error); return undefined; - }, pollingInterval); + } + const numberOfBlocks = lastBlockNumber - starterBlockNumber; + if (numberOfBlocks >= web3Context.transactionBlockTimeout) { + return new TransactionBlockTimeoutError({ + starterBlockNumber, + numberOfBlocks, + transactionHash, + }); + } + return undefined; + }, pollingInterval); const clean = () => { clearInterval(intervalId); diff --git a/packages/web3-eth/src/utils/send_tx_helper.ts b/packages/web3-eth/src/utils/send_tx_helper.ts index 0037e1051fa..fbe48c0e868 100644 --- a/packages/web3-eth/src/utils/send_tx_helper.ts +++ b/packages/web3-eth/src/utils/send_tx_helper.ts @@ -123,13 +123,18 @@ export class SendTxHelper< public async checkRevertBeforeSending(tx: TransactionCall) { if (this.options.checkRevertBeforeSending !== false) { let formatTx = tx; - if (isNullish(tx.data) && isNullish(tx.input) && isNullish(tx.gas)) { // eth.call runs into error if data isnt filled and gas is not defined, its a simple transaction so we fill it with 21000 + if (isNullish(tx.data) && isNullish(tx.input) && isNullish(tx.gas)) { + // eth.call runs into error if data isnt filled and gas is not defined, its a simple transaction so we fill it with 21000 formatTx = { ...tx, - gas: 21000 - } + gas: 21000, + }; } - const reason = await getRevertReason(this.web3Context, formatTx, this.options.contractAbi); + const reason = await getRevertReason( + this.web3Context, + formatTx, + this.options.contractAbi, + ); if (reason !== undefined) { throw await getTransactionError( this.web3Context, diff --git a/packages/web3-eth/src/utils/watch_transaction_by_polling.ts b/packages/web3-eth/src/utils/watch_transaction_by_polling.ts index a429eabb818..3c249c8298a 100644 --- a/packages/web3-eth/src/utils/watch_transaction_by_polling.ts +++ b/packages/web3-eth/src/utils/watch_transaction_by_polling.ts @@ -56,7 +56,7 @@ export const watchTransactionByPolling = < let confirmations = 1; const intervalId = setInterval(() => { (async () => { - if (confirmations >= web3Context.transactionConfirmationBlocks){ + if (confirmations >= web3Context.transactionConfirmationBlocks) { clearInterval(intervalId); return; } diff --git a/packages/web3-eth/src/web3_eth.ts b/packages/web3-eth/src/web3_eth.ts index abce5c2c317..a9db13d5abb 100644 --- a/packages/web3-eth/src/web3_eth.ts +++ b/packages/web3-eth/src/web3_eth.ts @@ -99,7 +99,6 @@ export const registeredSubscriptions = { * ``` */ export class Web3Eth extends Web3Context { - private transactionMiddleware?: TransactionMiddleware; public constructor( @@ -129,11 +128,11 @@ export class Web3Eth extends Web3Context { if (process.env.TEST_ACCOUNT_ADDRESS !== undefined) { return process.env.TEST_ACCOUNT_ADDRESS; // eslint-disable-next-line no-else-return - } else if (getSystemTestBackend() === BACKEND.SEPOLIA || getSystemTestBackend() === BACKEND.MAINNET) { + } else if ( + getSystemTestBackend() === BACKEND.SEPOLIA || + getSystemTestBackend() === BACKEND.MAINNET + ) { return secrets[getSystemTestBackend().toUpperCase() as 'SEPOLIA' | 'MAINNET'].ACCOUNT .address; } @@ -64,7 +67,10 @@ export const getAllowedSendTransaction = (): boolean => { return Boolean(process.env.ALLOWED_SEND_TRANSACTION); // eslint-disable-next-line no-else-return - } else if (getSystemTestBackend() === BACKEND.SEPOLIA || getSystemTestBackend() === BACKEND.MAINNET) { + } else if ( + getSystemTestBackend() === BACKEND.SEPOLIA || + getSystemTestBackend() === BACKEND.MAINNET + ) { return secrets[getSystemTestBackend().toUpperCase() as 'SEPOLIA' | 'MAINNET'] .ALLOWED_SEND_TRANSACTION; } @@ -76,7 +82,10 @@ export const getE2ETestAccountPrivateKey = (): string => { if (process.env.TEST_ACCOUNT_PRIVATE_KEY !== undefined) { return process.env.TEST_ACCOUNT_PRIVATE_KEY; // eslint-disable-next-line no-else-return - } else if (getSystemTestBackend() === BACKEND.SEPOLIA || getSystemTestBackend() === BACKEND.MAINNET) { + } else if ( + getSystemTestBackend() === BACKEND.SEPOLIA || + getSystemTestBackend() === BACKEND.MAINNET + ) { return secrets[getSystemTestBackend().toUpperCase() as 'SEPOLIA' | 'MAINNET'].ACCOUNT .privateKey; } diff --git a/packages/web3-eth/test/e2e/setup.js b/packages/web3-eth/test/e2e/setup.js index c480060944a..d527ad558d3 100644 --- a/packages/web3-eth/test/e2e/setup.js +++ b/packages/web3-eth/test/e2e/setup.js @@ -18,4 +18,3 @@ along with web3.js. If not, see . // Have to use `require` because of Jest issue https://jestjs.io/docs/ecmascript-modules // eslint-disable-next-line @typescript-eslint/no-require-imports require('../config/setup'); - diff --git a/packages/web3-eth/test/fixtures/transactions_data.ts b/packages/web3-eth/test/fixtures/transactions_data.ts index 189e2135ae4..5daf37d9bb9 100644 --- a/packages/web3-eth/test/fixtures/transactions_data.ts +++ b/packages/web3-eth/test/fixtures/transactions_data.ts @@ -16,102 +16,104 @@ along with web3.js. If not, see . */ export const blockMockResult = { - "jsonrpc": "2.0", - "id": "a40a81fa-1f8b-4bb2-a0ad-eef9b6d4636f", - "result": { - "baseFeePerGas": "0x44dab2983", - "blobGasUsed": "0x20000", - "difficulty": "0x0", - "excessBlobGas": "0x1c0000", - "extraData": "0x407273796e636275696c646572", - "gasLimit": "0x1c9c380", - "gasUsed": "0xb7a086", - "hash": "0xf2b1729965179032b17165678a1a212fa31cb008e30f4011ffe8ebdddbd02b95", - "logsBloom": "0xc3a70590c1c62524173d1892e33888067101934dc0891c2c9a898252b6f320215084a48906452960820188d32bba6fb82ec989018a0268603a00a4c6432a11276c9a038c676938eb68bc436c9905a9a1b08d238fb4458f48498215808bec81112e2a3a54869ff22422a8e491093da8a40f601d198417041cd22f799f9048865006e0b069ab049b852442b310396248088145e2810f230f9a44000c6868bc73e9afa8832a8ac92fd609007ac53c0a9cba0645ce298080184624e8040831dbc331f5e618072407050250021b3210e542781183a612d4618c1244000d421a6ca9c01a57e86a085402c55ab413f840a001e7117894d0469e20c2304a9655e344f60d", - "miner": "0x1f9090aae28b8a3dceadf281b0f12828e676c326", - "mixHash": "0x787ab1d511b72df60a705bb4cfc4e92e2f9d203e3e007ae3a0f757425951ca24", - "nonce": "0x0000000000000000", - "number": "0x131ad16", - "parentBeaconBlockRoot": "0x03bbca9fd0c7a0a020de04287f489112c79bc268220e9ff8e18957cd0d5c3cad", - "parentHash": "0xb1d8fa7b8346421d373a6d4c28575155516cea17c12a3df7201170c9e561b38c", - "receiptsRoot": "0x4ec500bdcd761ad505b2a989156c9a9628058d415acc93d800487c7c76308c59", - "sha3Uncles": "0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347", - "size": "0xcb90", - "stateRoot": "0xafbb8743c0a5f4740e322217cb1f2780ee5c57c32bcd04e9256b09efc1a70568", - "timestamp": "0x6661ab8b", - "totalDifficulty": "0xc70d815d562d3cfa955", - "transactions": [ - "0x589956b75d19dbaf9911f246c23d4b3327ef234872ec1931c419041b23eb5b41", - "0x4d3793f20c25979bd329cafdd889ba6be015cfc999acce8642d6e757b5192e93", - "0x5ba5618ca5a14bab50862255dc69726a498346f9832bd0fd1394e8834e56790b", - "0x6df9678f350db7e30afc930b7246bf1c144b9acb7fd1d25d7e107d550ed5a061", - "0xb8f48ff2876cc393725ea4162421754dfb74ff2364a12d4d3de2c6269f1958c7", - "0x2e5cf7c0607025038b6ccd871dc9ce85af686fd5fa2c82e605198af9afa92cca", - "0x307fb855836feff5d8d0969fa4a44d3c6ae31d335da6577f48f9496d6fe9e0b9", - "0x1362bed1aa8a30d28b7b76c35c2a8601b257058beffa9490dcb20de12bcb15b2", - "0x234c7cc346c204022b2e5ead6d2e8c02317aeb0ec5ca82bd97c2b5d5e59a280b", - ], - "transactionsRoot": "0xc21a4d667b5f841538430b1e2c002c598f2178628ad1d61ea2fda462d1216607", - "uncles": [], - "withdrawals": [ - { - "address": "0xea97dc2523c0479484076660f150833e264c41e9", - "amount": "0x11b6d8c", - "index": "0x2dbe454", - "validatorIndex": "0x10f646" - }, - { - "address": "0xb3e84b6c6409826dc45432b655d8c9489a14a0d7", - "amount": "0x11b4ce2", - "index": "0x2dbe455", - "validatorIndex": "0x10f647" - }, - { - "address": "0x7e2a2fa2a064f693f0a55c5639476d913ff12d05", - "amount": "0x11ad733", - "index": "0x2dbe456", - "validatorIndex": "0x10f648" - }, - - ], - "withdrawalsRoot": "0x2914fa2f5ed93880ed45b58e8f6d14f20c645988400d83c59109964e2053fe1a" - } + jsonrpc: '2.0', + id: 'a40a81fa-1f8b-4bb2-a0ad-eef9b6d4636f', + result: { + baseFeePerGas: '0x44dab2983', + blobGasUsed: '0x20000', + difficulty: '0x0', + excessBlobGas: '0x1c0000', + extraData: '0x407273796e636275696c646572', + gasLimit: '0x1c9c380', + gasUsed: '0xb7a086', + hash: '0xf2b1729965179032b17165678a1a212fa31cb008e30f4011ffe8ebdddbd02b95', + logsBloom: + '0xc3a70590c1c62524173d1892e33888067101934dc0891c2c9a898252b6f320215084a48906452960820188d32bba6fb82ec989018a0268603a00a4c6432a11276c9a038c676938eb68bc436c9905a9a1b08d238fb4458f48498215808bec81112e2a3a54869ff22422a8e491093da8a40f601d198417041cd22f799f9048865006e0b069ab049b852442b310396248088145e2810f230f9a44000c6868bc73e9afa8832a8ac92fd609007ac53c0a9cba0645ce298080184624e8040831dbc331f5e618072407050250021b3210e542781183a612d4618c1244000d421a6ca9c01a57e86a085402c55ab413f840a001e7117894d0469e20c2304a9655e344f60d', + miner: '0x1f9090aae28b8a3dceadf281b0f12828e676c326', + mixHash: '0x787ab1d511b72df60a705bb4cfc4e92e2f9d203e3e007ae3a0f757425951ca24', + nonce: '0x0000000000000000', + number: '0x131ad16', + parentBeaconBlockRoot: '0x03bbca9fd0c7a0a020de04287f489112c79bc268220e9ff8e18957cd0d5c3cad', + parentHash: '0xb1d8fa7b8346421d373a6d4c28575155516cea17c12a3df7201170c9e561b38c', + receiptsRoot: '0x4ec500bdcd761ad505b2a989156c9a9628058d415acc93d800487c7c76308c59', + sha3Uncles: '0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347', + size: '0xcb90', + stateRoot: '0xafbb8743c0a5f4740e322217cb1f2780ee5c57c32bcd04e9256b09efc1a70568', + timestamp: '0x6661ab8b', + totalDifficulty: '0xc70d815d562d3cfa955', + transactions: [ + '0x589956b75d19dbaf9911f246c23d4b3327ef234872ec1931c419041b23eb5b41', + '0x4d3793f20c25979bd329cafdd889ba6be015cfc999acce8642d6e757b5192e93', + '0x5ba5618ca5a14bab50862255dc69726a498346f9832bd0fd1394e8834e56790b', + '0x6df9678f350db7e30afc930b7246bf1c144b9acb7fd1d25d7e107d550ed5a061', + '0xb8f48ff2876cc393725ea4162421754dfb74ff2364a12d4d3de2c6269f1958c7', + '0x2e5cf7c0607025038b6ccd871dc9ce85af686fd5fa2c82e605198af9afa92cca', + '0x307fb855836feff5d8d0969fa4a44d3c6ae31d335da6577f48f9496d6fe9e0b9', + '0x1362bed1aa8a30d28b7b76c35c2a8601b257058beffa9490dcb20de12bcb15b2', + '0x234c7cc346c204022b2e5ead6d2e8c02317aeb0ec5ca82bd97c2b5d5e59a280b', + ], + transactionsRoot: '0xc21a4d667b5f841538430b1e2c002c598f2178628ad1d61ea2fda462d1216607', + uncles: [], + withdrawals: [ + { + address: '0xea97dc2523c0479484076660f150833e264c41e9', + amount: '0x11b6d8c', + index: '0x2dbe454', + validatorIndex: '0x10f646', + }, + { + address: '0xb3e84b6c6409826dc45432b655d8c9489a14a0d7', + amount: '0x11b4ce2', + index: '0x2dbe455', + validatorIndex: '0x10f647', + }, + { + address: '0x7e2a2fa2a064f693f0a55c5639476d913ff12d05', + amount: '0x11ad733', + index: '0x2dbe456', + validatorIndex: '0x10f648', + }, + ], + withdrawalsRoot: '0x2914fa2f5ed93880ed45b58e8f6d14f20c645988400d83c59109964e2053fe1a', + }, }; export const receiptMockResult = { - "jsonrpc": "2.0", - "id": 1, - "result": { - "blockHash": "0xf4ad699b98241caf3930779b7d919a77f1727e67cef6ed1ce2a4c655ba812d54", - "blockNumber": "0x131ad35", - // eslint-disable-next-line no-null/no-null - "contractAddress": null, - "cumulativeGasUsed": "0x8cae7a", - "effectiveGasPrice": "0x4c9bc2d65", - "from": "0xab6fd3a7c6ce9db945889cd018e028e055f3bc2e", - "gasUsed": "0xa145", - "logs": [ - { - "address": "0xdac17f958d2ee523a2206206994597c13d831ec7", - "blockHash": "0xf4ad699b98241caf3930779b7d919a77f1727e67cef6ed1ce2a4c655ba812d54", - "blockNumber": "0x131ad35", - "data": "0x000000000000000000000000000000000000000000000000000000000016e360", - "logIndex": "0xdf", - "removed": false, - "topics": [ - "0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef", - "0x000000000000000000000000ab6fd3a7c6ce9db945889cd018e028e055f3bc2e", - "0x00000000000000000000000051112f9f08a2174fe3fc96aad8f07e82d1cccd00" - ], - "transactionHash": "0xdf7756865c2056ce34c4eabe4eff42ad251a9f920a1c620c00b4ea0988731d3f", - "transactionIndex": "0x82" - } - ], - "logsBloom": "0x00000000000000000000000002000000000000000000000000000000004000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000400000000000100000000000000000000000000080000000000000000000040000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000000000000000000000800000000000000400000000000000000000000", - "status": "0x1", - "to": "0xdac17f958d2ee523a2206206994597c13d831ec7", - "transactionHash": "0xdf7756865c2056ce34c4eabe4eff42ad251a9f920a1c620c00b4ea0988731d3f", - "transactionIndex": "0x82", - "type": "0x2" - } -}; \ No newline at end of file + jsonrpc: '2.0', + id: 1, + result: { + blockHash: '0xf4ad699b98241caf3930779b7d919a77f1727e67cef6ed1ce2a4c655ba812d54', + blockNumber: '0x131ad35', + // eslint-disable-next-line no-null/no-null + contractAddress: null, + cumulativeGasUsed: '0x8cae7a', + effectiveGasPrice: '0x4c9bc2d65', + from: '0xab6fd3a7c6ce9db945889cd018e028e055f3bc2e', + gasUsed: '0xa145', + logs: [ + { + address: '0xdac17f958d2ee523a2206206994597c13d831ec7', + blockHash: '0xf4ad699b98241caf3930779b7d919a77f1727e67cef6ed1ce2a4c655ba812d54', + blockNumber: '0x131ad35', + data: '0x000000000000000000000000000000000000000000000000000000000016e360', + logIndex: '0xdf', + removed: false, + topics: [ + '0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef', + '0x000000000000000000000000ab6fd3a7c6ce9db945889cd018e028e055f3bc2e', + '0x00000000000000000000000051112f9f08a2174fe3fc96aad8f07e82d1cccd00', + ], + transactionHash: + '0xdf7756865c2056ce34c4eabe4eff42ad251a9f920a1c620c00b4ea0988731d3f', + transactionIndex: '0x82', + }, + ], + logsBloom: + '0x00000000000000000000000002000000000000000000000000000000004000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000400000000000100000000000000000000000000080000000000000000000040000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000000000000000000000800000000000000400000000000000000000000', + status: '0x1', + to: '0xdac17f958d2ee523a2206206994597c13d831ec7', + transactionHash: '0xdf7756865c2056ce34c4eabe4eff42ad251a9f920a1c620c00b4ea0988731d3f', + transactionIndex: '0x82', + type: '0x2', + }, +}; diff --git a/packages/web3-eth/test/integration/block/rpc.getBlock.test.ts b/packages/web3-eth/test/integration/block/rpc.getBlock.test.ts index 50731193bcc..77b1b5742d2 100644 --- a/packages/web3-eth/test/integration/block/rpc.getBlock.test.ts +++ b/packages/web3-eth/test/integration/block/rpc.getBlock.test.ts @@ -33,7 +33,7 @@ import { describeIf, createNewAccount, refillAccount, - BACKEND + BACKEND, } from '../../fixtures/system_test_utils'; import { BasicAbi, BasicBytecode } from '../../shared_fixtures/build/Basic'; import { toAllVariants } from '../../shared_fixtures/utils'; diff --git a/packages/web3-eth/test/integration/block/rpc.getBlockTransactionCount.test.ts b/packages/web3-eth/test/integration/block/rpc.getBlockTransactionCount.test.ts index ce4ad2e26a1..ece1091e937 100644 --- a/packages/web3-eth/test/integration/block/rpc.getBlockTransactionCount.test.ts +++ b/packages/web3-eth/test/integration/block/rpc.getBlockTransactionCount.test.ts @@ -99,7 +99,7 @@ describe('rpc with block', () => { )('getBlockTransactionCount', async ({ block }) => { const res = await web3Eth.getBlockTransactionCount(blockData[block]); const shouldBe = ['earliest', 'pending'].includes(String(blockData[block])) ? 0 : 1; - + expect(Number(res)).toBe(shouldBe); }); }); diff --git a/packages/web3-eth/test/integration/block/rpc.getBlockUncleCount.test.ts b/packages/web3-eth/test/integration/block/rpc.getBlockUncleCount.test.ts index ae822a99a5a..a777eee29c5 100644 --- a/packages/web3-eth/test/integration/block/rpc.getBlockUncleCount.test.ts +++ b/packages/web3-eth/test/integration/block/rpc.getBlockUncleCount.test.ts @@ -24,7 +24,7 @@ import { closeOpenConnection, describeIf, getSystemTestBackend, - BACKEND + BACKEND, } from '../../fixtures/system_test_utils'; import { BasicAbi, BasicBytecode } from '../../shared_fixtures/build/Basic'; import { toAllVariants } from '../../shared_fixtures/utils'; diff --git a/packages/web3-eth/test/integration/block/rpc.getUncle.test.ts b/packages/web3-eth/test/integration/block/rpc.getUncle.test.ts index 9b820fd9077..07882d8524a 100644 --- a/packages/web3-eth/test/integration/block/rpc.getUncle.test.ts +++ b/packages/web3-eth/test/integration/block/rpc.getUncle.test.ts @@ -26,7 +26,7 @@ import { closeOpenConnection, describeIf, getSystemTestBackend, - BACKEND + BACKEND, } from '../../fixtures/system_test_utils'; import { BasicAbi, BasicBytecode } from '../../shared_fixtures/build/Basic'; import { toAllVariants } from '../../shared_fixtures/utils'; diff --git a/packages/web3-eth/test/integration/defaults.test.ts b/packages/web3-eth/test/integration/defaults.test.ts index 351152158b4..b52934e386a 100644 --- a/packages/web3-eth/test/integration/defaults.test.ts +++ b/packages/web3-eth/test/integration/defaults.test.ts @@ -41,7 +41,7 @@ import { getSystemTestProvider, isIpc, sendFewSampleTxs, - waitForCondition + waitForCondition, } from '../fixtures/system_test_utils'; import { @@ -78,83 +78,72 @@ describe('defaults', () => { await closeOpenConnection(web3Eth); await closeOpenConnection(contract); }); - it('defaultAccount', async () => { - const tempAcc2 = await createTempAccount(); - const tempAcc3 = await createTempAccount(); - const contractMsgFrom = await new Contract( - MsgSenderAbi, - web3Eth.getContextObject() as any, - ) - .deploy({ - data: MsgSenderBytecode, - arguments: ['test'], - }) - .send({ from: tempAcc2.address, gas: '2700000' }); - // default - expect(web3Eth.defaultAccount).toBeUndefined(); - - // after set - web3Eth.setConfig({ - defaultAccount: tempAcc.address, - }); - expect(web3Eth.defaultAccount).toBe(tempAcc.address); + it('defaultAccount', async () => { + const tempAcc2 = await createTempAccount(); + const tempAcc3 = await createTempAccount(); + const contractMsgFrom = await new Contract(MsgSenderAbi, web3Eth.getContextObject() as any) + .deploy({ + data: MsgSenderBytecode, + arguments: ['test'], + }) + .send({ from: tempAcc2.address, gas: '2700000' }); + // default + expect(web3Eth.defaultAccount).toBeUndefined(); + + // after set + web3Eth.setConfig({ + defaultAccount: tempAcc.address, + }); + expect(web3Eth.defaultAccount).toBe(tempAcc.address); - // set by create new instance - const eth2 = new Web3Eth({ - config: { - defaultAccount: tempAcc3.address, - }, - }); - expect(eth2.defaultAccount).toBe(tempAcc3.address); - - // check utils - expect(getTransactionFromOrToAttr('from', eth2)).toBe(tempAcc3.address); - // TODO: after handleRevert implementation https://github.com/ChainSafe/web3.js/issues/5069 add following tests in future release - // set handleRevert true and test following functions with invalid input tx data and see revert reason present in error details: - contractMsgFrom.setConfig({ - defaultAccount: tempAcc.address, - }); + // set by create new instance + const eth2 = new Web3Eth({ + config: { + defaultAccount: tempAcc3.address, + }, + }); + expect(eth2.defaultAccount).toBe(tempAcc3.address); + + // check utils + expect(getTransactionFromOrToAttr('from', eth2)).toBe(tempAcc3.address); + // TODO: after handleRevert implementation https://github.com/ChainSafe/web3.js/issues/5069 add following tests in future release + // set handleRevert true and test following functions with invalid input tx data and see revert reason present in error details: + contractMsgFrom.setConfig({ + defaultAccount: tempAcc.address, + }); - const tx = await contractMsgFrom.methods - .setTestString('test2') - .send({ gas: '1000000' }); - const txSend = await web3Eth.sendTransaction({ - to: tempAcc2.address, - value: '0x1', - }); - expect(tx.from).toBe(tempAcc.address.toLowerCase()); - expect(txSend.from).toBe(tempAcc.address.toLowerCase()); + const tx = await contractMsgFrom.methods.setTestString('test2').send({ gas: '1000000' }); + const txSend = await web3Eth.sendTransaction({ + to: tempAcc2.address, + value: '0x1', + }); + expect(tx.from).toBe(tempAcc.address.toLowerCase()); + expect(txSend.from).toBe(tempAcc.address.toLowerCase()); - const tx2 = await contractMsgFrom.methods.setTestString('test3').send({ - from: tempAcc2.address, - }); - const tx2Send = await web3Eth.sendTransaction({ - to: tempAcc.address, - value: '0x1', - from: tempAcc2.address, - }); - expect(tx2.from).toBe(tempAcc2.address.toLowerCase()); - expect(tx2Send.from).toBe(tempAcc2.address.toLowerCase()); - - const fromDefault = await contractMsgFrom.methods?.from().call(); - const fromPass = await contractMsgFrom.methods?.from().call({ from: tempAcc.address }); - const fromPass2 = await contractMsgFrom.methods - ?.from() - .call({ from: tempAcc2.address }); - expect((fromDefault as unknown as string).toLowerCase()).toBe( - tempAcc.address.toLowerCase(), - ); - expect((fromPass as unknown as string).toLowerCase()).toBe( - tempAcc.address.toLowerCase(), - ); - expect((fromPass2 as unknown as string).toLowerCase()).toBe( - tempAcc2.address.toLowerCase(), - ); - await closeOpenConnection(eth2); - await closeOpenConnection(contractMsgFrom); + const tx2 = await contractMsgFrom.methods.setTestString('test3').send({ + from: tempAcc2.address, + }); + const tx2Send = await web3Eth.sendTransaction({ + to: tempAcc.address, + value: '0x1', + from: tempAcc2.address, }); - it('handleRevert', () => { - /* + expect(tx2.from).toBe(tempAcc2.address.toLowerCase()); + expect(tx2Send.from).toBe(tempAcc2.address.toLowerCase()); + + const fromDefault = await contractMsgFrom.methods?.from().call(); + const fromPass = await contractMsgFrom.methods?.from().call({ from: tempAcc.address }); + const fromPass2 = await contractMsgFrom.methods?.from().call({ from: tempAcc2.address }); + expect((fromDefault as unknown as string).toLowerCase()).toBe( + tempAcc.address.toLowerCase(), + ); + expect((fromPass as unknown as string).toLowerCase()).toBe(tempAcc.address.toLowerCase()); + expect((fromPass2 as unknown as string).toLowerCase()).toBe(tempAcc2.address.toLowerCase()); + await closeOpenConnection(eth2); + await closeOpenConnection(contractMsgFrom); + }); + it('handleRevert', () => { + /* //TO DO: after handleRevert implementation https://github.com/ChainSafe/web3.js/issues/5069 add following tests in future release /* set handleRevert true and test following functions with invalid input tx data and see revert reason present in error details: @@ -164,907 +153,908 @@ describe('defaults', () => { contract.methods.myMethod(…).call(…) */ - // default - expect(web3Eth.handleRevert).toBe(false); + // default + expect(web3Eth.handleRevert).toBe(false); - // after set - web3Eth.setConfig({ + // after set + web3Eth.setConfig({ + handleRevert: true, + }); + expect(web3Eth.handleRevert).toBe(true); + + // set by create new instance + const eth2 = new Web3Eth({ + config: { handleRevert: true, - }); - expect(web3Eth.handleRevert).toBe(true); + }, + }); + expect(eth2.handleRevert).toBe(true); + }); + it('defaultBlock', async () => { + const contractDeployed = await contract.deploy(deployOptions).send(sendOptions); + // default + expect(web3Eth.defaultBlock).toBe('latest'); - // set by create new instance - const eth2 = new Web3Eth({ - config: { - handleRevert: true, - }, - }); - expect(eth2.handleRevert).toBe(true); + web3Eth.setConfig({ + defaultBlock: 'safe', }); - it('defaultBlock', async () => { - const contractDeployed = await contract.deploy(deployOptions).send(sendOptions); - // default - expect(web3Eth.defaultBlock).toBe('latest'); + expect(web3Eth.defaultBlock).toBe('safe'); - web3Eth.setConfig({ - defaultBlock: 'safe', - }); - expect(web3Eth.defaultBlock).toBe('safe'); + web3Eth.setConfig({ + defaultBlock: 'finalized', + }); + expect(web3Eth.defaultBlock).toBe('finalized'); - web3Eth.setConfig({ - defaultBlock: 'finalized', - }); - expect(web3Eth.defaultBlock).toBe('finalized'); + // after set + web3Eth.setConfig({ + defaultBlock: 'earliest', + }); + expect(web3Eth.defaultBlock).toBe('earliest'); - // after set - web3Eth.setConfig({ + // set by create new instance + const eth2 = new Web3Eth({ + provider: web3Eth.provider, + config: { defaultBlock: 'earliest', - }); - expect(web3Eth.defaultBlock).toBe('earliest'); - - // set by create new instance - const eth2 = new Web3Eth({ - provider: web3Eth.provider, - config: { - defaultBlock: 'earliest', - }, - }); - expect(eth2.defaultBlock).toBe('earliest'); + }, + }); + expect(eth2.defaultBlock).toBe('earliest'); - // check implementation - const acc = await createNewAccount({ refill: true, unlock: true }); + // check implementation + const acc = await createNewAccount({ refill: true, unlock: true }); - await sendFewTxes({ - from: acc.address, - times: 1, - value: '0x1', - }); - const balance = await eth2.getBalance(acc.address); - const code = await eth2.getCode(contractDeployed?.options?.address as string); - const storage = await eth2.getStorageAt( - contractDeployed?.options?.address as string, - 0, - ); - const transactionCount = await eth2.getTransactionCount(acc.address); - expect(storage === '0x' ? 0 : Number(hexToNumber(storage))).toBe(0); - expect(code).toBe('0x'); - expect(balance).toBe(BigInt(0)); - expect(transactionCount).toBe(BigInt(0)); - - // pass blockNumber to rewrite defaultBlockNumber - const balanceWithBlockNumber = await eth2.getBalance(acc.address, 'latest'); - const transactionCountWithBlockNumber = await eth2.getTransactionCount( - acc.address, - 'latest', - ); - const codeWithBlockNumber = await eth2.getCode( - contractDeployed?.options?.address as string, - 'latest', - ); - const storageWithBlockNumber = await eth2.getStorageAt( - contractDeployed?.options?.address as string, - 0, - 'latest', - ); - expect(Number(hexToNumber(storageWithBlockNumber))).toBe(10); - expect(transactionCountWithBlockNumber).toBe(BigInt(1)); - expect(Number(balanceWithBlockNumber)).toBeGreaterThan(0); - expect(codeWithBlockNumber.startsWith(BasicBytecode.slice(0, 10))).toBe(true); - - // set new default block to config - eth2.setConfig({ - defaultBlock: 'latest', - }); - const balanceLatest = await eth2.getBalance(acc.address); - const codeLatest = await eth2.getCode(contractDeployed?.options?.address as string); - const storageLatest = await eth2.getStorageAt( - contractDeployed?.options?.address as string, - 0, - ); - const transactionCountLatest = await eth2.getTransactionCount(acc.address); - expect(codeLatest.startsWith(BasicBytecode.slice(0, 10))).toBe(true); - expect(Number(hexToNumber(storageLatest))).toBe(10); - expect(transactionCountLatest).toBe(BigInt(1)); - expect(Number(balanceLatest)).toBeGreaterThan(0); - await closeOpenConnection(eth2); - await closeOpenConnection(contractDeployed); + await sendFewTxes({ + from: acc.address, + times: 1, + value: '0x1', }); - it('transactionSendTimeout', async () => { - // default - expect(web3Eth.transactionSendTimeout).toBe(750 * 1000); - - // after set - web3Eth.setConfig({ - transactionSendTimeout: 1, - }); - expect(web3Eth.transactionSendTimeout).toBe(1); + const balance = await eth2.getBalance(acc.address); + const code = await eth2.getCode(contractDeployed?.options?.address as string); + const storage = await eth2.getStorageAt(contractDeployed?.options?.address as string, 0); + const transactionCount = await eth2.getTransactionCount(acc.address); + expect(storage === '0x' ? 0 : Number(hexToNumber(storage))).toBe(0); + expect(code).toBe('0x'); + expect(balance).toBe(BigInt(0)); + expect(transactionCount).toBe(BigInt(0)); + + // pass blockNumber to rewrite defaultBlockNumber + const balanceWithBlockNumber = await eth2.getBalance(acc.address, 'latest'); + const transactionCountWithBlockNumber = await eth2.getTransactionCount( + acc.address, + 'latest', + ); + const codeWithBlockNumber = await eth2.getCode( + contractDeployed?.options?.address as string, + 'latest', + ); + const storageWithBlockNumber = await eth2.getStorageAt( + contractDeployed?.options?.address as string, + 0, + 'latest', + ); + expect(Number(hexToNumber(storageWithBlockNumber))).toBe(10); + expect(transactionCountWithBlockNumber).toBe(BigInt(1)); + expect(Number(balanceWithBlockNumber)).toBeGreaterThan(0); + expect(codeWithBlockNumber.startsWith(BasicBytecode.slice(0, 10))).toBe(true); + + // set new default block to config + eth2.setConfig({ + defaultBlock: 'latest', + }); + const balanceLatest = await eth2.getBalance(acc.address); + const codeLatest = await eth2.getCode(contractDeployed?.options?.address as string); + const storageLatest = await eth2.getStorageAt( + contractDeployed?.options?.address as string, + 0, + ); + const transactionCountLatest = await eth2.getTransactionCount(acc.address); + expect(codeLatest.startsWith(BasicBytecode.slice(0, 10))).toBe(true); + expect(Number(hexToNumber(storageLatest))).toBe(10); + expect(transactionCountLatest).toBe(BigInt(1)); + expect(Number(balanceLatest)).toBeGreaterThan(0); + await closeOpenConnection(eth2); + await closeOpenConnection(contractDeployed); + }); + it('transactionSendTimeout', async () => { + // default + expect(web3Eth.transactionSendTimeout).toBe(750 * 1000); - // set by create new instance - const eth2 = new Web3Eth({ - provider: web3Eth.provider, - config: { - transactionSendTimeout: 120, - }, - }); - expect(eth2.transactionSendTimeout).toBe(120); - await closeOpenConnection(eth2); + // after set + web3Eth.setConfig({ + transactionSendTimeout: 1, + }); + expect(web3Eth.transactionSendTimeout).toBe(1); + + // set by create new instance + const eth2 = new Web3Eth({ + provider: web3Eth.provider, + config: { + transactionSendTimeout: 120, + }, }); - it('transactionBlockTimeout', () => { - // default - expect(web3Eth.transactionBlockTimeout).toBe(50); + expect(eth2.transactionSendTimeout).toBe(120); + await closeOpenConnection(eth2); + }); + it('transactionBlockTimeout', () => { + // default + expect(web3Eth.transactionBlockTimeout).toBe(50); - // after set - web3Eth.setConfig({ - transactionBlockTimeout: 1, - }); - expect(web3Eth.transactionBlockTimeout).toBe(1); + // after set + web3Eth.setConfig({ + transactionBlockTimeout: 1, + }); + expect(web3Eth.transactionBlockTimeout).toBe(1); - // set by create new instance - const eth2 = new Web3Eth({ - config: { - transactionBlockTimeout: 120, - }, - }); - expect(eth2.transactionBlockTimeout).toBe(120); + // set by create new instance + const eth2 = new Web3Eth({ + config: { + transactionBlockTimeout: 120, + }, }); - it('transactionConfirmationBlocks default change should work', async () => { - // default - // eslint-disable-next-line jest/no-standalone-expect - expect(web3Eth.transactionConfirmationBlocks).toBe(24); - - // after set - web3Eth.setConfig({ - transactionConfirmationBlocks: 3, - }); - // eslint-disable-next-line jest/no-standalone-expect - expect(web3Eth.transactionConfirmationBlocks).toBe(3); + expect(eth2.transactionBlockTimeout).toBe(120); + }); + it('transactionConfirmationBlocks default change should work', async () => { + // default + // eslint-disable-next-line jest/no-standalone-expect + expect(web3Eth.transactionConfirmationBlocks).toBe(24); + + // after set + web3Eth.setConfig({ + transactionConfirmationBlocks: 3, + }); + // eslint-disable-next-line jest/no-standalone-expect + expect(web3Eth.transactionConfirmationBlocks).toBe(3); + + // set by create new instance + const eth2 = new Web3Eth({ + config: { + transactionConfirmationBlocks: 4, + }, + }); + // eslint-disable-next-line jest/no-standalone-expect + expect(eth2.transactionConfirmationBlocks).toBe(4); + }); - // set by create new instance - const eth2 = new Web3Eth({ - config: { - transactionConfirmationBlocks: 4, - }, - }); - // eslint-disable-next-line jest/no-standalone-expect - expect(eth2.transactionConfirmationBlocks).toBe(4); + it('transactionConfirmationBlocks implementation', async () => { + const tempAcc2 = await createTempAccount(); + const waitConfirmations = 1; + const eth = new Web3Eth(getSystemTestProvider()); + eth.setConfig({ transactionConfirmationBlocks: waitConfirmations }); - }); + const from = tempAcc.address; + const to = tempAcc2.address; + const value = `0x1`; + + let confirmationCount = 0; - it('transactionConfirmationBlocks implementation', async () => { - const tempAcc2 = await createTempAccount(); - const waitConfirmations = 1; - const eth = new Web3Eth(getSystemTestProvider()); - eth.setConfig({ transactionConfirmationBlocks: waitConfirmations }); - - const from = tempAcc.address; - const to = tempAcc2.address; - const value = `0x1`; - - let confirmationCount = 0; - - const sentTx: Web3PromiEvent< - TransactionReceipt, - SendTransactionEvents - > = eth.sendTransaction({ + const sentTx: Web3PromiEvent< + TransactionReceipt, + SendTransactionEvents + > = eth + .sendTransaction({ to, value, from, - }).on('confirmation', (_data) => { + }) + .on('confirmation', _data => { confirmationCount += 1; if (confirmationCount >= waitConfirmations) { - sentTx.removeAllListeners(); // Clean up listeners + sentTx.removeAllListeners(); // Clean up listeners } }); - const receipt = await sentTx; - expect(Number(receipt.status)).toBe(1); + const receipt = await sentTx; + expect(Number(receipt.status)).toBe(1); - // Optionally send a few sample transactions - await sendFewSampleTxs(isIpc ? 5 * waitConfirmations : 2 * waitConfirmations); - - expect(confirmationCount).toBe(waitConfirmations); + // Optionally send a few sample transactions + await sendFewSampleTxs(isIpc ? 5 * waitConfirmations : 2 * waitConfirmations); - await waitForCondition( - () => confirmationCount >= waitConfirmations, - async () => { await closeOpenConnection(eth)}, - 10, - 5000); - }); + expect(confirmationCount).toBe(waitConfirmations); + + await waitForCondition( + () => confirmationCount >= waitConfirmations, + async () => { + await closeOpenConnection(eth); + }, + 10, + 5000, + ); + }); - it('transactionPollingInterval and transactionPollingTimeout', async () => { - // default - expect(web3Eth.transactionPollingInterval).toBe(1000); - expect(web3Eth.transactionPollingTimeout).toBe(750 * 1000); + it('transactionPollingInterval and transactionPollingTimeout', async () => { + // default + expect(web3Eth.transactionPollingInterval).toBe(1000); + expect(web3Eth.transactionPollingTimeout).toBe(750 * 1000); - // after set - web3Eth.setConfig({ - transactionPollingInterval: 3, + // after set + web3Eth.setConfig({ + transactionPollingInterval: 3, + transactionPollingTimeout: 10, + }); + expect(web3Eth.transactionPollingInterval).toBe(3); + expect(web3Eth.transactionPollingTimeout).toBe(10); + + // set by create new instance + const eth2 = new Web3Eth({ + config: { + transactionPollingInterval: 400, transactionPollingTimeout: 10, - }); - expect(web3Eth.transactionPollingInterval).toBe(3); - expect(web3Eth.transactionPollingTimeout).toBe(10); - - // set by create new instance - const eth2 = new Web3Eth({ - config: { - transactionPollingInterval: 400, - transactionPollingTimeout: 10, - }, - }); - expect(eth2.transactionPollingInterval).toBe(400); - expect(eth2.transactionPollingTimeout).toBe(10); + }, + }); + expect(eth2.transactionPollingInterval).toBe(400); + expect(eth2.transactionPollingTimeout).toBe(10); + }); + // todo will work with not instance mining + // itIf(isHttp)('transactionReceiptPollingInterval and transactionConfirmationPollingInterval implementation', async () => { + // eth2 = new Web3Eth({ + // provider: web3Eth.provider, + // config: { + // transactionPollingInterval: 400, + // transactionPollingTimeout: 10, + // }, + // }); + // + // const sentTx: Web3PromiEvent = eth2.sendTransaction({ + // to: tempAcc2.address, + // value: '0x1', + // from: tempAcc.address, + // }); + // + // const res = await Promise.race([ + // new Promise((resolve) => setTimeout(resolve, 410)), + // new Promise((resolve: Resolve) => { + // sentTx.on('receipt', (params: TransactionReceipt) => { + // expect(params.status).toBe(BigInt(1)); + // resolve(params); + // }); + // }), + // ]); + // expect((res as TransactionReceipt).status).toBe(BigInt(1)); + // + // const sentTx2: Web3PromiEvent = eth2.sendTransaction({ + // to: tempAcc2.address, + // value: '0x1', + // from: tempAcc.address, + // }); + // const res2 = await Promise.race([ + // new Promise((resolve) => setTimeout(()=>resolve(false), 300)), + // new Promise((resolve: Resolve) => { + // sentTx2.on('receipt', (params: TransactionReceipt) => { + // expect(params.status).toBe(BigInt(1)); + // resolve(params); + // }); + // }), + // ]); + // expect((res2 as boolean)).toBe(false); + // + // + // }); + it('transactionReceiptPollingInterval and transactionConfirmationPollingInterval', () => { + // default + expect(web3Eth.transactionReceiptPollingInterval).toBeUndefined(); + expect(web3Eth.transactionConfirmationPollingInterval).toBeUndefined(); + + // after set + web3Eth.setConfig({ + transactionReceiptPollingInterval: 3, + transactionConfirmationPollingInterval: 10, }); - // todo will work with not instance mining - // itIf(isHttp)('transactionReceiptPollingInterval and transactionConfirmationPollingInterval implementation', async () => { - // eth2 = new Web3Eth({ - // provider: web3Eth.provider, - // config: { - // transactionPollingInterval: 400, - // transactionPollingTimeout: 10, - // }, - // }); - // - // const sentTx: Web3PromiEvent = eth2.sendTransaction({ - // to: tempAcc2.address, - // value: '0x1', - // from: tempAcc.address, - // }); - // - // const res = await Promise.race([ - // new Promise((resolve) => setTimeout(resolve, 410)), - // new Promise((resolve: Resolve) => { - // sentTx.on('receipt', (params: TransactionReceipt) => { - // expect(params.status).toBe(BigInt(1)); - // resolve(params); - // }); - // }), - // ]); - // expect((res as TransactionReceipt).status).toBe(BigInt(1)); - // - // const sentTx2: Web3PromiEvent = eth2.sendTransaction({ - // to: tempAcc2.address, - // value: '0x1', - // from: tempAcc.address, - // }); - // const res2 = await Promise.race([ - // new Promise((resolve) => setTimeout(()=>resolve(false), 300)), - // new Promise((resolve: Resolve) => { - // sentTx2.on('receipt', (params: TransactionReceipt) => { - // expect(params.status).toBe(BigInt(1)); - // resolve(params); - // }); - // }), - // ]); - // expect((res2 as boolean)).toBe(false); - // - // - // }); - it('transactionReceiptPollingInterval and transactionConfirmationPollingInterval', () => { - // default - expect(web3Eth.transactionReceiptPollingInterval).toBeUndefined(); - expect(web3Eth.transactionConfirmationPollingInterval).toBeUndefined(); - - // after set - web3Eth.setConfig({ - transactionReceiptPollingInterval: 3, + expect(web3Eth.transactionReceiptPollingInterval).toBe(3); + expect(web3Eth.transactionConfirmationPollingInterval).toBe(10); + + // set by create new instance + const eth2 = new Web3Eth({ + config: { + transactionReceiptPollingInterval: 400, transactionConfirmationPollingInterval: 10, - }); - expect(web3Eth.transactionReceiptPollingInterval).toBe(3); - expect(web3Eth.transactionConfirmationPollingInterval).toBe(10); - - // set by create new instance - const eth2 = new Web3Eth({ - config: { - transactionReceiptPollingInterval: 400, - transactionConfirmationPollingInterval: 10, - }, - }); - expect(eth2.transactionReceiptPollingInterval).toBe(400); - expect(eth2.transactionConfirmationPollingInterval).toBe(10); + }, }); - it('blockHeaderTimeout', () => { - // default - expect(web3Eth.blockHeaderTimeout).toBe(10); + expect(eth2.transactionReceiptPollingInterval).toBe(400); + expect(eth2.transactionConfirmationPollingInterval).toBe(10); + }); + it('blockHeaderTimeout', () => { + // default + expect(web3Eth.blockHeaderTimeout).toBe(10); - // after set - web3Eth.setConfig({ - blockHeaderTimeout: 3, - }); - expect(web3Eth.blockHeaderTimeout).toBe(3); + // after set + web3Eth.setConfig({ + blockHeaderTimeout: 3, + }); + expect(web3Eth.blockHeaderTimeout).toBe(3); - // set by create new instance - const eth2 = new Web3Eth({ - config: { - blockHeaderTimeout: 4, - }, - }); - expect(eth2.blockHeaderTimeout).toBe(4); + // set by create new instance + const eth2 = new Web3Eth({ + config: { + blockHeaderTimeout: 4, + }, }); + expect(eth2.blockHeaderTimeout).toBe(4); + }); - it('enableExperimentalFeatures useSubscriptionWhenCheckingBlockTimeout', () => { - // default - expect(web3Eth.enableExperimentalFeatures.useSubscriptionWhenCheckingBlockTimeout).toBe( - false, - ); + it('enableExperimentalFeatures useSubscriptionWhenCheckingBlockTimeout', () => { + // default + expect(web3Eth.enableExperimentalFeatures.useSubscriptionWhenCheckingBlockTimeout).toBe( + false, + ); + + // after set + web3Eth.setConfig({ + enableExperimentalFeatures: { + useSubscriptionWhenCheckingBlockTimeout: true, + useRpcCallSpecification: false, + }, + }); + expect(web3Eth.enableExperimentalFeatures.useSubscriptionWhenCheckingBlockTimeout).toBe( + true, + ); - // after set - web3Eth.setConfig({ + // set by create new instance + const eth2 = new Web3Eth({ + config: { enableExperimentalFeatures: { useSubscriptionWhenCheckingBlockTimeout: true, useRpcCallSpecification: false, }, - }); - expect(web3Eth.enableExperimentalFeatures.useSubscriptionWhenCheckingBlockTimeout).toBe( - true, - ); - - // set by create new instance - const eth2 = new Web3Eth({ - config: { - enableExperimentalFeatures: { - useSubscriptionWhenCheckingBlockTimeout: true, - useRpcCallSpecification: false, - }, - }, - }); - expect(eth2.enableExperimentalFeatures.useSubscriptionWhenCheckingBlockTimeout).toBe( - true, - ); + }, }); + expect(eth2.enableExperimentalFeatures.useSubscriptionWhenCheckingBlockTimeout).toBe(true); + }); - it('enableExperimentalFeatures useRpcCallSpecification', () => { - // default - expect(web3Eth.enableExperimentalFeatures.useRpcCallSpecification).toBe(false); + it('enableExperimentalFeatures useRpcCallSpecification', () => { + // default + expect(web3Eth.enableExperimentalFeatures.useRpcCallSpecification).toBe(false); - // after set - web3Eth.setConfig({ + // after set + web3Eth.setConfig({ + enableExperimentalFeatures: { + useSubscriptionWhenCheckingBlockTimeout: false, + useRpcCallSpecification: true, + }, + }); + expect(web3Eth.enableExperimentalFeatures.useRpcCallSpecification).toBe(true); + + // set by create new instance + const eth2 = new Web3Eth({ + config: { enableExperimentalFeatures: { useSubscriptionWhenCheckingBlockTimeout: false, useRpcCallSpecification: true, }, - }); - expect(web3Eth.enableExperimentalFeatures.useRpcCallSpecification).toBe(true); - - // set by create new instance - const eth2 = new Web3Eth({ - config: { - enableExperimentalFeatures: { - useSubscriptionWhenCheckingBlockTimeout: false, - useRpcCallSpecification: true, - }, - }, - }); - expect(eth2.enableExperimentalFeatures.useRpcCallSpecification).toBe(true); - + }, }); + expect(eth2.enableExperimentalFeatures.useRpcCallSpecification).toBe(true); + }); - it('should fallback to polling if provider support `on` but `newBlockHeaders` does not arrive in `blockHeaderTimeout` seconds', async () => { - const tempAcc2 = await createTempAccount(); - - const tempEth: Web3Eth = new Web3Eth(clientUrl); - // Ensure the provider supports subscriptions to simulate the test scenario - // It will cause providers that does not support subscriptions (like http) to throw exception when subscribing. - // This case is tested to ensure that even if an error happen at subscription, - // polling will still get the data from next blocks. - (tempEth.provider as Web3BaseProvider).supportsSubscriptions = () => true; - - // Cause the events to take a long time (more than blockHeaderTimeout), - // to ensure that polling of new blocks works in such cases. - // This will cause the providers that supports subscription (like WebSocket) - // to never return data through listening to new events - - // eslint-disable-next-line @typescript-eslint/no-misused-promises - (tempEth.provider as Web3BaseProvider).on = async () => { - await new Promise(res => { - setTimeout(res, 1000000); - }); - }; - - // Make the test run faster by casing the polling to start after 1 second - tempEth.blockHeaderTimeout = 1; - const from = tempAcc2.address; - const to = tempAcc.address; - const value = `0x1`; - - const sentTx: Web3PromiEvent< - TransactionReceipt, - SendTransactionEvents - > = tempEth.sendTransaction({ - from, - to, - value, + it('should fallback to polling if provider support `on` but `newBlockHeaders` does not arrive in `blockHeaderTimeout` seconds', async () => { + const tempAcc2 = await createTempAccount(); + + const tempEth: Web3Eth = new Web3Eth(clientUrl); + // Ensure the provider supports subscriptions to simulate the test scenario + // It will cause providers that does not support subscriptions (like http) to throw exception when subscribing. + // This case is tested to ensure that even if an error happen at subscription, + // polling will still get the data from next blocks. + (tempEth.provider as Web3BaseProvider).supportsSubscriptions = () => true; + + // Cause the events to take a long time (more than blockHeaderTimeout), + // to ensure that polling of new blocks works in such cases. + // This will cause the providers that supports subscription (like WebSocket) + // to never return data through listening to new events + + // eslint-disable-next-line @typescript-eslint/no-misused-promises + (tempEth.provider as Web3BaseProvider).on = async () => { + await new Promise(res => { + setTimeout(res, 1000000); }); + }; - let confirmationCount = 0; - const confirmationPromise = new Promise((resolve: (status: bigint) => void) => { - // Tx promise is handled separately - // eslint-disable-next-line no-void - void sentTx.on( - 'confirmation', - async ({ - confirmations, - receipt: { status }, - }: { - confirmations: bigint; - receipt: { status: bigint }; - }) => { - confirmationCount = Number(confirmations); - // Being able to get 2 confirmations means the polling for new blocks works - if (confirmations >= 2) { - sentTx.removeAllListeners(); - resolve(status); - } else { - // Send few transaction to cause dev providers creating new blocks to fire the 'confirmation' event again. - await sendFewSampleTxs(5); - } - }, - ); - }); - const receipt = await sentTx; - expect(Number(receipt.status)).toBe(1); + // Make the test run faster by casing the polling to start after 1 second + tempEth.blockHeaderTimeout = 1; + const from = tempAcc2.address; + const to = tempAcc.address; + const value = `0x1`; + + const sentTx: Web3PromiEvent< + TransactionReceipt, + SendTransactionEvents + > = tempEth.sendTransaction({ + from, + to, + value, + }); - // Ensure the promise the get the confirmations resolves with no error - const status = await confirmationPromise; - expect(status).toBe(BigInt(1)); + let confirmationCount = 0; + const confirmationPromise = new Promise((resolve: (status: bigint) => void) => { + // Tx promise is handled separately + // eslint-disable-next-line no-void + void sentTx.on( + 'confirmation', + async ({ + confirmations, + receipt: { status }, + }: { + confirmations: bigint; + receipt: { status: bigint }; + }) => { + confirmationCount = Number(confirmations); + // Being able to get 2 confirmations means the polling for new blocks works + if (confirmations >= 2) { + sentTx.removeAllListeners(); + resolve(status); + } else { + // Send few transaction to cause dev providers creating new blocks to fire the 'confirmation' event again. + await sendFewSampleTxs(5); + } + }, + ); + }); + const receipt = await sentTx; + expect(Number(receipt.status)).toBe(1); + + // Ensure the promise the get the confirmations resolves with no error + const status = await confirmationPromise; + expect(status).toBe(BigInt(1)); + + await waitForCondition( + () => confirmationCount >= 2, + async () => { + await closeOpenConnection(tempEth); + }, + ); + }); - await waitForCondition( - () => confirmationCount >= 2, - async () => { await closeOpenConnection(tempEth)}); + it('maxListenersWarningThreshold test default config', () => { + // default + expect(web3Eth.maxListenersWarningThreshold).toBe(100); + }); + it('maxListenersWarningThreshold set maxListeners through variable', () => { + const eth2 = new Web3Eth({}); + eth2.maxListenersWarningThreshold = 3; + expect(eth2.maxListenersWarningThreshold).toBe(3); + expect(eth2.getMaxListeners()).toBe(3); + }); + it('maxListenersWarningThreshold set config', () => { + const eth3 = new Web3Eth({}); + eth3.setConfig({ + maxListenersWarningThreshold: 3, }); + expect(eth3.maxListenersWarningThreshold).toBe(3); + expect(eth3.getMaxListeners()).toBe(3); + }); + it('defaultNetworkId', async () => { + // default + expect(web3Eth.defaultNetworkId).toBeUndefined(); - it('maxListenersWarningThreshold test default config', () => { - // default - expect(web3Eth.maxListenersWarningThreshold).toBe(100); + // after set + web3Eth.setConfig({ + defaultNetworkId: 3, }); - it('maxListenersWarningThreshold set maxListeners through variable', () => { - const eth2 = new Web3Eth({}); - eth2.maxListenersWarningThreshold = 3; - expect(eth2.maxListenersWarningThreshold).toBe(3); - expect(eth2.getMaxListeners()).toBe(3); + expect(web3Eth.defaultNetworkId).toBe(3); + + // set by create new instance + const eth2 = new Web3Eth({ + provider: web3Eth.provider, + config: { + defaultNetworkId: 4, + }, }); - it('maxListenersWarningThreshold set config', () => { - const eth3 = new Web3Eth({}); - eth3.setConfig({ - maxListenersWarningThreshold: 3, - }); - expect(eth3.maxListenersWarningThreshold).toBe(3); - expect(eth3.getMaxListeners()).toBe(3); + expect(eth2.defaultNetworkId).toBe(4); + const res = await defaultTransactionBuilder({ + transaction: { + from: '0xEB014f8c8B418Db6b45774c326A0E64C78914dC0', + to: '0x3535353535353535353535353535353535353535', + value: '0x174876e800', + gas: '0x5208', + }, + web3Context: eth2 as Web3Context, + }); + expect(res.networkId).toBe(4); + + // pass network id + const resWithPassNetworkId = await defaultTransactionBuilder({ + transaction: { + from: '0xEB014f8c8B418Db6b45774c326A0E64C78914dC0', + to: '0x3535353535353535353535353535353535353535', + value: '0x174876e800', + gas: '0x5208', + networkId: 5, + }, + web3Context: eth2 as Web3Context, }); - it('defaultNetworkId', async () => { - // default - expect(web3Eth.defaultNetworkId).toBeUndefined(); - - // after set - web3Eth.setConfig({ - defaultNetworkId: 3, - }); - expect(web3Eth.defaultNetworkId).toBe(3); - // set by create new instance - const eth2 = new Web3Eth({ - provider: web3Eth.provider, - config: { - defaultNetworkId: 4, - }, - }); - expect(eth2.defaultNetworkId).toBe(4); - const res = await defaultTransactionBuilder({ - transaction: { - from: '0xEB014f8c8B418Db6b45774c326A0E64C78914dC0', - to: '0x3535353535353535353535353535353535353535', - value: '0x174876e800', - gas: '0x5208', - }, - web3Context: eth2 as Web3Context, - }); - expect(res.networkId).toBe(4); - - // pass network id - const resWithPassNetworkId = await defaultTransactionBuilder({ - transaction: { - from: '0xEB014f8c8B418Db6b45774c326A0E64C78914dC0', - to: '0x3535353535353535353535353535353535353535', - value: '0x174876e800', - gas: '0x5208', - networkId: 5, - }, - web3Context: eth2 as Web3Context, - }); + expect(resWithPassNetworkId.networkId).toBe(BigInt(5)); - expect(resWithPassNetworkId.networkId).toBe(BigInt(5)); + await closeOpenConnection(eth2); + }); + it('defaultChain', async () => { + // default + expect(web3Eth.defaultChain).toBe('mainnet'); - await closeOpenConnection(eth2); + // after set + web3Eth.setConfig({ + defaultChain: 'ropsten', + }); + expect(web3Eth.defaultChain).toBe('ropsten'); + + // set by create new instance + const eth2 = new Web3Eth({ + provider: web3Eth.provider, + config: { + defaultChain: 'rinkeby', + }, }); - it('defaultChain', async () => { - // default - expect(web3Eth.defaultChain).toBe('mainnet'); + expect(eth2.defaultChain).toBe('rinkeby'); + const res = await defaultTransactionBuilder({ + transaction: { + from: '0xEB014f8c8B418Db6b45774c326A0E64C78914dC0', + to: '0x3535353535353535353535353535353535353535', + value: '0x174876e800', + gas: '0x5208', + }, + web3Context: eth2 as Web3Context, + }); + expect(res.chain).toBe('rinkeby'); + await closeOpenConnection(eth2); + }); + it('defaultHardfork', async () => { + // default + expect(web3Eth.defaultHardfork).toBe('london'); - // after set - web3Eth.setConfig({ - defaultChain: 'ropsten', - }); - expect(web3Eth.defaultChain).toBe('ropsten'); + // after set + web3Eth.setConfig({ + defaultHardfork: 'dao', + }); + expect(web3Eth.defaultHardfork).toBe('dao'); + + // set by create new instance + const eth2 = new Web3Eth({ + provider: web3Eth.provider, + config: { + defaultHardfork: 'istanbul', + defaultTransactionType: '0x0', + }, + }); + expect(eth2.defaultHardfork).toBe('istanbul'); + expect(eth2.defaultTransactionType).toBe('0x0'); + + const res = await prepareTransactionForSigning( + { + from: '0xEB014f8c8B418Db6b45774c326A0E64C78914dC0', + to: '0x3535353535353535353535353535353535353535', + value: '0x174876e800', + gas: '0x5208', + gasPrice: '0x4a817c800', + data: '0x0', + nonce: '0x4', + chainId: '0x1', + gasLimit: '0x5208', + }, + eth2, + ); + expect(res.common.hardfork()).toBe('istanbul'); + await closeOpenConnection(eth2); + }); + it('defaultCommon', () => { + // default + expect(web3Eth.defaultCommon).toBeUndefined(); + const baseChain: ValidChains = 'mainnet'; + const hardfork: Hardfork = 'dao'; + const common = { + customChain: { + name: 'test', + networkId: 123, + chainId: 1234, + }, + baseChain, + hardfork, + }; + // after set + web3Eth.setConfig({ + defaultCommon: common, + }); + expect(web3Eth.defaultCommon).toBe(common); - // set by create new instance - const eth2 = new Web3Eth({ - provider: web3Eth.provider, - config: { - defaultChain: 'rinkeby', - }, - }); - expect(eth2.defaultChain).toBe('rinkeby'); - const res = await defaultTransactionBuilder({ - transaction: { - from: '0xEB014f8c8B418Db6b45774c326A0E64C78914dC0', - to: '0x3535353535353535353535353535353535353535', - value: '0x174876e800', - gas: '0x5208', - }, - web3Context: eth2 as Web3Context, - }); - expect(res.chain).toBe('rinkeby'); - await closeOpenConnection(eth2); + // set by create new instance + const eth2 = new Web3Eth({ + config: { + defaultCommon: common, + }, }); - it('defaultHardfork', async () => { - // default - expect(web3Eth.defaultHardfork).toBe('london'); + expect(eth2.defaultCommon).toBe(common); + }); - // after set - web3Eth.setConfig({ - defaultHardfork: 'dao', - }); - expect(web3Eth.defaultHardfork).toBe('dao'); - - // set by create new instance - const eth2 = new Web3Eth({ - provider: web3Eth.provider, - config: { - defaultHardfork: 'istanbul', - defaultTransactionType: '0x0', - }, - }); - expect(eth2.defaultHardfork).toBe('istanbul'); - expect(eth2.defaultTransactionType).toBe('0x0'); - - const res = await prepareTransactionForSigning( - { - from: '0xEB014f8c8B418Db6b45774c326A0E64C78914dC0', - to: '0x3535353535353535353535353535353535353535', - value: '0x174876e800', - gas: '0x5208', - gasPrice: '0x4a817c800', - data: '0x0', - nonce: '0x4', - chainId: '0x1', - gasLimit: '0x5208', - }, - eth2, - ); - expect(res.common.hardfork()).toBe('istanbul'); - await closeOpenConnection(eth2); + it('defaultTransactionType', async () => { + // default + expect(web3Eth.defaultTransactionType).toBe('0x2'); + // after set + web3Eth.setConfig({ + defaultTransactionType: '0x3', }); - it('defaultCommon', () => { - // default - expect(web3Eth.defaultCommon).toBeUndefined(); - const baseChain: ValidChains = 'mainnet'; - const hardfork: Hardfork = 'dao'; - const common = { - customChain: { - name: 'test', - networkId: 123, - chainId: 1234, - }, - baseChain, - hardfork, - }; - // after set - web3Eth.setConfig({ - defaultCommon: common, - }); - expect(web3Eth.defaultCommon).toBe(common); + expect(web3Eth.defaultTransactionType).toBe('0x3'); - // set by create new instance - const eth2 = new Web3Eth({ - config: { - defaultCommon: common, - }, - }); - expect(eth2.defaultCommon).toBe(common); + // revert back to default + web3Eth.setConfig({ + defaultTransactionType: '0x2', }); - - it('defaultTransactionType', async () => { - // default - expect(web3Eth.defaultTransactionType).toBe('0x2'); - // after set - web3Eth.setConfig({ - defaultTransactionType: '0x3', - }); - expect(web3Eth.defaultTransactionType).toBe('0x3'); - // revert back to default - web3Eth.setConfig({ - defaultTransactionType: '0x2', - }); + // set by create new instance + const eth = new Web3Eth({ + provider: web3Eth.provider, + config: { + defaultTransactionType: '0x4444', + }, + }); - // set by create new instance - const eth = new Web3Eth({ - provider: web3Eth.provider, - config: { - defaultTransactionType: '0x4444', - }, - }); - - expect(eth.defaultTransactionType).toBe('0x4444'); - - const res = getTransactionType( - { - from: '0xEB014f8c8B418Db6b45774c326A0E64C78914dC0', - to: '0x3535353535353535353535353535353535353535', - value: '0x174876e800', - gas: '0x5208', - data: '0x0', - nonce: '0x4', - chainId: '0x1', - gasLimit: '0x5208', - }, - eth, - ); - expect(res).toBe('0x4444'); - - // test override to 0x2 if: - // tx.maxFeePerGas !== undefined || - // tx.maxPriorityFeePerGas !== undefined || - // tx.hardfork === 'london' || - // tx.common?.hardfork === 'london' - const maxFeePerGasOverride = getTransactionType( - { - from: '0xEB014f8c8B418Db6b45774c326A0E64C78914dC0', - to: '0x3535353535353535353535353535353535353535', - value: '0x174876e800', - gas: '0x5208', - data: '0x0', - nonce: '0x4', - chainId: '0x1', - gasLimit: '0x5208', - maxFeePerGas: '0x32', - }, - eth, - ); - expect(maxFeePerGasOverride).toBe('0x2'); - const maxPriorityFeePerGasOverride = getTransactionType( - { - from: '0xEB014f8c8B418Db6b45774c326A0E64C78914dC0', - to: '0x3535353535353535353535353535353535353535', - value: '0x174876e800', - gas: '0x5208', - data: '0x0', - nonce: '0x4', - chainId: '0x1', - gasLimit: '0x5208', - maxPriorityFeePerGas: '0x32', - }, - eth, - ); - expect(maxPriorityFeePerGasOverride).toBe('0x2'); - const hardforkOverride = getTransactionType( - { - from: '0xEB014f8c8B418Db6b45774c326A0E64C78914dC0', - to: '0x3535353535353535353535353535353535353535', - value: '0x174876e800', - gas: '0x5208', - data: '0x0', - nonce: '0x4', - chainId: '0x1', - gasLimit: '0x5208', + expect(eth.defaultTransactionType).toBe('0x4444'); + + const res = getTransactionType( + { + from: '0xEB014f8c8B418Db6b45774c326A0E64C78914dC0', + to: '0x3535353535353535353535353535353535353535', + value: '0x174876e800', + gas: '0x5208', + data: '0x0', + nonce: '0x4', + chainId: '0x1', + gasLimit: '0x5208', + }, + eth, + ); + expect(res).toBe('0x4444'); + + // test override to 0x2 if: + // tx.maxFeePerGas !== undefined || + // tx.maxPriorityFeePerGas !== undefined || + // tx.hardfork === 'london' || + // tx.common?.hardfork === 'london' + const maxFeePerGasOverride = getTransactionType( + { + from: '0xEB014f8c8B418Db6b45774c326A0E64C78914dC0', + to: '0x3535353535353535353535353535353535353535', + value: '0x174876e800', + gas: '0x5208', + data: '0x0', + nonce: '0x4', + chainId: '0x1', + gasLimit: '0x5208', + maxFeePerGas: '0x32', + }, + eth, + ); + expect(maxFeePerGasOverride).toBe('0x2'); + const maxPriorityFeePerGasOverride = getTransactionType( + { + from: '0xEB014f8c8B418Db6b45774c326A0E64C78914dC0', + to: '0x3535353535353535353535353535353535353535', + value: '0x174876e800', + gas: '0x5208', + data: '0x0', + nonce: '0x4', + chainId: '0x1', + gasLimit: '0x5208', + maxPriorityFeePerGas: '0x32', + }, + eth, + ); + expect(maxPriorityFeePerGasOverride).toBe('0x2'); + const hardforkOverride = getTransactionType( + { + from: '0xEB014f8c8B418Db6b45774c326A0E64C78914dC0', + to: '0x3535353535353535353535353535353535353535', + value: '0x174876e800', + gas: '0x5208', + data: '0x0', + nonce: '0x4', + chainId: '0x1', + gasLimit: '0x5208', + hardfork: 'london', + }, + eth, + ); + expect(hardforkOverride).toBe('0x2'); + const commonOverride = getTransactionType( + { + from: '0xEB014f8c8B418Db6b45774c326A0E64C78914dC0', + to: '0x3535353535353535353535353535353535353535', + value: '0x174876e800', + gas: '0x5208', + data: '0x0', + nonce: '0x4', + chainId: '0x1', + gasLimit: '0x5208', + common: { + customChain: { name: 'ropsten', networkId: '2', chainId: '0x1' }, hardfork: 'london', }, - eth, - ); - expect(hardforkOverride).toBe('0x2'); - const commonOverride = getTransactionType( - { - from: '0xEB014f8c8B418Db6b45774c326A0E64C78914dC0', - to: '0x3535353535353535353535353535353535353535', - value: '0x174876e800', - gas: '0x5208', - data: '0x0', - nonce: '0x4', - chainId: '0x1', - gasLimit: '0x5208', - common: { - customChain: { name: 'ropsten', networkId: '2', chainId: '0x1' }, - hardfork: 'london', + }, + eth, + ); + expect(commonOverride).toBe('0x2'); + + // override to 0x1 if: + // tx.accessList !== undefined || tx.hardfork === 'berlin' || tx.common?.hardfork === 'berlin' + + const accessListOverride = getTransactionType( + { + from: '0xEB014f8c8B418Db6b45774c326A0E64C78914dC0', + to: '0x3535353535353535353535353535353535353535', + value: '0x174876e800', + gas: '0x5208', + data: '0x0', + nonce: '0x4', + chainId: '0x1', + gasLimit: '0x5208', + accessList: [ + { + address: '0xEB014f8c8B418Db6b45774c326A0E64C78914dC0', + storageKeys: ['0x3535353535353535353535353535353535353535'], }, - }, - eth, - ); - expect(commonOverride).toBe('0x2'); - - // override to 0x1 if: - // tx.accessList !== undefined || tx.hardfork === 'berlin' || tx.common?.hardfork === 'berlin' - - const accessListOverride = getTransactionType( - { - from: '0xEB014f8c8B418Db6b45774c326A0E64C78914dC0', - to: '0x3535353535353535353535353535353535353535', - value: '0x174876e800', - gas: '0x5208', - data: '0x0', - nonce: '0x4', - chainId: '0x1', - gasLimit: '0x5208', - accessList: [ - { - address: '0xEB014f8c8B418Db6b45774c326A0E64C78914dC0', - storageKeys: ['0x3535353535353535353535353535353535353535'], - }, - ], - }, - eth, - ); - expect(accessListOverride).toBe('0x1'); - - const hardforkBerlinOverride = getTransactionType( - { - from: '0xEB014f8c8B418Db6b45774c326A0E64C78914dC0', - to: '0x3535353535353535353535353535353535353535', - value: '0x174876e800', - gas: '0x5208', - data: '0x0', - nonce: '0x4', - chainId: '0x1', - gasLimit: '0x5208', + ], + }, + eth, + ); + expect(accessListOverride).toBe('0x1'); + + const hardforkBerlinOverride = getTransactionType( + { + from: '0xEB014f8c8B418Db6b45774c326A0E64C78914dC0', + to: '0x3535353535353535353535353535353535353535', + value: '0x174876e800', + gas: '0x5208', + data: '0x0', + nonce: '0x4', + chainId: '0x1', + gasLimit: '0x5208', + hardfork: 'berlin', + }, + eth, + ); + expect(hardforkBerlinOverride).toBe('0x0'); + + const commonBerlinOverride = getTransactionType( + { + from: '0xEB014f8c8B418Db6b45774c326A0E64C78914dC0', + to: '0x3535353535353535353535353535353535353535', + value: '0x174876e800', + gas: '0x5208', + data: '0x0', + nonce: '0x4', + chainId: '0x1', + gasLimit: '0x5208', + common: { + customChain: { name: 'ropsten', networkId: '2', chainId: '0x1' }, hardfork: 'berlin', }, - eth, - ); - expect(hardforkBerlinOverride).toBe('0x0'); - - const commonBerlinOverride = getTransactionType( - { - from: '0xEB014f8c8B418Db6b45774c326A0E64C78914dC0', - to: '0x3535353535353535353535353535353535353535', - value: '0x174876e800', - gas: '0x5208', - data: '0x0', - nonce: '0x4', - chainId: '0x1', - gasLimit: '0x5208', - common: { - customChain: { name: 'ropsten', networkId: '2', chainId: '0x1' }, - hardfork: 'berlin', - }, - }, - eth, - ); - expect(commonBerlinOverride).toBe('0x0'); - await closeOpenConnection(eth); + }, + eth, + ); + expect(commonBerlinOverride).toBe('0x0'); + await closeOpenConnection(eth); + }); + it('defaultMaxPriorityFeePerGas', async () => { + // default + expect(web3Eth.defaultMaxPriorityFeePerGas).toBe(numberToHex(2500000000)); + // after set + web3Eth.setConfig({ + defaultMaxPriorityFeePerGas: numberToHex(2100000000), }); - it('defaultMaxPriorityFeePerGas', async () => { - // default - expect(web3Eth.defaultMaxPriorityFeePerGas).toBe(numberToHex(2500000000)); - // after set - web3Eth.setConfig({ - defaultMaxPriorityFeePerGas: numberToHex(2100000000), - }); - expect(web3Eth.defaultMaxPriorityFeePerGas).toBe(numberToHex(2100000000)); - - // set by create new instance - const eth2 = new Web3Eth({ - provider: web3Eth.provider, - config: { - defaultMaxPriorityFeePerGas: numberToHex(1200000000), - }, - }); - expect(eth2.defaultMaxPriorityFeePerGas).toBe(numberToHex(1200000000)); - - const res = await getTransactionGasPricing( - { - from: '0xEB014f8c8B418Db6b45774c326A0E64C78914dC0', - to: '0x3535353535353535353535353535353535353535', - value: '0x174876e800', - type: '0x2', - gas: '0x5208', - data: '0x0', - nonce: '0x4', - chainId: '0x1', - gasLimit: '0x5208', - }, - eth2, - DEFAULT_RETURN_FORMAT, - ); - expect(res?.maxPriorityFeePerGas).toBe(BigInt(1200000000)); - - // override test - const resOverride = await getTransactionGasPricing( - { - from: '0xEB014f8c8B418Db6b45774c326A0E64C78914dC0', - to: '0x3535353535353535353535353535353535353535', - value: '0x174876e800', - type: '0x2', - gas: '0x5208', - data: '0x0', - nonce: '0x4', - chainId: '0x1', - gasLimit: '0x5208', - maxPriorityFeePerGas: '0x123123123', - }, - eth2, - DEFAULT_RETURN_FORMAT, - ); - expect(resOverride?.maxPriorityFeePerGas).toBe(BigInt('4883362083')); - await closeOpenConnection(eth2); + expect(web3Eth.defaultMaxPriorityFeePerGas).toBe(numberToHex(2100000000)); + + // set by create new instance + const eth2 = new Web3Eth({ + provider: web3Eth.provider, + config: { + defaultMaxPriorityFeePerGas: numberToHex(1200000000), + }, }); - it('transactionBuilder', async () => { - // default - expect(web3Eth.transactionBuilder).toBeUndefined(); + expect(eth2.defaultMaxPriorityFeePerGas).toBe(numberToHex(1200000000)); + + const res = await getTransactionGasPricing( + { + from: '0xEB014f8c8B418Db6b45774c326A0E64C78914dC0', + to: '0x3535353535353535353535353535353535353535', + value: '0x174876e800', + type: '0x2', + gas: '0x5208', + data: '0x0', + nonce: '0x4', + chainId: '0x1', + gasLimit: '0x5208', + }, + eth2, + DEFAULT_RETURN_FORMAT, + ); + expect(res?.maxPriorityFeePerGas).toBe(BigInt(1200000000)); + + // override test + const resOverride = await getTransactionGasPricing( + { + from: '0xEB014f8c8B418Db6b45774c326A0E64C78914dC0', + to: '0x3535353535353535353535353535353535353535', + value: '0x174876e800', + type: '0x2', + gas: '0x5208', + data: '0x0', + nonce: '0x4', + chainId: '0x1', + gasLimit: '0x5208', + maxPriorityFeePerGas: '0x123123123', + }, + eth2, + DEFAULT_RETURN_FORMAT, + ); + expect(resOverride?.maxPriorityFeePerGas).toBe(BigInt('4883362083')); + await closeOpenConnection(eth2); + }); + it('transactionBuilder', async () => { + // default + expect(web3Eth.transactionBuilder).toBeUndefined(); - // default - expect(web3Eth.transactionBuilder).toBeUndefined(); + // default + expect(web3Eth.transactionBuilder).toBeUndefined(); - const newBuilderMock = jest.fn() as unknown as TransactionBuilder; + const newBuilderMock = jest.fn() as unknown as TransactionBuilder; - web3Eth.setConfig({ - transactionBuilder: newBuilderMock, - }); - expect(web3Eth.transactionBuilder).toBe(newBuilderMock); + web3Eth.setConfig({ + transactionBuilder: newBuilderMock, + }); + expect(web3Eth.transactionBuilder).toBe(newBuilderMock); - // set by create new instance - const eth2 = new Web3Eth({ - config: { - transactionBuilder: newBuilderMock, - }, - }); - expect(eth2.transactionBuilder).toBe(newBuilderMock); - - await transactionBuilder({ - transaction: { - from: '0xEB014f8c8B418Db6b45774c326A0E64C78914dC0', - to: '0x3535353535353535353535353535353535353535', - value: '0x174876e800', - gas: '0x5208', - gasPrice: '0x4a817c800', - data: '0x0', - nonce: '0x4', - chainId: '0x1', - gasLimit: '0x5208', - }, - web3Context: eth2, - }); - expect(newBuilderMock).toHaveBeenCalled(); + // set by create new instance + const eth2 = new Web3Eth({ + config: { + transactionBuilder: newBuilderMock, + }, + }); + expect(eth2.transactionBuilder).toBe(newBuilderMock); + + await transactionBuilder({ + transaction: { + from: '0xEB014f8c8B418Db6b45774c326A0E64C78914dC0', + to: '0x3535353535353535353535353535353535353535', + value: '0x174876e800', + gas: '0x5208', + gasPrice: '0x4a817c800', + data: '0x0', + nonce: '0x4', + chainId: '0x1', + gasLimit: '0x5208', + }, + web3Context: eth2, }); - it('transactionTypeParser', () => { - // default - expect(web3Eth.transactionTypeParser).toBeUndefined(); + expect(newBuilderMock).toHaveBeenCalled(); + }); + it('transactionTypeParser', () => { + // default + expect(web3Eth.transactionTypeParser).toBeUndefined(); - const newParserMock = jest.fn() as unknown as TransactionTypeParser; + const newParserMock = jest.fn() as unknown as TransactionTypeParser; - web3Eth.setConfig({ - transactionTypeParser: newParserMock, - }); - expect(web3Eth.transactionTypeParser).toBe(newParserMock); + web3Eth.setConfig({ + transactionTypeParser: newParserMock, + }); + expect(web3Eth.transactionTypeParser).toBe(newParserMock); - // set by create new instance - const eth2 = new Web3Eth({ - config: { - transactionTypeParser: newParserMock, - }, - }); - expect(eth2.transactionTypeParser).toBe(newParserMock); - detectTransactionType( - { - from: '0xEB014f8c8B418Db6b45774c326A0E64C78914dC0', - to: '0x3535353535353535353535353535353535353535', - value: '0x174876e800', - gas: '0x5208', - gasPrice: '0x4a817c800', - data: '0x0', - nonce: '0x4', - chainId: '0x1', - gasLimit: '0x5208', - }, - eth2, - ); - expect(newParserMock).toHaveBeenCalled(); + // set by create new instance + const eth2 = new Web3Eth({ + config: { + transactionTypeParser: newParserMock, + }, }); -}); \ No newline at end of file + expect(eth2.transactionTypeParser).toBe(newParserMock); + detectTransactionType( + { + from: '0xEB014f8c8B418Db6b45774c326A0E64C78914dC0', + to: '0x3535353535353535353535353535353535353535', + value: '0x174876e800', + gas: '0x5208', + gasPrice: '0x4a817c800', + data: '0x0', + nonce: '0x4', + chainId: '0x1', + gasLimit: '0x5208', + }, + eth2, + ); + expect(newParserMock).toHaveBeenCalled(); + }); +}); diff --git a/packages/web3-eth/test/integration/defaults.transactionBlockTimeout.test.ts b/packages/web3-eth/test/integration/defaults.transactionBlockTimeout.test.ts index ba7fd5f15e0..15eb401ea51 100644 --- a/packages/web3-eth/test/integration/defaults.transactionBlockTimeout.test.ts +++ b/packages/web3-eth/test/integration/defaults.transactionBlockTimeout.test.ts @@ -32,8 +32,7 @@ import { sendFewSampleTxs, getSystemTestBackend, describeIf, - BACKEND - + BACKEND, } from '../fixtures/system_test_utils'; const MAX_32_SIGNED_INTEGER = 2147483647; @@ -45,9 +44,9 @@ describeIf(getSystemTestBackend() !== BACKEND.HARDHAT)('defaults', () => { let clientUrl: string | SupportedProviders; let account1: Web3Account; let account2: Web3Account; - let transactionBlockTimeout: number; - let transactionSendTimeout: number; - let transactionPollingTimeout: number; + let transactionBlockTimeout: number; + let transactionSendTimeout: number; + let transactionPollingTimeout: number; let blockHeaderTimeout: number; beforeEach(() => { @@ -62,7 +61,7 @@ describeIf(getSystemTestBackend() !== BACKEND.HARDHAT)('defaults', () => { afterEach(async () => { web3.eth.transactionBlockTimeout = transactionBlockTimeout; - web3.eth.transactionSendTimeout = transactionSendTimeout ; + web3.eth.transactionSendTimeout = transactionSendTimeout; web3.eth.transactionPollingTimeout = transactionPollingTimeout; web3.eth.blockHeaderTimeout = blockHeaderTimeout; await closeOpenConnection(web3); @@ -89,7 +88,7 @@ describeIf(getSystemTestBackend() !== BACKEND.HARDHAT)('defaults', () => { // So, send 2 transactions, one after another, because in this test `transactionBlockTimeout = 2`. // eslint-disable-next-line no-void await sendFewSampleTxs(2); - + // Increase other timeouts so only `transactionBlockTimeout` would be reached web3.eth.transactionSendTimeout = MAX_32_SIGNED_INTEGER; web3.eth.transactionPollingTimeout = MAX_32_SIGNED_INTEGER; @@ -99,7 +98,6 @@ describeIf(getSystemTestBackend() !== BACKEND.HARDHAT)('defaults', () => { await expect(sentTx).rejects.toThrow(/was not mined within [0-9]+ blocks/); await expect(sentTx).rejects.toThrow(TransactionBlockTimeoutError); - }); // The code of this test case is identical to the pervious one except for `eth.enableExperimentalFeatures = true` @@ -139,7 +137,6 @@ describeIf(getSystemTestBackend() !== BACKEND.HARDHAT)('defaults', () => { await expect(sentTx).rejects.toThrow(/was not mined within [0-9]+ blocks/); await expect(sentTx).rejects.toThrow(TransactionBlockTimeoutError); - }, ); }); diff --git a/packages/web3-eth/test/integration/get_revert_reason.test.ts b/packages/web3-eth/test/integration/get_revert_reason.test.ts index 4180742a21b..664b9569cf9 100644 --- a/packages/web3-eth/test/integration/get_revert_reason.test.ts +++ b/packages/web3-eth/test/integration/get_revert_reason.test.ts @@ -27,7 +27,7 @@ import { getSystemTestBackend, getSystemTestProvider, BACKEND, - closeOpenConnection + closeOpenConnection, } from '../fixtures/system_test_utils'; describe('Web3Eth.getRevertReason', () => { @@ -163,7 +163,7 @@ describe('Web3Eth.getRevertReason', () => { case BACKEND.HARDHAT: expect(response).toMatchObject({ data: '', - reason: "Error: VM Exception while processing transaction: reverted with an unrecognized custom error (return data: 0x72090e4d)", + reason: 'Error: VM Exception while processing transaction: reverted with an unrecognized custom error (return data: 0x72090e4d)', signature: '0x72090e4d', customErrorName: 'ErrorWithNoParams', customErrorDecodedSignature: 'ErrorWithNoParams()', @@ -202,7 +202,7 @@ describe('Web3Eth.getRevertReason', () => { case BACKEND.HARDHAT: expect(response).toMatchObject({ data: '000000000000000000000000000000000000000000000000000000000000002a0000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000001c5468697320697320616e206572726f72207769746820706172616d7300000000', - reason: "Error: VM Exception while processing transaction: reverted with an unrecognized custom error (return data: 0xc85bda60000000000000000000000000000000000000000000000000000000000000002a0000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000001c5468697320697320616e206572726f72207769746820706172616d7300000000)", + reason: 'Error: VM Exception while processing transaction: reverted with an unrecognized custom error (return data: 0xc85bda60000000000000000000000000000000000000000000000000000000000000002a0000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000001c5468697320697320616e206572726f72207769746820706172616d7300000000)', signature: '0xc85bda60', customErrorName: 'ErrorWithParams', customErrorDecodedSignature: 'ErrorWithParams(uint256,string)', diff --git a/packages/web3-eth/test/integration/nonce.test.ts b/packages/web3-eth/test/integration/nonce.test.ts index 201c0728d5f..96621c97b54 100644 --- a/packages/web3-eth/test/integration/nonce.test.ts +++ b/packages/web3-eth/test/integration/nonce.test.ts @@ -26,7 +26,7 @@ import { createLocalAccount, getSystemTestBackend, getSystemTestProvider, - BACKEND + BACKEND, } from '../fixtures/system_test_utils'; const gas = 30000; @@ -86,13 +86,13 @@ describe('defaults', () => { web3Eth.transactionPollingTimeout / 1000 } seconds`, ); - } else if (getSystemTestBackend() === BACKEND.HARDHAT){ + } else if (getSystemTestBackend() === BACKEND.HARDHAT) { // eslint-disable-next-line jest/no-conditional-expect - expect((error as any).message).toContain("Nonce too high") - } else { - throw error; + expect((error as any).message).toContain('Nonce too high'); + } else { + throw error; + } } - } - }); + }); }); }); diff --git a/packages/web3-eth/test/integration/watch_transaction.test.ts b/packages/web3-eth/test/integration/watch_transaction.test.ts index 733b64a089b..63b27374366 100644 --- a/packages/web3-eth/test/integration/watch_transaction.test.ts +++ b/packages/web3-eth/test/integration/watch_transaction.test.ts @@ -86,14 +86,15 @@ describeIf(isSocket)('watch subscription transaction', () => { await receiptPromise; await sendFewSampleTxs(isIpc ? 2 * waitConfirmations : waitConfirmations); - const resourcePromise = waitForCondition( - () => shouldBe >= waitConfirmations, + const resourcePromise = waitForCondition( + () => shouldBe >= waitConfirmations, async () => { sentTx.removeAllListeners(); - await closeOpenConnection(web3);} - ); + await closeOpenConnection(web3); + }, + ); - await Promise.all([confirmationPromise,resourcePromise]); + await Promise.all([confirmationPromise, resourcePromise]); }); }); }); diff --git a/packages/web3-eth/test/integration/web3_eth/createAccessList.test.ts b/packages/web3-eth/test/integration/web3_eth/createAccessList.test.ts index 3e1186c3cda..2f102be3b57 100644 --- a/packages/web3-eth/test/integration/web3_eth/createAccessList.test.ts +++ b/packages/web3-eth/test/integration/web3_eth/createAccessList.test.ts @@ -22,7 +22,7 @@ import { describeIf, getSystemTestBackend, getSystemTestProvider, - BACKEND + BACKEND, } from '../../fixtures/system_test_utils'; describeIf(getSystemTestBackend() === BACKEND.GETH)('Web3Eth.createAccessList', () => { diff --git a/packages/web3-eth/test/integration/web3_eth/estimate_gas.test.ts b/packages/web3-eth/test/integration/web3_eth/estimate_gas.test.ts index e26de249a3e..96951950f3a 100644 --- a/packages/web3-eth/test/integration/web3_eth/estimate_gas.test.ts +++ b/packages/web3-eth/test/integration/web3_eth/estimate_gas.test.ts @@ -24,7 +24,7 @@ import { itIf, isGeth, getSystemTestBackend, - BACKEND + BACKEND, } from '../../fixtures/system_test_utils'; describe('Web3Eth.estimateGas', () => { diff --git a/packages/web3-eth/test/integration/web3_eth/getFeeHistory.test.ts b/packages/web3-eth/test/integration/web3_eth/getFeeHistory.test.ts index fd8aec67383..0cbd85fc752 100644 --- a/packages/web3-eth/test/integration/web3_eth/getFeeHistory.test.ts +++ b/packages/web3-eth/test/integration/web3_eth/getFeeHistory.test.ts @@ -22,7 +22,7 @@ import { describeIf, getSystemTestBackend, closeOpenConnection, - BACKEND + BACKEND, } from '../../fixtures/system_test_utils'; import { feeHistorySchema } from '../../../src/schemas'; diff --git a/packages/web3-eth/test/integration/web3_eth/send_signed_transaction.test.ts b/packages/web3-eth/test/integration/web3_eth/send_signed_transaction.test.ts index f74a12938ac..fccd63dcc1b 100644 --- a/packages/web3-eth/test/integration/web3_eth/send_signed_transaction.test.ts +++ b/packages/web3-eth/test/integration/web3_eth/send_signed_transaction.test.ts @@ -38,7 +38,7 @@ import { getSystemTestBackend, getSystemTestProvider, describeIf, - BACKEND + BACKEND, } from '../../fixtures/system_test_utils'; import { getTransactionGasPricing } from '../../../src/utils/get_transaction_gas_pricing'; import { SimpleRevertAbi, SimpleRevertDeploymentData } from '../../fixtures/simple_revert'; diff --git a/packages/web3-eth/test/integration/web3_eth/sign.test.ts b/packages/web3-eth/test/integration/web3_eth/sign.test.ts index b468dbb1cb0..a46a5ca28f1 100644 --- a/packages/web3-eth/test/integration/web3_eth/sign.test.ts +++ b/packages/web3-eth/test/integration/web3_eth/sign.test.ts @@ -23,7 +23,7 @@ import { createTempAccount, getSystemTestBackend, getSystemTestProvider, - BACKEND + BACKEND, } from '../../fixtures/system_test_utils'; describe('Web3Eth.sign', () => { diff --git a/packages/web3-eth/test/integration/web3_eth/sign_transaction.test.ts b/packages/web3-eth/test/integration/web3_eth/sign_transaction.test.ts index 630a67cfba2..97d865b2c8d 100644 --- a/packages/web3-eth/test/integration/web3_eth/sign_transaction.test.ts +++ b/packages/web3-eth/test/integration/web3_eth/sign_transaction.test.ts @@ -23,7 +23,7 @@ import { getSystemTestProvider, describeIf, getSystemTestBackend, - BACKEND + BACKEND, } from '../../fixtures/system_test_utils'; // hardhat does not support eth_signtransaction diff --git a/packages/web3-eth/test/integration/web3_eth/submit_work.test.ts b/packages/web3-eth/test/integration/web3_eth/submit_work.test.ts index d3817d551b4..c1728fda297 100644 --- a/packages/web3-eth/test/integration/web3_eth/submit_work.test.ts +++ b/packages/web3-eth/test/integration/web3_eth/submit_work.test.ts @@ -21,7 +21,7 @@ import { getSystemTestBackend, getSystemTestProvider, itIf, - BACKEND + BACKEND, } from '../../fixtures/system_test_utils'; describe('Web3Eth.submitWork', () => { @@ -36,13 +36,16 @@ describe('Web3Eth.submitWork', () => { }); // Hardhat and Geth doesn't support eth_submitWork - itIf(getSystemTestBackend() !== BACKEND.GETH && getSystemTestBackend() !== BACKEND.HARDHAT)('should submit work', async () => { - const response = await web3Eth.submitWork( - '0x0000000000000001', - '0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef', - '0xD1FE5700000000000000000000000000D1FE5700000000000000000000000000', - ); - // eslint-disable-next-line jest/no-standalone-expect - expect(response).toBe(false); - }); + itIf(getSystemTestBackend() !== BACKEND.GETH && getSystemTestBackend() !== BACKEND.HARDHAT)( + 'should submit work', + async () => { + const response = await web3Eth.submitWork( + '0x0000000000000001', + '0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef', + '0xD1FE5700000000000000000000000000D1FE5700000000000000000000000000', + ); + // eslint-disable-next-line jest/no-standalone-expect + expect(response).toBe(false); + }, + ); }); diff --git a/packages/web3-eth/test/unit/default_transaction_builder.test.ts b/packages/web3-eth/test/unit/default_transaction_builder.test.ts index 0e065806393..5d8e9b34b39 100644 --- a/packages/web3-eth/test/unit/default_transaction_builder.test.ts +++ b/packages/web3-eth/test/unit/default_transaction_builder.test.ts @@ -242,7 +242,6 @@ describe('defaultTransactionBuilder', () => { expect(result.value).toBe('0x0'); }); - it('should not populate with 0x0 if provided', async () => { const input = { ...transaction }; delete input.maxPriorityFeePerGas; diff --git a/packages/web3-eth/test/unit/detect_transaction_type.test.ts b/packages/web3-eth/test/unit/detect_transaction_type.test.ts index 4d583bbad17..094bbebff68 100644 --- a/packages/web3-eth/test/unit/detect_transaction_type.test.ts +++ b/packages/web3-eth/test/unit/detect_transaction_type.test.ts @@ -28,7 +28,6 @@ import { transactionTypeValidationError, } from '../fixtures/detect_transaction_type'; - jest.mock('../../src/rpc_method_wrappers'); describe('detectTransactionType', () => { diff --git a/packages/web3-eth/test/unit/prepare_transaction_for_signing.test.ts b/packages/web3-eth/test/unit/prepare_transaction_for_signing.test.ts index d53785c2e36..ce83a505d17 100644 --- a/packages/web3-eth/test/unit/prepare_transaction_for_signing.test.ts +++ b/packages/web3-eth/test/unit/prepare_transaction_for_signing.test.ts @@ -15,12 +15,7 @@ You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see . */ -import { - EthExecutionAPI, - HexString, - Web3NetAPI, - Transaction as TransactionType, -} from 'web3-types'; +import { EthExecutionAPI, HexString, Web3NetAPI, Transaction as TransactionType } from 'web3-types'; import { Web3Context } from 'web3-core'; import HttpProvider from 'web3-providers-http'; import { isNullish } from 'web3-validator'; diff --git a/packages/web3-eth/test/unit/rpc_method_wrappers/fixtures/get_block.ts b/packages/web3-eth/test/unit/rpc_method_wrappers/fixtures/get_block.ts index 250f770bd64..b129ab368b3 100644 --- a/packages/web3-eth/test/unit/rpc_method_wrappers/fixtures/get_block.ts +++ b/packages/web3-eth/test/unit/rpc_method_wrappers/fixtures/get_block.ts @@ -73,7 +73,7 @@ export const mockRpcResponseHydrated: Block = { export const noTransactionBlock: Block = { ...mockRpcResponse, transactions: [], -} +}; /** * Array consists of: diff --git a/packages/web3-eth/test/unit/rpc_method_wrappers/get_block.test.ts b/packages/web3-eth/test/unit/rpc_method_wrappers/get_block.test.ts index 365fb09d9ec..9e5d6540ed4 100644 --- a/packages/web3-eth/test/unit/rpc_method_wrappers/get_block.test.ts +++ b/packages/web3-eth/test/unit/rpc_method_wrappers/get_block.test.ts @@ -28,7 +28,12 @@ import { isBytes, isNullish } from 'web3-validator'; import { ethRpcMethods } from 'web3-rpc-methods'; import { getBlock } from '../../../src/rpc_method_wrappers'; -import { mockRpcResponse, mockRpcResponseHydrated, testData, noTransactionBlock } from './fixtures/get_block'; +import { + mockRpcResponse, + mockRpcResponseHydrated, + testData, + noTransactionBlock, +} from './fixtures/get_block'; import { blockSchema } from '../../../src/schemas'; jest.mock('web3-rpc-methods'); @@ -97,9 +102,7 @@ describe('getBlock', () => { expectedMockRpcResponse, expectedReturnFormat, ); - const expectedFormattedResult = {...formattedResult, - transactions: [] - }; + const expectedFormattedResult = { ...formattedResult, transactions: [] }; const inputBlockIsBytes = isBytes(inputBlock as Bytes); ( (inputBlockIsBytes diff --git a/packages/web3-eth/test/unit/rpc_method_wrappers/send_transaction_middleware.test.ts b/packages/web3-eth/test/unit/rpc_method_wrappers/send_transaction_middleware.test.ts index 63dddbb759f..aa289605788 100644 --- a/packages/web3-eth/test/unit/rpc_method_wrappers/send_transaction_middleware.test.ts +++ b/packages/web3-eth/test/unit/rpc_method_wrappers/send_transaction_middleware.test.ts @@ -15,84 +15,82 @@ You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see . */ -import { Web3Context } from "web3-core"; -import { DEFAULT_RETURN_FORMAT, Web3EthExecutionAPI } from "web3-types"; -import {blockMockResult,receiptMockResult } from "../../fixtures/transactions_data"; -import { TransactionMiddleware, sendTransaction } from "../../../src"; +import { Web3Context } from 'web3-core'; +import { DEFAULT_RETURN_FORMAT, Web3EthExecutionAPI } from 'web3-types'; +import { blockMockResult, receiptMockResult } from '../../fixtures/transactions_data'; +import { TransactionMiddleware, sendTransaction } from '../../../src'; const mockTransactionMiddleware: TransactionMiddleware = { - processTransaction: jest.fn(async (transaction) => { - const tx = {...transaction} - tx.data = '0x123'; - return Promise.resolve(tx)} -), + processTransaction: jest.fn(async transaction => { + const tx = { ...transaction }; + tx.data = '0x123'; + return Promise.resolve(tx); + }), }; describe('sendTransaction', () => { let web3Context: Web3Context; - + beforeEach(() => { let blockNum = 0; web3Context = new Web3Context('http://127.0.0.1:8545'); - web3Context.requestManager.send = jest.fn(async (request) => { + web3Context.requestManager.send = jest.fn(async request => { blockNum += 1; - if(request.method === 'eth_getBlockByNumber'){ - + if (request.method === 'eth_getBlockByNumber') { return Promise.resolve(blockMockResult.result); } - if(request.method === 'eth_call'){ - - return Promise.resolve("0x"); + if (request.method === 'eth_call') { + return Promise.resolve('0x'); } - if(request.method === 'eth_blockNumber'){ - + if (request.method === 'eth_blockNumber') { return Promise.resolve(blockNum.toString(16)); } - if(request.method === 'eth_sendTransaction'){ - - return Promise.resolve("0xdf7756865c2056ce34c4eabe4eff42ad251a9f920a1c620c00b4ea0988731d3f"); + if (request.method === 'eth_sendTransaction') { + return Promise.resolve( + '0xdf7756865c2056ce34c4eabe4eff42ad251a9f920a1c620c00b4ea0988731d3f', + ); } if (request.method === 'eth_getTransactionReceipt') { return Promise.resolve(receiptMockResult.result); } - - return Promise.resolve("Unknown Request" as any); + + return Promise.resolve('Unknown Request' as any); }); }); afterEach(() => jest.resetAllMocks()); - it('should call processTransaction when transactionMiddleware is provided', async () => { - const transaction = { - from: '0x6E599DA0bfF7A6598AC1224E4985430Bf16458a4', - to: '0x6f1DF96865D09d21e8f3f9a7fbA3b17A11c7C53C', - value: '0x1', - data: '0x1' - }; - - await sendTransaction( - web3Context, - transaction, - DEFAULT_RETURN_FORMAT, - {}, - mockTransactionMiddleware, - ); - - expect(mockTransactionMiddleware.processTransaction).toHaveBeenCalledWith(transaction); - }); - - it('should not call processTransaction when transactionMiddleware is not provided', async () => { - const transaction = { - from: '0x6E599DA0bfF7A6598AC1224E4985430Bf16458a4', - to: '0x6f1DF96865D09d21e8f3f9a7fbA3b17A11c7C53C', - value: '0x1', - data: '0x1' - }; - - await sendTransaction(web3Context, transaction, DEFAULT_RETURN_FORMAT); - - expect(mockTransactionMiddleware.processTransaction).not.toHaveBeenCalled(); - }); -}); \ No newline at end of file + it('should call processTransaction when transactionMiddleware is provided', async () => { + const transaction = { + from: '0x6E599DA0bfF7A6598AC1224E4985430Bf16458a4', + to: '0x6f1DF96865D09d21e8f3f9a7fbA3b17A11c7C53C', + value: '0x1', + data: '0x1', + }; + + await sendTransaction( + web3Context, + transaction, + DEFAULT_RETURN_FORMAT, + {}, + mockTransactionMiddleware, + ); + + expect(mockTransactionMiddleware.processTransaction).toHaveBeenCalledWith(transaction); + }); + + it('should not call processTransaction when transactionMiddleware is not provided', async () => { + const transaction = { + from: '0x6E599DA0bfF7A6598AC1224E4985430Bf16458a4', + to: '0x6f1DF96865D09d21e8f3f9a7fbA3b17A11c7C53C', + value: '0x1', + data: '0x1', + }; + + await sendTransaction(web3Context, transaction, DEFAULT_RETURN_FORMAT); + + expect(mockTransactionMiddleware.processTransaction).not.toHaveBeenCalled(); + }); +}); diff --git a/packages/web3-eth/test/unit/send_tx_helper.test.ts b/packages/web3-eth/test/unit/send_tx_helper.test.ts index 6b40496f5a6..23e0d2aa526 100644 --- a/packages/web3-eth/test/unit/send_tx_helper.test.ts +++ b/packages/web3-eth/test/unit/send_tx_helper.test.ts @@ -21,7 +21,7 @@ import { JsonRpcResponse, TransactionReceipt, Web3BaseWalletAccount, - TransactionCall + TransactionCall, } from 'web3-types'; import { Web3Context, Web3EventMap, Web3PromiEvent } from 'web3-core'; import { @@ -163,16 +163,15 @@ describe('sendTxHelper class', () => { returnFormat: DEFAULT_RETURN_FORMAT, }); - const tx = {from:"0x"} as TransactionCall + const tx = { from: '0x' } as TransactionCall; - await _sendTxHelper.checkRevertBeforeSending(tx); + await _sendTxHelper.checkRevertBeforeSending(tx); - const expectedTx = { - ...tx, - gas: 21000, - }; + const expectedTx = { + ...tx, + gas: 21000, + }; expect(utils.getRevertReason).toHaveBeenCalledWith(web3Context, expectedTx, undefined); - }); it('emit handleError with handleRevert', async () => { const error = new ContractExecutionError({ code: 1, message: 'error' }); diff --git a/packages/web3-eth/test/unit/utils/get_transaction_type.test.ts b/packages/web3-eth/test/unit/utils/get_transaction_type.test.ts index 73111b42067..203dcdfc4ec 100644 --- a/packages/web3-eth/test/unit/utils/get_transaction_type.test.ts +++ b/packages/web3-eth/test/unit/utils/get_transaction_type.test.ts @@ -23,32 +23,30 @@ import { format } from 'web3-utils'; import { transactionSchema } from '../../../src/schemas'; import { getTransactionType } from '../../../src/utils/transaction_builder'; - describe('getTransactionType', () => { const expectedFrom = '0xb8CE9ab6943e0eCED004cDe8e3bBed6568B2Fa01'; - const transaction: Transaction = { - from: expectedFrom, - to: '0x3535353535353535353535353535353535353535', - value: '0x174876e800', - gas: BigInt(21000), - data: '0x', - nonce: 0x42, - chain: 'mainnet', - chainId: 0x1, - networkId: 0x4, - }; - const formattedTransaction = format(transactionSchema, transaction, ETH_DATA_FORMAT); - - const web3Context = new Web3Context({ - provider: new HttpProvider('http://127.0.0.1:80'), - config: { - defaultAccount: expectedFrom, - }, - }); - - it('should default to 0x2 when transaction type cannot be inferred and use default transaction type', async () => { + const transaction: Transaction = { + from: expectedFrom, + to: '0x3535353535353535353535353535353535353535', + value: '0x174876e800', + gas: BigInt(21000), + data: '0x', + nonce: 0x42, + chain: 'mainnet', + chainId: 0x1, + networkId: 0x4, + }; + const formattedTransaction = format(transactionSchema, transaction, ETH_DATA_FORMAT); + + const web3Context = new Web3Context({ + provider: new HttpProvider('http://127.0.0.1:80'), + config: { + defaultAccount: expectedFrom, + }, + }); + it('should default to 0x2 when transaction type cannot be inferred and use default transaction type', async () => { const transactionType = getTransactionType(formattedTransaction, web3Context); expect(transactionType).toBe('0x2'); }); diff --git a/packages/web3-eth/test/unit/utils/wait_for_transaction_receipt.test.ts b/packages/web3-eth/test/unit/utils/wait_for_transaction_receipt.test.ts index 4a598a00fe7..5e8d4f601d3 100644 --- a/packages/web3-eth/test/unit/utils/wait_for_transaction_receipt.test.ts +++ b/packages/web3-eth/test/unit/utils/wait_for_transaction_receipt.test.ts @@ -173,4 +173,4 @@ describe('waitForTransactionReceipt unit test', () => { expect(res.transactionHash).toStrictEqual(txHash); expect(res.blockHash).toStrictEqual(blockHash); }); -}); \ No newline at end of file +}); diff --git a/packages/web3-eth/test/unit/utils/watch_transaction_by_subscription.test.ts b/packages/web3-eth/test/unit/utils/watch_transaction_by_subscription.test.ts index 23c92c793a6..0b027b9dc14 100644 --- a/packages/web3-eth/test/unit/utils/watch_transaction_by_subscription.test.ts +++ b/packages/web3-eth/test/unit/utils/watch_transaction_by_subscription.test.ts @@ -27,13 +27,11 @@ import { } from '../rpc_method_wrappers/fixtures/send_signed_transaction'; import { blockMockResult } from '../../fixtures/transactions_data'; - jest.mock('web3-providers-ws'); const testMessage = 'Title: %s\ninputSignedTransaction: %s\nexpectedTransactionHash: %s\nexpectedTransactionReceipt: %s\n'; - describe('watchTransactionBySubscription', () => { const CONFIRMATION_BLOCKS = 5; describe('should revert to polling in cases where getting by subscription did not workout', () => { @@ -41,34 +39,29 @@ describe('watchTransactionBySubscription', () => { beforeEach(() => { web3Context = new Web3Context({ - provider: new WebSocketProvider('wss://localhost:8546'),} - ); + provider: new WebSocketProvider('wss://localhost:8546'), + }); (web3Context.provider as any).supportsSubscriptions = () => true; web3Context.transactionConfirmationBlocks = CONFIRMATION_BLOCKS; - web3Context.enableExperimentalFeatures.useSubscriptionWhenCheckingBlockTimeout = - true; - + web3Context.enableExperimentalFeatures.useSubscriptionWhenCheckingBlockTimeout = true; }); it.each(testData)( `should call getBlockByNumber if blockHeaderTimeout reached\n ${testMessage}`, - async (_, inputTransaction,) => { - + async (_, inputTransaction) => { let blockNum = 100; let ethGetBlockByNumberCount = 0; - web3Context.requestManager.send = jest.fn(async (request) => { - + web3Context.requestManager.send = jest.fn(async request => { if (request.method === 'eth_getBlockByNumber') { ethGetBlockByNumberCount += 1; - return Promise.resolve( - { ...blockMockResult.result, - number: (request as any).params[0] - }); + return Promise.resolve({ + ...blockMockResult.result, + number: (request as any).params[0], + }); } if (request.method === 'eth_call') { - - return Promise.resolve("0x"); + return Promise.resolve('0x'); } if (request.method === 'eth_blockNumber') { blockNum += 1; @@ -80,9 +73,9 @@ describe('watchTransactionBySubscription', () => { if (request.method === 'eth_getTransactionReceipt') { return Promise.resolve(expectedTransactionReceipt); } - + // eslint-disable-next-line @typescript-eslint/no-unsafe-return - return Promise.reject(new Error("Unknown Request")) as any; + return Promise.reject(new Error('Unknown Request')) as any; }); const promiEvent = rpcMethodWrappers.sendSignedTransaction( @@ -93,33 +86,35 @@ describe('watchTransactionBySubscription', () => { let confirmationsCount = 0; const confirmationPromise = new Promise((resolve, reject) => { - const handleConfirmation = (confirmation: { confirmations: bigint }) => { - confirmationsCount += 1; - - if (confirmation.confirmations >= CONFIRMATION_BLOCKS) { - resolve(); - } + confirmationsCount += 1; + + if (confirmation.confirmations >= CONFIRMATION_BLOCKS) { + resolve(); + } }; - + const handleError = (_error: any) => { - reject(); + reject(); }; - + promiEvent - .on('confirmation', handleConfirmation) - .on('error', handleError) - .then((res) => { - // eslint-disable-next-line jest/no-conditional-expect - expect(res).toBeDefined(); - }) - .catch(reject); - }); + .on('confirmation', handleConfirmation) + .on('error', handleError) + .then(res => { + // eslint-disable-next-line jest/no-conditional-expect + expect(res).toBeDefined(); + }) + .catch(reject); + }); // Wait for the confirmationPromise to resolve or timeout after 5 seconds let timeoutId; const timeout = new Promise((_res, reject) => { - timeoutId = setTimeout(() => reject(new Error('Timeout waiting for confirmations')), 500000); + timeoutId = setTimeout( + () => reject(new Error('Timeout waiting for confirmations')), + 500000, + ); }); await Promise.race([confirmationPromise, timeout]); @@ -128,10 +123,7 @@ describe('watchTransactionBySubscription', () => { expect(confirmationsCount).toBe(CONFIRMATION_BLOCKS); expect(ethGetBlockByNumberCount).toBe(CONFIRMATION_BLOCKS - 1); // means polling called getblock 4 times as first confirmation is receipt it self - - } + }, ); - - }); }); diff --git a/packages/web3-eth/test/unit/web3_eth_calculate_fee_data.test.ts b/packages/web3-eth/test/unit/web3_eth_calculate_fee_data.test.ts index ed1b504a3be..58cf6deb6fd 100644 --- a/packages/web3-eth/test/unit/web3_eth_calculate_fee_data.test.ts +++ b/packages/web3-eth/test/unit/web3_eth_calculate_fee_data.test.ts @@ -49,9 +49,9 @@ describe('Web3Eth.calculateFeeData', () => { jest.spyOn(ethRpcMethods, 'getBlockByNumber').mockReturnValueOnce({ baseFeePerGas } as any); jest.spyOn(ethRpcMethods, 'getGasPrice').mockReturnValueOnce(gasPrice as any); // eslint-disable-next-line @typescript-eslint/no-unsafe-call - jest - .spyOn(ethRpcMethods, 'getMaxPriorityFeePerGas') - .mockReturnValueOnce(maxPriorityFeePerGas as any); + jest.spyOn(ethRpcMethods, 'getMaxPriorityFeePerGas').mockReturnValueOnce( + maxPriorityFeePerGas as any, + ); const feeData = await web3Eth.calculateFeeData(baseFeePerGasFactor, maxPriorityFeePerGas); expect(feeData).toMatchObject({ diff --git a/packages/web3-eth/test/unit/web3_eth_methods_no_parameters.test.ts b/packages/web3-eth/test/unit/web3_eth_methods_no_parameters.test.ts index a66a1ecdd46..c01ae8f0fc6 100644 --- a/packages/web3-eth/test/unit/web3_eth_methods_no_parameters.test.ts +++ b/packages/web3-eth/test/unit/web3_eth_methods_no_parameters.test.ts @@ -79,7 +79,9 @@ describe('web3_eth_methods_no_parameters', () => { it('getMaxPriorityFeePerGas', async () => { await web3Eth.getMaxPriorityFeePerGas(); - expect(ethRpcMethods.getMaxPriorityFeePerGas).toHaveBeenCalledWith(web3Eth.requestManager); + expect(ethRpcMethods.getMaxPriorityFeePerGas).toHaveBeenCalledWith( + web3Eth.requestManager, + ); }); }); }); diff --git a/packages/web3-eth/test/unit/web3_eth_methods_with_parameters.test.ts b/packages/web3-eth/test/unit/web3_eth_methods_with_parameters.test.ts index 76d753bde4b..7186e2e63de 100644 --- a/packages/web3-eth/test/unit/web3_eth_methods_with_parameters.test.ts +++ b/packages/web3-eth/test/unit/web3_eth_methods_with_parameters.test.ts @@ -65,17 +65,17 @@ describe('web3_eth_methods_with_parameters', () => { it('should set and unset the transactionMiddleware correctly', () => { const mockTransactionMiddleware: TransactionMiddleware = { - processTransaction: jest.fn(), + processTransaction: jest.fn(), }; - + web3Eth.setTransactionMiddleware(mockTransactionMiddleware); - + expect(web3Eth.getTransactionMiddleware()).toBe(mockTransactionMiddleware); web3Eth.setTransactionMiddleware(undefined as any); expect(web3Eth.getTransactionMiddleware()).toBeUndefined(); - }); + }); describe('should call RPC method with expected parameters', () => { describe('only has returnFormat parameter', () => { diff --git a/packages/web3-net/CHANGELOG.md b/packages/web3-net/CHANGELOG.md index 5e7ea9073b3..ff3ca87f519 100644 --- a/packages/web3-net/CHANGELOG.md +++ b/packages/web3-net/CHANGELOG.md @@ -147,4 +147,4 @@ Documentation: - `defaultReturnFormat` was added to all methods that have `ReturnType` param. (#6947) -## [Unreleased] \ No newline at end of file +## [Unreleased] diff --git a/packages/web3-net/test/fixtures/rpc_method_wrappers.ts b/packages/web3-net/test/fixtures/rpc_method_wrappers.ts index 701a966e67e..0e76bcdd39b 100644 --- a/packages/web3-net/test/fixtures/rpc_method_wrappers.ts +++ b/packages/web3-net/test/fixtures/rpc_method_wrappers.ts @@ -29,4 +29,4 @@ export const getPeerCountValidData: [DataFormat, any, any][] = [ [{ number: FMT_NUMBER.STR, bytes: FMT_BYTES.HEX }, '0x2', '2'], [{ number: FMT_NUMBER.NUMBER, bytes: FMT_BYTES.HEX }, '0x2', 2], [{ number: FMT_NUMBER.BIGINT, bytes: FMT_BYTES.HEX }, '0x2', BigInt('2')], -]; \ No newline at end of file +]; diff --git a/packages/web3-net/test/integration/web3_net.test.ts b/packages/web3-net/test/integration/web3_net.test.ts index 60b0438f555..1d79a06b29d 100644 --- a/packages/web3-net/test/integration/web3_net.test.ts +++ b/packages/web3-net/test/integration/web3_net.test.ts @@ -40,8 +40,8 @@ describe('Web3 net', () => { it('should be able to get id', async () => { const networkId = await web3Net.getId(); - // eslint-disable-next-line jest/no-conditional-expect - expect(networkId).toBe(BigInt(1337)); + // eslint-disable-next-line jest/no-conditional-expect + expect(networkId).toBe(BigInt(1337)); }); it('should be able to listen', async () => { diff --git a/packages/web3-net/test/unit/rpc_method_wrappers.test.ts b/packages/web3-net/test/unit/rpc_method_wrappers.test.ts index e3f5bb9ad2a..47d014e2b3e 100644 --- a/packages/web3-net/test/unit/rpc_method_wrappers.test.ts +++ b/packages/web3-net/test/unit/rpc_method_wrappers.test.ts @@ -56,7 +56,6 @@ describe('rpc_method_wrappers', () => { }, ); }); - it('isListening', async () => { await isListening(web3Net); diff --git a/packages/web3-providers-http/CHANGELOG.md b/packages/web3-providers-http/CHANGELOG.md index 2169826c339..5705b0ae18d 100644 --- a/packages/web3-providers-http/CHANGELOG.md +++ b/packages/web3-providers-http/CHANGELOG.md @@ -133,6 +133,6 @@ Documentation: ### Added -- Added `statusCode` of response in ResponseError, `statusCode` is optional property in ResponseError. +- Added `statusCode` of response in ResponseError, `statusCode` is optional property in ResponseError. -## [Unreleased] \ No newline at end of file +## [Unreleased] diff --git a/packages/web3-providers-http/src/index.ts b/packages/web3-providers-http/src/index.ts index d596d1251f6..984be60033b 100644 --- a/packages/web3-providers-http/src/index.ts +++ b/packages/web3-providers-http/src/index.ts @@ -78,10 +78,10 @@ export default class HttpProvider< }, body: JSON.stringify(payload), }); - if (!response.ok) { + if (!response.ok) { // eslint-disable-next-line @typescript-eslint/no-unsafe-argument throw new ResponseError(await response.json(), undefined, undefined, response.status); - }; + } return (await response.json()) as JsonRpcResponseWithResult; } diff --git a/packages/web3-providers-ipc/CHANGELOG.md b/packages/web3-providers-ipc/CHANGELOG.md index 6f75b93995e..263a1241ea5 100644 --- a/packages/web3-providers-ipc/CHANGELOG.md +++ b/packages/web3-providers-ipc/CHANGELOG.md @@ -135,4 +135,4 @@ Documentation: - Fixed bug in chunks processing logic (#6496) -## [Unreleased] \ No newline at end of file +## [Unreleased] diff --git a/packages/web3-providers-ws/CHANGELOG.md b/packages/web3-providers-ws/CHANGELOG.md index 3dbc8c54694..61047ecb90a 100644 --- a/packages/web3-providers-ws/CHANGELOG.md +++ b/packages/web3-providers-ws/CHANGELOG.md @@ -134,4 +134,4 @@ Documentation: - Update dependancies (#7109) -## [Unreleased] \ No newline at end of file +## [Unreleased] diff --git a/packages/web3-providers-ws/test/integration/geth_fault_tolerance.test.ts b/packages/web3-providers-ws/test/integration/geth_fault_tolerance.test.ts index a047666dccb..fc9cb89d2ea 100644 --- a/packages/web3-providers-ws/test/integration/geth_fault_tolerance.test.ts +++ b/packages/web3-providers-ws/test/integration/geth_fault_tolerance.test.ts @@ -15,11 +15,15 @@ You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see . */ -import { - HttpProvider -} from 'web3-providers-http'; +import { HttpProvider } from 'web3-providers-http'; import { ConnectionNotOpenError } from 'web3-errors'; -import { EthExecutionAPI, Web3APIPayload, SocketRequestItem, JsonRpcResponse, ProviderRpcError } from 'web3-types'; +import { + EthExecutionAPI, + Web3APIPayload, + SocketRequestItem, + JsonRpcResponse, + ProviderRpcError, +} from 'web3-types'; import { Web3DeferredPromise } from 'web3-utils'; import { waitForSocketConnect, @@ -38,14 +42,14 @@ describeIf(getSystemTestBackend() === 'geth' && isWs)('geth tests', () => { await httpProvider.request({ method: 'admin_startWS', id: '1', - jsonrpc: '2.0' - }) - } + jsonrpc: '2.0', + }); + }; const closeServer = async () => { await httpProvider.request({ method: 'admin_stopWS', id: '2', - jsonrpc: '2.0' + jsonrpc: '2.0', }); }; const jsonRpcPayload = { @@ -56,30 +60,29 @@ describeIf(getSystemTestBackend() === 'geth' && isWs)('geth tests', () => { // simulate abrupt disconnection, ganache server always closes with code 1000 so we need to simulate closing with different error code const changeCloseCode = async (webSocketProvider: WebSocketProvider) => - new Promise(resolve => { - // @ts-expect-error replace close handler - // eslint-disable-next-line @typescript-eslint/no-unused-vars, no-param-reassign - webSocketProvider._onCloseHandler = (_: CloseEvent) => { - // @ts-expect-error replace close event - webSocketProvider._onCloseEvent({ code: 1003 }); - }; - // @ts-expect-error run protected method - webSocketProvider._removeSocketListeners(); - // @ts-expect-error run protected method - webSocketProvider._addSocketListeners(); - resolve(); - }); + new Promise(resolve => { + // @ts-expect-error replace close handler + // eslint-disable-next-line @typescript-eslint/no-unused-vars, no-param-reassign + webSocketProvider._onCloseHandler = (_: CloseEvent) => { + // @ts-expect-error replace close event + webSocketProvider._onCloseEvent({ code: 1003 }); + }; + // @ts-expect-error run protected method + webSocketProvider._removeSocketListeners(); + // @ts-expect-error run protected method + webSocketProvider._addSocketListeners(); + resolve(); + }); beforeAll(() => { httpProvider = new HttpProvider(httpProviderUrl); - }) + }); beforeEach(async () => { await openServer(); - }) - afterAll(async() => { + }); + afterAll(async () => { await closeServer(); - }) - + }); describe('WebSocketProvider fault tests - geth', () => { it('"error" when there is no connection', async () => { @@ -104,11 +107,15 @@ describeIf(getSystemTestBackend() === 'geth' && isWs)('geth tests', () => { it('"discconect" handler fires if the server closes', async () => { await openServer(); const err = jest.fn(); - const webSocketProvider = new WebSocketProvider(wsProviderUrl, {}, { - delay: 100, - autoReconnect: false, - maxAttempts: 1, - }); + const webSocketProvider = new WebSocketProvider( + wsProviderUrl, + {}, + { + delay: 100, + autoReconnect: false, + maxAttempts: 1, + }, + ); await waitForSocketConnect(webSocketProvider); @@ -137,7 +144,7 @@ describeIf(getSystemTestBackend() === 'geth' && isWs)('geth tests', () => { }); webSocketProvider.once('disconnect', () => { mockDisconnect(); - }) + }); webSocketProvider.disconnect(); expect(mockReject).toHaveBeenCalledTimes(0); expect(mockDisconnect).toHaveBeenCalledTimes(1); @@ -287,10 +294,13 @@ describeIf(getSystemTestBackend() === 'geth' && isWs)('geth tests', () => { // when server is not listening send request, and expect that lib will try to reconnect and at end will throw con not open error await expect( - webSocketProvider.request( - {"method":"eth_getBlockByNumber","params":["0xc5043f",false],"id":1,"jsonrpc":"2.0"} - )) - .rejects.toThrow(ConnectionNotOpenError); + webSocketProvider.request({ + method: 'eth_getBlockByNumber', + params: ['0xc5043f', false], + id: 1, + jsonrpc: '2.0', + }), + ).rejects.toThrow(ConnectionNotOpenError); expect(mockCallBack).toHaveBeenCalled(); webSocketProvider.disconnect(); @@ -411,4 +421,4 @@ describeIf(getSystemTestBackend() === 'geth' && isWs)('geth tests', () => { await closeServer(); }); }); -}); \ No newline at end of file +}); diff --git a/packages/web3-providers-ws/test/integration/web_socket_provider_integration.test.ts b/packages/web3-providers-ws/test/integration/web_socket_provider_integration.test.ts index ccc1a97714f..3ca823acb6b 100644 --- a/packages/web3-providers-ws/test/integration/web_socket_provider_integration.test.ts +++ b/packages/web3-providers-ws/test/integration/web_socket_provider_integration.test.ts @@ -139,15 +139,18 @@ describeIf(isWs)('WebSocketProvider - implemented methods', () => { }); it('should error when no connection is established', async () => { - const wsProvider = new WebSocketProvider("ws://localhost:999",{}, { autoReconnect: false }); + const wsProvider = new WebSocketProvider( + 'ws://localhost:999', + {}, + { autoReconnect: false }, + ); let errored = false; - try{ + try { await wsProvider.request(jsonRpcPayload); // should not be able to reach here - - }catch(e){ + } catch (e) { // eslint-disable-next-line jest/no-conditional-expect - expect((e as any).message).toBe('Connection not open') + expect((e as any).message).toBe('Connection not open'); errored = true; } expect(errored).toBe(true); diff --git a/packages/web3-providers-ws/test/unit/__mocks__/isomorphic-ws.ts b/packages/web3-providers-ws/test/unit/__mocks__/isomorphic-ws.ts index d5e9d79cef9..0f5f07cbb7f 100644 --- a/packages/web3-providers-ws/test/unit/__mocks__/isomorphic-ws.ts +++ b/packages/web3-providers-ws/test/unit/__mocks__/isomorphic-ws.ts @@ -24,7 +24,7 @@ export default class WebSocket extends EventEmitter { public OPEN = 1; public constructor() { - super() + super(); // eslint-disable-next-line @typescript-eslint/no-unsafe-call // Connected state this.readyState = 1; @@ -43,11 +43,10 @@ export default class WebSocket extends EventEmitter { } public addEventListener(_event: any, _cb: () => void) { - this.on(_event, _cb) - + this.on(_event, _cb); } public removeEventListener(_event: any, _cb: () => void) { - this.off(_event, _cb) + this.off(_event, _cb); } } diff --git a/packages/web3-providers-ws/test/unit/check_implementation.test.ts b/packages/web3-providers-ws/test/unit/check_implementation.test.ts index 138855b9509..a437b1c7488 100644 --- a/packages/web3-providers-ws/test/unit/check_implementation.test.ts +++ b/packages/web3-providers-ws/test/unit/check_implementation.test.ts @@ -92,7 +92,7 @@ describe('WebSocketProvider', () => { const _onDisconnect = jest.fn(); // @ts-expect-error mock method ws._socketConnection.close = jest.fn(); - + // @ts-expect-error mock method ws._clearQueues = _clearQueues; // @ts-expect-error mock method @@ -126,7 +126,7 @@ describe('WebSocketProvider', () => { const ws = new WebSocketProvider('ws://localhost:8545'); // @ts-expect-error mock method ws._socketConnection.listeners = () => { - throw new Error('error'); + throw new Error('error'); }; const addEventListener = jest.fn(); // @ts-expect-error mock method @@ -147,6 +147,6 @@ describe('WebSocketProvider', () => { expect(removeEventListener).toHaveBeenCalledWith('open', ws._onOpenHandler); // @ts-expect-error mock method expect(removeEventListener).toHaveBeenCalledWith('close', ws._onCloseHandler); - }); + }); }); }); diff --git a/packages/web3-rpc-methods/CHANGELOG.md b/packages/web3-rpc-methods/CHANGELOG.md index 050b6451539..5cb444b1a83 100644 --- a/packages/web3-rpc-methods/CHANGELOG.md +++ b/packages/web3-rpc-methods/CHANGELOG.md @@ -144,4 +144,4 @@ Documentation: - Change `estimateGas` method to add possibility pass Transaction type (#7000) -## [Unreleased] \ No newline at end of file +## [Unreleased] diff --git a/packages/web3-rpc-methods/test/unit/eth_rpc_methods/get_uncle_by_block_number.test.ts b/packages/web3-rpc-methods/test/unit/eth_rpc_methods/get_uncle_by_block_number.test.ts index 93e8a633582..208a39ce5e1 100644 --- a/packages/web3-rpc-methods/test/unit/eth_rpc_methods/get_uncle_by_block_number.test.ts +++ b/packages/web3-rpc-methods/test/unit/eth_rpc_methods/get_uncle_by_block_number.test.ts @@ -31,12 +31,10 @@ describe('getUncleByBlockNumberAndIndex', () => { }); it('should call requestManager.send with eth_getUncleByBlockNumberAndIndex method', async () => { - await ethRpcMethods.getUncleByBlockNumberAndIndex(requestManager, 0, '1' ); - expect(requestManagerSendSpy).toHaveBeenCalledWith({ - method: 'eth_getUncleByBlockNumberAndIndex', - params: [0,'1'], - }); - }, - ); - + await ethRpcMethods.getUncleByBlockNumberAndIndex(requestManager, 0, '1'); + expect(requestManagerSendSpy).toHaveBeenCalledWith({ + method: 'eth_getUncleByBlockNumberAndIndex', + params: [0, '1'], + }); + }); }); diff --git a/packages/web3-rpc-methods/test/unit/personal_rpc_methods/eth_personal.test.ts b/packages/web3-rpc-methods/test/unit/personal_rpc_methods/eth_personal.test.ts index a487df07964..73bbe20eb4e 100644 --- a/packages/web3-rpc-methods/test/unit/personal_rpc_methods/eth_personal.test.ts +++ b/packages/web3-rpc-methods/test/unit/personal_rpc_methods/eth_personal.test.ts @@ -38,7 +38,7 @@ describe('Eth Personal', () => { }); it('should call requestManager.send with personal_newAccount method', async () => { - const pass = "ABC123"; + const pass = 'ABC123'; await personalRpcMethods.newAccount(requestManager, pass); expect(requestManagerSendSpy).toHaveBeenCalledWith({ method: 'personal_newAccount', @@ -47,8 +47,8 @@ describe('Eth Personal', () => { }); it('should call requestManager.send with personal_unlockAccount method', async () => { - const pass = "ABC123"; - const address = "0x4106486FB42F3Abf07CC07ef5DEE38f60319e789"; + const pass = 'ABC123'; + const address = '0x4106486FB42F3Abf07CC07ef5DEE38f60319e789'; const duration = 100; await personalRpcMethods.unlockAccount(requestManager, address, pass, duration); @@ -59,9 +59,9 @@ describe('Eth Personal', () => { }); it('should call requestManager.send with personal_lockAccount method', async () => { - const address = "0x4106486FB42F3Abf07CC07ef5DEE38f60319e789"; + const address = '0x4106486FB42F3Abf07CC07ef5DEE38f60319e789'; - await personalRpcMethods.lockAccount(requestManager, address ); + await personalRpcMethods.lockAccount(requestManager, address); expect(requestManagerSendSpy).toHaveBeenCalledWith({ method: 'personal_lockAccount', @@ -70,76 +70,77 @@ describe('Eth Personal', () => { }); it('should call requestManager.send with personal_importRawKey method', async () => { - const passPhrase = "123456"; - const keyData = "abe40cb08850da918ee951b237fa87946499b2d8643e4aa12b0610b050c731f6"; - await personalRpcMethods.importRawKey(requestManager, keyData, passPhrase ); + const passPhrase = '123456'; + const keyData = 'abe40cb08850da918ee951b237fa87946499b2d8643e4aa12b0610b050c731f6'; + await personalRpcMethods.importRawKey(requestManager, keyData, passPhrase); expect(requestManagerSendSpy).toHaveBeenCalledWith({ method: 'personal_importRawKey', - params: [keyData,passPhrase], + params: [keyData, passPhrase], }); }); it('should call requestManager.send with personal_sendTransaction method', async () => { - const passPhrase = "123456"; + const passPhrase = '123456'; const tx = { - from: "0x0d4aa485ecbc499c70860feb7e5aaeaf5fd8172e", - gasPrice: "20000", - gas: "21000", - to: "0x4106486FB42F3Abf07CC07ef5DEE38f60319e789", - value: "1000000", - data: "", - nonce: 0, - }; - await personalRpcMethods.sendTransaction(requestManager, tx, passPhrase ); + from: '0x0d4aa485ecbc499c70860feb7e5aaeaf5fd8172e', + gasPrice: '20000', + gas: '21000', + to: '0x4106486FB42F3Abf07CC07ef5DEE38f60319e789', + value: '1000000', + data: '', + nonce: 0, + }; + await personalRpcMethods.sendTransaction(requestManager, tx, passPhrase); expect(requestManagerSendSpy).toHaveBeenCalledWith({ method: 'personal_sendTransaction', - params: [tx,passPhrase], + params: [tx, passPhrase], }); }); it('should call requestManager.send with personal_signTransaction method', async () => { - const passPhrase = "123456"; + const passPhrase = '123456'; const tx = { - from: "0x0d4aa485ecbc499c70860feb7e5aaeaf5fd8172e", - gasPrice: "20000", - gas: "21000", - to: "0x4106486FB42F3Abf07CC07ef5DEE38f60319e789", - value: "1000000", - data: "", - nonce: 0, - }; - await personalRpcMethods.signTransaction(requestManager, tx, passPhrase ); + from: '0x0d4aa485ecbc499c70860feb7e5aaeaf5fd8172e', + gasPrice: '20000', + gas: '21000', + to: '0x4106486FB42F3Abf07CC07ef5DEE38f60319e789', + value: '1000000', + data: '', + nonce: 0, + }; + await personalRpcMethods.signTransaction(requestManager, tx, passPhrase); expect(requestManagerSendSpy).toHaveBeenCalledWith({ method: 'personal_signTransaction', - params: [tx,passPhrase], + params: [tx, passPhrase], }); }); it('should call requestManager.send with personal_sign method', async () => { - const data = "Hello world"; - const address = "0x0D4Aa485ECbC499c70860fEb7e5AaeAf5fd8172E"; - const pass = "123456"; + const data = 'Hello world'; + const address = '0x0D4Aa485ECbC499c70860fEb7e5AaeAf5fd8172E'; + const pass = '123456'; - await personalRpcMethods.sign(requestManager, data,address,pass); + await personalRpcMethods.sign(requestManager, data, address, pass); expect(requestManagerSendSpy).toHaveBeenCalledWith({ method: 'personal_sign', - params: [ data,address,pass], + params: [data, address, pass], }); }); it('should call requestManager.send with personal_ecRecover method', async () => { - const data = "Hello world"; - const signature = "0x5d21d01b3198ac34d0585a9d76c4d1c8123e5e06746c8962318a1c08ffb207596e6fce4a6f377b7c0fc98c5f646cd73438c80e8a1a95cbec55a84c2889dca0301b"; - - await personalRpcMethods.ecRecover(requestManager,data, signature); + const data = 'Hello world'; + const signature = + '0x5d21d01b3198ac34d0585a9d76c4d1c8123e5e06746c8962318a1c08ffb207596e6fce4a6f377b7c0fc98c5f646cd73438c80e8a1a95cbec55a84c2889dca0301b'; + + await personalRpcMethods.ecRecover(requestManager, data, signature); expect(requestManagerSendSpy).toHaveBeenCalledWith({ method: 'personal_ecRecover', - params: [ data, signature], + params: [data, signature], }); }); }); diff --git a/packages/web3-rpc-providers/CHANGELOG.md b/packages/web3-rpc-providers/CHANGELOG.md index 4943590a855..a9e2c2a8b79 100644 --- a/packages/web3-rpc-providers/CHANGELOG.md +++ b/packages/web3-rpc-providers/CHANGELOG.md @@ -39,17 +39,17 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added -- RC release +- RC release ## [1.0.0.rc.1] ### Added - - When error is returned with code 429, throw rate limit error (#7102) +- When error is returned with code 429, throw rate limit error (#7102) ### Changed - - Change request return type `Promise` to `Promise>` (#7102) +- Change request return type `Promise` to `Promise>` (#7102) ## [1.0.0-rc.2] @@ -58,4 +58,4 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Updated rate limit error of QuickNode provider for HTTP transport - Added optional `HttpProviderOptions | SocketOptions` in `Web3ExternalProvider` and `QuickNodeProvider` for provider configs -## [Unreleased] \ No newline at end of file +## [Unreleased] diff --git a/packages/web3-rpc-providers/README.md b/packages/web3-rpc-providers/README.md index 59284dbb29b..66ba07a4f87 100644 --- a/packages/web3-rpc-providers/README.md +++ b/packages/web3-rpc-providers/README.md @@ -11,7 +11,6 @@ This is a sub-package of [web3.js][repo]. - ## Installation You can install the package either using [NPM](https://www.npmjs.com/package/web3-rpc-providers) or using [Yarn](https://yarnpkg.com/package/web3-rpc-providers) diff --git a/packages/web3-rpc-providers/src/errors.ts b/packages/web3-rpc-providers/src/errors.ts index d698fbb66ab..0d849789f00 100644 --- a/packages/web3-rpc-providers/src/errors.ts +++ b/packages/web3-rpc-providers/src/errors.ts @@ -24,7 +24,10 @@ export class QuickNodeRateLimitError extends BaseWeb3Error { public code = ERR_QUICK_NODE_RATE_LIMIT; public constructor(error?: Error) { - super(`You've reach the rate limit of free RPC calls from our Partner Quick Nodes. There are two options you can either create a paid Quick Nodes account and get 20% off for 2 months using WEB3JS referral code, or use Free public RPC endpoint.`, error); + super( + `You've reach the rate limit of free RPC calls from our Partner Quick Nodes. There are two options you can either create a paid Quick Nodes account and get 20% off for 2 months using WEB3JS referral code, or use Free public RPC endpoint.`, + error, + ); } } @@ -36,4 +39,4 @@ export class ProviderConfigOptionsError extends BaseWeb3Error { super(`Invalid provider config options given for ${msg}`); } } -/* eslint-enable max-classes-per-file */ \ No newline at end of file +/* eslint-enable max-classes-per-file */ diff --git a/packages/web3-rpc-providers/src/index.ts b/packages/web3-rpc-providers/src/index.ts index 637cdae4cc0..577d8e6b960 100644 --- a/packages/web3-rpc-providers/src/index.ts +++ b/packages/web3-rpc-providers/src/index.ts @@ -23,4 +23,4 @@ export * from './web3_provider.js'; export * from './errors.js'; // default providers -export const mainnet = new QuickNodeProvider(); \ No newline at end of file +export const mainnet = new QuickNodeProvider(); diff --git a/packages/web3-rpc-providers/src/types.ts b/packages/web3-rpc-providers/src/types.ts index e23714977c1..9fda306ae0d 100644 --- a/packages/web3-rpc-providers/src/types.ts +++ b/packages/web3-rpc-providers/src/types.ts @@ -15,39 +15,39 @@ You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see . */ -import {ClientOptions, ClientRequestArgs} from "web3-providers-ws"; +import { ClientOptions, ClientRequestArgs } from 'web3-providers-ws'; import { ReconnectOptions } from 'web3-utils'; export enum Transport { - HTTPS = "https", - WebSocket = "wss" -}; + HTTPS = 'https', + WebSocket = 'wss', +} export enum Network { - ETH_MAINNET = "eth_mainnet", - ETH_GOERLI = "eth_goerli", - ETH_SEPOLIA = "eth_sepolia", - ETH_HOLESKY = "eth_holesky", + ETH_MAINNET = 'eth_mainnet', + ETH_GOERLI = 'eth_goerli', + ETH_SEPOLIA = 'eth_sepolia', + ETH_HOLESKY = 'eth_holesky', - POLYGON_MAINNET= "polygon_mainnet", - POLYGON_MUMBAI= "polygon_mumbai", - POLYGON_AMONY= "polygon_amony", + POLYGON_MAINNET = 'polygon_mainnet', + POLYGON_MUMBAI = 'polygon_mumbai', + POLYGON_AMONY = 'polygon_amony', - ARBITRUM_MAINNET = "arbitrum_mainnet", - ARBITRUM_SEPOLIA = "arbitrum_sepolia", + ARBITRUM_MAINNET = 'arbitrum_mainnet', + ARBITRUM_SEPOLIA = 'arbitrum_sepolia', - BASE_MAINNET = "base_mainnet", - BASE_SEPOLIA = "base_sepolia", + BASE_MAINNET = 'base_mainnet', + BASE_SEPOLIA = 'base_sepolia', - OPTIMISM_MAINNET = "optimism_mainnet", - OPTIMISM_SEPOLIA = "optimism_sepolia", + OPTIMISM_MAINNET = 'optimism_mainnet', + OPTIMISM_SEPOLIA = 'optimism_sepolia', - BNB_MAINNET = "bnb_mainnet", - BNB_TESTNET = "bnb_testnet" -}; + BNB_MAINNET = 'bnb_mainnet', + BNB_TESTNET = 'bnb_testnet', +} // Combining the ws types export type SocketOptions = { - socketOptions?: ClientOptions | ClientRequestArgs; - reconnectOptions?: Partial; -}; \ No newline at end of file + socketOptions?: ClientOptions | ClientRequestArgs; + reconnectOptions?: Partial; +}; diff --git a/packages/web3-rpc-providers/src/web3_provider.ts b/packages/web3-rpc-providers/src/web3_provider.ts index 498dec60433..922d8217256 100644 --- a/packages/web3-rpc-providers/src/web3_provider.ts +++ b/packages/web3-rpc-providers/src/web3_provider.ts @@ -15,20 +15,28 @@ You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see . */ -import HttpProvider, { HttpProviderOptions } from "web3-providers-http"; -import WebSocketProvider from "web3-providers-ws"; +import HttpProvider, { HttpProviderOptions } from 'web3-providers-http'; +import WebSocketProvider from 'web3-providers-ws'; import { - EthExecutionAPI, JsonRpcResult, ProviderConnectInfo, ProviderMessage, - ProviderRpcError, Web3APIMethod, Web3APIPayload, Web3APIReturnType, Web3APISpec, Web3BaseProvider, - Web3Eip1193ProviderEventCallback, - Web3ProviderEventCallback, - Web3ProviderMessageEventCallback, - Web3ProviderStatus, - JsonRpcResponseWithResult, -} from "web3-types"; -import { Eip1193Provider } from "web3-utils"; -import { Transport, Network, SocketOptions } from "./types.js"; -import { ProviderConfigOptionsError } from "./errors.js"; + EthExecutionAPI, + JsonRpcResult, + ProviderConnectInfo, + ProviderMessage, + ProviderRpcError, + Web3APIMethod, + Web3APIPayload, + Web3APIReturnType, + Web3APISpec, + Web3BaseProvider, + Web3Eip1193ProviderEventCallback, + Web3ProviderEventCallback, + Web3ProviderMessageEventCallback, + Web3ProviderStatus, + JsonRpcResponseWithResult, +} from 'web3-types'; +import { Eip1193Provider } from 'web3-utils'; +import { Transport, Network, SocketOptions } from './types.js'; +import { ProviderConfigOptionsError } from './errors.js'; /* This class can be used to create new providers only when there is custom logic required in each Request method like @@ -39,120 +47,167 @@ no additional logic implementation is required in the provider. */ export abstract class Web3ExternalProvider< - API extends Web3APISpec = EthExecutionAPI, + API extends Web3APISpec = EthExecutionAPI, > extends Eip1193Provider { - - public provider!: Web3BaseProvider; - public readonly transport: Transport; - - public abstract getRPCURL(network: Network, transport: Transport, token: string, host: string): string; - - public constructor( - network: Network, - transport: Transport, - token: string, - host: string, - providerConfigOptions?: HttpProviderOptions | SocketOptions) { - - super(); - - if(providerConfigOptions!== undefined && - transport === Transport.HTTPS && - !('providerOptions' in providerConfigOptions)){ - - throw new ProviderConfigOptionsError("HTTP Provider"); - } - else if(providerConfigOptions!== undefined && - transport === Transport.WebSocket && - !( 'socketOptions' in providerConfigOptions || - 'reconnectOptions' in providerConfigOptions - )){ - throw new ProviderConfigOptionsError("Websocket Provider"); - } - - this.transport = transport; - if (transport === Transport.HTTPS) { - this.provider = new HttpProvider( - this.getRPCURL(network, transport, token, host), - providerConfigOptions as HttpProviderOptions); - } - else if (transport === Transport.WebSocket) { - this.provider = new WebSocketProvider( - this.getRPCURL(network, transport, token, host), - (providerConfigOptions as SocketOptions)?.socketOptions, - (providerConfigOptions as SocketOptions)?.reconnectOptions); - } - } - - public async request< - Method extends Web3APIMethod, - ResultType = Web3APIReturnType, - >( - payload: Web3APIPayload, - requestOptions?: RequestInit, - ): Promise> { - - if (this.transport === Transport.HTTPS) { - return await ((this.provider as HttpProvider).request(payload, requestOptions)) as unknown as JsonRpcResponseWithResult; - } - - return (this.provider as WebSocketProvider).request(payload); - - } - - public getStatus(): Web3ProviderStatus { - return this.provider.getStatus(); - } - public supportsSubscriptions(): boolean { - return this.provider.supportsSubscriptions(); - } - public once(type: "disconnect", listener: Web3Eip1193ProviderEventCallback): void; - public once(type: string, listener: Web3Eip1193ProviderEventCallback | Web3ProviderEventCallback): void; - public once(type: "connect", listener: Web3Eip1193ProviderEventCallback): void; - public once(type: "chainChanged", listener: Web3Eip1193ProviderEventCallback): void; - public once(type: "accountsChanged", listener: Web3Eip1193ProviderEventCallback): void; - public once(_type: string, _listener: unknown): void { - if (this.provider?.once) - // eslint-disable-next-line @typescript-eslint/no-unsafe-argument - this.provider.once(_type, _listener as any); - } - public removeAllListeners?(_type: string): void { - if (this.provider?.removeAllListeners) - this.provider.removeAllListeners(_type); - } - public connect(): void { - if (this.provider?.connect) - this.provider.connect(); - } - public disconnect(_code?: number | undefined, _data?: string | undefined): void { - if (this.provider?.disconnect) - this.provider.disconnect(_code, _data); - } - public reset(): void { - if (this.provider?.reset) - this.provider.reset(); - } - - public on(type: "disconnect", listener: Web3Eip1193ProviderEventCallback): void; - public on(type: string, listener: Web3Eip1193ProviderEventCallback | Web3ProviderMessageEventCallback): void; - public on(type: string, listener: Web3Eip1193ProviderEventCallback | Web3ProviderMessageEventCallback): void; - public on(type: "connect", listener: Web3Eip1193ProviderEventCallback): void; - public on(type: "chainChanged", listener: Web3Eip1193ProviderEventCallback): void; - public on(type: "accountsChanged", listener: Web3Eip1193ProviderEventCallback): void; - public on(_type: unknown, _listener: unknown): void { - if (this.provider) - // eslint-disable-next-line @typescript-eslint/no-unsafe-argument - this.provider.on(_type as any, _listener as any); - } - public removeListener(type: "disconnect", listener: Web3Eip1193ProviderEventCallback): void; - public removeListener(type: string, listener: Web3Eip1193ProviderEventCallback | Web3ProviderEventCallback): void; - public removeListener(type: "connect", listener: Web3Eip1193ProviderEventCallback): void; - public removeListener(type: "chainChanged", listener: Web3Eip1193ProviderEventCallback): void; - public removeListener(type: "accountsChanged", listener: Web3Eip1193ProviderEventCallback): void; - public removeListener(_type: unknown, _listener: unknown): void { - if (this.provider) - // eslint-disable-next-line @typescript-eslint/no-unsafe-argument - this.provider.removeListener(_type as any, _listener as any); - } + public provider!: Web3BaseProvider; + public readonly transport: Transport; + + public abstract getRPCURL( + network: Network, + transport: Transport, + token: string, + host: string, + ): string; + + public constructor( + network: Network, + transport: Transport, + token: string, + host: string, + providerConfigOptions?: HttpProviderOptions | SocketOptions, + ) { + super(); + + if ( + providerConfigOptions !== undefined && + transport === Transport.HTTPS && + !('providerOptions' in providerConfigOptions) + ) { + throw new ProviderConfigOptionsError('HTTP Provider'); + } else if ( + providerConfigOptions !== undefined && + transport === Transport.WebSocket && + !( + 'socketOptions' in providerConfigOptions || + 'reconnectOptions' in providerConfigOptions + ) + ) { + throw new ProviderConfigOptionsError('Websocket Provider'); + } + + this.transport = transport; + if (transport === Transport.HTTPS) { + this.provider = new HttpProvider( + this.getRPCURL(network, transport, token, host), + providerConfigOptions as HttpProviderOptions, + ); + } else if (transport === Transport.WebSocket) { + this.provider = new WebSocketProvider( + this.getRPCURL(network, transport, token, host), + (providerConfigOptions as SocketOptions)?.socketOptions, + (providerConfigOptions as SocketOptions)?.reconnectOptions, + ); + } + } + + public async request< + Method extends Web3APIMethod, + ResultType = Web3APIReturnType, + >( + payload: Web3APIPayload, + requestOptions?: RequestInit, + ): Promise> { + if (this.transport === Transport.HTTPS) { + return (await (this.provider as HttpProvider).request( + payload, + requestOptions, + )) as unknown as JsonRpcResponseWithResult; + } + + return (this.provider as WebSocketProvider).request(payload); + } + + public getStatus(): Web3ProviderStatus { + return this.provider.getStatus(); + } + public supportsSubscriptions(): boolean { + return this.provider.supportsSubscriptions(); + } + public once( + type: 'disconnect', + listener: Web3Eip1193ProviderEventCallback, + ): void; + public once( + type: string, + listener: Web3Eip1193ProviderEventCallback | Web3ProviderEventCallback, + ): void; + public once( + type: 'connect', + listener: Web3Eip1193ProviderEventCallback, + ): void; + public once(type: 'chainChanged', listener: Web3Eip1193ProviderEventCallback): void; + public once( + type: 'accountsChanged', + listener: Web3Eip1193ProviderEventCallback, + ): void; + public once(_type: string, _listener: unknown): void { + if (this.provider?.once) + // eslint-disable-next-line @typescript-eslint/no-unsafe-argument + this.provider.once(_type, _listener as any); + } + public removeAllListeners?(_type: string): void { + if (this.provider?.removeAllListeners) this.provider.removeAllListeners(_type); + } + public connect(): void { + if (this.provider?.connect) this.provider.connect(); + } + public disconnect(_code?: number | undefined, _data?: string | undefined): void { + if (this.provider?.disconnect) this.provider.disconnect(_code, _data); + } + public reset(): void { + if (this.provider?.reset) this.provider.reset(); + } + + public on( + type: 'disconnect', + listener: Web3Eip1193ProviderEventCallback, + ): void; + public on( + type: string, + listener: + | Web3Eip1193ProviderEventCallback + | Web3ProviderMessageEventCallback, + ): void; + public on( + type: string, + listener: + | Web3Eip1193ProviderEventCallback + | Web3ProviderMessageEventCallback, + ): void; + public on( + type: 'connect', + listener: Web3Eip1193ProviderEventCallback, + ): void; + public on(type: 'chainChanged', listener: Web3Eip1193ProviderEventCallback): void; + public on(type: 'accountsChanged', listener: Web3Eip1193ProviderEventCallback): void; + public on(_type: unknown, _listener: unknown): void { + if (this.provider) + // eslint-disable-next-line @typescript-eslint/no-unsafe-argument + this.provider.on(_type as any, _listener as any); + } + public removeListener( + type: 'disconnect', + listener: Web3Eip1193ProviderEventCallback, + ): void; + public removeListener( + type: string, + listener: Web3Eip1193ProviderEventCallback | Web3ProviderEventCallback, + ): void; + public removeListener( + type: 'connect', + listener: Web3Eip1193ProviderEventCallback, + ): void; + public removeListener( + type: 'chainChanged', + listener: Web3Eip1193ProviderEventCallback, + ): void; + public removeListener( + type: 'accountsChanged', + listener: Web3Eip1193ProviderEventCallback, + ): void; + public removeListener(_type: unknown, _listener: unknown): void { + if (this.provider) + // eslint-disable-next-line @typescript-eslint/no-unsafe-argument + this.provider.removeListener(_type as any, _listener as any); + } } - diff --git a/packages/web3-rpc-providers/src/web3_provider_quicknode.ts b/packages/web3-rpc-providers/src/web3_provider_quicknode.ts index 459cf5d5d38..ae74fa49860 100644 --- a/packages/web3-rpc-providers/src/web3_provider_quicknode.ts +++ b/packages/web3-rpc-providers/src/web3_provider_quicknode.ts @@ -15,98 +15,106 @@ You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see . */ -import { EthExecutionAPI, JsonRpcResponseWithResult, Web3APIMethod, Web3APIPayload, Web3APIReturnType, Web3APISpec } from "web3-types"; -import { ResponseError } from "web3-errors"; -import { HttpProviderOptions } from "web3-providers-http"; -import { Transport, Network, SocketOptions } from "./types.js"; -import { Web3ExternalProvider } from "./web3_provider.js"; -import { QuickNodeRateLimitError } from "./errors.js"; +import { + EthExecutionAPI, + JsonRpcResponseWithResult, + Web3APIMethod, + Web3APIPayload, + Web3APIReturnType, + Web3APISpec, +} from 'web3-types'; +import { ResponseError } from 'web3-errors'; +import { HttpProviderOptions } from 'web3-providers-http'; +import { Transport, Network, SocketOptions } from './types.js'; +import { Web3ExternalProvider } from './web3_provider.js'; +import { QuickNodeRateLimitError } from './errors.js'; const isValid = (str: string) => str !== undefined && str.trim().length > 0; export class QuickNodeProvider< -API extends Web3APISpec = EthExecutionAPI, + API extends Web3APISpec = EthExecutionAPI, > extends Web3ExternalProvider { - - // eslint-disable-next-line default-param-last - public constructor( network: Network = Network.ETH_MAINNET, transport: Transport = Transport.HTTPS, token = "", host = "", providerConfigOptions?: HttpProviderOptions | SocketOptions) { - - super(network, transport, token, host, providerConfigOptions); - - } - - public async request< - Method extends Web3APIMethod, - ResultType = Web3APIReturnType, - >( - payload: Web3APIPayload, - requestOptions?: RequestInit, - ): Promise> { - - try { - return await super.request(payload, requestOptions); - } catch (error) { - if (error instanceof ResponseError && error.statusCode === 429){ - throw new QuickNodeRateLimitError(error); - } - throw error; - } - } - - // eslint-disable-next-line class-methods-use-this - public getRPCURL(network: Network, - transport: Transport, - _token: string, - _host: string) { - - let host = ""; - let token = ""; - - switch (network) { - case Network.ETH_MAINNET: - host = isValid(_host) ? _host : "powerful-holy-bush.quiknode.pro"; - token = isValid(_token) ? _token : "3240624a343867035925ff7561eb60dfdba2a668"; - break; - case Network.ETH_SEPOLIA: - host = isValid(_host) ? _host : "dimensional-fabled-glitter.ethereum-sepolia.quiknode.pro"; - token = isValid(_token) ? _token : "382a3b5a4b938f2d6e8686c19af4b22921fde2cd"; - break - case Network.ETH_HOLESKY: - host = isValid(_host) ? _host : "yolo-morning-card.ethereum-holesky.quiknode.pro"; - token = isValid(_token) ? _token : "481ebe70638c4dcf176af617a16d02ab866b9af9"; - break; - - case Network.ARBITRUM_MAINNET: - host = isValid(_host) ? _host : "autumn-divine-dinghy.arbitrum-mainnet.quiknode.pro"; - token = isValid(_token) ? _token : "a5d7bfbf60b5ae9ce3628e53d69ef50d529e9a8c"; - break; - case Network.ARBITRUM_SEPOLIA: - host = isValid(_host) ? _host : "few-patient-pond.arbitrum-sepolia.quiknode.pro"; - token = isValid(_token) ? _token : "3be985450970628c860b959c65cd2642dcafe53c"; - break; - - case Network.BNB_MAINNET: - host = isValid(_host) ? _host : "purple-empty-reel.bsc.quiknode.pro"; - token = isValid(_token) ? _token : "ebf6c532961e21f092ff2facce1ec4c89c540158"; - break; - case Network.BNB_TESTNET: - host = isValid(_host) ? _host : "floral-rough-scion.bsc-testnet.quiknode.pro"; - token = isValid(_token) ? _token : "5b297e5acff5f81f4c37ebf6f235f7299b6f9d28"; - break; - - case Network.POLYGON_MAINNET: - host = isValid(_host) ? _host : "small-chaotic-moon.matic.quiknode.pro"; - token = isValid(_token) ? _token : "847569f8a017e84d985e10d0f44365d965a951f1"; - break; - case Network.POLYGON_AMONY: - host = isValid(_host) ? _host : "prettiest-side-shape.matic-amoy.quiknode.pro"; - token = isValid(_token) ? _token : "79a9476eea661d4f82de614db1d8a895b14b881c"; - break; - default: - throw new Error("Network info not avalible."); - } - - return `${transport}://${host}/${token}`; - } + // eslint-disable-next-line default-param-last + public constructor( + network: Network = Network.ETH_MAINNET, + transport: Transport = Transport.HTTPS, + token = '', + host = '', + providerConfigOptions?: HttpProviderOptions | SocketOptions, + ) { + super(network, transport, token, host, providerConfigOptions); + } + + public async request< + Method extends Web3APIMethod, + ResultType = Web3APIReturnType, + >( + payload: Web3APIPayload, + requestOptions?: RequestInit, + ): Promise> { + try { + return await super.request(payload, requestOptions); + } catch (error) { + if (error instanceof ResponseError && error.statusCode === 429) { + throw new QuickNodeRateLimitError(error); + } + throw error; + } + } + + // eslint-disable-next-line class-methods-use-this + public getRPCURL(network: Network, transport: Transport, _token: string, _host: string) { + let host = ''; + let token = ''; + + switch (network) { + case Network.ETH_MAINNET: + host = isValid(_host) ? _host : 'powerful-holy-bush.quiknode.pro'; + token = isValid(_token) ? _token : '3240624a343867035925ff7561eb60dfdba2a668'; + break; + case Network.ETH_SEPOLIA: + host = isValid(_host) + ? _host + : 'dimensional-fabled-glitter.ethereum-sepolia.quiknode.pro'; + token = isValid(_token) ? _token : '382a3b5a4b938f2d6e8686c19af4b22921fde2cd'; + break; + case Network.ETH_HOLESKY: + host = isValid(_host) ? _host : 'yolo-morning-card.ethereum-holesky.quiknode.pro'; + token = isValid(_token) ? _token : '481ebe70638c4dcf176af617a16d02ab866b9af9'; + break; + + case Network.ARBITRUM_MAINNET: + host = isValid(_host) + ? _host + : 'autumn-divine-dinghy.arbitrum-mainnet.quiknode.pro'; + token = isValid(_token) ? _token : 'a5d7bfbf60b5ae9ce3628e53d69ef50d529e9a8c'; + break; + case Network.ARBITRUM_SEPOLIA: + host = isValid(_host) ? _host : 'few-patient-pond.arbitrum-sepolia.quiknode.pro'; + token = isValid(_token) ? _token : '3be985450970628c860b959c65cd2642dcafe53c'; + break; + + case Network.BNB_MAINNET: + host = isValid(_host) ? _host : 'purple-empty-reel.bsc.quiknode.pro'; + token = isValid(_token) ? _token : 'ebf6c532961e21f092ff2facce1ec4c89c540158'; + break; + case Network.BNB_TESTNET: + host = isValid(_host) ? _host : 'floral-rough-scion.bsc-testnet.quiknode.pro'; + token = isValid(_token) ? _token : '5b297e5acff5f81f4c37ebf6f235f7299b6f9d28'; + break; + + case Network.POLYGON_MAINNET: + host = isValid(_host) ? _host : 'small-chaotic-moon.matic.quiknode.pro'; + token = isValid(_token) ? _token : '847569f8a017e84d985e10d0f44365d965a951f1'; + break; + case Network.POLYGON_AMONY: + host = isValid(_host) ? _host : 'prettiest-side-shape.matic-amoy.quiknode.pro'; + token = isValid(_token) ? _token : '79a9476eea661d4f82de614db1d8a895b14b881c'; + break; + default: + throw new Error('Network info not avalible.'); + } + + return `${transport}://${host}/${token}`; + } } - diff --git a/packages/web3-rpc-providers/test/unit/constructor.test.ts b/packages/web3-rpc-providers/test/unit/constructor.test.ts index 16133129d55..cc34cb1fcd3 100644 --- a/packages/web3-rpc-providers/test/unit/constructor.test.ts +++ b/packages/web3-rpc-providers/test/unit/constructor.test.ts @@ -15,7 +15,6 @@ You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see . */ - import HttpProvider, { HttpProviderOptions } from 'web3-providers-http'; import WebSocketProvider from 'web3-providers-ws'; import WebSocket from 'isomorphic-ws'; @@ -26,136 +25,222 @@ import { ProviderConfigOptionsError } from '../../src/errors'; // Mock implementation so ws doesnt have openhandle after test exits as it attempts to connects at start jest.mock('isomorphic-ws', () => { - return { - __esModule: true, - default: jest.fn().mockImplementation(() => { - // eslint-disable-next-line @typescript-eslint/ban-types - const eventListeners: { [key: string]: Function[] } = {}; - - return { - addEventListener: jest.fn((event, handler) => { - if (!eventListeners[event]) { - eventListeners[event] = []; - } - // eslint-disable-next-line @typescript-eslint/no-unsafe-return - eventListeners[event].push(handler); - }), - removeEventListener: jest.fn((event, handler) => { - if (eventListeners[event]) { - eventListeners[event] = eventListeners[event].filter(h => h !== handler); - } - }), - dispatchEvent: jest.fn((event) => { - const eventType = event.type; - if (eventListeners[eventType]) { - // eslint-disable-next-line @typescript-eslint/no-unsafe-return - eventListeners[eventType].forEach(handler => handler(event)); - } - }), - close: jest.fn(), - send: jest.fn(), - readyState: WebSocket.OPEN, - }; - }), - }; + return { + __esModule: true, + default: jest.fn().mockImplementation(() => { + // eslint-disable-next-line @typescript-eslint/ban-types + const eventListeners: { [key: string]: Function[] } = {}; + + return { + addEventListener: jest.fn((event, handler) => { + if (!eventListeners[event]) { + eventListeners[event] = []; + } + // eslint-disable-next-line @typescript-eslint/no-unsafe-return + eventListeners[event].push(handler); + }), + removeEventListener: jest.fn((event, handler) => { + if (eventListeners[event]) { + eventListeners[event] = eventListeners[event].filter(h => h !== handler); + } + }), + dispatchEvent: jest.fn(event => { + const eventType = event.type; + if (eventListeners[eventType]) { + // eslint-disable-next-line @typescript-eslint/no-unsafe-return + eventListeners[eventType].forEach(handler => handler(event)); + } + }), + close: jest.fn(), + send: jest.fn(), + readyState: WebSocket.OPEN, + }; + }), + }; }); class MockWeb3ExternalProviderA extends Web3ExternalProvider { - public constructor(network: Network, transport: Transport, token: string, host?: string, providerConfigOptions?: HttpProviderOptions | SocketOptions) { - super(network, transport, token, host ?? "", providerConfigOptions); - } - // eslint-disable-next-line class-methods-use-this - public getRPCURL(_network: Network, _transport: Transport, _token: string, _host = ""): string { - let transport = ""; - if (_transport === Transport.HTTPS) - transport = "http://"; - else if (_transport === Transport.WebSocket) - transport = "wss://"; - - return `${transport}127.0.0.1/`; - } + public constructor( + network: Network, + transport: Transport, + token: string, + host?: string, + providerConfigOptions?: HttpProviderOptions | SocketOptions, + ) { + super(network, transport, token, host ?? '', providerConfigOptions); + } + // eslint-disable-next-line class-methods-use-this + public getRPCURL(_network: Network, _transport: Transport, _token: string, _host = ''): string { + let transport = ''; + if (_transport === Transport.HTTPS) transport = 'http://'; + else if (_transport === Transport.WebSocket) transport = 'wss://'; + + return `${transport}127.0.0.1/`; + } } describe('Web3ExternalProvider', () => { - const network: Network = Network.ETH_MAINNET; - const transport: Transport = Transport.HTTPS; - const token = 'test-token'; - const host = 'test-host'; - - it('should initialize the provider correctly', () => { - - const provider = new MockWeb3ExternalProviderA(network, transport, token); - - expect(provider.provider).toBeInstanceOf(HttpProvider); - }); - - it('should initialize the provider with WebSocketProvider for WebSocket transport', () => { - const transport1: Transport = Transport.WebSocket; - - const provider = new MockWeb3ExternalProviderA(network, transport1, token); - expect(provider.provider).toBeInstanceOf(WebSocketProvider); - }); - - it('should throw ProviderConfigOptionsError for HTTP provider with missing providerOptions', () => { - const providerConfigOptions: HttpProviderOptions | SocketOptions = { /* missing providerOptions */ }; - expect(() => new MockWeb3ExternalProviderA(network, transport, token, host, providerConfigOptions)).toThrow(ProviderConfigOptionsError); - }); - - it('should throw ProviderConfigOptionsError for HTTP provider with WS providerOptions', () => { - const providerConfigOptions: SocketOptions = { - socketOptions: { /* options */ }, - reconnectOptions: { /* options */ }, - }; - expect(() => new MockWeb3ExternalProviderA(network, transport, token, host, providerConfigOptions)).toThrow(ProviderConfigOptionsError); - }); - - it('should throw ProviderConfigOptionsError for WebSocket provider with missing socketOptions and reconnectOptions', () => { - const providerConfigOptions: HttpProviderOptions | SocketOptions = { /* missing socketOptions and reconnectOptions */ }; - expect(() => new MockWeb3ExternalProviderA(network, Transport.WebSocket, token, host, providerConfigOptions)).toThrow(ProviderConfigOptionsError); - }); - - it('should throw ProviderConfigOptionsError for WebSocket provider with HTTP options', () => { - const providerConfigOptions: HttpProviderOptions = { providerOptions: { /* options */ } }; - expect(() => new MockWeb3ExternalProviderA(network, Transport.WebSocket, token, host, providerConfigOptions)).toThrow(ProviderConfigOptionsError); - }); - - it('should create provider instance and not throw ProviderConfigOptionsError for WebSocket provider with missing reconnectOptions', () => { - const providerConfigOptions: SocketOptions = { - socketOptions: { /* options */ }, - }; - - // Create an instance of the MockWeb3ExternalProviderA - const provider = new MockWeb3ExternalProviderA(network, Transport.WebSocket, token, host, providerConfigOptions); - - // Expect that the provider is created successfully - expect(provider).toBeInstanceOf(MockWeb3ExternalProviderA); - }); - - it('should create provider instance and not throw ProviderConfigOptionsError for WebSocket provider with missing socketOptions', () => { - const providerConfigOptions: SocketOptions = { - reconnectOptions: { /* options */ }, - }; - - // Create an instance of the MockWeb3ExternalProviderA - const provider = new MockWeb3ExternalProviderA(network, Transport.WebSocket, token, host, providerConfigOptions); - - // Expect that the provider is created successfully - expect(provider).toBeInstanceOf(MockWeb3ExternalProviderA); - }); - - it('should create an HttpProvider with providerOptions', () => { - const providerConfigOptions: HttpProviderOptions = { providerOptions: { /* options */ } }; - const provider = new MockWeb3ExternalProviderA(network, transport, token, host, providerConfigOptions); - expect(provider.provider).toBeInstanceOf(HttpProvider); - }); - - it('should create a WebSocketProvider with socketOptions and reconnectOptions', () => { - const providerConfigOptions: SocketOptions = { - socketOptions: { /* options */ }, - reconnectOptions: { /* options */ }, - }; - const provider = new MockWeb3ExternalProviderA(network, Transport.WebSocket, token, host, providerConfigOptions); - expect(provider.provider).toBeInstanceOf(WebSocketProvider); - }); + const network: Network = Network.ETH_MAINNET; + const transport: Transport = Transport.HTTPS; + const token = 'test-token'; + const host = 'test-host'; + + it('should initialize the provider correctly', () => { + const provider = new MockWeb3ExternalProviderA(network, transport, token); + + expect(provider.provider).toBeInstanceOf(HttpProvider); + }); + + it('should initialize the provider with WebSocketProvider for WebSocket transport', () => { + const transport1: Transport = Transport.WebSocket; + + const provider = new MockWeb3ExternalProviderA(network, transport1, token); + expect(provider.provider).toBeInstanceOf(WebSocketProvider); + }); + + it('should throw ProviderConfigOptionsError for HTTP provider with missing providerOptions', () => { + const providerConfigOptions: HttpProviderOptions | SocketOptions = { + /* missing providerOptions */ + }; + expect( + () => + new MockWeb3ExternalProviderA( + network, + transport, + token, + host, + providerConfigOptions, + ), + ).toThrow(ProviderConfigOptionsError); + }); + + it('should throw ProviderConfigOptionsError for HTTP provider with WS providerOptions', () => { + const providerConfigOptions: SocketOptions = { + socketOptions: { + /* options */ + }, + reconnectOptions: { + /* options */ + }, + }; + expect( + () => + new MockWeb3ExternalProviderA( + network, + transport, + token, + host, + providerConfigOptions, + ), + ).toThrow(ProviderConfigOptionsError); + }); + + it('should throw ProviderConfigOptionsError for WebSocket provider with missing socketOptions and reconnectOptions', () => { + const providerConfigOptions: HttpProviderOptions | SocketOptions = { + /* missing socketOptions and reconnectOptions */ + }; + expect( + () => + new MockWeb3ExternalProviderA( + network, + Transport.WebSocket, + token, + host, + providerConfigOptions, + ), + ).toThrow(ProviderConfigOptionsError); + }); + + it('should throw ProviderConfigOptionsError for WebSocket provider with HTTP options', () => { + const providerConfigOptions: HttpProviderOptions = { + providerOptions: { + /* options */ + }, + }; + expect( + () => + new MockWeb3ExternalProviderA( + network, + Transport.WebSocket, + token, + host, + providerConfigOptions, + ), + ).toThrow(ProviderConfigOptionsError); + }); + + it('should create provider instance and not throw ProviderConfigOptionsError for WebSocket provider with missing reconnectOptions', () => { + const providerConfigOptions: SocketOptions = { + socketOptions: { + /* options */ + }, + }; + + // Create an instance of the MockWeb3ExternalProviderA + const provider = new MockWeb3ExternalProviderA( + network, + Transport.WebSocket, + token, + host, + providerConfigOptions, + ); + + // Expect that the provider is created successfully + expect(provider).toBeInstanceOf(MockWeb3ExternalProviderA); + }); + + it('should create provider instance and not throw ProviderConfigOptionsError for WebSocket provider with missing socketOptions', () => { + const providerConfigOptions: SocketOptions = { + reconnectOptions: { + /* options */ + }, + }; + + // Create an instance of the MockWeb3ExternalProviderA + const provider = new MockWeb3ExternalProviderA( + network, + Transport.WebSocket, + token, + host, + providerConfigOptions, + ); + + // Expect that the provider is created successfully + expect(provider).toBeInstanceOf(MockWeb3ExternalProviderA); + }); + + it('should create an HttpProvider with providerOptions', () => { + const providerConfigOptions: HttpProviderOptions = { + providerOptions: { + /* options */ + }, + }; + const provider = new MockWeb3ExternalProviderA( + network, + transport, + token, + host, + providerConfigOptions, + ); + expect(provider.provider).toBeInstanceOf(HttpProvider); + }); + + it('should create a WebSocketProvider with socketOptions and reconnectOptions', () => { + const providerConfigOptions: SocketOptions = { + socketOptions: { + /* options */ + }, + reconnectOptions: { + /* options */ + }, + }; + const provider = new MockWeb3ExternalProviderA( + network, + Transport.WebSocket, + token, + host, + providerConfigOptions, + ); + expect(provider.provider).toBeInstanceOf(WebSocketProvider); + }); }); - diff --git a/packages/web3-rpc-providers/test/unit/request.test.ts b/packages/web3-rpc-providers/test/unit/request.test.ts index 6107949b0f1..3de14fc0513 100644 --- a/packages/web3-rpc-providers/test/unit/request.test.ts +++ b/packages/web3-rpc-providers/test/unit/request.test.ts @@ -14,113 +14,112 @@ 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 { Web3APIPayload, EthExecutionAPI, Web3APIMethod, JsonRpcResponse } from "web3-types"; -import { ResponseError } from "web3-errors"; -import { Network, Transport } from "../../src/types"; -import { Web3ExternalProvider } from "../../src/web3_provider"; +import { Web3APIPayload, EthExecutionAPI, Web3APIMethod, JsonRpcResponse } from 'web3-types'; +import { ResponseError } from 'web3-errors'; +import { Network, Transport } from '../../src/types'; +import { Web3ExternalProvider } from '../../src/web3_provider'; import { QuickNodeRateLimitError } from '../../src/errors'; import { QuickNodeProvider } from '../../src/web3_provider_quicknode'; jest.mock('web3-providers-ws', () => { - return { - __esModule: true, - default: jest.fn().mockImplementation(() => ({ - request: jest.fn().mockResolvedValue({ result: 'mock-result' }), - })), - }; + return { + __esModule: true, + default: jest.fn().mockImplementation(() => ({ + request: jest.fn().mockResolvedValue({ result: 'mock-result' }), + })), + }; }); class MockWeb3ExternalProvider extends Web3ExternalProvider { - public constructor(network: Network, transport: Transport, token: string){ - super(network, transport, token, ""); - } - // eslint-disable-next-line class-methods-use-this - public getRPCURL(_network: Network, _transport: Transport, _token: string): string { - return 'https://example.com/'; - } - } + public constructor(network: Network, transport: Transport, token: string) { + super(network, transport, token, ''); + } + // eslint-disable-next-line class-methods-use-this + public getRPCURL(_network: Network, _transport: Transport, _token: string): string { + return 'https://example.com/'; + } +} describe('Web3ExternalProvider', () => { - it('should make a request using the HTTPS provider', async () => { - const network: Network = Network.ETH_MAINNET; - const transport: Transport = Transport.HTTPS; - const token = 'your-token'; - - const mockHttpProvider = { - request: jest.fn(), - }; - - const mockResponse = { result: 'mock-result' }; - mockHttpProvider.request.mockResolvedValue(mockResponse); - - const provider = new MockWeb3ExternalProvider(network, transport, token); - (provider as any).provider = mockHttpProvider; - - const payload: Web3APIPayload> = { - method: 'eth_getBalance', - params: ['0x0123456789012345678901234567890123456789', 'latest'], - }; - - const result = await provider.request(payload); - expect(result).toEqual(mockResponse); - }); - - it('should make a request using the WebSocket provider', async () => { - const network: Network = Network.ETH_MAINNET; - const transport: Transport = Transport.WebSocket; - const token = 'your-token'; - - const provider = new MockWeb3ExternalProvider(network, transport, token); - (provider as any).getRPCURL = jest.fn().mockReturnValue('ws://mock-rpc-url.com'); - - const payload: Web3APIPayload> = { - method: 'eth_getBalance', - params: ['0x0123456789012345678901234567890123456789', 'latest'], - }; - - const result = await provider.request(payload); - expect(result).toEqual({ result: 'mock-result' }); - }); - - it('should throw a rate limiting error when status code is 429', async () => { - const network: Network = Network.ETH_MAINNET; - const transport: Transport = Transport.HTTPS; - const token = 'your-token'; - - const mockHttpProvider = { - request: jest.fn(), - }; - - // Create a mock ResponseError with status code 429 - // Create a mock JsonRpcResponse to pass to ResponseError - const mockJsonRpcResponse: JsonRpcResponse = { - jsonrpc: '2.0', - id: '458408f4-7e2c-43f1-b61d-1fe09a9ee25a', - error: { - code: 429, - message: 'Rate limit exceeded', - }, - }; - - // Create a mock ResponseError with status code 429 - const mockError = new ResponseError( - mockJsonRpcResponse, - undefined, - undefined, // request can be undefined - 429 // statusCode - ); - - // Mock the request method to throw the ResponseError - mockHttpProvider.request.mockRejectedValue(mockError); - - const provider = new QuickNodeProvider(network, transport, token); - (provider as any).provider = mockHttpProvider; - - const payload: Web3APIPayload> = { - method: 'eth_getBalance', - params: ['0x0123456789012345678901234567890123456789', 'latest'], - }; - await expect(provider.request(payload)).rejects.toThrow(QuickNodeRateLimitError); - }); - -}); \ No newline at end of file + it('should make a request using the HTTPS provider', async () => { + const network: Network = Network.ETH_MAINNET; + const transport: Transport = Transport.HTTPS; + const token = 'your-token'; + + const mockHttpProvider = { + request: jest.fn(), + }; + + const mockResponse = { result: 'mock-result' }; + mockHttpProvider.request.mockResolvedValue(mockResponse); + + const provider = new MockWeb3ExternalProvider(network, transport, token); + (provider as any).provider = mockHttpProvider; + + const payload: Web3APIPayload> = { + method: 'eth_getBalance', + params: ['0x0123456789012345678901234567890123456789', 'latest'], + }; + + const result = await provider.request(payload); + expect(result).toEqual(mockResponse); + }); + + it('should make a request using the WebSocket provider', async () => { + const network: Network = Network.ETH_MAINNET; + const transport: Transport = Transport.WebSocket; + const token = 'your-token'; + + const provider = new MockWeb3ExternalProvider(network, transport, token); + (provider as any).getRPCURL = jest.fn().mockReturnValue('ws://mock-rpc-url.com'); + + const payload: Web3APIPayload> = { + method: 'eth_getBalance', + params: ['0x0123456789012345678901234567890123456789', 'latest'], + }; + + const result = await provider.request(payload); + expect(result).toEqual({ result: 'mock-result' }); + }); + + it('should throw a rate limiting error when status code is 429', async () => { + const network: Network = Network.ETH_MAINNET; + const transport: Transport = Transport.HTTPS; + const token = 'your-token'; + + const mockHttpProvider = { + request: jest.fn(), + }; + + // Create a mock ResponseError with status code 429 + // Create a mock JsonRpcResponse to pass to ResponseError + const mockJsonRpcResponse: JsonRpcResponse = { + jsonrpc: '2.0', + id: '458408f4-7e2c-43f1-b61d-1fe09a9ee25a', + error: { + code: 429, + message: 'Rate limit exceeded', + }, + }; + + // Create a mock ResponseError with status code 429 + const mockError = new ResponseError( + mockJsonRpcResponse, + undefined, + undefined, // request can be undefined + 429, // statusCode + ); + + // Mock the request method to throw the ResponseError + mockHttpProvider.request.mockRejectedValue(mockError); + + const provider = new QuickNodeProvider(network, transport, token); + (provider as any).provider = mockHttpProvider; + + const payload: Web3APIPayload> = { + method: 'eth_getBalance', + params: ['0x0123456789012345678901234567890123456789', 'latest'], + }; + await expect(provider.request(payload)).rejects.toThrow(QuickNodeRateLimitError); + }); +}); diff --git a/packages/web3-types/CHANGELOG.md b/packages/web3-types/CHANGELOG.md index 9fba5349a3c..281d77fb528 100644 --- a/packages/web3-types/CHANGELOG.md +++ b/packages/web3-types/CHANGELOG.md @@ -163,7 +163,6 @@ Documentation: - add `asEIP1193Provider` to `Web3BaseProvider` so every inherited class can have the returned value of `request` method, fully compatible with EIP-1193. (#6407) - ## [1.3.0] ### Added @@ -200,7 +199,7 @@ Documentation: ### Added -- Added `result` as optional `never` and `error` as optional `never in type `JsonRpcNotification` (#7091) -- Added `JsonRpcNotfication` as a union type in `JsonRpcResponse` (#7091) +- Added `result` as optional `never` and `error` as optional `never in type `JsonRpcNotification` (#7091) +- Added `JsonRpcNotfication` as a union type in `JsonRpcResponse` (#7091) ## [Unreleased] diff --git a/packages/web3-types/src/apis/eth_execution_api.ts b/packages/web3-types/src/apis/eth_execution_api.ts index 3abb0b29af0..a2ee39bb767 100644 --- a/packages/web3-types/src/apis/eth_execution_api.ts +++ b/packages/web3-types/src/apis/eth_execution_api.ts @@ -193,7 +193,10 @@ export type EthExecutionAPI = { eth_getUncleCountByBlockHash: (blockHash: HexString32Bytes) => Uint; eth_getUncleCountByBlockNumber: (blockNumber: BlockNumberOrTag) => Uint; eth_getUncleByBlockHashAndIndex: (blockHash: HexString32Bytes, uncleIndex: Uint) => BlockAPI; - eth_getUncleByBlockNumberAndIndex: (blockNumber: BlockNumberOrTag, uncleIndex: Uint) => BlockAPI; + eth_getUncleByBlockNumberAndIndex: ( + blockNumber: BlockNumberOrTag, + uncleIndex: Uint, + ) => BlockAPI; // https://github.com/ethereum/execution-apis/blob/main/src/eth/transaction.yaml eth_getTransactionByHash: (transactionHash: HexString32Bytes) => TransactionInfoAPI | undefined; diff --git a/packages/web3-types/src/eth_abi_types.ts b/packages/web3-types/src/eth_abi_types.ts index e46b79e8498..0daaa2db877 100644 --- a/packages/web3-types/src/eth_abi_types.ts +++ b/packages/web3-types/src/eth_abi_types.ts @@ -142,7 +142,6 @@ export type AbiErrorFragment = AbiBaseFragment & { readonly inputs?: ReadonlyArray; }; - export type AbiInput = | string | AbiParameter @@ -155,14 +154,12 @@ export type AbiInput = } | { readonly [key: string]: unknown }; - export interface AbiOutput { - name: string; - type: string; - components?: AbiOutput[]; - internalType?: string; - } - - +export interface AbiOutput { + name: string; + type: string; + components?: AbiOutput[]; + internalType?: string; +} // https://docs.soliditylang.org/en/latest/abi-spec.html#json export type AbiFragment = @@ -170,12 +167,11 @@ export type AbiFragment = | AbiFunctionFragment | AbiEventFragment | AbiErrorFragment - | AbiFallbackFragment + | AbiFallbackFragment; // to be compatible with web3js v1 -export type AbiItem = AbiFragment -export type ContractAbi = ReadonlyArray | ReadonlyArray - +export type AbiItem = AbiFragment; +export type ContractAbi = ReadonlyArray | ReadonlyArray; // https://docs.soliditylang.org/en/develop/abi-spec.html#json export type JsonFunctionInterface = { diff --git a/packages/web3-types/src/web3_base_provider.ts b/packages/web3-types/src/web3_base_provider.ts index 5f840aa7488..5a9e9899d13 100644 --- a/packages/web3-types/src/web3_base_provider.ts +++ b/packages/web3-types/src/web3_base_provider.ts @@ -112,7 +112,6 @@ export type ProviderChainId = string; export type ProviderAccounts = string[]; - export type Eip1193EventName = | 'connect' | 'disconnect' @@ -149,7 +148,6 @@ export interface MetaMaskProvider extends SimpleProvide isMetaMask: boolean; } - export type Eip1193Compatible = Omit< // eslint-disable-next-line no-use-before-define Omit, diff --git a/packages/web3-utils/src/formatter.ts b/packages/web3-utils/src/formatter.ts index a25c69c26a4..5050a26ef7d 100644 --- a/packages/web3-utils/src/formatter.ts +++ b/packages/web3-utils/src/formatter.ts @@ -133,9 +133,8 @@ export const convertScalarValue = (value: unknown, ethType: string, format: Data } if (baseType === 'string') { - return String(value); - } - + return String(value); + } } catch (error) { // If someone didn't use `eth` keyword we can return original value // as the scope of this code is formatting not validation @@ -328,18 +327,18 @@ export const convert = ( } // The following code is basically saying: - // if the schema specifies oneOf, then we are to loop - // over each possible schema and check if they type of the schema specifies format - // and if so we use the oneOfSchemaProp as the schema for formatting - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-call - if ((schemaProp?.format === undefined) && (schemaProp?.oneOf !== undefined)) { - for (const [_index, oneOfSchemaProp] of schemaProp.oneOf.entries()) { - if ((oneOfSchemaProp?.format !== undefined)) { - schemaProp = oneOfSchemaProp; - break; - } - }; - } + // if the schema specifies oneOf, then we are to loop + // over each possible schema and check if they type of the schema specifies format + // and if so we use the oneOfSchemaProp as the schema for formatting + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-call + if (schemaProp?.format === undefined && schemaProp?.oneOf !== undefined) { + for (const [_index, oneOfSchemaProp] of schemaProp.oneOf.entries()) { + if (oneOfSchemaProp?.format !== undefined) { + schemaProp = oneOfSchemaProp; + break; + } + } + } object[key] = convertScalarValue(value, schemaProp.format as string, format); diff --git a/packages/web3-utils/test/unit/formatter.test.ts b/packages/web3-utils/test/unit/formatter.test.ts index 9f2bbfc3f1b..041f148abec 100644 --- a/packages/web3-utils/test/unit/formatter.test.ts +++ b/packages/web3-utils/test/unit/formatter.test.ts @@ -852,12 +852,10 @@ describe('formatter', () => { }, }; - const data ={ + const data = { from: '0x7ed0e85b8e1e925600b4373e6d108f34ab38a401', to: 123, - } - ; - + }; const result = { from: '0x7ed0e85b8e1e925600b4373e6d108f34ab38a401', to: '123' }; expect( @@ -878,11 +876,11 @@ describe('formatter', () => { }, }; - const data ={ - from: '0x7ed0e85b8e1e925600b4373e6d108f34ab38a401' + const data = { + from: '0x7ed0e85b8e1e925600b4373e6d108f34ab38a401', }; - const result = { from: '0x7ed0e85b8e1e925600b4373e6d108f34ab38a401'}; + const result = { from: '0x7ed0e85b8e1e925600b4373e6d108f34ab38a401' }; expect( format(schema, data, { number: FMT_NUMBER.HEX, bytes: FMT_BYTES.HEX }), diff --git a/packages/web3-validator/CHANGELOG.md b/packages/web3-validator/CHANGELOG.md index da4cc2c0136..8410b156c08 100644 --- a/packages/web3-validator/CHANGELOG.md +++ b/packages/web3-validator/CHANGELOG.md @@ -166,13 +166,13 @@ Documentation: ### Fixed -- 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) ## [2.0.6] ### Fixed -- The JSON schema conversion process now correctly assigns an id when the `abi.name` is not available, for example, in the case of public mappings. (#6981) -- `browser` entry point that was pointing to an non-existing bundle file was removed from `package.json` (#7015) +- The JSON schema conversion process now correctly assigns an id when the `abi.name` is not available, for example, in the case of public mappings. (#6981) +- `browser` entry point that was pointing to an non-existing bundle file was removed from `package.json` (#7015) -## [Unreleased] \ No newline at end of file +## [Unreleased] diff --git a/packages/web3-validator/src/utils.ts b/packages/web3-validator/src/utils.ts index 6f9fd6f7f55..2e025022816 100644 --- a/packages/web3-validator/src/utils.ts +++ b/packages/web3-validator/src/utils.ts @@ -206,25 +206,25 @@ export const abiSchemaToJsonSchema = ( nestedTuple.$id = abiName; (lastSchema.items as JsonSchema[]).push(nestedTuple); } else if (baseType === 'tuple' && isArray) { - const arraySize = arraySizes[0]; - const item: JsonSchema = { - type: 'array', - $id: abiName, - items: abiSchemaToJsonSchema(abiComponents, abiName), - ...(arraySize >= 0 && { minItems: arraySize, maxItems: arraySize }), - }; - - (lastSchema.items as JsonSchema[]).push(item); + const arraySize = arraySizes[0]; + const item: JsonSchema = { + type: 'array', + $id: abiName, + items: abiSchemaToJsonSchema(abiComponents, abiName), + ...(arraySize >= 0 && { minItems: arraySize, maxItems: arraySize }), + }; + + (lastSchema.items as JsonSchema[]).push(item); } else if (isArray) { - const arraySize = arraySizes[0]; - const item: JsonSchema = { - type: 'array', - $id: abiName, - items: convertEthType(abiType), - ...(arraySize >= 0 && { minItems: arraySize, maxItems: arraySize }), - }; - - (lastSchema.items as JsonSchema[]).push(item); + const arraySize = arraySizes[0]; + const item: JsonSchema = { + type: 'array', + $id: abiName, + items: convertEthType(abiType), + ...(arraySize >= 0 && { minItems: arraySize, maxItems: arraySize }), + }; + + (lastSchema.items as JsonSchema[]).push(item); } else if (Array.isArray(lastSchema.items)) { // Array of non-tuple items lastSchema.items.push({ $id: abiName, ...convertEthType(abiType) }); @@ -446,17 +446,14 @@ const charCodeMap = { F: 70, a: 97, f: 102, - } as const - - function charCodeToBase16(char: number) { - if (char >= charCodeMap.zero && char <= charCodeMap.nine) - return char - charCodeMap.zero - if (char >= charCodeMap.A && char <= charCodeMap.F) - return char - (charCodeMap.A - 10) - if (char >= charCodeMap.a && char <= charCodeMap.f) - return char - (charCodeMap.a - 10) - return undefined - } +} as const; + +function charCodeToBase16(char: number) { + if (char >= charCodeMap.zero && char <= charCodeMap.nine) return char - charCodeMap.zero; + if (char >= charCodeMap.A && char <= charCodeMap.F) return char - (charCodeMap.A - 10); + if (char >= charCodeMap.a && char <= charCodeMap.f) return char - (charCodeMap.a - 10); + return undefined; +} export function hexToUint8Array(hex: string): Uint8Array { let offset = 0; @@ -468,21 +465,19 @@ export function hexToUint8Array(hex: string): Uint8Array { } const length = (hex.length - offset) / 2; const bytes = new Uint8Array(length); - for (let index = 0, j = offset; index < length; index+=1) { - // eslint-disable-next-line no-plusplus - const nibbleLeft = charCodeToBase16(hex.charCodeAt(j++)) - // eslint-disable-next-line no-plusplus - const nibbleRight = charCodeToBase16(hex.charCodeAt(j++)) - if (nibbleLeft === undefined || nibbleRight === undefined) { - throw new InvalidBytesError( - `Invalid byte sequence ("${hex[j - 2]}${ - hex[j - 1] - }" in "${hex}").`, - ) - } - bytes[index] = nibbleLeft * 16 + nibbleRight + for (let index = 0, j = offset; index < length; index += 1) { + // eslint-disable-next-line no-plusplus + const nibbleLeft = charCodeToBase16(hex.charCodeAt(j++)); + // eslint-disable-next-line no-plusplus + const nibbleRight = charCodeToBase16(hex.charCodeAt(j++)); + if (nibbleLeft === undefined || nibbleRight === undefined) { + throw new InvalidBytesError( + `Invalid byte sequence ("${hex[j - 2]}${hex[j - 1]}" in "${hex}").`, + ); + } + bytes[index] = nibbleLeft * 16 + nibbleRight; } - return bytes + return bytes; } // @TODO: Remove this function and its usages once all sub dependencies uses version 1.3.3 or above of @noble/hashes diff --git a/packages/web3-validator/src/validation/bytes.ts b/packages/web3-validator/src/validation/bytes.ts index 928efec6982..c05b666526b 100644 --- a/packages/web3-validator/src/validation/bytes.ts +++ b/packages/web3-validator/src/validation/bytes.ts @@ -23,7 +23,9 @@ import { isHexStrict } from './string.js'; * checks input if typeof data is valid Uint8Array input */ export const isUint8Array = (data: ValidInputTypes): data is Uint8Array => - data instanceof Uint8Array || data?.constructor?.name === 'Uint8Array' || data?.constructor?.name === 'Buffer'; + data instanceof Uint8Array || + data?.constructor?.name === 'Uint8Array' || + data?.constructor?.name === 'Buffer'; export const isBytes = ( value: ValidInputTypes | Uint8Array | number[], diff --git a/packages/web3-validator/src/validator.ts b/packages/web3-validator/src/validator.ts index 82d7a596052..c2e49d8c253 100644 --- a/packages/web3-validator/src/validator.ts +++ b/packages/web3-validator/src/validator.ts @@ -44,9 +44,12 @@ const convertToZod = (schema: JsonSchema): ZodType => { } if (schema?.type === 'array' && schema?.items) { - if (Array.isArray(schema.items) && schema.items.length > 1 - && schema.maxItems !== undefined - && new Set(schema.items.map((item: JsonSchema) => item.$id)).size === schema.items.length) { + if ( + Array.isArray(schema.items) && + schema.items.length > 1 && + schema.maxItems !== undefined && + new Set(schema.items.map((item: JsonSchema) => item.$id)).size === schema.items.length + ) { const arr: Partial<[ZodTypeAny, ...ZodTypeAny[]]> = []; for (const item of schema.items) { const zItem = convertToZod(item); @@ -57,10 +60,12 @@ const convertToZod = (schema: JsonSchema): ZodType => { return z.tuple(arr as [ZodTypeAny, ...ZodTypeAny[]]); } const nextSchema = Array.isArray(schema.items) ? schema.items[0] : schema.items; - let zodArraySchema = z.array(convertToZod(nextSchema)); + let zodArraySchema = z.array(convertToZod(nextSchema)); - zodArraySchema = schema.minItems !== undefined ? zodArraySchema.min(schema.minItems) : zodArraySchema; - zodArraySchema = schema.maxItems !== undefined ? zodArraySchema.max(schema.maxItems) : zodArraySchema; + zodArraySchema = + schema.minItems !== undefined ? zodArraySchema.min(schema.minItems) : zodArraySchema; + zodArraySchema = + schema.maxItems !== undefined ? zodArraySchema.max(schema.maxItems) : zodArraySchema; return zodArraySchema; } diff --git a/packages/web3-validator/test/fixtures/abi_to_json_schema.ts b/packages/web3-validator/test/fixtures/abi_to_json_schema.ts index e9e4391700c..99bfcc8e7bd 100644 --- a/packages/web3-validator/test/fixtures/abi_to_json_schema.ts +++ b/packages/web3-validator/test/fixtures/abi_to_json_schema.ts @@ -746,55 +746,55 @@ const abiToJsonSchemaCases: AbiToJsonSchemaCase[] = [ }, json: { fullSchema: { - type: 'array', - items: [ - { - type: 'array', - $id: 'a', - items: [ - { - type: 'array', - $id: 'a', - items: { - format: 'uint', - required: true, - }, - minItems: 2, - maxItems: 2, - } - ], - maxItems: 3, - minItems: 3, - } - ], - maxItems: 1, - minItems: 1, - }, + type: 'array', + items: [ + { + type: 'array', + $id: 'a', + items: [ + { + type: 'array', + $id: 'a', + items: { + format: 'uint', + required: true, + }, + minItems: 2, + maxItems: 2, + }, + ], + maxItems: 3, + minItems: 3, + }, + ], + maxItems: 1, + minItems: 1, + }, shortSchema: { - type: 'array', - items: [ - { - type: 'array', - $id: '/0/0', - items: [ - { - type: 'array', - $id: '/0/0', - items: { - format: 'uint', - required: true, - }, - minItems: 2, - maxItems: 2, - } - ], - maxItems: 3, - minItems: 3, - } - ], - maxItems: 1, - minItems: 1, - }, + type: 'array', + items: [ + { + type: 'array', + $id: '/0/0', + items: [ + { + type: 'array', + $id: '/0/0', + items: { + format: 'uint', + required: true, + }, + minItems: 2, + maxItems: 2, + }, + ], + maxItems: 3, + minItems: 3, + }, + ], + maxItems: 1, + minItems: 1, + }, data: [ [ [1, 1], @@ -825,51 +825,51 @@ const abiToJsonSchemaCases: AbiToJsonSchemaCase[] = [ }, json: { fullSchema: { - type: 'array', - items: [ - { - type: 'array', - $id: 'a', - items: [ - { - type: 'array', - $id: 'a', - items: { - format: 'uint', - required: true, - } - } - ], - maxItems: 3, - minItems: 3, - } - ], - maxItems: 1, - minItems: 1, - }, + type: 'array', + items: [ + { + type: 'array', + $id: 'a', + items: [ + { + type: 'array', + $id: 'a', + items: { + format: 'uint', + required: true, + }, + }, + ], + maxItems: 3, + minItems: 3, + }, + ], + maxItems: 1, + minItems: 1, + }, shortSchema: { - type: 'array', - items: [ - { - type: 'array', - $id: '/0/0', - items: [ - { - type: 'array', - $id: '/0/0', - items: { - format: 'uint', - required: true, - } - } - ], - maxItems: 3, - minItems: 3, - } - ], - maxItems: 1, - minItems: 1, - }, + type: 'array', + items: [ + { + type: 'array', + $id: '/0/0', + items: [ + { + type: 'array', + $id: '/0/0', + items: { + format: 'uint', + required: true, + }, + }, + ], + maxItems: 3, + minItems: 3, + }, + ], + maxItems: 1, + minItems: 1, + }, data: [ [ [1, 1], @@ -924,77 +924,77 @@ const abiToJsonSchemaCases: AbiToJsonSchemaCase[] = [ }, json: { fullSchema: { - type: 'array', - items: [ - { - type: 'array', - $id: 'a', - items: [ - { - type: 'array', - $id: 'a', - items: { - type: 'array', - items: [ - { - $id: 'level', - format: 'uint', - required: true, - }, - { - $id: 'message', - format: 'string', - required: true, - } - ], - maxItems: 2, - minItems: 2, - } - } - ], - maxItems: 3, - minItems: 3, - } - ], - maxItems: 1, - minItems: 1 - }, + type: 'array', + items: [ + { + type: 'array', + $id: 'a', + items: [ + { + type: 'array', + $id: 'a', + items: { + type: 'array', + items: [ + { + $id: 'level', + format: 'uint', + required: true, + }, + { + $id: 'message', + format: 'string', + required: true, + }, + ], + maxItems: 2, + minItems: 2, + }, + }, + ], + maxItems: 3, + minItems: 3, + }, + ], + maxItems: 1, + minItems: 1, + }, shortSchema: { - type: 'array', - items: [ - { - type: 'array', - $id: '/0/0', - items: [ - { - type: 'array', - $id: '/0/0', - items: { - type: 'array', - items: [ - { - $id: '/0/0/0', - format: 'uint', - required: true, - }, - { - $id: '/0/0/1', - format: 'string', - required: true, - } - ], - maxItems: 2, - minItems: 2, - } - } - ], - maxItems: 3, - minItems: 3, - } - ], - maxItems: 1, - minItems: 1 - }, + type: 'array', + items: [ + { + type: 'array', + $id: '/0/0', + items: [ + { + type: 'array', + $id: '/0/0', + items: { + type: 'array', + items: [ + { + $id: '/0/0/0', + format: 'uint', + required: true, + }, + { + $id: '/0/0/1', + format: 'string', + required: true, + }, + ], + maxItems: 2, + minItems: 2, + }, + }, + ], + maxItems: 3, + minItems: 3, + }, + ], + maxItems: 1, + minItems: 1, + }, data: [ [ [ @@ -1071,81 +1071,81 @@ const abiToJsonSchemaCases: AbiToJsonSchemaCase[] = [ }, json: { fullSchema: { - type: 'array', - items: [ - { - type: 'array', - $id: 'a', - items: [ - { - type: 'array', - $id: 'a', - items: { - type: 'array', - items: [ - { - $id: 'level', - format: 'uint', - required: true, - }, - { - $id: 'message', - format: 'string', - required: true, - } - ], - maxItems: 2, - minItems: 2, - }, - minItems: 3, - maxItems: 3, - } - ], - maxItems: 5, - minItems: 5, - } - ], - maxItems: 1, - minItems: 1, - }, + type: 'array', + items: [ + { + type: 'array', + $id: 'a', + items: [ + { + type: 'array', + $id: 'a', + items: { + type: 'array', + items: [ + { + $id: 'level', + format: 'uint', + required: true, + }, + { + $id: 'message', + format: 'string', + required: true, + }, + ], + maxItems: 2, + minItems: 2, + }, + minItems: 3, + maxItems: 3, + }, + ], + maxItems: 5, + minItems: 5, + }, + ], + maxItems: 1, + minItems: 1, + }, shortSchema: { - type: 'array', - items: [ - { - type: 'array', - $id: '/0/0', - items: [ - { - type: 'array', - $id: '/0/0', - items: { - type: 'array', - items: [ - { - $id: '/0/0/0', - format: 'uint', - required: true, - }, - { - $id: '/0/0/1', - format: 'string', - required: true, - } - ], - maxItems: 2, - minItems: 2, - }, - minItems: 3, - maxItems: 3, - } - ], - maxItems: 5, - minItems: 5, - } - ], - maxItems: 1, - minItems: 1, - }, + type: 'array', + items: [ + { + type: 'array', + $id: '/0/0', + items: [ + { + type: 'array', + $id: '/0/0', + items: { + type: 'array', + items: [ + { + $id: '/0/0/0', + format: 'uint', + required: true, + }, + { + $id: '/0/0/1', + format: 'string', + required: true, + }, + ], + maxItems: 2, + minItems: 2, + }, + minItems: 3, + maxItems: 3, + }, + ], + maxItems: 5, + minItems: 5, + }, + ], + maxItems: 1, + minItems: 1, + }, data: [ [ [ @@ -1433,186 +1433,186 @@ const abiToJsonSchemaCases: AbiToJsonSchemaCase[] = [ 'bool', ], data: [ - [ - [ - [ - [0, 0], - [1, 1], - ], - [ - [2, 2], - [3, 3], - ], - ], - [ - [ - [0, 0], - [-1, -1], - ], - [ - [-2, -2], - [-3, -3], - ], - [ - [-4, -4], - [-5, -5], - ], - ], - [ - [ - [4, 4], - [5, 5], - ], - ] - ], - 123, - true, - ], + [ + [ + [ + [0, 0], + [1, 1], + ], + [ + [2, 2], + [3, 3], + ], + ], + [ + [ + [0, 0], + [-1, -1], + ], + [ + [-2, -2], + [-3, -3], + ], + [ + [-4, -4], + [-5, -5], + ], + ], + [ + [ + [4, 4], + [5, 5], + ], + ], + ], + 123, + true, + ], }, json: { fullSchema: { - type: 'array', - items: [ - { - type: 'array', - $id: 'rects', - items: [ - { - type: 'array', - $id: 'rects', - items: { - type: 'array', - items: [ - { - type: 'array', - items: [ - { - $id: 'x', - format: 'int256', - required: true, - }, - { - $id: 'y', - format: 'int256', - required: true - } - ], - maxItems: 2, - minItems: 2, - $id: 'start', - }, - { - type: 'array', - items: [ - { - $id: 'x', - format: 'int256', - required: true, - }, - { - $id: 'y', - format: 'int256', - required: true, - } - ], - maxItems: 2, - minItems: 2, - $id: 'end', - } - ], - maxItems: 2, - minItems: 2, - } - } - ], - maxItems: 3, - minItems: 3, - }, - { - $id: 'numberValue', - format: 'uint256', - required: true, - }, - { - $id: 'boolValue', - format: 'bool', - required: true, - } - ], - maxItems: 3, - minItems: 3, - }, + type: 'array', + items: [ + { + type: 'array', + $id: 'rects', + items: [ + { + type: 'array', + $id: 'rects', + items: { + type: 'array', + items: [ + { + type: 'array', + items: [ + { + $id: 'x', + format: 'int256', + required: true, + }, + { + $id: 'y', + format: 'int256', + required: true, + }, + ], + maxItems: 2, + minItems: 2, + $id: 'start', + }, + { + type: 'array', + items: [ + { + $id: 'x', + format: 'int256', + required: true, + }, + { + $id: 'y', + format: 'int256', + required: true, + }, + ], + maxItems: 2, + minItems: 2, + $id: 'end', + }, + ], + maxItems: 2, + minItems: 2, + }, + }, + ], + maxItems: 3, + minItems: 3, + }, + { + $id: 'numberValue', + format: 'uint256', + required: true, + }, + { + $id: 'boolValue', + format: 'bool', + required: true, + }, + ], + maxItems: 3, + minItems: 3, + }, shortSchema: { type: 'array', - items: [ - { - type: 'array', - $id: '/0/0', - items: [ - { - type: 'array', - $id: '/0/0', - items: { - type: 'array', - items: [ - { - type: 'array', - items: [ - { - $id: '/0/0/0/0', - format: 'int256', - required: true, - }, - { - $id: '/0/0/0/1', - format: 'int256', - required: true, - } - ], - maxItems: 2, - minItems: 2, - $id: '/0/0/0', - }, - { - type: 'array', - items: [ - { - $id: '/0/0/1/0', - format: 'int256', - required: true, - }, - { - $id: '/0/0/1/1', - format: 'int256', - required: true, - } - ], - maxItems: 2, - minItems: 2, - $id: '/0/0/1', - } - ], - maxItems: 2, - minItems: 2, - } - } - ], - maxItems: 3, - minItems: 3, - }, - { - $id: '/0/1', - format: 'uint256', - required: true, - }, - { - $id: '/0/2', - format: 'bool', - required: true, - } - ], - maxItems: 3, - minItems: 3, + items: [ + { + type: 'array', + $id: '/0/0', + items: [ + { + type: 'array', + $id: '/0/0', + items: { + type: 'array', + items: [ + { + type: 'array', + items: [ + { + $id: '/0/0/0/0', + format: 'int256', + required: true, + }, + { + $id: '/0/0/0/1', + format: 'int256', + required: true, + }, + ], + maxItems: 2, + minItems: 2, + $id: '/0/0/0', + }, + { + type: 'array', + items: [ + { + $id: '/0/0/1/0', + format: 'int256', + required: true, + }, + { + $id: '/0/0/1/1', + format: 'int256', + required: true, + }, + ], + maxItems: 2, + minItems: 2, + $id: '/0/0/1', + }, + ], + maxItems: 2, + minItems: 2, + }, + }, + ], + maxItems: 3, + minItems: 3, + }, + { + $id: '/0/1', + format: 'uint256', + required: true, + }, + { + $id: '/0/2', + format: 'bool', + required: true, + }, + ], + maxItems: 3, + minItems: 3, }, data: [ [ @@ -1685,50 +1685,50 @@ const abiToJsonSchemaCases: AbiToJsonSchemaCase[] = [ }, json: { fullSchema: { - type: 'array', - items: [ - { - type: 'array', - $id: 'x1', - items: [ - { - type: 'array', - $id: 'x1', - items: { - format: 'uint256', - required: true, - } - } - ] - }, - { - type: 'array', - $id: 'x2', - items: [ - { - type: 'array', - $id: 'x2', - items: { - format: 'uint256', - required: true, - } - } - ] - }, - { - $id: 'x3', - format: 'uint256', - required: true, - } - ], - maxItems: 3, - minItems: 3, - }, + type: 'array', + items: [ + { + type: 'array', + $id: 'x1', + items: [ + { + type: 'array', + $id: 'x1', + items: { + format: 'uint256', + required: true, + }, + }, + ], + }, + { + type: 'array', + $id: 'x2', + items: [ + { + type: 'array', + $id: 'x2', + items: { + format: 'uint256', + required: true, + }, + }, + ], + }, + { + $id: 'x3', + format: 'uint256', + required: true, + }, + ], + maxItems: 3, + minItems: 3, + }, shortSchema: { type: 'array', items: [ { - $id: '/0/0', + $id: '/0/0', type: 'array', items: [ { @@ -1742,7 +1742,7 @@ const abiToJsonSchemaCases: AbiToJsonSchemaCase[] = [ ], }, { - $id: '/0/1', + $id: '/0/1', type: 'array', items: [ { diff --git a/packages/web3-validator/test/fixtures/validation.ts b/packages/web3-validator/test/fixtures/validation.ts index 8619145308a..fee254d818b 100644 --- a/packages/web3-validator/test/fixtures/validation.ts +++ b/packages/web3-validator/test/fixtures/validation.ts @@ -648,7 +648,6 @@ export const validBytesData: any[] = [ new Uint8Array(hexToBytes('abce')), new Uint8Array([0x91, 0x92]), Buffer.from([0x91, 0x92]), - ]; export const validBytesDataWithSize: [any, number][] = [ diff --git a/packages/web3-validator/test/unit/web3_validator.test.ts b/packages/web3-validator/test/unit/web3_validator.test.ts index ae04d036762..616d5c19a26 100644 --- a/packages/web3-validator/test/unit/web3_validator.test.ts +++ b/packages/web3-validator/test/unit/web3_validator.test.ts @@ -14,7 +14,7 @@ GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see . */ -import { SchemaFormatError } from 'web3-errors' +import { SchemaFormatError } from 'web3-errors'; import { abiToJsonSchemaCases } from '../fixtures/abi_to_json_schema'; import { Web3Validator } from '../../src/web3_validator'; import { Web3ValidatorError } from '../../src/errors'; @@ -33,12 +33,12 @@ describe('web3-validator', () => { }); describe('validate', () => { - describe('should pass for valid data', () => { - it.each(abiToJsonSchemaCases)('$title', ({ abi }) => { - const arrayData: ReadonlyArray = abi.data as Array; - expect(validator.validate(abi.fullSchema, arrayData)).toBeUndefined(); - }); - }) + describe('should pass for valid data', () => { + it.each(abiToJsonSchemaCases)('$title', ({ abi }) => { + const arrayData: ReadonlyArray = abi.data as Array; + expect(validator.validate(abi.fullSchema, arrayData)).toBeUndefined(); + }); + }); it('should raise error with empty value', () => { expect(() => validator.validate(['string'], [])).toThrow( diff --git a/packages/web3/CHANGELOG.md b/packages/web3/CHANGELOG.md index d03dc239294..f22108d5fd4 100644 --- a/packages/web3/CHANGELOG.md +++ b/packages/web3/CHANGELOG.md @@ -177,7 +177,7 @@ Documentation: ### Added -- Added methods (privateKeyToAddress, parseAndValidatePrivateKey, and privateKeyToPublicKey) to web3.eth.accounts (#6620) +- Added methods (privateKeyToAddress, parseAndValidatePrivateKey, and privateKeyToPublicKey) to web3.eth.accounts (#6620) ### Changed @@ -197,7 +197,6 @@ Documentation: - Added EIP-6963 utility function `requestEIP6963Providers` for multi provider discovery ( other details are in root changelog ) - ## [4.7.0] ### added @@ -208,17 +207,17 @@ Documentation: #### 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] @@ -236,27 +235,25 @@ Documentation: #### 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) @@ -276,7 +273,7 @@ Documentation: #### web3-errors -- Added `InvalidIntegerError` error for fromWei and toWei (#7052) +- Added `InvalidIntegerError` error for fromWei and toWei (#7052) #### web3-eth @@ -302,8 +299,8 @@ Documentation: #### web3-utils -- `toWei` add warning when using large numbers or large decimals that may cause precision loss (#6908) -- `toWei` and `fromWei` now supports integers as a unit. (#7053) +- `toWei` add warning when using large numbers or large decimals that may cause precision loss (#6908) +- `toWei` and `fromWei` now supports integers as a unit. (#7053) ### Fixed @@ -313,13 +310,13 @@ Documentation: #### web3-utils -- `toWei` support numbers in scientific notation (#6908) -- `toWei` and `fromWei` trims according to ether unit successfuly (#7044) +- `toWei` support numbers in scientific notation (#6908) +- `toWei` and `fromWei` trims according to ether unit successfuly (#7044) #### web3-validator -- The JSON schema conversion process now correctly assigns an id when the `abi.name` is not available, for example, in the case of public mappings. (#6981) -- `browser` entry point that was pointing to an non-existing bundle file was removed from `package.json` (#7015) +- The JSON schema conversion process now correctly assigns an id when the `abi.name` is not available, for example, in the case of public mappings. (#6981) +- `browser` entry point that was pointing to an non-existing bundle file was removed from `package.json` (#7015) #### web3-core @@ -373,7 +370,7 @@ Documentation: ### web3-rpc-providers -- RC release +- RC release ### Fixed @@ -381,7 +378,6 @@ Documentation: - `getName` reverse resolution - ## [4.11.0] ### Fixed @@ -402,7 +398,7 @@ Documentation: #### web3-eth-accounts -- baseTransaction method updated (#7095) +- baseTransaction method updated (#7095) #### web3-providers-ws @@ -425,7 +421,7 @@ Documentation: #### web3-errors -- Fixed the undefined data in `Eip838ExecutionError` constructor (#6905) +- Fixed the undefined data in `Eip838ExecutionError` constructor (#6905) #### web3-eth @@ -436,7 +432,6 @@ Documentation: - Remove redundant constructor of contractBuilder (#7150) - ## [4.12.0] ### Fixed @@ -447,7 +442,7 @@ Documentation: #### web3-eth-accounts -- Fix `TransactionFactory.registerTransactionType` not working, if there is a version mistatch between `web3-eth` and `web3-eth-accounts` by saving `extraTxTypes` at `globals`. (#7197) +- Fix `TransactionFactory.registerTransactionType` not working, if there is a version mistatch between `web3-eth` and `web3-eth-accounts` by saving `extraTxTypes` at `globals`. (#7197) ### Added @@ -457,11 +452,11 @@ Documentation: #### web3-eth-contract -- Added `populateTransaction` to the `contract.deploy(...)` properties. (#7197) +- Added `populateTransaction` to the `contract.deploy(...)` properties. (#7197) #### web3-providers-http -- Added `statusCode` of response in ResponseError, `statusCode` is optional property in ResponseError. +- Added `statusCode` of response in ResponseError, `statusCode` is optional property in ResponseError. #### web3-rpc-providers @@ -470,14 +465,14 @@ Documentation: #### web3-errors -- Added optional `statusCode` property of response in ResponseError. +- Added optional `statusCode` property of response in ResponseError. ### Changed #### web3-eth-contract - The returnred properties of `contract.deploy(...)` are structured with a newly created class named `DeployerMethodClass`. (#7197) -- Add a missed accepted type for the `abi` parameter, at `dataInputEncodeMethodHelper` and `getSendTxParams`. (#7197) +- Add a missed accepted type for the `abi` parameter, at `dataInputEncodeMethodHelper` and `getSendTxParams`. (#7197) ## [4.12.1] @@ -485,6 +480,6 @@ Documentation: #### web3-eth-accounts -- Revert `TransactionFactory.registerTransactionType` if there is a version mistatch between `web3-eth` and `web3-eth-accounts` and fix nextjs problem. (#7216) +- Revert `TransactionFactory.registerTransactionType` if there is a version mistatch between `web3-eth` and `web3-eth-accounts` and fix nextjs problem. (#7216) -## [Unreleased] \ No newline at end of file +## [Unreleased] diff --git a/packages/web3/README.md b/packages/web3/README.md index e83698ec2f8..efab77af94e 100644 --- a/packages/web3/README.md +++ b/packages/web3/README.md @@ -9,24 +9,24 @@ [![NPM Package][npm-image]][npm-url] [![Downloads][downloads-image]][npm-url] -This is the main package of [web3.js](repo), it contains a collection of comprehensive [TypeScript](https://www.typescriptlang.org/) libraries for Interaction with the [Ethereum JSON RPC API](https://ethereum.org/developers/docs/apis/json-rpc) and utility functions. +This is the main package of [web3.js](repo), it contains a collection of comprehensive [TypeScript](https://www.typescriptlang.org/) libraries for Interaction with the [Ethereum JSON RPC API](https://ethereum.org/developers/docs/apis/json-rpc) and utility functions. ## Features -- **[Web3.js Plugins🧩](https://docs.web3js.org/guides/web3_plugin_guide/)**: Enhance or add any functionality by creating scalable web3 plugins for any project. -- **Abstractions over the [JSON-RPC API](https://ethereum.org/en/developers/docs/apis/json-rpc)**: Simplifying interaction for your Developer Experience. -- **Language aligned to the official [Ethereum terminology](https://ethereum.org/en/glossary)** -- **Tree-shaking focus**: Include only what you need during bundling for optimized performance. -- **Dynamic contract types and full API in TypeScript**: Enforced with strict types for enhanced security and safety. -- **Complete utilities and functionalities for all your Ethereum needs** -- **More efficient ABI Encoder & Decoder** -- **Extensive [documentation](https://docs.web3js.org/) with guides and APIs** -- **Large collection of test cases** -- **First-class APIs for interacting with [Smart Contracts](https://ethereum.org/en/glossary#smart-contract)** -- **ESM and CJS module builds**: Support for both ECMAScript module and CommonJS module builds for flexible integration with various project setups. -- **[Contracts dynamic types](https://docs.web3js.org/guides/smart_contracts/infer_contract_types/) & full API in TypeScript** -- **Using native BigInt instead of large BigNumber libraries**: Use native BigInt for improved efficiency compared to using large external BigNumber libraries. -- **Custom Output formatters**: Format any returned value to be a string, number, BigInt, etc., providing flexibility in handling output data. +- **[Web3.js Plugins🧩](https://docs.web3js.org/guides/web3_plugin_guide/)**: Enhance or add any functionality by creating scalable web3 plugins for any project. +- **Abstractions over the [JSON-RPC API](https://ethereum.org/en/developers/docs/apis/json-rpc)**: Simplifying interaction for your Developer Experience. +- **Language aligned to the official [Ethereum terminology](https://ethereum.org/en/glossary)** +- **Tree-shaking focus**: Include only what you need during bundling for optimized performance. +- **Dynamic contract types and full API in TypeScript**: Enforced with strict types for enhanced security and safety. +- **Complete utilities and functionalities for all your Ethereum needs** +- **More efficient ABI Encoder & Decoder** +- **Extensive [documentation](https://docs.web3js.org/) with guides and APIs** +- **Large collection of test cases** +- **First-class APIs for interacting with [Smart Contracts](https://ethereum.org/en/glossary#smart-contract)** +- **ESM and CJS module builds**: Support for both ECMAScript module and CommonJS module builds for flexible integration with various project setups. +- **[Contracts dynamic types](https://docs.web3js.org/guides/smart_contracts/infer_contract_types/) & full API in TypeScript** +- **Using native BigInt instead of large BigNumber libraries**: Use native BigInt for improved efficiency compared to using large external BigNumber libraries. +- **Custom Output formatters**: Format any returned value to be a string, number, BigInt, etc., providing flexibility in handling output data. ## Installation diff --git a/packages/web3/src/accounts.ts b/packages/web3/src/accounts.ts index b0c2765257f..ed64927be54 100644 --- a/packages/web3/src/accounts.ts +++ b/packages/web3/src/accounts.ts @@ -30,8 +30,8 @@ import { signTransaction, sign, Wallet, - privateKeyToAddress, - parseAndValidatePrivateKey, + privateKeyToAddress, + parseAndValidatePrivateKey, privateKeyToPublicKey, } from 'web3-eth-accounts'; @@ -102,8 +102,8 @@ export const initAccountsForContext = (context: Web3Context) => recover, encrypt, wallet, - privateKeyToAddress, - parseAndValidatePrivateKey, + privateKeyToAddress, + parseAndValidatePrivateKey, privateKeyToPublicKey, - } + }; }; diff --git a/packages/web3/src/providers.exports.ts b/packages/web3/src/providers.exports.ts index c3d8bfcba08..3d20b0116b9 100644 --- a/packages/web3/src/providers.exports.ts +++ b/packages/web3/src/providers.exports.ts @@ -19,4 +19,4 @@ export { Eip1193Provider, SocketProvider } from 'web3-utils'; export * as http from 'web3-providers-http'; export * as ws from 'web3-providers-ws'; -export * from './web3_eip6963.js'; \ No newline at end of file +export * from './web3_eip6963.js'; diff --git a/packages/web3/src/web3_eip6963.ts b/packages/web3/src/web3_eip6963.ts index 787502a4125..cf7f44a19be 100644 --- a/packages/web3/src/web3_eip6963.ts +++ b/packages/web3/src/web3_eip6963.ts @@ -15,77 +15,77 @@ You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see . */ -import { Web3APISpec, EIP1193Provider } from "web3-types"; - +import { Web3APISpec, EIP1193Provider } from 'web3-types'; export enum Eip6963EventName { - eip6963announceProvider = 'eip6963:announceProvider', - eip6963requestProvider = 'eip6963:requestProvider', -}; + eip6963announceProvider = 'eip6963:announceProvider', + eip6963requestProvider = 'eip6963:requestProvider', +} export interface EIP6963ProviderInfo { - uuid: string; - name: string; - icon: string; - rdns: string; + uuid: string; + name: string; + icon: string; + rdns: string; } export interface EIP6963ProviderDetail { - info: EIP6963ProviderInfo; - provider: EIP1193Provider; + info: EIP6963ProviderInfo; + provider: EIP1193Provider; } export interface EIP6963AnnounceProviderEvent extends CustomEvent { - type: Eip6963EventName.eip6963announceProvider; - detail: EIP6963ProviderDetail; + type: Eip6963EventName.eip6963announceProvider; + detail: EIP6963ProviderDetail; } export interface EIP6963RequestProviderEvent extends Event { - type: Eip6963EventName.eip6963requestProvider; + type: Eip6963EventName.eip6963requestProvider; } export const eip6963ProvidersMap: Map = new Map(); -export const web3ProvidersMapUpdated = "web3:providersMapUpdated"; +export const web3ProvidersMapUpdated = 'web3:providersMapUpdated'; export interface EIP6963ProvidersMapUpdateEvent extends CustomEvent { - type: string; - detail: Map; -} - -export const requestEIP6963Providers = async () => - new Promise((resolve, reject) => { - if (typeof window === 'undefined') { - reject(new Error("window object not available, EIP-6963 is intended to be used within a browser")); - } - - window.addEventListener( - Eip6963EventName.eip6963announceProvider as any, - (event: EIP6963AnnounceProviderEvent) => { - - eip6963ProvidersMap.set( - event.detail.info.uuid, - event.detail); - - const newEvent: EIP6963ProvidersMapUpdateEvent = new CustomEvent( - web3ProvidersMapUpdated, - { detail: eip6963ProvidersMap } - ); - - window.dispatchEvent(newEvent); - resolve(eip6963ProvidersMap); - - } - ); - - window.dispatchEvent(new Event(Eip6963EventName.eip6963requestProvider)); - - }); - - -export const onNewProviderDiscovered = (callback: (providerEvent: EIP6963AnnounceProviderEvent) => void) => { - if (typeof window === 'undefined') { - throw new Error("window object not available, EIP-6963 is intended to be used within a browser"); - } - window.addEventListener(web3ProvidersMapUpdated as any, callback ); + type: string; + detail: Map; } +export const requestEIP6963Providers = async () => + new Promise((resolve, reject) => { + if (typeof window === 'undefined') { + reject( + new Error( + 'window object not available, EIP-6963 is intended to be used within a browser', + ), + ); + } + + window.addEventListener( + Eip6963EventName.eip6963announceProvider as any, + (event: EIP6963AnnounceProviderEvent) => { + eip6963ProvidersMap.set(event.detail.info.uuid, event.detail); + + const newEvent: EIP6963ProvidersMapUpdateEvent = new CustomEvent( + web3ProvidersMapUpdated, + { detail: eip6963ProvidersMap }, + ); + + window.dispatchEvent(newEvent); + resolve(eip6963ProvidersMap); + }, + ); + + window.dispatchEvent(new Event(Eip6963EventName.eip6963requestProvider)); + }); + +export const onNewProviderDiscovered = ( + callback: (providerEvent: EIP6963AnnounceProviderEvent) => void, +) => { + if (typeof window === 'undefined') { + throw new Error( + 'window object not available, EIP-6963 is intended to be used within a browser', + ); + } + window.addEventListener(web3ProvidersMapUpdated as any, callback); +}; diff --git a/packages/web3/test/cjs_black_box/.eslintrc.cjs b/packages/web3/test/cjs_black_box/.eslintrc.cjs index 88d28e7e786..b95638b5c51 100644 --- a/packages/web3/test/cjs_black_box/.eslintrc.cjs +++ b/packages/web3/test/cjs_black_box/.eslintrc.cjs @@ -7,6 +7,6 @@ module.exports = { parserOptions: { project: './tsconfig.json', tsconfigRootDir: __dirname, - ecmaVersion: 12 + ecmaVersion: 12, }, }; diff --git a/packages/web3/test/cjs_black_box/test/web3-eth-contract/erc20.test.ts b/packages/web3/test/cjs_black_box/test/web3-eth-contract/erc20.test.ts index 3f8f88238e0..64b3b4809f1 100644 --- a/packages/web3/test/cjs_black_box/test/web3-eth-contract/erc20.test.ts +++ b/packages/web3/test/cjs_black_box/test/web3-eth-contract/erc20.test.ts @@ -22,7 +22,7 @@ import { isWs, getSystemTestProvider, createNewAccount, - BACKEND + BACKEND, // eslint-disable-next-line import/no-relative-packages } from '../../../shared_fixtures/system_tests_utils'; import { diff --git a/packages/web3/test/config/jest.config.js b/packages/web3/test/config/jest.config.js index d61c13316fa..28d62955096 100644 --- a/packages/web3/test/config/jest.config.js +++ b/packages/web3/test/config/jest.config.js @@ -40,5 +40,5 @@ module.exports = { * This can be done programmatically using jest.resetModules(). */ resetModules: true, - testTimeout: 600000, + testTimeout: 600000, }; diff --git a/packages/web3/test/e2e/setup.js b/packages/web3/test/e2e/setup.js index c480060944a..d527ad558d3 100644 --- a/packages/web3/test/e2e/setup.js +++ b/packages/web3/test/e2e/setup.js @@ -18,4 +18,3 @@ along with web3.js. If not, see . // Have to use `require` because of Jest issue https://jestjs.io/docs/ecmascript-modules // eslint-disable-next-line @typescript-eslint/no-require-imports require('../config/setup'); - diff --git a/packages/web3/test/esm_black_box/test/web3-eth-contract/erc20.test.ts b/packages/web3/test/esm_black_box/test/web3-eth-contract/erc20.test.ts index dda2509ac97..ab52726b29e 100644 --- a/packages/web3/test/esm_black_box/test/web3-eth-contract/erc20.test.ts +++ b/packages/web3/test/esm_black_box/test/web3-eth-contract/erc20.test.ts @@ -25,7 +25,7 @@ import { isWs, getSystemTestProvider, createNewAccount, - BACKEND + BACKEND, } from '../../../shared_fixtures/system_tests_utils'; import { ERC20TokenAbi, ERC20TokenBytecode } from '../../../shared_fixtures/contracts/ERC20Token'; diff --git a/packages/web3/test/fixtures/transaction_middleware.ts b/packages/web3/test/fixtures/transaction_middleware.ts index f2d74a973e0..0bfa79d9563 100644 --- a/packages/web3/test/fixtures/transaction_middleware.ts +++ b/packages/web3/test/fixtures/transaction_middleware.ts @@ -15,24 +15,21 @@ You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see . */ -import { TransactionMiddleware, TransactionMiddlewareData } from "web3-eth"; +import { TransactionMiddleware, TransactionMiddlewareData } from 'web3-eth'; -// Sample Transaction Middleware +// Sample Transaction Middleware export class CTransactionMiddleware implements TransactionMiddleware { - // eslint-disable-next-line class-methods-use-this - public async processTransaction(transaction: TransactionMiddlewareData, - _options?: { [key: string]: unknown } | undefined): - - Promise { - + public async processTransaction( + transaction: TransactionMiddlewareData, + _options?: { [key: string]: unknown } | undefined, + ): Promise { // eslint-disable-next-line prefer-const let txObj = { ...transaction }; - // Add your logic here for transaction modification + // Add your logic here for transaction modification txObj.data = '0x123'; return Promise.resolve(txObj); } - } diff --git a/packages/web3/test/integration/contract-middleware.test.ts b/packages/web3/test/integration/contract-middleware.test.ts index dd8c4b8df1b..789f7e3c6f7 100644 --- a/packages/web3/test/integration/contract-middleware.test.ts +++ b/packages/web3/test/integration/contract-middleware.test.ts @@ -15,13 +15,16 @@ You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see . */ -import { CTransactionMiddleware } from -// eslint-disable-next-line import/no-relative-packages -"../fixtures/transaction_middleware"; +import { + CTransactionMiddleware, + // eslint-disable-next-line import/no-relative-packages +} from '../fixtures/transaction_middleware'; -import { blockMockResult, receiptMockResult } from -// eslint-disable-next-line import/no-relative-packages -"../../../../tools/web3-plugin-example/test/unit/fixtures/transactions_data"; +import { + blockMockResult, + receiptMockResult, + // eslint-disable-next-line import/no-relative-packages +} from '../../../../tools/web3-plugin-example/test/unit/fixtures/transactions_data'; import { Web3 } from '../../src/index'; import { @@ -51,7 +54,6 @@ describe('Contract Middleware', () => { expect(web3.eth.getTransactionMiddleware()).toBeDefined(); expect(contractB.getTransactionMiddleware()).toBeDefined(); expect(web3.eth.getTransactionMiddleware()).toEqual(contractB.getTransactionMiddleware()); - }); it('should send transaction middleware in contract new instance if its set at eth package', async () => { @@ -69,32 +71,30 @@ describe('Contract Middleware', () => { const account = web3.eth.accounts.create(); let blockNum = 1000; - web3.requestManager.send = jest.fn(async (request) => { + web3.requestManager.send = jest.fn(async request => { blockNum += 1; if (request.method === 'eth_getBlockByNumber') { - return Promise.resolve(blockMockResult.result); } if (request.method === 'eth_call') { - - return Promise.resolve("0x"); + return Promise.resolve('0x'); } if (request.method === 'eth_blockNumber') { - return Promise.resolve(blockNum.toString(16)); } if (request.method === 'eth_sendTransaction') { - sendTransactionSpy(request.params); - return Promise.resolve("0xdf7756865c2056ce34c4eabe4eff42ad251a9f920a1c620c00b4ea0988731d3f"); + return Promise.resolve( + '0xdf7756865c2056ce34c4eabe4eff42ad251a9f920a1c620c00b4ea0988731d3f', + ); } if (request.method === 'eth_getTransactionReceipt') { return Promise.resolve(receiptMockResult.result); } - return Promise.resolve("Unknown Request" as any); + return Promise.resolve('Unknown Request' as any); }); await contract.methods.transfer(account.address, 100).send({ from: account?.address }); @@ -106,11 +106,10 @@ describe('Contract Middleware', () => { expect(sendTransactionSpy).toHaveBeenCalledWith( expect.arrayContaining([ expect.objectContaining({ - data: "0x123", + data: '0x123', from: account.address, - }) - ]) + }), + ]), ); }); }); - diff --git a/packages/web3/test/integration/external-providers/hardhat.test.ts b/packages/web3/test/integration/external-providers/hardhat.test.ts index 6a4fb6ff28b..3bc154988c9 100644 --- a/packages/web3/test/integration/external-providers/hardhat.test.ts +++ b/packages/web3/test/integration/external-providers/hardhat.test.ts @@ -18,7 +18,7 @@ along with web3.js. If not, see . // eslint-disable-next-line import/no-extraneous-dependencies import hardhat from 'hardhat'; -import { performBasicRpcCalls, failErrorCalls} from './helper'; +import { performBasicRpcCalls, failErrorCalls } from './helper'; describe('compatibility with `hardhat` provider', () => { it('should initialize Web3, get accounts & block number and send a transaction', async () => { @@ -28,6 +28,5 @@ describe('compatibility with `hardhat` provider', () => { it('should throw on error calls', async () => { const result = failErrorCalls(hardhat.network.provider); await expect(result).rejects.toThrow(); - - }) + }); }); diff --git a/packages/web3/test/integration/setup.js b/packages/web3/test/integration/setup.js index c480060944a..d527ad558d3 100644 --- a/packages/web3/test/integration/setup.js +++ b/packages/web3/test/integration/setup.js @@ -18,4 +18,3 @@ along with web3.js. If not, see . // Have to use `require` because of Jest issue https://jestjs.io/docs/ecmascript-modules // eslint-disable-next-line @typescript-eslint/no-require-imports require('../config/setup'); - diff --git a/packages/web3/test/integration/web3.config.test.ts b/packages/web3/test/integration/web3.config.test.ts index 33a3e8e2ad0..0baf0d5f969 100644 --- a/packages/web3/test/integration/web3.config.test.ts +++ b/packages/web3/test/integration/web3.config.test.ts @@ -30,7 +30,7 @@ describe('Web3 instance', () => { let web3: Web3; let currentAttempt = 0; - beforeEach(() => { + beforeEach(() => { currentAttempt = 0; }); @@ -45,11 +45,11 @@ describe('Web3 instance', () => { try { await closeOpenConnection(web3); } catch (e) { - console.warn("Failed to close open con", e) + console.warn('Failed to close open con', e); } }); - afterEach(async () => { + afterEach(async () => { if (isWs) { // make sure we try to close the connection after it is established if ( @@ -65,19 +65,19 @@ describe('Web3 instance', () => { } }); - it('should be send transaction, change for defaultTransactionType and successfully send transaction with different type', async () => { + it('should be send transaction, change for defaultTransactionType and successfully send transaction with different type', async () => { const transaction = { - from: accounts[0], - to: accounts[0], - value: 100000, - } - - const receipt = await web3.eth.sendTransaction(transaction); - expect(receipt.type).toEqual(BigInt(2)) + from: accounts[0], + to: accounts[0], + value: 100000, + }; - web3.setConfig({defaultTransactionType: "0x0"}); - - const receipt2 = await web3.eth.sendTransaction(transaction); - expect(receipt2.type).toEqual(BigInt(0)) - }) -}) \ No newline at end of file + const receipt = await web3.eth.sendTransaction(transaction); + expect(receipt.type).toEqual(BigInt(2)); + + web3.setConfig({ defaultTransactionType: '0x0' }); + + const receipt2 = await web3.eth.sendTransaction(transaction); + expect(receipt2.type).toEqual(BigInt(0)); + }); +}); diff --git a/packages/web3/test/integration/web3RPCProviders.test.ts b/packages/web3/test/integration/web3RPCProviders.test.ts index 24bc312610d..1faeffad452 100644 --- a/packages/web3/test/integration/web3RPCProviders.test.ts +++ b/packages/web3/test/integration/web3RPCProviders.test.ts @@ -15,47 +15,50 @@ You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see . */ -import { mainnet , Network, QuickNodeProvider, Transport } from "web3-rpc-providers"; +import { mainnet, Network, QuickNodeProvider, Transport } from 'web3-rpc-providers'; import { Web3 } from '../../src/index'; describe('Web3 RPC Provider Integration tests', () => { - const transports = Object.values(Transport); - const networks = [Network.ETH_MAINNET, Network.ETH_HOLESKY, Network.ETH_SEPOLIA, - Network.ARBITRUM_MAINNET, Network.ARBITRUM_SEPOLIA, - Network.BNB_MAINNET, Network.BNB_TESTNET, - Network.POLYGON_MAINNET, Network.POLYGON_AMONY]; - - transports.forEach((transport) => { - networks.forEach((network) => { - it(`QuickNodeProvider should work with ${transport} transport and ${network} network`, async () => { - - const provider = new QuickNodeProvider(network, transport); - const web3 = new Web3(provider); - const result = await web3.eth.getBlockNumber() - - expect(typeof result).toBe('bigint'); - expect(result > 0).toBe(true); - - if (transport === Transport.WebSocket) { - web3.provider?.disconnect(); - } - - }); - }); - }); - it(`should work with mainnet provider`, async () => { - const web3 = new Web3(mainnet); - const result = await web3.eth.getBlockNumber() - expect(typeof result).toBe('bigint'); - expect(result > 0).toBe(true); - - }); - - it(`should work with default provider`, async () => { - const web3 = new Web3(); - const result = await web3.eth.getBlockNumber() - expect(typeof result).toBe('bigint'); - expect(result > 0).toBe(true); - - }); -}); \ No newline at end of file + const transports = Object.values(Transport); + const networks = [ + Network.ETH_MAINNET, + Network.ETH_HOLESKY, + Network.ETH_SEPOLIA, + Network.ARBITRUM_MAINNET, + Network.ARBITRUM_SEPOLIA, + Network.BNB_MAINNET, + Network.BNB_TESTNET, + Network.POLYGON_MAINNET, + Network.POLYGON_AMONY, + ]; + + transports.forEach(transport => { + networks.forEach(network => { + it(`QuickNodeProvider should work with ${transport} transport and ${network} network`, async () => { + const provider = new QuickNodeProvider(network, transport); + const web3 = new Web3(provider); + const result = await web3.eth.getBlockNumber(); + + expect(typeof result).toBe('bigint'); + expect(result > 0).toBe(true); + + if (transport === Transport.WebSocket) { + web3.provider?.disconnect(); + } + }); + }); + }); + it(`should work with mainnet provider`, async () => { + const web3 = new Web3(mainnet); + const result = await web3.eth.getBlockNumber(); + expect(typeof result).toBe('bigint'); + expect(result > 0).toBe(true); + }); + + it(`should work with default provider`, async () => { + const web3 = new Web3(); + const result = await web3.eth.getBlockNumber(); + expect(typeof result).toBe('bigint'); + expect(result > 0).toBe(true); + }); +}); diff --git a/packages/web3/test/integration/ws.test.ts b/packages/web3/test/integration/ws.test.ts index 7a11403fb32..0aa70152553 100644 --- a/packages/web3/test/integration/ws.test.ts +++ b/packages/web3/test/integration/ws.test.ts @@ -16,13 +16,9 @@ along with web3.js. If not, see . */ import { WebSocketProvider } from 'web3-providers-ws'; -import { - describeIf, getSystemTestProvider, isWs, -} from '../shared_fixtures/system_tests_utils'; +import { describeIf, getSystemTestProvider, isWs } from '../shared_fixtures/system_tests_utils'; import Web3 from '../../src/index'; - - describe('Web3 instance', () => { let web3: Web3; @@ -33,11 +29,13 @@ describe('Web3 instance', () => { describeIf(isWs)('web3 ws tests', () => { it('should connect and disconnect using safe disconnect subscription successfully', async () => { - const subscription = await web3.eth.subscribe("newBlockHeaders"); - // eslint-disable-next-line - subscription.unsubscribe(); - // eslint-disable-next-line - await expect((web3.currentProvider as WebSocketProvider).safeDisconnect()).resolves.not.toThrow(); + const subscription = await web3.eth.subscribe('newBlockHeaders'); + // eslint-disable-next-line + subscription.unsubscribe(); + // eslint-disable-next-line + await expect( + (web3.currentProvider as WebSocketProvider).safeDisconnect(), + ).resolves.not.toThrow(); }); }); -}); \ No newline at end of file +}); diff --git a/packages/web3/test/stress/long_ws_tests/nodejs_test/long_connection_ws.js b/packages/web3/test/stress/long_ws_tests/nodejs_test/long_connection_ws.js index 6d7a60a04cb..39770ed6def 100644 --- a/packages/web3/test/stress/long_ws_tests/nodejs_test/long_connection_ws.js +++ b/packages/web3/test/stress/long_ws_tests/nodejs_test/long_connection_ws.js @@ -16,7 +16,7 @@ along with web3.js. If not, see . */ /* eslint-disable */ const { Web3 } = require('../../../../lib/commonjs'); -const secrets = require('../../../../../../.secrets.json'); +const secrets = require('../../../../../../.secrets.json'); let web3; let attempt = 0; @@ -26,45 +26,51 @@ let end; // constantly send requests through WS for 10 hours const sendRequests = () => { - start = new Date(); - console.log("start:",start) - return new Promise((resolve, reject) => { - // send a request in intervals of 10 minutes - intervalId = setInterval( async() => { - try{ - const block = await web3.eth.getBlock() - attempt++; - console.log(block) - console.log("successful calls:", attempt, "has ran for:", attempt*10, "minutes") - if (attempt === 144) { // after 10 hours - clearInterval(intervalId); - resolve(""); - } - } catch (error) { - clearInterval(intervalId); - reject(error); - } - },600000) // every 10 minutes - }) - -} + start = new Date(); + console.log('start:', start); + return new Promise((resolve, reject) => { + // send a request in intervals of 10 minutes + intervalId = setInterval(async () => { + try { + const block = await web3.eth.getBlock(); + attempt++; + console.log(block); + console.log('successful calls:', attempt, 'has ran for:', attempt * 10, 'minutes'); + if (attempt === 144) { + // after 10 hours + clearInterval(intervalId); + resolve(''); + } + } catch (error) { + clearInterval(intervalId); + reject(error); + } + }, 600000); // every 10 minutes + }); +}; const main = async () => { - - try { - // You will need to set mainnet infura provider - const provider = secrets.MAINNET.WS; - web3 = new Web3(provider); - const promise = sendRequests(); - await promise; - end = new Date(); - console.log("websocket test successful") - } catch (e) { - console.warn("error occurred during ws test, on attempt: ", attempt, "program ran for: ", attempt ,"minutes with error: ", e) - } - console.log("start", start) - console.log("end", end) - process.exit(); -} + try { + // You will need to set mainnet infura provider + const provider = secrets.MAINNET.WS; + web3 = new Web3(provider); + const promise = sendRequests(); + await promise; + end = new Date(); + console.log('websocket test successful'); + } catch (e) { + console.warn( + 'error occurred during ws test, on attempt: ', + attempt, + 'program ran for: ', + attempt, + 'minutes with error: ', + e, + ); + } + console.log('start', start); + console.log('end', end); + process.exit(); +}; main(); diff --git a/packages/web3/test/stress/setup.js b/packages/web3/test/stress/setup.js index c480060944a..d527ad558d3 100644 --- a/packages/web3/test/stress/setup.js +++ b/packages/web3/test/stress/setup.js @@ -18,4 +18,3 @@ along with web3.js. If not, see . // Have to use `require` because of Jest issue https://jestjs.io/docs/ecmascript-modules // eslint-disable-next-line @typescript-eslint/no-require-imports require('../config/setup'); - diff --git a/packages/web3/test/unit/contract-middleware.test.ts b/packages/web3/test/unit/contract-middleware.test.ts index 1d7f7d2095d..cf178bef3ad 100644 --- a/packages/web3/test/unit/contract-middleware.test.ts +++ b/packages/web3/test/unit/contract-middleware.test.ts @@ -15,9 +15,10 @@ You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see . */ -import { CTransactionMiddleware } from -// eslint-disable-next-line import/no-relative-packages -"../fixtures/transaction_middleware"; +import { + CTransactionMiddleware, + // eslint-disable-next-line import/no-relative-packages +} from '../fixtures/transaction_middleware'; import { Web3 } from '../../src/index'; import { @@ -47,8 +48,5 @@ describe('Contract Middleware', () => { expect(web3.eth.getTransactionMiddleware()).toBeDefined(); expect(contractB.getTransactionMiddleware()).toBeDefined(); expect(web3.eth.getTransactionMiddleware()).toEqual(contractB.getTransactionMiddleware()); - }); - }); - diff --git a/packages/web3/test/unit/web3.config.test.ts b/packages/web3/test/unit/web3.config.test.ts index dbe6682c391..3478d83c8e9 100644 --- a/packages/web3/test/unit/web3.config.test.ts +++ b/packages/web3/test/unit/web3.config.test.ts @@ -16,137 +16,155 @@ along with web3.js. If not, see . */ import { ETH_DATA_FORMAT } from 'web3-types'; -import {Web3Context} from 'web3-core'; +import { Web3Context } from 'web3-core'; import { Web3 } from '../../src'; describe('web3config web3 tests', () => { - - describe('web3config contract', () => { - - it('create web3context with configs and should set it for web3', async () => { - const context = new Web3Context("http://127.0.0.1:8545"); - context.setConfig({defaultTransactionType: "0x0"}); - const web3 = new Web3(context); - expect(web3.getContextObject().config.defaultTransactionType).toBe("0x0"); - expect(web3.config.defaultTransactionType).toBe("0x0"); - expect(web3.eth.getContextObject().config.defaultTransactionType).toBe("0x0") - }); - - it('should be able to create web3 and setconfig for contracts', async () => { - const web3 = new Web3("http://127.0.0.1:8545"); - web3.setConfig({defaultTransactionType: "0x0"}); - expect(web3.getContextObject().config.defaultTransactionType).toBe("0x0"); - expect(web3.config.defaultTransactionType).toBe("0x0"); - expect(web3.eth.getContextObject().config.defaultTransactionType).toBe("0x0") - - const contract = new web3.eth.Contract([], ""); - expect(contract.config.defaultTransactionType).toBe("0x0") - expect(contract.getContextObject().config.defaultTransactionType).toBe("0x0"); - - contract.setConfig({contractDataInputFill:"both"}); - expect(contract.getContextObject().config.contractDataInputFill).toBe("both"); - - // web3 config shouldn't change - expect(web3.getContextObject().config.contractDataInputFill).toBe("data"); - expect(web3.config.contractDataInputFill).toBe("data"); - expect(web3.eth.getContextObject().config.contractDataInputFill).toBe("data") - }); - it('should change web3 config context but not contract config context', async () => { - const web3 = new Web3("http://127.0.0.1:8545"); - const contract = new web3.eth.Contract([]) - web3.setConfig({defaultTransactionType:"0x0"}); - expect(contract.getContextObject().config.defaultTransactionType).toBe("0x2") - expect(web3.getContextObject().config.defaultTransactionType).toBe("0x0"); - }); - - it('should not change web3config when changing contract config context', async () => { - const web3 = new Web3("http://127.0.0.1:8545"); - const contract = new web3.eth.Contract([]) - contract.setConfig({defaultTransactionType:"0x0"}); - expect(contract.getContextObject().config.defaultTransactionType).toBe("0x0") - expect(web3.getContextObject().config.defaultTransactionType).toBe("0x2"); - }); - - it('should create two contracts with different configs', () => { - const web3 = new Web3('http://127.0.0.1:8545'); - - web3.setConfig({ contractDataInputFill: "data" }); - const c1 = new web3.eth.Contract([], '') - - const c2 = new web3.eth.Contract([], new Web3Context({config: {contractDataInputFill: "input"}})) - - const c3 = new web3.eth.Contract([], {dataInputFill: "input"}) - expect(web3.config.contractDataInputFill).toBe("data") - expect(c1.config.contractDataInputFill).toBe("data") - expect(c2.config.contractDataInputFill).toBe("input"); - expect(c3.config.contractDataInputFill).toBe("input"); - - }); - - it('should create a contract with context and returnFormat properly with different parameters', () => { - const web3 = new Web3('http://127.0.0.1:8545'); - web3.setConfig({ contractDataInputFill: "data" }); - - // create contract with context in second param - const c1 = new web3.eth.Contract([], new Web3Context({config: {contractDataInputFill: "input"}})) - - // create contract with context in third param - const c2 = new web3.eth.Contract([], "", new Web3Context({config: {contractDataInputFill: "both"}})) - - // create contract with context in fourth param - const c3 = new web3.eth.Contract([], "", {gas: "gas"}, new Web3Context({config: {contractDataInputFill: "both"}})) - - expect(c1.config.contractDataInputFill).toBe("input") - expect(c1.getContextObject().config.contractDataInputFill).toBe("input"); - - expect(c2.config.contractDataInputFill).toBe("both") - expect(c2.getContextObject().config.contractDataInputFill).toBe("both"); - - expect(c3.config.contractDataInputFill).toBe("both") - expect(c3.getContextObject().config.contractDataInputFill).toBe("both"); - - // create contract with returnFormat in fourth param - const c4 = new web3.eth.Contract([], "", {gas: "gas"}, ETH_DATA_FORMAT); - - // create contract with returnFormat in fifth param - const c5 = new web3.eth.Contract([], "", {gas: "gas"}, new Web3Context({config: {contractDataInputFill: "data"}}), ETH_DATA_FORMAT) - - expect(c4.config.contractDataInputFill).toBe("data") - expect(c4.getContextObject().config.contractDataInputFill).toBe("data"); - - expect(c5.config.contractDataInputFill).toBe("data") - expect(c5.getContextObject().config.contractDataInputFill).toBe("data"); - }) - - it('should create contracts with different ways to configure', () => { - const web3 = new Web3('http://127.0.0.1:8545'); - web3.setConfig({ contractDataInputFill: "data" }); - - const c1 = new web3.eth.Contract([], '') - - const c2 = new web3.eth.Contract([], new Web3Context({config: {contractDataInputFill: "input"}})) - - const c3 = new web3.eth.Contract([], {dataInputFill: "input"}) - - expect(web3.config.contractDataInputFill).toBe("data") - expect(c1.config.contractDataInputFill).toBe("data") - expect(c2.config.contractDataInputFill).toBe("input"); - expect(c3.config.contractDataInputFill).toBe("input"); - - }); - - it('should populate dataInputFill properly', () => { - const web3 = new Web3("http://127.0.0.1:8545"); - // create a contract with options as second parameter - const c1 = new web3.eth.Contract([], {dataInputFill: "both"}); - expect((c1.config.contractDataInputFill)).toBe("both"); - - // create a contract with options as third parameter - const c2 = new web3.eth.Contract([], "", {dataInputFill: "both"}); - expect((c2.config.contractDataInputFill)).toBe("both"); - - }); - }) - // TODO: finish config unit tests - + describe('web3config contract', () => { + it('create web3context with configs and should set it for web3', async () => { + const context = new Web3Context('http://127.0.0.1:8545'); + context.setConfig({ defaultTransactionType: '0x0' }); + const web3 = new Web3(context); + expect(web3.getContextObject().config.defaultTransactionType).toBe('0x0'); + expect(web3.config.defaultTransactionType).toBe('0x0'); + expect(web3.eth.getContextObject().config.defaultTransactionType).toBe('0x0'); + }); + + it('should be able to create web3 and setconfig for contracts', async () => { + const web3 = new Web3('http://127.0.0.1:8545'); + web3.setConfig({ defaultTransactionType: '0x0' }); + expect(web3.getContextObject().config.defaultTransactionType).toBe('0x0'); + expect(web3.config.defaultTransactionType).toBe('0x0'); + expect(web3.eth.getContextObject().config.defaultTransactionType).toBe('0x0'); + + const contract = new web3.eth.Contract([], ''); + expect(contract.config.defaultTransactionType).toBe('0x0'); + expect(contract.getContextObject().config.defaultTransactionType).toBe('0x0'); + + contract.setConfig({ contractDataInputFill: 'both' }); + expect(contract.getContextObject().config.contractDataInputFill).toBe('both'); + + // web3 config shouldn't change + expect(web3.getContextObject().config.contractDataInputFill).toBe('data'); + expect(web3.config.contractDataInputFill).toBe('data'); + expect(web3.eth.getContextObject().config.contractDataInputFill).toBe('data'); + }); + it('should change web3 config context but not contract config context', async () => { + const web3 = new Web3('http://127.0.0.1:8545'); + const contract = new web3.eth.Contract([]); + web3.setConfig({ defaultTransactionType: '0x0' }); + expect(contract.getContextObject().config.defaultTransactionType).toBe('0x2'); + expect(web3.getContextObject().config.defaultTransactionType).toBe('0x0'); + }); + + it('should not change web3config when changing contract config context', async () => { + const web3 = new Web3('http://127.0.0.1:8545'); + const contract = new web3.eth.Contract([]); + contract.setConfig({ defaultTransactionType: '0x0' }); + expect(contract.getContextObject().config.defaultTransactionType).toBe('0x0'); + expect(web3.getContextObject().config.defaultTransactionType).toBe('0x2'); + }); + + it('should create two contracts with different configs', () => { + const web3 = new Web3('http://127.0.0.1:8545'); + + web3.setConfig({ contractDataInputFill: 'data' }); + const c1 = new web3.eth.Contract([], ''); + + const c2 = new web3.eth.Contract( + [], + new Web3Context({ config: { contractDataInputFill: 'input' } }), + ); + + const c3 = new web3.eth.Contract([], { dataInputFill: 'input' }); + expect(web3.config.contractDataInputFill).toBe('data'); + expect(c1.config.contractDataInputFill).toBe('data'); + expect(c2.config.contractDataInputFill).toBe('input'); + expect(c3.config.contractDataInputFill).toBe('input'); + }); + + it('should create a contract with context and returnFormat properly with different parameters', () => { + const web3 = new Web3('http://127.0.0.1:8545'); + web3.setConfig({ contractDataInputFill: 'data' }); + + // create contract with context in second param + const c1 = new web3.eth.Contract( + [], + new Web3Context({ config: { contractDataInputFill: 'input' } }), + ); + + // create contract with context in third param + const c2 = new web3.eth.Contract( + [], + '', + new Web3Context({ config: { contractDataInputFill: 'both' } }), + ); + + // create contract with context in fourth param + const c3 = new web3.eth.Contract( + [], + '', + { gas: 'gas' }, + new Web3Context({ config: { contractDataInputFill: 'both' } }), + ); + + expect(c1.config.contractDataInputFill).toBe('input'); + expect(c1.getContextObject().config.contractDataInputFill).toBe('input'); + + expect(c2.config.contractDataInputFill).toBe('both'); + expect(c2.getContextObject().config.contractDataInputFill).toBe('both'); + + expect(c3.config.contractDataInputFill).toBe('both'); + expect(c3.getContextObject().config.contractDataInputFill).toBe('both'); + + // create contract with returnFormat in fourth param + const c4 = new web3.eth.Contract([], '', { gas: 'gas' }, ETH_DATA_FORMAT); + + // create contract with returnFormat in fifth param + const c5 = new web3.eth.Contract( + [], + '', + { gas: 'gas' }, + new Web3Context({ config: { contractDataInputFill: 'data' } }), + ETH_DATA_FORMAT, + ); + + expect(c4.config.contractDataInputFill).toBe('data'); + expect(c4.getContextObject().config.contractDataInputFill).toBe('data'); + + expect(c5.config.contractDataInputFill).toBe('data'); + expect(c5.getContextObject().config.contractDataInputFill).toBe('data'); + }); + + it('should create contracts with different ways to configure', () => { + const web3 = new Web3('http://127.0.0.1:8545'); + web3.setConfig({ contractDataInputFill: 'data' }); + + const c1 = new web3.eth.Contract([], ''); + + const c2 = new web3.eth.Contract( + [], + new Web3Context({ config: { contractDataInputFill: 'input' } }), + ); + + const c3 = new web3.eth.Contract([], { dataInputFill: 'input' }); + + expect(web3.config.contractDataInputFill).toBe('data'); + expect(c1.config.contractDataInputFill).toBe('data'); + expect(c2.config.contractDataInputFill).toBe('input'); + expect(c3.config.contractDataInputFill).toBe('input'); + }); + + it('should populate dataInputFill properly', () => { + const web3 = new Web3('http://127.0.0.1:8545'); + // create a contract with options as second parameter + const c1 = new web3.eth.Contract([], { dataInputFill: 'both' }); + expect(c1.config.contractDataInputFill).toBe('both'); + + // create a contract with options as third parameter + const c2 = new web3.eth.Contract([], '', { dataInputFill: 'both' }); + expect(c2.config.contractDataInputFill).toBe('both'); + }); + }); + // TODO: finish config unit tests }); diff --git a/packages/web3/test/unit/web3.test.ts b/packages/web3/test/unit/web3.test.ts index 3cd00a9e718..fdd20f8a6b0 100644 --- a/packages/web3/test/unit/web3.test.ts +++ b/packages/web3/test/unit/web3.test.ts @@ -21,9 +21,9 @@ import { Web3 } from '../../src/web3'; describe('Web3 object', () => { it('should be able to set and read web3 providers', () => { - const web3NoProvider = new Web3(""); + const web3NoProvider = new Web3(''); expect(web3NoProvider).toBeTruthy(); - expect(web3NoProvider.provider).toBe(""); + expect(web3NoProvider.provider).toBe(''); const web3 = new Web3('http://somenode'); expect(web3).toBeTruthy(); diff --git a/packages/web3/test/unit/web3eip6963.test.ts b/packages/web3/test/unit/web3eip6963.test.ts index 1f465aba124..e9e719e7552 100644 --- a/packages/web3/test/unit/web3eip6963.test.ts +++ b/packages/web3/test/unit/web3eip6963.test.ts @@ -15,77 +15,81 @@ You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see . */ -import { - onNewProviderDiscovered, - requestEIP6963Providers -} from "../../src/web3_eip6963"; +import { onNewProviderDiscovered, requestEIP6963Providers } from '../../src/web3_eip6963'; describe('requestEIP6963Providers', () => { - it('should reject with an error if window object is not available', async () => { - // Mocking window object absence - (global as any).window = undefined; - - // eslint-disable-next-line @typescript-eslint/no-unsafe-call - await expect(requestEIP6963Providers()).rejects.toThrow("window object not available, EIP-6963 is intended to be used within a browser"); - }); - - it('should resolve with updated providers map when events are triggered', async () => { - class CustomEventPolyfill extends Event { - public detail: any; - public constructor(eventType: string, eventInitDict: any) { - super(eventType, eventInitDict); - this.detail = eventInitDict.detail; - } - } - - (global as any).CustomEvent = CustomEventPolyfill; - - const mockProviderDetail = { - info: { uuid: 'test-uuid', name: 'Test Provider', icon: 'test-icon', rdns: 'test-rdns' }, - provider: {} // Mock provider object - }; - - const mockEvent = { - type: 'eip6963:announceProvider', - detail: mockProviderDetail - }; - - // Mock window methods - (global as any).window = { - addEventListener: jest.fn().mockImplementation( - - (_event, callback) => callback(mockEvent)), // eslint-disable-line - dispatchEvent: jest.fn() - }; - - const result = await requestEIP6963Providers(); - - expect(result).toEqual(new Map([['test-uuid', mockProviderDetail]])); - }); - - it('onNewProviderDiscovered should throw an error if window object is not available', () => { - // Mock the window object not being available - (global as any).window = undefined; - - // Expect an error to be thrown - expect(() => { - // eslint-disable-next-line @typescript-eslint/no-empty-function - onNewProviderDiscovered((_providerEvent) => {}); - }).toThrow("window object not available, EIP-6963 is intended to be used within a browser"); - - - }); - - it('onNewProviderDiscovered should add an event listener when window object is available', () => { - (global as any).window = { - addEventListener: jest.fn(), - }; - - const callback = jest.fn(); - onNewProviderDiscovered(callback); - - // Expect the callback to have been called when the event listener is added - expect(global.window.addEventListener).toHaveBeenCalledWith('web3:providersMapUpdated', callback); - }); - -}); \ No newline at end of file + it('should reject with an error if window object is not available', async () => { + // Mocking window object absence + (global as any).window = undefined; + + // eslint-disable-next-line @typescript-eslint/no-unsafe-call + await expect(requestEIP6963Providers()).rejects.toThrow( + 'window object not available, EIP-6963 is intended to be used within a browser', + ); + }); + + it('should resolve with updated providers map when events are triggered', async () => { + class CustomEventPolyfill extends Event { + public detail: any; + public constructor(eventType: string, eventInitDict: any) { + super(eventType, eventInitDict); + this.detail = eventInitDict.detail; + } + } + + (global as any).CustomEvent = CustomEventPolyfill; + + const mockProviderDetail = { + info: { + uuid: 'test-uuid', + name: 'Test Provider', + icon: 'test-icon', + rdns: 'test-rdns', + }, + provider: {}, // Mock provider object + }; + + const mockEvent = { + type: 'eip6963:announceProvider', + detail: mockProviderDetail, + }; + + // Mock window methods + (global as any).window = { + addEventListener: jest + .fn() + .mockImplementation((_event, callback) => callback(mockEvent)), // eslint-disable-line + dispatchEvent: jest.fn(), + }; + + const result = await requestEIP6963Providers(); + + expect(result).toEqual(new Map([['test-uuid', mockProviderDetail]])); + }); + + it('onNewProviderDiscovered should throw an error if window object is not available', () => { + // Mock the window object not being available + (global as any).window = undefined; + + // Expect an error to be thrown + expect(() => { + // eslint-disable-next-line @typescript-eslint/no-empty-function + onNewProviderDiscovered(_providerEvent => {}); + }).toThrow('window object not available, EIP-6963 is intended to be used within a browser'); + }); + + it('onNewProviderDiscovered should add an event listener when window object is available', () => { + (global as any).window = { + addEventListener: jest.fn(), + }; + + const callback = jest.fn(); + onNewProviderDiscovered(callback); + + // Expect the callback to have been called when the event listener is added + expect(global.window.addEventListener).toHaveBeenCalledWith( + 'web3:providersMapUpdated', + callback, + ); + }); +}); diff --git a/scripts/system_tests_utils.ts b/scripts/system_tests_utils.ts index 11f9bcef717..e634b98a35b 100644 --- a/scripts/system_tests_utils.ts +++ b/scripts/system_tests_utils.ts @@ -55,7 +55,7 @@ import { // eslint-disable-next-line import/no-extraneous-dependencies import { Personal } from 'web3-eth-personal'; // eslint-disable-next-line import/no-extraneous-dependencies -import {Web3, WebSocketProvider } from 'web3'; +import { Web3, WebSocketProvider } from 'web3'; // eslint-disable-next-line import/no-extraneous-dependencies import { NonPayableMethodObject } from 'web3-eth-contract'; @@ -83,7 +83,7 @@ export const BACKEND = { MAINNET: 'mainnet', }; -export const getSystemTestProviderUrl = (): string => +export const getSystemTestProviderUrl = (): string => getEnvVar('WEB3_SYSTEM_TEST_PROVIDER') ?? DEFAULT_SYSTEM_PROVIDER; export const getSystemTestProvider = (): @@ -156,21 +156,18 @@ export const waitForOpenConnection = async ( export const closeOpenConnection = async (web3Context: Web3Context) => { if ( - web3Context?.provider && ( - web3Context?.provider instanceof WebSocketProvider || - web3Context?.provider instanceof IpcProvider - - ) && + web3Context?.provider && + (web3Context?.provider instanceof WebSocketProvider || + web3Context?.provider instanceof IpcProvider) && 'disconnect' in (web3Context.provider as unknown as Web3BaseProvider) ) { - - (web3Context.provider as unknown as Web3BaseProvider).reset(); - (web3Context.provider as unknown as Web3BaseProvider).disconnect(); + (web3Context.provider as unknown as Web3BaseProvider).reset(); + (web3Context.provider as unknown as Web3BaseProvider).disconnect(); - await new Promise(resolve => { - setTimeout(resolve, 1000); - }); - } + await new Promise(resolve => { + setTimeout(resolve, 1000); + }); + } }; export const createAccountProvider = (context: Web3Context) => { @@ -232,8 +229,7 @@ export const refillAccount = async (from: string, to: string, value: string | nu value, }); - if(receipt.status !== BigInt(1)) - throw new Error("refillAccount failed"); + if (receipt.status !== BigInt(1)) throw new Error('refillAccount failed'); await closeOpenConnection(web3Eth); }; @@ -246,7 +242,6 @@ export const createNewAccount = async (config?: { password?: string; doNotImport?: boolean; }): Promise<{ address: string; privateKey: string }> => { - const acc = config?.privateKey ? privateKeyToAccount(config?.privateKey) : _createAccount(); const clientUrl = DEFAULT_SYSTEM_PROVIDER; @@ -295,7 +290,6 @@ export const createNewAccount = async (config?: { return { address: acc.address.toLowerCase(), privateKey: acc.privateKey }; }; - let tempAccountList: { address: string; privateKey: string }[] = []; const walletsOnWorker = 20; @@ -482,7 +476,7 @@ export const sendFewSampleTxs = async (cnt = 1) => { const web3 = new Web3(DEFAULT_SYSTEM_PROVIDER); const fromAcc = await createLocalAccount(web3); const toAcc = createAccount(); - const res: TransactionReceipt[]= []; + const res: TransactionReceipt[] = []; for (let i = 0; i < cnt; i += 1) { // eslint-disable-next-line no-await-in-loop const receipt = await web3.eth.sendTransaction({ @@ -492,12 +486,9 @@ export const sendFewSampleTxs = async (cnt = 1) => { gas: '300000', }); - if(receipt.status !== BigInt(1)) - throw new Error("sendFewSampleTxs failed "); + if (receipt.status !== BigInt(1)) throw new Error('sendFewSampleTxs failed '); - res.push( - receipt - ); + res.push(receipt); } await closeOpenConnection(web3); return res; @@ -523,14 +514,15 @@ export const waitForCondition = async ( conditionFunc: () => boolean, logicFunc: () => Promise | void, maxIterations = 10, // 10 times - duration = 8000, // check after each 8 seconds + duration = 8000, // check after each 8 seconds ): Promise => { return new Promise((resolve, reject) => { let iterations = 0; // eslint-disable-next-line @typescript-eslint/no-misused-promises const interval = setInterval(async () => { try { - if (iterations > 0 && conditionFunc()) { // wait duration before first check + if (iterations > 0 && conditionFunc()) { + // wait duration before first check clearInterval(interval); await logicFunc(); resolve(); @@ -548,4 +540,4 @@ export const waitForCondition = async ( } }, duration); }); -}; \ No newline at end of file +}; diff --git a/templates/.prettierignore.tmpl b/templates/.prettierignore.tmpl index 76075e77df3..32e43f51bd7 100644 --- a/templates/.prettierignore.tmpl +++ b/templates/.prettierignore.tmpl @@ -4,6 +4,7 @@ LICENSE mocha.opts .DS_Store REVISION +.eslintcache # rc files .*rc diff --git a/templates/cypress.config.js b/templates/cypress.config.js index 977e51c90db..2b000caf46e 100644 --- a/templates/cypress.config.js +++ b/templates/cypress.config.js @@ -25,7 +25,7 @@ const config = { }, specPattern: 'test/integration/**/**/*.test.ts', excludeSpecPattern: ['**/contract_defaults_extra.test.ts'], - defaultCommandTimeout: 120000 + defaultCommandTimeout: 120000, }, }; diff --git a/tools/web3-plugin-example/CHANGELOG.md b/tools/web3-plugin-example/CHANGELOG.md index 76e9b8f8b96..f2a7f07a098 100644 --- a/tools/web3-plugin-example/CHANGELOG.md +++ b/tools/web3-plugin-example/CHANGELOG.md @@ -94,8 +94,8 @@ Transaction middleware (#7088) ## [1.1.1] -### Changed +### Changed - Dependencies updated -## [Unreleased] \ No newline at end of file +## [Unreleased] diff --git a/tools/web3-plugin-example/src/custom_rpc_methods.ts b/tools/web3-plugin-example/src/custom_rpc_methods.ts index d5ff583ddf5..80af3e76e2e 100644 --- a/tools/web3-plugin-example/src/custom_rpc_methods.ts +++ b/tools/web3-plugin-example/src/custom_rpc_methods.ts @@ -38,14 +38,11 @@ export class CustomRpcMethodsPlugin extends Web3PluginBase { } public link(parentContext: Web3Context): void { - - if (this.web3Middleware) - parentContext.requestManager.setMiddleware(this.web3Middleware); + if (this.web3Middleware) parentContext.requestManager.setMiddleware(this.web3Middleware); super.link(parentContext); } - public async customRpcMethod() { return this.requestManager.send({ method: 'custom_rpc_method', @@ -59,7 +56,6 @@ export class CustomRpcMethodsPlugin extends Web3PluginBase { params: [parameter1, parameter2], }); } - } // Module Augmentation diff --git a/tools/web3-plugin-example/src/request_manager_middleware.ts b/tools/web3-plugin-example/src/request_manager_middleware.ts index bf16bc619f8..6557b836651 100644 --- a/tools/web3-plugin-example/src/request_manager_middleware.ts +++ b/tools/web3-plugin-example/src/request_manager_middleware.ts @@ -42,16 +42,13 @@ export class Web3Middleware implements RequestManagerMiddleware { } return req; }); - } else if ( - (reqObj ).method === 'eth_call' && - Array.isArray((reqObj ).params) - ) { - (reqObj ) = { - ...(reqObj ), - // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment - params: [...((reqObj ).params ?? []), '0x0', '0x1'], - }; - } + } else if (reqObj.method === 'eth_call' && Array.isArray(reqObj.params)) { + reqObj = { + ...reqObj, + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + params: [...(reqObj.params ?? []), '0x0', '0x1'], + }; + } return Promise.resolve(reqObj as JsonRpcPayload); } diff --git a/tools/web3-plugin-example/src/transaction_middleware.ts b/tools/web3-plugin-example/src/transaction_middleware.ts index d38eec8127b..736f1fed6ff 100644 --- a/tools/web3-plugin-example/src/transaction_middleware.ts +++ b/tools/web3-plugin-example/src/transaction_middleware.ts @@ -15,24 +15,21 @@ You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see . */ -import { TransactionMiddleware, TransactionMiddlewareData } from "web3-eth"; +import { TransactionMiddleware, TransactionMiddlewareData } from 'web3-eth'; -// Sample Transaction Middleware +// Sample Transaction Middleware export class Web3TransactionMiddleware implements TransactionMiddleware { - // eslint-disable-next-line class-methods-use-this - public async processTransaction(transaction: TransactionMiddlewareData, - _options?: { [key: string]: unknown } | undefined): - - Promise { - + public async processTransaction( + transaction: TransactionMiddlewareData, + _options?: { [key: string]: unknown } | undefined, + ): Promise { // eslint-disable-next-line prefer-const let txObj = { ...transaction }; - // Add your logic here for transaction modification + // Add your logic here for transaction modification txObj.data = '0x123'; return Promise.resolve(txObj); } - } diff --git a/tools/web3-plugin-example/src/transaction_middleware_plugin.ts b/tools/web3-plugin-example/src/transaction_middleware_plugin.ts index bd9eca6b848..69fbc52adf9 100644 --- a/tools/web3-plugin-example/src/transaction_middleware_plugin.ts +++ b/tools/web3-plugin-example/src/transaction_middleware_plugin.ts @@ -31,16 +31,13 @@ export class TransactionMiddlewarePlugin extends Web3PluginBase { } public link(parentContext: Web3Context): void { - - if (this.txMiddleware){ + if (this.txMiddleware) { // Following can modify Web3-Eth and also Web3-Eth-Contract packages transactions - + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-call (parentContext as any).Web3Eth.setTransactionMiddleware(this.txMiddleware); } super.link(parentContext); } - } - diff --git a/tools/web3-plugin-example/test/unit/contract_transaction_middleware.test.ts b/tools/web3-plugin-example/test/unit/contract_transaction_middleware.test.ts index 024e4219d28..201a8b040e6 100644 --- a/tools/web3-plugin-example/test/unit/contract_transaction_middleware.test.ts +++ b/tools/web3-plugin-example/test/unit/contract_transaction_middleware.test.ts @@ -21,9 +21,7 @@ import { TransactionMiddlewarePlugin } from '../../src/transaction_middleware_pl import { blockMockResult, receiptMockResult } from './fixtures/transactions_data'; describe('Contract Transaction Middleware', () => { - it('should modify contracts deployment transaction before signing and sending', async () => { - // This will allow Contract Transaction modification before signing and gas estimations const web3 = new Web3('http://127.0.0.1:8545'); @@ -35,7 +33,7 @@ describe('Contract Transaction Middleware', () => { // Create a spy for eth_sendTransaction const sendTransactionSpy = jest.fn(); - web3.requestManager.send = jest.fn(async (request) => { + web3.requestManager.send = jest.fn(async request => { blockNum += 1; if (request.method === 'eth_getBlockByNumber') { @@ -47,13 +45,15 @@ describe('Contract Transaction Middleware', () => { if (request.method === 'eth_sendTransaction') { // Call the spy with the request params sendTransactionSpy(request.params); - return Promise.resolve("0xdf7756865c2056ce34c4eabe4eff42ad251a9f920a1c620c00b4ea0988731d3f"); + return Promise.resolve( + '0xdf7756865c2056ce34c4eabe4eff42ad251a9f920a1c620c00b4ea0988731d3f', + ); } if (request.method === 'eth_getTransactionReceipt') { return Promise.resolve(receiptMockResult.result); } - return Promise.resolve("Unknown Request" as any); + return Promise.resolve('Unknown Request' as any); }); /// Mock block ends here @@ -62,40 +62,41 @@ describe('Contract Transaction Middleware', () => { const contract: Contract = new web3.eth.Contract(GreeterAbi); - await contract.deploy( - { + await contract + .deploy({ data: GreeterBytecode, arguments: ['My Greeting'], } as any) - .send( - { from: '0x6E599DA0bfF7A6598AC1224E4985430Bf16458a4' } - ); // this should call Tx middleware for contract deploy + .send({ from: '0x6E599DA0bfF7A6598AC1224E4985430Bf16458a4' }); // this should call Tx middleware for contract deploy - const deployedContract = new web3.eth.Contract(GreeterAbi, "0x5FbDB2315678afecb367f032d93F642f64180aa3"); - await deployedContract.methods.increment().send( - { from: '0x6E599DA0bfF7A6598AC1224E4985430Bf16458a4' }); // this should call Tx middleware for method send + const deployedContract = new web3.eth.Contract( + GreeterAbi, + '0x5FbDB2315678afecb367f032d93F642f64180aa3', + ); + await deployedContract.methods + .increment() + .send({ from: '0x6E599DA0bfF7A6598AC1224E4985430Bf16458a4' }); // this should call Tx middleware for method send // First, check the number of calls expect(sendTransactionSpy).toHaveBeenCalledTimes(2); - const expectedData = "0x123"; + const expectedData = '0x123'; // Then, check each call individually expect(sendTransactionSpy.mock.calls[0][0]).toEqual( expect.arrayContaining([ expect.objectContaining({ - data: expectedData - }) - ]) + data: expectedData, + }), + ]), ); expect(sendTransactionSpy.mock.calls[1][0]).toEqual( expect.arrayContaining([ expect.objectContaining({ - data: expectedData - }) - ]) + data: expectedData, + }), + ]), ); }); - }); diff --git a/tools/web3-plugin-example/test/unit/fixtures/transactions_data.ts b/tools/web3-plugin-example/test/unit/fixtures/transactions_data.ts index 189e2135ae4..5daf37d9bb9 100644 --- a/tools/web3-plugin-example/test/unit/fixtures/transactions_data.ts +++ b/tools/web3-plugin-example/test/unit/fixtures/transactions_data.ts @@ -16,102 +16,104 @@ along with web3.js. If not, see . */ export const blockMockResult = { - "jsonrpc": "2.0", - "id": "a40a81fa-1f8b-4bb2-a0ad-eef9b6d4636f", - "result": { - "baseFeePerGas": "0x44dab2983", - "blobGasUsed": "0x20000", - "difficulty": "0x0", - "excessBlobGas": "0x1c0000", - "extraData": "0x407273796e636275696c646572", - "gasLimit": "0x1c9c380", - "gasUsed": "0xb7a086", - "hash": "0xf2b1729965179032b17165678a1a212fa31cb008e30f4011ffe8ebdddbd02b95", - "logsBloom": "0xc3a70590c1c62524173d1892e33888067101934dc0891c2c9a898252b6f320215084a48906452960820188d32bba6fb82ec989018a0268603a00a4c6432a11276c9a038c676938eb68bc436c9905a9a1b08d238fb4458f48498215808bec81112e2a3a54869ff22422a8e491093da8a40f601d198417041cd22f799f9048865006e0b069ab049b852442b310396248088145e2810f230f9a44000c6868bc73e9afa8832a8ac92fd609007ac53c0a9cba0645ce298080184624e8040831dbc331f5e618072407050250021b3210e542781183a612d4618c1244000d421a6ca9c01a57e86a085402c55ab413f840a001e7117894d0469e20c2304a9655e344f60d", - "miner": "0x1f9090aae28b8a3dceadf281b0f12828e676c326", - "mixHash": "0x787ab1d511b72df60a705bb4cfc4e92e2f9d203e3e007ae3a0f757425951ca24", - "nonce": "0x0000000000000000", - "number": "0x131ad16", - "parentBeaconBlockRoot": "0x03bbca9fd0c7a0a020de04287f489112c79bc268220e9ff8e18957cd0d5c3cad", - "parentHash": "0xb1d8fa7b8346421d373a6d4c28575155516cea17c12a3df7201170c9e561b38c", - "receiptsRoot": "0x4ec500bdcd761ad505b2a989156c9a9628058d415acc93d800487c7c76308c59", - "sha3Uncles": "0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347", - "size": "0xcb90", - "stateRoot": "0xafbb8743c0a5f4740e322217cb1f2780ee5c57c32bcd04e9256b09efc1a70568", - "timestamp": "0x6661ab8b", - "totalDifficulty": "0xc70d815d562d3cfa955", - "transactions": [ - "0x589956b75d19dbaf9911f246c23d4b3327ef234872ec1931c419041b23eb5b41", - "0x4d3793f20c25979bd329cafdd889ba6be015cfc999acce8642d6e757b5192e93", - "0x5ba5618ca5a14bab50862255dc69726a498346f9832bd0fd1394e8834e56790b", - "0x6df9678f350db7e30afc930b7246bf1c144b9acb7fd1d25d7e107d550ed5a061", - "0xb8f48ff2876cc393725ea4162421754dfb74ff2364a12d4d3de2c6269f1958c7", - "0x2e5cf7c0607025038b6ccd871dc9ce85af686fd5fa2c82e605198af9afa92cca", - "0x307fb855836feff5d8d0969fa4a44d3c6ae31d335da6577f48f9496d6fe9e0b9", - "0x1362bed1aa8a30d28b7b76c35c2a8601b257058beffa9490dcb20de12bcb15b2", - "0x234c7cc346c204022b2e5ead6d2e8c02317aeb0ec5ca82bd97c2b5d5e59a280b", - ], - "transactionsRoot": "0xc21a4d667b5f841538430b1e2c002c598f2178628ad1d61ea2fda462d1216607", - "uncles": [], - "withdrawals": [ - { - "address": "0xea97dc2523c0479484076660f150833e264c41e9", - "amount": "0x11b6d8c", - "index": "0x2dbe454", - "validatorIndex": "0x10f646" - }, - { - "address": "0xb3e84b6c6409826dc45432b655d8c9489a14a0d7", - "amount": "0x11b4ce2", - "index": "0x2dbe455", - "validatorIndex": "0x10f647" - }, - { - "address": "0x7e2a2fa2a064f693f0a55c5639476d913ff12d05", - "amount": "0x11ad733", - "index": "0x2dbe456", - "validatorIndex": "0x10f648" - }, - - ], - "withdrawalsRoot": "0x2914fa2f5ed93880ed45b58e8f6d14f20c645988400d83c59109964e2053fe1a" - } + jsonrpc: '2.0', + id: 'a40a81fa-1f8b-4bb2-a0ad-eef9b6d4636f', + result: { + baseFeePerGas: '0x44dab2983', + blobGasUsed: '0x20000', + difficulty: '0x0', + excessBlobGas: '0x1c0000', + extraData: '0x407273796e636275696c646572', + gasLimit: '0x1c9c380', + gasUsed: '0xb7a086', + hash: '0xf2b1729965179032b17165678a1a212fa31cb008e30f4011ffe8ebdddbd02b95', + logsBloom: + '0xc3a70590c1c62524173d1892e33888067101934dc0891c2c9a898252b6f320215084a48906452960820188d32bba6fb82ec989018a0268603a00a4c6432a11276c9a038c676938eb68bc436c9905a9a1b08d238fb4458f48498215808bec81112e2a3a54869ff22422a8e491093da8a40f601d198417041cd22f799f9048865006e0b069ab049b852442b310396248088145e2810f230f9a44000c6868bc73e9afa8832a8ac92fd609007ac53c0a9cba0645ce298080184624e8040831dbc331f5e618072407050250021b3210e542781183a612d4618c1244000d421a6ca9c01a57e86a085402c55ab413f840a001e7117894d0469e20c2304a9655e344f60d', + miner: '0x1f9090aae28b8a3dceadf281b0f12828e676c326', + mixHash: '0x787ab1d511b72df60a705bb4cfc4e92e2f9d203e3e007ae3a0f757425951ca24', + nonce: '0x0000000000000000', + number: '0x131ad16', + parentBeaconBlockRoot: '0x03bbca9fd0c7a0a020de04287f489112c79bc268220e9ff8e18957cd0d5c3cad', + parentHash: '0xb1d8fa7b8346421d373a6d4c28575155516cea17c12a3df7201170c9e561b38c', + receiptsRoot: '0x4ec500bdcd761ad505b2a989156c9a9628058d415acc93d800487c7c76308c59', + sha3Uncles: '0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347', + size: '0xcb90', + stateRoot: '0xafbb8743c0a5f4740e322217cb1f2780ee5c57c32bcd04e9256b09efc1a70568', + timestamp: '0x6661ab8b', + totalDifficulty: '0xc70d815d562d3cfa955', + transactions: [ + '0x589956b75d19dbaf9911f246c23d4b3327ef234872ec1931c419041b23eb5b41', + '0x4d3793f20c25979bd329cafdd889ba6be015cfc999acce8642d6e757b5192e93', + '0x5ba5618ca5a14bab50862255dc69726a498346f9832bd0fd1394e8834e56790b', + '0x6df9678f350db7e30afc930b7246bf1c144b9acb7fd1d25d7e107d550ed5a061', + '0xb8f48ff2876cc393725ea4162421754dfb74ff2364a12d4d3de2c6269f1958c7', + '0x2e5cf7c0607025038b6ccd871dc9ce85af686fd5fa2c82e605198af9afa92cca', + '0x307fb855836feff5d8d0969fa4a44d3c6ae31d335da6577f48f9496d6fe9e0b9', + '0x1362bed1aa8a30d28b7b76c35c2a8601b257058beffa9490dcb20de12bcb15b2', + '0x234c7cc346c204022b2e5ead6d2e8c02317aeb0ec5ca82bd97c2b5d5e59a280b', + ], + transactionsRoot: '0xc21a4d667b5f841538430b1e2c002c598f2178628ad1d61ea2fda462d1216607', + uncles: [], + withdrawals: [ + { + address: '0xea97dc2523c0479484076660f150833e264c41e9', + amount: '0x11b6d8c', + index: '0x2dbe454', + validatorIndex: '0x10f646', + }, + { + address: '0xb3e84b6c6409826dc45432b655d8c9489a14a0d7', + amount: '0x11b4ce2', + index: '0x2dbe455', + validatorIndex: '0x10f647', + }, + { + address: '0x7e2a2fa2a064f693f0a55c5639476d913ff12d05', + amount: '0x11ad733', + index: '0x2dbe456', + validatorIndex: '0x10f648', + }, + ], + withdrawalsRoot: '0x2914fa2f5ed93880ed45b58e8f6d14f20c645988400d83c59109964e2053fe1a', + }, }; export const receiptMockResult = { - "jsonrpc": "2.0", - "id": 1, - "result": { - "blockHash": "0xf4ad699b98241caf3930779b7d919a77f1727e67cef6ed1ce2a4c655ba812d54", - "blockNumber": "0x131ad35", - // eslint-disable-next-line no-null/no-null - "contractAddress": null, - "cumulativeGasUsed": "0x8cae7a", - "effectiveGasPrice": "0x4c9bc2d65", - "from": "0xab6fd3a7c6ce9db945889cd018e028e055f3bc2e", - "gasUsed": "0xa145", - "logs": [ - { - "address": "0xdac17f958d2ee523a2206206994597c13d831ec7", - "blockHash": "0xf4ad699b98241caf3930779b7d919a77f1727e67cef6ed1ce2a4c655ba812d54", - "blockNumber": "0x131ad35", - "data": "0x000000000000000000000000000000000000000000000000000000000016e360", - "logIndex": "0xdf", - "removed": false, - "topics": [ - "0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef", - "0x000000000000000000000000ab6fd3a7c6ce9db945889cd018e028e055f3bc2e", - "0x00000000000000000000000051112f9f08a2174fe3fc96aad8f07e82d1cccd00" - ], - "transactionHash": "0xdf7756865c2056ce34c4eabe4eff42ad251a9f920a1c620c00b4ea0988731d3f", - "transactionIndex": "0x82" - } - ], - "logsBloom": "0x00000000000000000000000002000000000000000000000000000000004000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000400000000000100000000000000000000000000080000000000000000000040000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000000000000000000000800000000000000400000000000000000000000", - "status": "0x1", - "to": "0xdac17f958d2ee523a2206206994597c13d831ec7", - "transactionHash": "0xdf7756865c2056ce34c4eabe4eff42ad251a9f920a1c620c00b4ea0988731d3f", - "transactionIndex": "0x82", - "type": "0x2" - } -}; \ No newline at end of file + jsonrpc: '2.0', + id: 1, + result: { + blockHash: '0xf4ad699b98241caf3930779b7d919a77f1727e67cef6ed1ce2a4c655ba812d54', + blockNumber: '0x131ad35', + // eslint-disable-next-line no-null/no-null + contractAddress: null, + cumulativeGasUsed: '0x8cae7a', + effectiveGasPrice: '0x4c9bc2d65', + from: '0xab6fd3a7c6ce9db945889cd018e028e055f3bc2e', + gasUsed: '0xa145', + logs: [ + { + address: '0xdac17f958d2ee523a2206206994597c13d831ec7', + blockHash: '0xf4ad699b98241caf3930779b7d919a77f1727e67cef6ed1ce2a4c655ba812d54', + blockNumber: '0x131ad35', + data: '0x000000000000000000000000000000000000000000000000000000000016e360', + logIndex: '0xdf', + removed: false, + topics: [ + '0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef', + '0x000000000000000000000000ab6fd3a7c6ce9db945889cd018e028e055f3bc2e', + '0x00000000000000000000000051112f9f08a2174fe3fc96aad8f07e82d1cccd00', + ], + transactionHash: + '0xdf7756865c2056ce34c4eabe4eff42ad251a9f920a1c620c00b4ea0988731d3f', + transactionIndex: '0x82', + }, + ], + logsBloom: + '0x00000000000000000000000002000000000000000000000000000000004000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000400000000000100000000000000000000000000080000000000000000000040000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000000000000000000000800000000000000400000000000000000000000', + status: '0x1', + to: '0xdac17f958d2ee523a2206206994597c13d831ec7', + transactionHash: '0xdf7756865c2056ce34c4eabe4eff42ad251a9f920a1c620c00b4ea0988731d3f', + transactionIndex: '0x82', + type: '0x2', + }, +}; diff --git a/tools/web3-plugin-example/test/unit/transaction_middleware.test.ts b/tools/web3-plugin-example/test/unit/transaction_middleware.test.ts index 2009e028283..40a71a4fb1e 100644 --- a/tools/web3-plugin-example/test/unit/transaction_middleware.test.ts +++ b/tools/web3-plugin-example/test/unit/transaction_middleware.test.ts @@ -20,8 +20,7 @@ import { TransactionMiddlewarePlugin } from '../../src/transaction_middleware_pl import { blockMockResult, receiptMockResult } from './fixtures/transactions_data'; describe('Transaction Middleware', () => { - - // This will allow Transaction modification before signing and gas estimations + // This will allow Transaction modification before signing and gas estimations it('should modify transaction before signing', async () => { const web3 = new Web3('http://127.0.0.1:8545'); const plugin = new TransactionMiddlewarePlugin(); @@ -29,34 +28,32 @@ describe('Transaction Middleware', () => { /// Mock block starts - Mock web3 internal calls for test let blockNum = 1000; - web3.requestManager.send = jest.fn(async (request) => { + web3.requestManager.send = jest.fn(async request => { blockNum += 1; - if(request.method === 'eth_getBlockByNumber'){ - + if (request.method === 'eth_getBlockByNumber') { return Promise.resolve(blockMockResult.result); } - if(request.method === 'eth_call'){ - - return Promise.resolve("0x"); + if (request.method === 'eth_call') { + return Promise.resolve('0x'); } - if(request.method === 'eth_blockNumber'){ - + if (request.method === 'eth_blockNumber') { return Promise.resolve(blockNum.toString(16)); } - if(request.method === 'eth_sendTransaction'){ - - // Test that middleware modified transaction - // eslint-disable-next-line jest/no-conditional-expect - expect((request.params as any)[0].data).toBe("0x123"); - - return Promise.resolve("0xdf7756865c2056ce34c4eabe4eff42ad251a9f920a1c620c00b4ea0988731d3f"); + if (request.method === 'eth_sendTransaction') { + // Test that middleware modified transaction + // eslint-disable-next-line jest/no-conditional-expect + expect((request.params as any)[0].data).toBe('0x123'); + + return Promise.resolve( + '0xdf7756865c2056ce34c4eabe4eff42ad251a9f920a1c620c00b4ea0988731d3f', + ); } if (request.method === 'eth_getTransactionReceipt') { return Promise.resolve(receiptMockResult.result); } - - return Promise.resolve("Unknown Request" as any); + + return Promise.resolve('Unknown Request' as any); }); /// Mock block ends here @@ -67,10 +64,9 @@ describe('Transaction Middleware', () => { from: '0x6E599DA0bfF7A6598AC1224E4985430Bf16458a4', to: '0x6f1DF96865D09d21e8f3f9a7fbA3b17A11c7C53C', value: '0x1', - data: '0x1' + data: '0x1', }; - - await web3.eth.sendTransaction(transaction as any); + await web3.eth.sendTransaction(transaction as any); }); }); From 219c04b8254fecb4a383bd712bd3ccdc4bef83ef Mon Sep 17 00:00:00 2001 From: luu-alex <98a.lexluu@gmail.com> Date: Thu, 29 Aug 2024 04:09:47 +0800 Subject: [PATCH 2/5] update eslint --- .eslintrc.js | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/.eslintrc.js b/.eslintrc.js index 241a06879e7..04b753dcb28 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -16,4 +16,13 @@ module.exports = { typescript: {}, // this loads tsconfig.json to eslint }, }, + overrides: [ + { + "files": ["*.test.ts"], + "rules": { + "@typescript-eslint/no-unsafe-call": "off", + "import/no-unresolved": "off" + } + } + ] }; From 44740463ee68f1335ddf5152256ac096a4973b21 Mon Sep 17 00:00:00 2001 From: luu-alex <98a.lexluu@gmail.com> Date: Thu, 29 Aug 2024 04:15:34 +0800 Subject: [PATCH 3/5] pre commit will run prettier on commited files --- .husky/pre-commit | 2 +- package.json | 6 +- yarn.lock | 281 +++++++++++++++++++++++++++++++++++++++++----- 3 files changed, 257 insertions(+), 32 deletions(-) diff --git a/.husky/pre-commit b/.husky/pre-commit index 2f53ba1badd..d24fdfc601b 100755 --- a/.husky/pre-commit +++ b/.husky/pre-commit @@ -1,4 +1,4 @@ #!/usr/bin/env sh . "$(dirname -- "$0")/_/husky.sh" -yarn format +npx lint-staged diff --git a/package.json b/package.json index 02f2757993d..8e741afb9f6 100644 --- a/package.json +++ b/package.json @@ -30,6 +30,9 @@ "tools/*" ] }, + "lint-staged": { + "*.{js,jsx,ts,tsx,css,md}": "prettier --write" + }, "scripts": { "version": "yarn run bootstrap && yarn build", "bootstrap": "lerna bootstrap", @@ -93,8 +96,6 @@ "test:blackbox:infura:ws": "yarn pre-blackbox && ./scripts/verdaccio.sh startBackgroundAndPublish && lerna run test:blackbox:infura:ws --stream && yarn post-blackbox", "test:manual:long-connection-ws": "node packages/web3/test/stress/long_ws_tests/nodejs_test/long_connection_ws.js", "test:stress": "yarn test:stress:geth:ws && yarn test:stress:geth:http && yarn test:stress:geth:ipc && yarn test:e2e:stress:geth:ws:chrome", - "husky:install": "husky install", - "husky:uninstall": "husky uninstall", "postinstall": "yarn build", "compile:contracts": "node ./scripts/compile_contracts.js && yarn format && yarn lint:fix", "publish:canary": "lerna publish --canary --dist-tag dev --preid dev.$(git rev-parse --short HEAD) --exact --graph-type all --force-publish \"*\" --no-verify-access --yes", @@ -121,6 +122,7 @@ "husky": "^8.0.3", "jest": "^29.7.0", "lerna": "^6.6.2", + "lint-staged": "^15.2.9", "npm-auth-to-token": "^1.0.0", "prettier": "^2.7.1", "prettier-plugin-solidity": "^1.0.0-beta.20", diff --git a/yarn.lock b/yarn.lock index e5ac4b827bb..0884fd08293 100644 --- a/yarn.lock +++ b/yarn.lock @@ -3083,6 +3083,13 @@ ansi-escapes@^4.2.1, ansi-escapes@^4.3.0: dependencies: type-fest "^0.21.3" +ansi-escapes@^7.0.0: + version "7.0.0" + resolved "https://registry.yarnpkg.com/ansi-escapes/-/ansi-escapes-7.0.0.tgz#00fc19f491bbb18e1d481b97868204f92109bfe7" + integrity sha512-GdYO7a61mR0fOlAsvC9/rIHf7L96sBc6dEWzeOu+KAea5bZyQRPIpojrVoI4AXGJS/ycu/fBTdLrUkA4ODrvjw== + dependencies: + environment "^1.0.0" + ansi-regex@^2.0.0: version "2.1.1" resolved "https://registry.yarnpkg.com/ansi-regex/-/ansi-regex-2.1.1.tgz#c3b33ab5ee360d86e0e628f0468ae7ef27d654df" @@ -3127,7 +3134,7 @@ ansi-styles@^5.0.0: resolved "https://registry.yarnpkg.com/ansi-styles/-/ansi-styles-5.2.0.tgz#07449690ad45777d1924ac2abb2fc8895dba836b" integrity sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA== -ansi-styles@^6.1.0: +ansi-styles@^6.0.0, ansi-styles@^6.1.0, ansi-styles@^6.2.1: version "6.2.1" resolved "https://registry.yarnpkg.com/ansi-styles/-/ansi-styles-6.2.1.tgz#0e62320cf99c21afff3b3012192546aacbfb05c5" integrity sha512-bN798gFfQX+viw3R7yrGWRqnrN2oRkEkUjjl4JNn4E8GxxbjtG3FbrEIIY3l8/hrwUwIeCZvi4QuOTP4MErVug== @@ -3651,6 +3658,13 @@ braces@^3.0.2, braces@~3.0.2: dependencies: fill-range "^7.0.1" +braces@^3.0.3: + version "3.0.3" + resolved "https://registry.yarnpkg.com/braces/-/braces-3.0.3.tgz#490332f40919452272d55a8480adc0c441358789" + integrity sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA== + dependencies: + fill-range "^7.1.1" + brorand@^1.1.0: version "1.1.0" resolved "https://registry.yarnpkg.com/brorand/-/brorand-1.1.0.tgz#12c25efe40a45e3c323eb8675a0a0ce57b22371f" @@ -3931,6 +3945,11 @@ chalk@^4.0.0, chalk@^4.0.2, chalk@^4.1.0, chalk@^4.1.1, chalk@^4.1.2: ansi-styles "^4.1.0" supports-color "^7.1.0" +chalk@~5.3.0: + version "5.3.0" + resolved "https://registry.yarnpkg.com/chalk/-/chalk-5.3.0.tgz#67c20a7ebef70e7f3970a01f90fa210cb6860385" + integrity sha512-dLitG79d+GV1Nb/VYcCDFivJeK1hiukt9QjRNVOsUtTy1rR1YJsmpGGTZ3qJos+uw7WmWF4wUwBd9jxjocFC2w== + char-regex@^1.0.2: version "1.0.2" resolved "https://registry.yarnpkg.com/char-regex/-/char-regex-1.0.2.tgz#d744358226217f981ed58f479b1d6bcc29545dcf" @@ -4041,6 +4060,13 @@ cli-cursor@3.1.0, cli-cursor@^3.1.0: dependencies: restore-cursor "^3.1.0" +cli-cursor@^5.0.0: + version "5.0.0" + resolved "https://registry.yarnpkg.com/cli-cursor/-/cli-cursor-5.0.0.tgz#24a4831ecf5a6b01ddeb32fb71a4b2088b0dce38" + integrity sha512-aCj4O5wKyszjMmDT4tZj93kxyydN/K5zPWSCe6/0AV/AA1pqe5ZBIw0a2ZfPQV7lL5/yb5HsUreJ6UFAF1tEQw== + dependencies: + restore-cursor "^5.0.0" + cli-spinners@2.6.1: version "2.6.1" resolved "https://registry.yarnpkg.com/cli-spinners/-/cli-spinners-2.6.1.tgz#adc954ebe281c37a6319bfa401e6dd2488ffb70d" @@ -4051,6 +4077,14 @@ cli-spinners@^2.5.0: resolved "https://registry.yarnpkg.com/cli-spinners/-/cli-spinners-2.7.0.tgz#f815fd30b5f9eaac02db604c7a231ed7cb2f797a" integrity sha512-qu3pN8Y3qHNgE2AFweciB1IfMnmZ/fsNTEE+NOFjmGB2F/7rLhnhzppvpCnN4FovtP26k8lHyy9ptEbNwWFLzw== +cli-truncate@^4.0.0: + version "4.0.0" + resolved "https://registry.yarnpkg.com/cli-truncate/-/cli-truncate-4.0.0.tgz#6cc28a2924fee9e25ce91e973db56c7066e6172a" + integrity sha512-nPdaFdQ0h/GEigbPClz11D0v/ZJEwxmeVZGeMo3Z5StPtUTkA9o1lD6QwoirYiSDzbcwn2XcjwmCp68W1IS4TA== + dependencies: + slice-ansi "^5.0.0" + string-width "^7.0.0" + cli-width@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/cli-width/-/cli-width-3.0.0.tgz#a2f48437a2caa9a22436e794bf071ec9e61cedf6" @@ -4162,6 +4196,11 @@ colorette@^2.0.14: resolved "https://registry.yarnpkg.com/colorette/-/colorette-2.0.19.tgz#cdf044f47ad41a0f4b56b3a0d5b4e6e1a2d5a798" integrity sha512-3tlv/dIP7FWvj3BsbHrGLJ6l/oKh1O3TcgBqMn+yyCagOxc23fyzDS6HypQbgxWbkpDnf52p1LuR4eWDQ/K9WQ== +colorette@^2.0.20: + version "2.0.20" + resolved "https://registry.yarnpkg.com/colorette/-/colorette-2.0.20.tgz#9eb793e6833067f7235902fcd3b09917a000a95a" + integrity sha512-IfEDxwoWIjkeXL1eXcDiow4UbKjhLdq6/EuSVR9GMN7KVH3r9gQ83e73hsz1Nd1T3ijd5xv1wcWRYO+D6kCI2w== + columnify@1.6.0: version "1.6.0" resolved "https://registry.yarnpkg.com/columnify/-/columnify-1.6.0.tgz#6989531713c9008bb29735e61e37acf5bd553cf3" @@ -4202,6 +4241,11 @@ commander@^8.1.0: resolved "https://registry.yarnpkg.com/commander/-/commander-8.3.0.tgz#4837ea1b2da67b9c616a67afbb0fafee567bca66" integrity sha512-OkTL9umf+He2DZkUq8f8J9of7yL6RJKI24dVITBmNfZBmri9zYZQrKkuXiKhyfPSu8tUhnVBB1iKXevvnlR4Ww== +commander@~12.1.0: + version "12.1.0" + resolved "https://registry.yarnpkg.com/commander/-/commander-12.1.0.tgz#01423b36f501259fdaac4d0e4d60c96c991585d3" + integrity sha512-Vw8qHK3bZM9y/P10u3Vib8o/DdkvA2OtPtZvD871QKjy74Wj1WSKFILMPRPSdUSx5RFK1arlJzEtA4PkFgnbuA== + common-ancestor-path@^1.0.1: version "1.0.1" resolved "https://registry.yarnpkg.com/common-ancestor-path/-/common-ancestor-path-1.0.1.tgz#4f7d2d1394d91b7abdf51871c62f71eadb0182a7" @@ -4601,6 +4645,13 @@ debug@^3.2.7: dependencies: ms "^2.1.1" +debug@~4.3.6: + version "4.3.6" + resolved "https://registry.yarnpkg.com/debug/-/debug-4.3.6.tgz#2ab2c38fbaffebf8aa95fdfe6d88438c7a13c52b" + integrity sha512-O/09Bd4Z1fBrU4VzkhFqVgpPzaGbw6Sm9FEkBT1A/YBXQFGuuSxa1dN2nxgxS34JmKXqYx8CZAwEVoJFImUXIg== + dependencies: + ms "2.1.2" + decamelize-keys@^1.1.0: version "1.1.0" resolved "https://registry.yarnpkg.com/decamelize-keys/-/decamelize-keys-1.1.0.tgz#d171a87933252807eb3cb61dc1c1445d078df2d9" @@ -4933,6 +4984,11 @@ emoji-regex@^10.1.0: resolved "https://registry.yarnpkg.com/emoji-regex/-/emoji-regex-10.1.0.tgz#d50e383743c0f7a5945c47087295afc112e3cf66" integrity sha512-xAEnNCT3w2Tg6MA7ly6QqYJvEoY1tm9iIjJ3yMKK9JPlWuRHAMoe5iETwQnx3M9TVbFMfsrBgWKR+IsmswwNjg== +emoji-regex@^10.3.0: + version "10.4.0" + resolved "https://registry.yarnpkg.com/emoji-regex/-/emoji-regex-10.4.0.tgz#03553afea80b3975749cfcb36f776ca268e413d4" + integrity sha512-EC+0oUMY1Rqm4O6LLrgjtYDvcVYTy7chDnM4Q7030tP4Kwj3u/pR6gP9ygnp2CJMK5Gq+9Q2oqmrFJAz01DXjw== + emoji-regex@^8.0.0: version "8.0.0" resolved "https://registry.yarnpkg.com/emoji-regex/-/emoji-regex-8.0.0.tgz#e818fd69ce5ccfcb404594f842963bf53164cc37" @@ -5000,6 +5056,11 @@ envinfo@^7.7.3, envinfo@^7.7.4: resolved "https://registry.yarnpkg.com/envinfo/-/envinfo-7.8.1.tgz#06377e3e5f4d379fea7ac592d5ad8927e0c4d475" integrity sha512-/o+BXHmB7ocbHEAs6F2EnG0ogybVVUdkRunTT2glZU9XAaGmhqskrvKwqXuDfNjEO0LZKWdejEEpnq8aM0tOaw== +environment@^1.0.0: + version "1.1.0" + resolved "https://registry.yarnpkg.com/environment/-/environment-1.1.0.tgz#8e86c66b180f363c7ab311787e0259665f45a9f1" + integrity sha512-xUtoPkMggbz0MPyPiIWr1Kp4aeWJjDZ6SMvURhimjdZgsRuDplF5/s9hcgGhyXMhs+6vpnuoiZ2kFiu3FMnS8Q== + err-code@^2.0.2: version "2.0.3" resolved "https://registry.yarnpkg.com/err-code/-/err-code-2.0.3.tgz#23c2f3b756ffdfc608d30e27c9a941024807e7f9" @@ -5744,6 +5805,21 @@ execa@^7.1.1: signal-exit "^3.0.7" strip-final-newline "^3.0.0" +execa@~8.0.1: + version "8.0.1" + resolved "https://registry.yarnpkg.com/execa/-/execa-8.0.1.tgz#51f6a5943b580f963c3ca9c6321796db8cc39b8c" + integrity sha512-VyhnebXciFV2DESc+p6B+y0LjSm0krU4OgJN44qFAhBY0TJ+1V61tYD2+wHusZ6F9n5K+vl8k0sTy7PEfV4qpg== + dependencies: + cross-spawn "^7.0.3" + get-stream "^8.0.1" + human-signals "^5.0.0" + is-stream "^3.0.0" + merge-stream "^2.0.0" + npm-run-path "^5.1.0" + onetime "^6.0.0" + signal-exit "^4.1.0" + strip-final-newline "^3.0.0" + exit@^0.1.2: version "0.1.2" resolved "https://registry.yarnpkg.com/exit/-/exit-0.1.2.tgz#0632638f8d877cc82107d30a0fff1a17cba1cd0c" @@ -6008,6 +6084,13 @@ fill-range@^7.0.1: dependencies: to-regex-range "^5.0.1" +fill-range@^7.1.1: + version "7.1.1" + resolved "https://registry.yarnpkg.com/fill-range/-/fill-range-7.1.1.tgz#44265d3cac07e3ea7dc247516380643754a05292" + integrity sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg== + dependencies: + to-regex-range "^5.0.1" + finalhandler@1.2.0: version "1.2.0" resolved "https://registry.yarnpkg.com/finalhandler/-/finalhandler-1.2.0.tgz#7d23fe5731b207b4640e4fcd00aec1f9207a7b32" @@ -6329,6 +6412,11 @@ get-caller-file@^2.0.5: resolved "https://registry.yarnpkg.com/get-caller-file/-/get-caller-file-2.0.5.tgz#4f94412a82db32f36e3b0b9741f8a97feb031f7e" integrity sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg== +get-east-asian-width@^1.0.0: + version "1.2.0" + resolved "https://registry.yarnpkg.com/get-east-asian-width/-/get-east-asian-width-1.2.0.tgz#5e6ebd9baee6fb8b7b6bd505221065f0cd91f64e" + integrity sha512-2nk+7SIVb14QrgXFHcm84tD4bKQz0RxPuMT8Ag5KPOq7J5fEmAg0UbXdTOSHqNuHSU28k55qnceesxXRZGzKWA== + get-intrinsic@^1.0.2, get-intrinsic@^1.1.0, get-intrinsic@^1.1.1: version "1.1.2" resolved "https://registry.yarnpkg.com/get-intrinsic/-/get-intrinsic-1.1.2.tgz#336975123e05ad0b7ba41f152ee4aadbea6cf598" @@ -6368,6 +6456,11 @@ get-stream@^6.0.0, get-stream@^6.0.1: resolved "https://registry.yarnpkg.com/get-stream/-/get-stream-6.0.1.tgz#a262d8eef67aced57c2852ad6167526a43cbf7b7" integrity sha512-ts6Wi+2j3jQjqi70w5AlN8DFnkSwC+MqmxEzdEALB2qXZYV3X/b1CTfgPLGJNMeAWxdPfU8FO1ms3NUfaHCPYg== +get-stream@^8.0.1: + version "8.0.1" + resolved "https://registry.yarnpkg.com/get-stream/-/get-stream-8.0.1.tgz#def9dfd71742cd7754a7761ed43749a27d02eca2" + integrity sha512-VaUJspBffn/LMCJVoMvSAdmscJyS1auj5Zulnn5UoYcY531UWmdwhRWkcGKnGU93m5HSXP9LP2usOryrBtQowA== + get-symbol-description@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/get-symbol-description/-/get-symbol-description-1.0.0.tgz#7fdb81c900101fbd564dd5f1a30af5aadc1e58d6" @@ -6929,6 +7022,11 @@ human-signals@^4.3.0: resolved "https://registry.yarnpkg.com/human-signals/-/human-signals-4.3.1.tgz#ab7f811e851fca97ffbd2c1fe9a958964de321b2" integrity sha512-nZXjEF2nbo7lIw3mgYjItAfgQXog3OjJogSbKa2CQIIvSGWcKgeJnQlNXip6NglNzYH45nSRiEVimMvYL8DDqQ== +human-signals@^5.0.0: + version "5.0.0" + resolved "https://registry.yarnpkg.com/human-signals/-/human-signals-5.0.0.tgz#42665a284f9ae0dade3ba41ebc37eb4b852f3a28" + integrity sha512-AXcZb6vzzrFAUE61HnN4mpLqd/cSIwNQjtNWR0euPm6y0iqx3G4gOXaIDdtdDwZmhwe82LA6+zinmW4UBWVePQ== + humanize-ms@^1.2.1: version "1.2.1" resolved "https://registry.yarnpkg.com/humanize-ms/-/humanize-ms-1.2.1.tgz#c46e3159a293f6b896da29316d8b6fe8bb79bbed" @@ -7276,6 +7374,18 @@ is-fullwidth-code-point@^3.0.0: resolved "https://registry.yarnpkg.com/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz#f116f8064fe90b3f7844a38997c0b75051269f1d" integrity sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg== +is-fullwidth-code-point@^4.0.0: + version "4.0.0" + resolved "https://registry.yarnpkg.com/is-fullwidth-code-point/-/is-fullwidth-code-point-4.0.0.tgz#fae3167c729e7463f8461ce512b080a49268aa88" + integrity sha512-O4L094N2/dZ7xqVdrXhh9r1KODPJpFms8B5sGdJLPy664AgvXsreZUyCQQNItZRDlYug4xStLjNp/sz3HvBowQ== + +is-fullwidth-code-point@^5.0.0: + version "5.0.0" + resolved "https://registry.yarnpkg.com/is-fullwidth-code-point/-/is-fullwidth-code-point-5.0.0.tgz#9609efced7c2f97da7b60145ef481c787c7ba704" + integrity sha512-OVa3u9kkBbw7b8Xw5F9P+D/T9X+Z4+JruYVNapTjPYZYUznQ5YfWeFkOj606XYYW8yugTfC8Pj0hYqvi4ryAhA== + dependencies: + get-east-asian-width "^1.0.0" + is-function@^1.0.1: version "1.0.2" resolved "https://registry.yarnpkg.com/is-function/-/is-function-1.0.2.tgz#4f097f30abf6efadac9833b17ca5dc03f8144e08" @@ -8606,6 +8716,11 @@ libnpmpublish@7.1.4: sigstore "^1.4.0" ssri "^10.0.1" +lilconfig@~3.1.2: + version "3.1.2" + resolved "https://registry.yarnpkg.com/lilconfig/-/lilconfig-3.1.2.tgz#e4a7c3cb549e3a606c8dcc32e5ae1005e62c05cb" + integrity sha512-eop+wDAvpItUys0FWkHIKeC9ybYrTGbU41U5K7+bttZZeohvnY7M9dZ5kB21GNWiFT2q1OoPTvncPCgSOVO5ow== + lines-and-columns@^1.1.6: version "1.2.4" resolved "https://registry.yarnpkg.com/lines-and-columns/-/lines-and-columns-1.2.4.tgz#eca284f75d2965079309dc0ad9255abb2ebc1632" @@ -8616,6 +8731,34 @@ lines-and-columns@~2.0.3: resolved "https://registry.yarnpkg.com/lines-and-columns/-/lines-and-columns-2.0.3.tgz#b2f0badedb556b747020ab8ea7f0373e22efac1b" integrity sha512-cNOjgCnLB+FnvWWtyRTzmB3POJ+cXxTA81LoW7u8JdmhfXzriropYwpjShnz1QLLWsQwY7nIxoDmcPTwphDK9w== +lint-staged@^15.2.9: + version "15.2.9" + resolved "https://registry.yarnpkg.com/lint-staged/-/lint-staged-15.2.9.tgz#bf70d40b6b192df6ad756fb89822211615e0f4da" + integrity sha512-BZAt8Lk3sEnxw7tfxM7jeZlPRuT4M68O0/CwZhhaw6eeWu0Lz5eERE3m386InivXB64fp/mDID452h48tvKlRQ== + dependencies: + chalk "~5.3.0" + commander "~12.1.0" + debug "~4.3.6" + execa "~8.0.1" + lilconfig "~3.1.2" + listr2 "~8.2.4" + micromatch "~4.0.7" + pidtree "~0.6.0" + string-argv "~0.3.2" + yaml "~2.5.0" + +listr2@~8.2.4: + version "8.2.4" + resolved "https://registry.yarnpkg.com/listr2/-/listr2-8.2.4.tgz#486b51cbdb41889108cb7e2c90eeb44519f5a77f" + integrity sha512-opevsywziHd3zHCVQGAj8zu+Z3yHNkkoYhWIGnq54RrCVwLz0MozotJEDnKsIBLvkfLGN6BLOyAeRrYI0pKA4g== + dependencies: + cli-truncate "^4.0.0" + colorette "^2.0.20" + eventemitter3 "^5.0.1" + log-update "^6.1.0" + rfdc "^1.4.1" + wrap-ansi "^9.0.0" + load-json-file@6.2.0: version "6.2.0" resolved "https://registry.yarnpkg.com/load-json-file/-/load-json-file-6.2.0.tgz#5c7770b42cafa97074ca2848707c61662f4251a1" @@ -8696,6 +8839,17 @@ log-symbols@4.1.0, log-symbols@^4.1.0: chalk "^4.1.0" is-unicode-supported "^0.1.0" +log-update@^6.1.0: + version "6.1.0" + resolved "https://registry.yarnpkg.com/log-update/-/log-update-6.1.0.tgz#1a04ff38166f94647ae1af562f4bd6a15b1b7cd4" + integrity sha512-9ie8ItPR6tjY5uYJh8K/Zrv/RMZ5VOlOWvtZdEHYSTFKZfIBPQa9tOAEeAWhd+AnIneLJ22w5fjOYtoutpWq5w== + dependencies: + ansi-escapes "^7.0.0" + cli-cursor "^5.0.0" + slice-ansi "^7.1.0" + strip-ansi "^7.1.0" + wrap-ansi "^9.0.0" + lru-cache@^5.1.1: version "5.1.1" resolved "https://registry.yarnpkg.com/lru-cache/-/lru-cache-5.1.1.tgz#1da27e6710271947695daf6848e847f01d84b920" @@ -8955,6 +9109,14 @@ micromatch@^4.0.0, micromatch@^4.0.2, micromatch@^4.0.4: braces "^3.0.2" picomatch "^2.3.1" +micromatch@~4.0.7: + version "4.0.8" + resolved "https://registry.yarnpkg.com/micromatch/-/micromatch-4.0.8.tgz#d66fa18f3a47076789320b9b1af32bd86d9fa202" + integrity sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA== + dependencies: + braces "^3.0.3" + picomatch "^2.3.1" + mime-db@1.52.0: version "1.52.0" resolved "https://registry.yarnpkg.com/mime-db/-/mime-db-1.52.0.tgz#bbabcdc02859f4987301c856e3387ce5ec43bf70" @@ -8982,6 +9144,11 @@ mimic-fn@^4.0.0: resolved "https://registry.yarnpkg.com/mimic-fn/-/mimic-fn-4.0.0.tgz#60a90550d5cb0b239cca65d893b1a53b29871ecc" integrity sha512-vqiC06CuhBTUdZH+RYl8sFrL096vA45Ok5ISO6sE/Mr1jRbGH4Csnhi8f3wKVl7x8mO4Au7Ir9D3Oyv1VYMFJw== +mimic-function@^5.0.0: + version "5.0.1" + resolved "https://registry.yarnpkg.com/mimic-function/-/mimic-function-5.0.1.tgz#acbe2b3349f99b9deaca7fb70e48b83e94e67076" + integrity sha512-VP79XUPxV2CigYP3jWwAUFSku2aKqBH7uTAapFWCBqutsbmDo96KY5o8uh6U+/YSIn5OxJnXp73beVkpqMIGhA== + min-document@^2.19.0: version "2.19.0" resolved "https://registry.yarnpkg.com/min-document/-/min-document-2.19.0.tgz#7bd282e3f5842ed295bb748cdd9f1ffa2c824685" @@ -9810,6 +9977,13 @@ onetime@^6.0.0: dependencies: mimic-fn "^4.0.0" +onetime@^7.0.0: + version "7.0.0" + resolved "https://registry.yarnpkg.com/onetime/-/onetime-7.0.0.tgz#9f16c92d8c9ef5120e3acd9dd9957cceecc1ab60" + integrity sha512-VXJjc87FScF88uafS3JllDgvAm+c/Slfz06lorj2uAY34rlUu0Nt+v8wreiImcrgAjjIHp1rXpTDlLOGw29WwQ== + dependencies: + mimic-function "^5.0.0" + open@^8.4.0: version "8.4.0" resolved "https://registry.yarnpkg.com/open/-/open-8.4.0.tgz#345321ae18f8138f82565a910fdc6b39e8c244f8" @@ -10189,6 +10363,11 @@ picomatch@^2.0.4, picomatch@^2.2.1, picomatch@^2.2.3, picomatch@^2.3.1: resolved "https://registry.yarnpkg.com/picomatch/-/picomatch-2.3.1.tgz#3ba3833733646d9d3e4995946c1365a67fb07a42" integrity sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA== +pidtree@~0.6.0: + version "0.6.0" + resolved "https://registry.yarnpkg.com/pidtree/-/pidtree-0.6.0.tgz#90ad7b6d42d5841e69e0a2419ef38f8883aa057c" + integrity sha512-eG2dWTVw5bzqGRztnHExczNxt5VGsE6OwTeCG3fdUf9KBsZzO3R5OIIIzWR+iZA0NtZ+RDVdaoE2dK1cn6jH4g== + pify@5.0.0, pify@^5.0.0: version "5.0.0" resolved "https://registry.yarnpkg.com/pify/-/pify-5.0.0.tgz#1f5eca3f5e87ebec28cc6d54a0e4aaf00acc127f" @@ -10804,6 +10983,14 @@ restore-cursor@^3.1.0: onetime "^5.1.0" signal-exit "^3.0.2" +restore-cursor@^5.0.0: + version "5.1.0" + resolved "https://registry.yarnpkg.com/restore-cursor/-/restore-cursor-5.1.0.tgz#0766d95699efacb14150993f55baf0953ea1ebe7" + integrity sha512-oMA2dcrw6u0YfxJQXm342bFKX/E4sG9rbTzO9ptUcR/e8A33cHuvStiYOwH7fszkZlZ1z/ta9AAoPk2F4qIOHA== + dependencies: + onetime "^7.0.0" + signal-exit "^4.1.0" + ret@~0.1.10: version "0.1.15" resolved "https://registry.yarnpkg.com/ret/-/ret-0.1.15.tgz#b8a4825d5bdb1fc3f6f53c2bc33f81388681c7bc" @@ -10824,6 +11011,11 @@ reusify@^1.0.4: resolved "https://registry.yarnpkg.com/reusify/-/reusify-1.0.4.tgz#90da382b1e126efc02146e90845a88db12925d76" integrity sha512-U9nH88a3fc/ekCF1l0/UP1IosiuIjyTh7hBvXVMHYgVcfGvt897Xguj2UOLDeI5BG2m7/uwyaLVT6fbtCwTyzw== +rfdc@^1.4.1: + version "1.4.1" + resolved "https://registry.yarnpkg.com/rfdc/-/rfdc-1.4.1.tgz#778f76c4fb731d93414e8f925fbecf64cce7f6ca" + integrity sha512-q1b3N5QkRUWUl7iyylaaj3kOpIT0N2i9MqIEQXP73GVsN9cw3fdx8X63cEmWhJGi2PPCF23Ijp7ktmd39rawIA== + rimraf@^2.2.8, rimraf@^2.6.3: version "2.7.1" resolved "https://registry.yarnpkg.com/rimraf/-/rimraf-2.7.1.tgz#35797f13a7fdadc566142c29d4f07ccad483e3ec" @@ -11151,6 +11343,11 @@ signal-exit@^4.0.1: resolved "https://registry.yarnpkg.com/signal-exit/-/signal-exit-4.0.2.tgz#ff55bb1d9ff2114c13b400688fa544ac63c36967" integrity sha512-MY2/qGx4enyjprQnFaZsHib3Yadh3IXyV2C321GY0pjGfVBu4un0uDJkwgdxqO+Rdx8JMT8IfJIRwbYVz3Ob3Q== +signal-exit@^4.1.0: + version "4.1.0" + resolved "https://registry.yarnpkg.com/signal-exit/-/signal-exit-4.1.0.tgz#952188c1cbd546070e2dd20d0f41c0ae0530cb04" + integrity sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw== + sigstore@^1.0.0, sigstore@^1.3.0, sigstore@^1.4.0: version "1.5.2" resolved "https://registry.yarnpkg.com/sigstore/-/sigstore-1.5.2.tgz#8d4c2a549341211cb08c687999843edc48c1a94c" @@ -11189,6 +11386,22 @@ slash@^4.0.0: resolved "https://registry.yarnpkg.com/slash/-/slash-4.0.0.tgz#2422372176c4c6c5addb5e2ada885af984b396a7" integrity sha512-3dOsAHXXUkQTpOYcoAxLIorMTp4gIQr5IW3iVb7A7lFIp0VHhnynm9izx6TssdrIcVIESAlVjtnO2K8bg+Coew== +slice-ansi@^5.0.0: + version "5.0.0" + resolved "https://registry.yarnpkg.com/slice-ansi/-/slice-ansi-5.0.0.tgz#b73063c57aa96f9cd881654b15294d95d285c42a" + integrity sha512-FC+lgizVPfie0kkhqUScwRu1O/lF6NOgJmlCgK+/LYxDCTk8sGelYaHDhFcDN+Sn3Cv+3VSa4Byeo+IMCzpMgQ== + dependencies: + ansi-styles "^6.0.0" + is-fullwidth-code-point "^4.0.0" + +slice-ansi@^7.1.0: + version "7.1.0" + resolved "https://registry.yarnpkg.com/slice-ansi/-/slice-ansi-7.1.0.tgz#cd6b4655e298a8d1bdeb04250a433094b347b9a9" + integrity sha512-bSiSngZ/jWeX93BqeIAbImyTbEihizcwNjFoRUIY/T1wWQsfsm2Vw1agPKylXvQTU7iASGdHhyqRlqQzfz+Htg== + dependencies: + ansi-styles "^6.2.1" + is-fullwidth-code-point "^5.0.0" + slide@^1.1.3: version "1.1.6" resolved "https://registry.yarnpkg.com/slide/-/slide-1.1.6.tgz#56eb027d65b4d2dce6cb2e2d32c4d4afc9e1d707" @@ -11455,6 +11668,11 @@ statuses@2.0.1: resolved "https://registry.yarnpkg.com/statuses/-/statuses-2.0.1.tgz#55cb000ccf1d48728bd23c685a063998cf1a1b63" integrity sha512-RwNA9Z/7PrK06rYLIzFMlaF+l73iwpzsqRIFgbMLbTcLD6cOao82TaWefPXQvB2fOC4AjuYSEndS7N/mTCbkdQ== +string-argv@~0.3.2: + version "0.3.2" + resolved "https://registry.yarnpkg.com/string-argv/-/string-argv-0.3.2.tgz#2b6d0ef24b656274d957d54e0a4bbf6153dc02b6" + integrity sha512-aqD2Q0144Z+/RqG52NeHEkZauTAUWJO8c6yTftGJKO3Tja5tUgIfmIl6kExvhtxSDP7fXB6DvzkfMpCd/F3G+Q== + string-length@^4.0.1: version "4.0.2" resolved "https://registry.yarnpkg.com/string-length/-/string-length-4.0.2.tgz#a8a8dc7bd5c1a82b9b3c8b87e125f66871b6e57a" @@ -11463,7 +11681,7 @@ string-length@^4.0.1: char-regex "^1.0.2" strip-ansi "^6.0.0" -"string-width-cjs@npm:string-width@^4.2.0": +"string-width-cjs@npm:string-width@^4.2.0", "string-width@^1.0.2 || 2 || 3 || 4", string-width@^4.1.0, string-width@^4.2.0, string-width@^4.2.3: version "4.2.3" resolved "https://registry.yarnpkg.com/string-width/-/string-width-4.2.3.tgz#269c7117d27b05ad2e536830a8ec895ef9c6d010" integrity sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g== @@ -11481,15 +11699,6 @@ string-width@^1.0.1: is-fullwidth-code-point "^1.0.0" strip-ansi "^3.0.0" -"string-width@^1.0.2 || 2 || 3 || 4", string-width@^4.1.0, string-width@^4.2.0, string-width@^4.2.3: - version "4.2.3" - resolved "https://registry.yarnpkg.com/string-width/-/string-width-4.2.3.tgz#269c7117d27b05ad2e536830a8ec895ef9c6d010" - integrity sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g== - dependencies: - emoji-regex "^8.0.0" - is-fullwidth-code-point "^3.0.0" - strip-ansi "^6.0.1" - string-width@^5.0.1, string-width@^5.1.2: version "5.1.2" resolved "https://registry.yarnpkg.com/string-width/-/string-width-5.1.2.tgz#14f8daec6d81e7221d2a357e668cab73bdbca794" @@ -11499,6 +11708,15 @@ string-width@^5.0.1, string-width@^5.1.2: emoji-regex "^9.2.2" strip-ansi "^7.0.1" +string-width@^7.0.0: + version "7.2.0" + resolved "https://registry.yarnpkg.com/string-width/-/string-width-7.2.0.tgz#b5bb8e2165ce275d4d43476dd2700ad9091db6dc" + integrity sha512-tsaTIkKW9b4N+AEj+SVA+WhJzV7/zMhcSu78mLKWSk7cXMOSHsBKFWUs0fWwq8QyK3MgJBQRX6Gbi4kYbdvGkQ== + dependencies: + emoji-regex "^10.3.0" + get-east-asian-width "^1.0.0" + strip-ansi "^7.1.0" + string.prototype.trimend@^1.0.5: version "1.0.5" resolved "https://registry.yarnpkg.com/string.prototype.trimend/-/string.prototype.trimend-1.0.5.tgz#914a65baaab25fbdd4ee291ca7dde57e869cb8d0" @@ -11536,7 +11754,7 @@ string_decoder@~1.1.1: dependencies: safe-buffer "~5.1.0" -"strip-ansi-cjs@npm:strip-ansi@^6.0.1": +"strip-ansi-cjs@npm:strip-ansi@^6.0.1", strip-ansi@^6.0.0, strip-ansi@^6.0.1: version "6.0.1" resolved "https://registry.yarnpkg.com/strip-ansi/-/strip-ansi-6.0.1.tgz#9e26c63d30f53443e9489495b2105d37b67a85d9" integrity sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A== @@ -11550,13 +11768,6 @@ strip-ansi@^3.0.0, strip-ansi@^3.0.1: dependencies: ansi-regex "^2.0.0" -strip-ansi@^6.0.0, strip-ansi@^6.0.1: - version "6.0.1" - resolved "https://registry.yarnpkg.com/strip-ansi/-/strip-ansi-6.0.1.tgz#9e26c63d30f53443e9489495b2105d37b67a85d9" - integrity sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A== - dependencies: - ansi-regex "^5.0.1" - strip-ansi@^7.0.1: version "7.0.1" resolved "https://registry.yarnpkg.com/strip-ansi/-/strip-ansi-7.0.1.tgz#61740a08ce36b61e50e65653f07060d000975fb2" @@ -11564,6 +11775,13 @@ strip-ansi@^7.0.1: dependencies: ansi-regex "^6.0.1" +strip-ansi@^7.1.0: + version "7.1.0" + resolved "https://registry.yarnpkg.com/strip-ansi/-/strip-ansi-7.1.0.tgz#d5b6568ca689d8561370b0707685d22434faff45" + integrity sha512-iq6eVVI64nQQTRYq2KtEg2d2uU7LElhTJwsH4YzIHZshxlgZms/wIc4VoDQTlG/IvVIrBKG06CrZnp0qv7hkcQ== + dependencies: + ansi-regex "^6.0.1" + strip-bom@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/strip-bom/-/strip-bom-3.0.0.tgz#2334c18e9c759f7bdd56fdef7e9ae3d588e68ed3" @@ -12643,16 +12861,7 @@ workerpool@6.2.1: resolved "https://registry.yarnpkg.com/workerpool/-/workerpool-6.2.1.tgz#46fc150c17d826b86a008e5a4508656777e9c343" integrity sha512-ILEIE97kDZvF9Wb9f6h5aXK4swSlKGUcOEGiIYb2OOu/IrDU9iwj0fD//SsA6E5ibwJxpEvhullJY4Sl4GcpAw== -"wrap-ansi-cjs@npm:wrap-ansi@^7.0.0": - version "7.0.0" - resolved "https://registry.yarnpkg.com/wrap-ansi/-/wrap-ansi-7.0.0.tgz#67e145cff510a6a6984bdf1152911d69d2eb9e43" - integrity sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q== - dependencies: - ansi-styles "^4.0.0" - string-width "^4.1.0" - strip-ansi "^6.0.0" - -wrap-ansi@^7.0.0: +"wrap-ansi-cjs@npm:wrap-ansi@^7.0.0", wrap-ansi@^7.0.0: version "7.0.0" resolved "https://registry.yarnpkg.com/wrap-ansi/-/wrap-ansi-7.0.0.tgz#67e145cff510a6a6984bdf1152911d69d2eb9e43" integrity sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q== @@ -12670,6 +12879,15 @@ wrap-ansi@^8.1.0: string-width "^5.0.1" strip-ansi "^7.0.1" +wrap-ansi@^9.0.0: + version "9.0.0" + resolved "https://registry.yarnpkg.com/wrap-ansi/-/wrap-ansi-9.0.0.tgz#1a3dc8b70d85eeb8398ddfb1e4a02cd186e58b3e" + integrity sha512-G8ura3S+3Z2G+mkgNRq8dqaFZAuxfsxpBB8OCTGRTCtp+l/v9nbFNmCUP1BZMts3G1142MsZfn6eeUKrr4PD1Q== + dependencies: + ansi-styles "^6.2.1" + string-width "^7.0.0" + strip-ansi "^7.1.0" + wrappy@1: version "1.0.2" resolved "https://registry.yarnpkg.com/wrappy/-/wrappy-1.0.2.tgz#b5243d8f3ec1aa35f1364605bc0d1036e30ab69f" @@ -12808,6 +13026,11 @@ yaml@^1.10.0: resolved "https://registry.yarnpkg.com/yaml/-/yaml-1.10.2.tgz#2301c5ffbf12b467de8da2333a459e29e7920e4b" integrity sha512-r3vXyErRCYJ7wg28yvBY5VSoAF8ZvlcW9/BwUzEtUsjvX/DKs24dIkuwjtuprwJJHsbyUbLApepYTR1BN4uHrg== +yaml@~2.5.0: + version "2.5.0" + resolved "https://registry.yarnpkg.com/yaml/-/yaml-2.5.0.tgz#c6165a721cf8000e91c36490a41d7be25176cf5d" + integrity sha512-2wWLbGbYDiSqqIKoPjar3MPgB94ErzCtrNE1FdqGuaO0pi2JGjmE8aW8TDZwzU7vuxcGRdL/4gPQwQ7hD5AMSw== + yargs-parser@20.2.4: version "20.2.4" resolved "https://registry.yarnpkg.com/yargs-parser/-/yargs-parser-20.2.4.tgz#b42890f14566796f85ae8e3a25290d205f154a54" From bd55114957292c2027afdcead9829ff9524a0862 Mon Sep 17 00:00:00 2001 From: luu-alex <98a.lexluu@gmail.com> Date: Thu, 29 Aug 2024 04:18:30 +0800 Subject: [PATCH 4/5] update --- .eslintrc.js | 20 +++++++++++++------- 1 file changed, 13 insertions(+), 7 deletions(-) diff --git a/.eslintrc.js b/.eslintrc.js index 04b753dcb28..28f41cacfb1 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -18,11 +18,17 @@ module.exports = { }, overrides: [ { - "files": ["*.test.ts"], - "rules": { - "@typescript-eslint/no-unsafe-call": "off", - "import/no-unresolved": "off" - } - } - ] + files: ['*.test.ts'], + rules: { + '@typescript-eslint/no-unsafe-call': 'off', + 'import/no-unresolved': 'off', + }, + }, + { + files: ['*.ts'], + rules: { + 'default-param-last': 'off', + }, + }, + ], }; From 7517ec6c91531ea9ed2f30f6d50b4da733ddd9c7 Mon Sep 17 00:00:00 2001 From: luu-alex <98a.lexluu@gmail.com> Date: Mon, 9 Sep 2024 10:49:28 -0400 Subject: [PATCH 5/5] remove prepush --- .husky/pre-push | 4 ---- 1 file changed, 4 deletions(-) delete mode 100755 .husky/pre-push diff --git a/.husky/pre-push b/.husky/pre-push deleted file mode 100755 index 3b614330e02..00000000000 --- a/.husky/pre-push +++ /dev/null @@ -1,4 +0,0 @@ -#!/bin/sh -. "$(dirname "$0")/_/husky.sh" - -yarn run lint