(\n\t\tpayload: JsonRpcPayload,\n\t\t// Used \"null\" value to match the legacy version\n\t\t// eslint-disable-next-line @typescript-eslint/ban-types\n\t\tcallback: (err: Error | null, response?: JsonRpcResponse) => void,\n\t): void;\n}\n\nexport interface LegacySendAsyncProvider {\n\tsendAsync(\n\t\tpayload: JsonRpcPayload,\n\t): Promise>;\n}\n\nexport interface LegacyRequestProvider {\n\trequest(\n\t\tpayload: JsonRpcPayload,\n\t\t// eslint-disable-next-line @typescript-eslint/ban-types\n\t\tcallback: (err: Error | null, response: JsonRpcResponse) => void,\n\t): void;\n}\n\nexport interface SimpleProvider {\n\trequest, ResponseType = Web3APIReturnType>(\n\t\targs: Web3APIPayload,\n\t): Promise | unknown>;\n}\n\nexport interface ProviderInfo {\n\tchainId: string;\n}\n\nexport type ProviderChainId = string;\n\nexport type ProviderAccounts = string[];\n\n\nexport type Eip1193EventName =\n\t| 'connect'\n\t| 'disconnect'\n\t| 'message'\n\t| 'chainChanged'\n\t| 'accountsChanged';\n\nexport interface EIP1193Provider extends SimpleProvider {\n\ton(event: 'connect', listener: (info: ProviderInfo) => void): void;\n\ton(event: 'disconnect', listener: (error: ProviderRpcError) => void): void;\n\ton(event: 'message', listener: (message: ProviderMessage) => void): void;\n\ton(event: 'chainChanged', listener: (chainId: ProviderChainId) => void): void;\n\ton(event: 'accountsChanged', listener: (accounts: ProviderAccounts) => void): void;\n\n\tremoveListener(event: 'connect', listener: (info: ProviderInfo) => void): void;\n\tremoveListener(event: 'disconnect', listener: (error: ProviderRpcError) => void): void;\n\tremoveListener(event: 'message', listener: (message: ProviderMessage) => void): void;\n\tremoveListener(event: 'chainChanged', listener: (chainId: ProviderChainId) => void): void;\n\tremoveListener(event: 'accountsChanged', listener: (accounts: ProviderAccounts) => void): void;\n}\n\nexport interface MetaMaskProvider extends SimpleProvider {\n\ton(event: 'connect', listener: (info: ProviderInfo) => void): void;\n\ton(event: 'disconnect', listener: (error: ProviderRpcError) => void): void;\n\ton(event: 'message', listener: (message: ProviderMessage) => void): void;\n\ton(event: 'chainChanged', listener: (chainId: ProviderChainId) => void): void;\n\ton(event: 'accountsChanged', listener: (accounts: ProviderAccounts) => void): void;\n\n\tremoveListener(event: 'connect', listener: (info: ProviderInfo) => void): void;\n\tremoveListener(event: 'disconnect', listener: (error: ProviderRpcError) => void): void;\n\tremoveListener(event: 'message', listener: (message: ProviderMessage) => void): void;\n\tremoveListener(event: 'chainChanged', listener: (chainId: ProviderChainId) => void): void;\n\tremoveListener(event: 'accountsChanged', listener: (accounts: ProviderAccounts) => void): void;\n\tisMetaMask: boolean;\n}\n\n\nexport type Eip1193Compatible = Omit<\n\t// eslint-disable-next-line no-use-before-define\n\tOmit,\n\t'asEIP1193Provider'\n> & {\n\trequest<\n\t\tMethod extends Web3APIMethod,\n\t\tResultType = Web3APIReturnType | unknown,\n\t>(\n\t\trequest: Web3APIPayload,\n\t): Promise;\n};\n\n// Provider interface compatible with EIP-1193\n// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1193.md\nexport abstract class Web3BaseProvider\n\timplements LegacySendProvider, LegacySendAsyncProvider, EIP1193Provider\n{\n\tpublic static isWeb3Provider(provider: unknown) {\n\t\treturn (\n\t\t\tprovider instanceof Web3BaseProvider ||\n\t\t\tBoolean(provider && (provider as { [symbol]: boolean })[symbol])\n\t\t);\n\t}\n\n\t// To match an object \"instanceof\" does not work if\n\t// matcher class and object is using different package versions\n\t// to overcome this bottleneck used this approach.\n\t// The symbol value for one string will always remain same regardless of package versions\n\t// eslint-disable-next-line class-methods-use-this\n\tpublic get [symbol]() {\n\t\treturn true;\n\t}\n\n\tpublic abstract getStatus(): Web3ProviderStatus;\n\tpublic abstract supportsSubscriptions(): boolean;\n\n\t/**\n\t * @deprecated Please use `.request` instead.\n\t * @param payload - Request Payload\n\t * @param callback - Callback\n\t */\n\tpublic send(\n\t\tpayload: JsonRpcPayload,\n\t\t// eslint-disable-next-line @typescript-eslint/ban-types\n\t\tcallback: (err: Error | null, response?: JsonRpcResponse) => void,\n\t) {\n\t\tthis.request, ResultType>(\n\t\t\tpayload as Web3APIPayload>,\n\t\t)\n\t\t\t.then(response => {\n\t\t\t\t// eslint-disable-next-line no-null/no-null\n\t\t\t\tcallback(null, response);\n\t\t\t})\n\t\t\t.catch((err: Error | Web3Error) => {\n\t\t\t\tcallback(err);\n\t\t\t});\n\t}\n\n\t/**\n\t * @deprecated Please use `.request` instead.\n\t * @param payload - Request Payload\n\t */\n\tpublic async sendAsync(payload: JsonRpcPayload) {\n\t\treturn this.request(payload as Web3APIPayload>) as Promise<\n\t\t\tJsonRpcResponse\n\t\t>;\n\t}\n\n\t/**\n\t * Modify the return type of the request method to be fully compatible with EIP-1193\n\t *\n\t * [deprecated] In the future major releases (\\>= v5) all providers are supposed to be fully compatible with EIP-1193.\n\t * So this method will not be needed and would not be available in the future.\n\t *\n\t * @returns A new instance of the provider with the request method fully compatible with EIP-1193\n\t *\n\t * @example\n\t * ```ts\n\t * const provider = new Web3HttpProvider('http://localhost:8545');\n\t * const fullyCompatibleProvider = provider.asEIP1193Provider();\n\t * const result = await fullyCompatibleProvider.request({ method: 'eth_getBalance' });\n\t * console.log(result); // '0x0234c8a3397aab58' or something like that\n\t * ```\n\t */\n\tpublic asEIP1193Provider(): Eip1193Compatible {\n\t\t// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n\t\tconst newObj = Object.create(this) as Eip1193Compatible;\n\t\t// eslint-disable-next-line @typescript-eslint/unbound-method\n\t\tconst originalRequest = newObj.request;\n\t\tnewObj.request = async function request(\n\t\t\targs: Web3APIPayload>,\n\t\t): Promise {\n\t\t\t// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion\n\t\t\tconst response = (await originalRequest(args)) as JsonRpcResponseWithResult;\n\t\t\treturn response.result;\n\t\t} as typeof newObj.request;\n\t\t// @ts-expect-error the property should not be available in the new object because of using Object.create(this).\n\t\t//\tBut it is available if we do not delete it.\n\t\tnewObj.asEIP1193Provider = undefined; // to prevent the user for calling this method again\n\t\treturn newObj;\n\t}\n\n\t// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1193.md#request\n\tpublic abstract request<\n\t\tMethod extends Web3APIMethod,\n\t\tResultType = Web3APIReturnType | unknown,\n\t>(args: Web3APIPayload): Promise>;\n\n\t// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1193.md#events\n\n\tpublic abstract on(\n\t\ttype: 'disconnect',\n\t\tlistener: Web3Eip1193ProviderEventCallback,\n\t): void;\n\tpublic abstract on(\n\t\ttype: 'message' | string,\n\t\tlistener:\n\t\t\t| Web3Eip1193ProviderEventCallback\n\t\t\t| Web3ProviderMessageEventCallback,\n\t): void;\n\t// for old providers\n\tpublic abstract on(\n\t\ttype: 'data' | string,\n\t\tlistener:\n\t\t\t| Web3Eip1193ProviderEventCallback\n\t\t\t| Web3ProviderMessageEventCallback,\n\t): void;\n\tpublic abstract on(\n\t\ttype: 'connect',\n\t\tlistener: Web3Eip1193ProviderEventCallback,\n\t): void;\n\tpublic abstract on(\n\t\ttype: 'chainChanged',\n\t\tlistener: Web3Eip1193ProviderEventCallback,\n\t): void;\n\tpublic abstract on(\n\t\ttype: 'accountsChanged',\n\t\tlistener: Web3Eip1193ProviderEventCallback,\n\t): void;\n\tpublic abstract removeListener(\n\t\ttype: 'disconnect',\n\t\tlistener: Web3Eip1193ProviderEventCallback,\n\t): void;\n\tpublic abstract removeListener(\n\t\ttype: 'message' | string,\n\t\tlistener: Web3Eip1193ProviderEventCallback | Web3ProviderEventCallback,\n\t): void;\n\tpublic abstract removeListener(\n\t\ttype: 'connect',\n\t\tlistener: Web3Eip1193ProviderEventCallback,\n\t): void;\n\tpublic abstract removeListener(\n\t\ttype: 'chainChanged',\n\t\tlistener: Web3Eip1193ProviderEventCallback,\n\t): void;\n\tpublic abstract removeListener(\n\t\ttype: 'accountsChanged',\n\t\tlistener: Web3Eip1193ProviderEventCallback,\n\t): void;\n\tpublic abstract once(\n\t\ttype: 'disconnect',\n\t\tlistener: Web3Eip1193ProviderEventCallback,\n\t): void;\n\tpublic abstract once(\n\t\ttype: 'message' | string,\n\t\tlistener: Web3Eip1193ProviderEventCallback | Web3ProviderEventCallback,\n\t): void;\n\tpublic abstract once(\n\t\ttype: 'connect',\n\t\tlistener: Web3Eip1193ProviderEventCallback,\n\t): void;\n\tpublic abstract once(\n\t\ttype: 'chainChanged',\n\t\tlistener: Web3Eip1193ProviderEventCallback,\n\t): void;\n\tpublic abstract once(\n\t\ttype: 'accountsChanged',\n\t\tlistener: Web3Eip1193ProviderEventCallback,\n\t): void;\n\tpublic abstract removeAllListeners?(type: string): void;\n\tpublic abstract connect(): void;\n\tpublic abstract disconnect(code?: number, data?: string): void;\n\tpublic abstract reset(): void;\n}\n\nexport type SupportedProviders =\n\t| EIP1193Provider\n\t| Web3BaseProvider\n\t| LegacyRequestProvider\n\t| LegacySendProvider\n\t| LegacySendAsyncProvider\n\t| SimpleProvider\n\t| MetaMaskProvider;\n\nexport type Web3BaseProviderConstructor = new (\n\turl: string,\n\tnet?: Socket,\n) => Web3BaseProvider;\n","/*\nThis file is part of web3.js.\n\nweb3.js is free software: you can redistribute it and/or modify\nit under the terms of the GNU Lesser General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nweb3.js is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU Lesser General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public License\nalong with web3.js. If not, see .\n*/\nimport { Transaction } from './eth_types.js';\nimport { HexString } from './primitives_types.js';\n\nexport type Cipher = 'aes-128-ctr' | 'aes-128-cbc' | 'aes-256-cbc';\n\nexport type CipherOptions = {\n\tsalt?: Uint8Array | string;\n\tiv?: Uint8Array | string;\n\tkdf?: 'scrypt' | 'pbkdf2';\n\tdklen?: number;\n\tc?: number; // iterrations\n\tn?: number; // cpu/memory cost\n\tr?: number; // block size\n\tp?: number; // parallelization cost\n};\n\nexport type ScryptParams = {\n\tdklen: number;\n\tn: number;\n\tp: number;\n\tr: number;\n\tsalt: Uint8Array | string;\n};\nexport type PBKDF2SHA256Params = {\n\tc: number; // iterations\n\tdklen: number;\n\tprf: 'hmac-sha256';\n\tsalt: Uint8Array | string;\n};\n\nexport type KeyStore = {\n\tcrypto: {\n\t\tcipher: Cipher;\n\t\tciphertext: string;\n\t\tcipherparams: {\n\t\t\tiv: string;\n\t\t};\n\t\tkdf: 'pbkdf2' | 'scrypt';\n\t\tkdfparams: ScryptParams | PBKDF2SHA256Params;\n\t\tmac: HexString;\n\t};\n\tid: string;\n\tversion: 3;\n\taddress: string;\n};\n\nexport interface Web3BaseWalletAccount {\n\t[key: string]: unknown;\n\treadonly address: string;\n\treadonly privateKey: string;\n\treadonly signTransaction: (tx: Transaction) => Promise<{\n\t\treadonly messageHash: HexString;\n\t\treadonly r: HexString;\n\t\treadonly s: HexString;\n\t\treadonly v: HexString;\n\t\treadonly rawTransaction: HexString;\n\t\treadonly transactionHash: HexString;\n\t}>;\n\treadonly sign: (data: Record | string) => {\n\t\treadonly messageHash: HexString;\n\t\treadonly r: HexString;\n\t\treadonly s: HexString;\n\t\treadonly v: HexString;\n\t\treadonly message?: string;\n\t\treadonly signature: HexString;\n\t};\n\treadonly encrypt: (password: string, options?: Record) => Promise;\n}\n\nexport interface Web3AccountProvider {\n\tprivateKeyToAccount: (privateKey: string) => T;\n\tcreate: () => T;\n\tdecrypt: (\n\t\tkeystore: KeyStore | string,\n\t\tpassword: string,\n\t\toptions?: Record,\n\t) => Promise;\n}\n\nexport abstract class Web3BaseWallet extends Array {\n\tprotected readonly _accountProvider: Web3AccountProvider;\n\n\tpublic constructor(accountProvider: Web3AccountProvider) {\n\t\tsuper();\n\t\tthis._accountProvider = accountProvider;\n\t}\n\n\tpublic abstract create(numberOfAccounts: number): this;\n\tpublic abstract add(account: T | string): this;\n\tpublic abstract get(addressOrIndex: string | number): T | undefined;\n\tpublic abstract remove(addressOrIndex: string | number): boolean;\n\tpublic abstract clear(): this;\n\tpublic abstract encrypt(\n\t\tpassword: string,\n\t\toptions?: Record,\n\t): Promise;\n\tpublic abstract decrypt(\n\t\tencryptedWallet: KeyStore[],\n\t\tpassword: string,\n\t\toptions?: Record,\n\t): Promise;\n\tpublic abstract save(password: string, keyName?: string): Promise;\n\tpublic abstract load(password: string, keyName?: string): Promise;\n}\n","/*\nThis file is part of web3.js.\n\nweb3.js is free software: you can redistribute it and/or modify\nit under the terms of the GNU Lesser General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nweb3.js is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU Lesser General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public License\nalong with web3.js. If not, see .\n*/\n\n// Response error\nexport const ERR_RESPONSE = 100;\nexport const ERR_INVALID_RESPONSE = 101;\n\n// Generic errors\nexport const ERR_PARAM = 200;\nexport const ERR_FORMATTERS = 201;\nexport const ERR_METHOD_NOT_IMPLEMENTED = 202;\nexport const ERR_OPERATION_TIMEOUT = 203;\nexport const ERR_OPERATION_ABORT = 204;\nexport const ERR_ABI_ENCODING = 205;\nexport const ERR_EXISTING_PLUGIN_NAMESPACE = 206;\nexport const ERR_INVALID_METHOD_PARAMS = 207;\nexport const ERR_MULTIPLE_ERRORS = 208;\n\n// Contract error codes\nexport const ERR_CONTRACT = 300;\nexport const ERR_CONTRACT_RESOLVER_MISSING = 301;\nexport const ERR_CONTRACT_ABI_MISSING = 302;\nexport const ERR_CONTRACT_REQUIRED_CALLBACK = 303;\nexport const ERR_CONTRACT_EVENT_NOT_EXISTS = 304;\nexport const ERR_CONTRACT_RESERVED_EVENT = 305;\nexport const ERR_CONTRACT_MISSING_DEPLOY_DATA = 306;\nexport const ERR_CONTRACT_MISSING_ADDRESS = 307;\nexport const ERR_CONTRACT_MISSING_FROM_ADDRESS = 308;\nexport const ERR_CONTRACT_INSTANTIATION = 309;\nexport const ERR_CONTRACT_EXECUTION_REVERTED = 310;\nexport const ERR_CONTRACT_TX_DATA_AND_INPUT = 311;\n\n// Transaction error codes\nexport const ERR_TX = 400;\nexport const ERR_TX_REVERT_INSTRUCTION = 401;\nexport const ERR_TX_REVERT_TRANSACTION = 402;\nexport const ERR_TX_NO_CONTRACT_ADDRESS = 403;\nexport const ERR_TX_CONTRACT_NOT_STORED = 404;\nexport const ERR_TX_REVERT_WITHOUT_REASON = 405;\nexport const ERR_TX_OUT_OF_GAS = 406;\nexport const ERR_RAW_TX_UNDEFINED = 407;\n\nexport const ERR_TX_INVALID_SENDER = 408;\nexport const ERR_TX_INVALID_CALL = 409;\nexport const ERR_TX_MISSING_CUSTOM_CHAIN = 410;\nexport const ERR_TX_MISSING_CUSTOM_CHAIN_ID = 411;\nexport const ERR_TX_CHAIN_ID_MISMATCH = 412;\nexport const ERR_TX_INVALID_CHAIN_INFO = 413;\nexport const ERR_TX_MISSING_CHAIN_INFO = 414;\nexport const ERR_TX_MISSING_GAS = 415;\nexport const ERR_TX_INVALID_LEGACY_GAS = 416;\nexport const ERR_TX_INVALID_FEE_MARKET_GAS = 417;\nexport const ERR_TX_INVALID_FEE_MARKET_GAS_PRICE = 418;\nexport const ERR_TX_INVALID_LEGACY_FEE_MARKET = 419;\nexport const ERR_TX_INVALID_OBJECT = 420;\nexport const ERR_TX_INVALID_NONCE_OR_CHAIN_ID = 421;\nexport const ERR_TX_UNABLE_TO_POPULATE_NONCE = 422;\nexport const ERR_TX_UNSUPPORTED_EIP_1559 = 423;\nexport const ERR_TX_UNSUPPORTED_TYPE = 424;\nexport const ERR_TX_DATA_AND_INPUT = 425;\nexport const ERR_TX_POLLING_TIMEOUT = 426;\nexport const ERR_TX_RECEIPT_MISSING_OR_BLOCKHASH_NULL = 427;\nexport const ERR_TX_RECEIPT_MISSING_BLOCK_NUMBER = 428;\n\nexport const ERR_TX_LOCAL_WALLET_NOT_AVAILABLE = 429;\n\nexport const ERR_TX_NOT_FOUND = 430;\nexport const ERR_TX_SEND_TIMEOUT = 431;\nexport const ERR_TX_BLOCK_TIMEOUT = 432;\n\nexport const ERR_TX_SIGNING = 433;\nexport const ERR_TX_GAS_MISMATCH = 434;\n\nexport const ERR_TX_CHAIN_MISMATCH = 435;\nexport const ERR_TX_HARDFORK_MISMATCH = 436;\nexport const ERR_TX_INVALID_RECEIVER = 437;\nexport const ERR_TX_REVERT_TRANSACTION_CUSTOM_ERROR = 438;\nexport const ERR_TX_INVALID_PROPERTIES_FOR_TYPE = 439;\n\nexport const ERR_TX_MISSING_GAS_INNER_ERROR = 440;\nexport const ERR_TX_GAS_MISMATCH_INNER_ERROR = 441;\n// Connection error codes\nexport const ERR_CONN = 500;\nexport const ERR_CONN_INVALID = 501;\nexport const ERR_CONN_TIMEOUT = 502;\nexport const ERR_CONN_NOT_OPEN = 503;\nexport const ERR_CONN_CLOSE = 504;\nexport const ERR_CONN_MAX_ATTEMPTS = 505;\nexport const ERR_CONN_PENDING_REQUESTS = 506;\nexport const ERR_REQ_ALREADY_SENT = 507;\n\n// Provider error codes\nexport const ERR_PROVIDER = 600;\nexport const ERR_INVALID_PROVIDER = 601;\nexport const ERR_INVALID_CLIENT = 602;\nexport const ERR_SUBSCRIPTION = 603;\nexport const ERR_WS_PROVIDER = 604;\n\n// Account error codes\nexport const ERR_PRIVATE_KEY_LENGTH = 701;\nexport const ERR_INVALID_PRIVATE_KEY = 702;\nexport const ERR_UNSUPPORTED_KDF = 703;\nexport const ERR_KEY_DERIVATION_FAIL = 704;\nexport const ERR_KEY_VERSION_UNSUPPORTED = 705;\nexport const ERR_INVALID_PASSWORD = 706;\nexport const ERR_IV_LENGTH = 707;\nexport const ERR_INVALID_KEYSTORE = 708;\nexport const ERR_PBKDF2_ITERATIONS = 709;\n\n// Signature error codes\nexport const ERR_SIGNATURE_FAILED = 801;\nexport const ERR_INVALID_SIGNATURE = 802;\n\nexport const GENESIS_BLOCK_NUMBER = '0x0';\n\n// RPC error codes (EIP-1193)\n// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1193.md#provider-errors\nexport const JSONRPC_ERR_REJECTED_REQUEST = 4001;\nexport const JSONRPC_ERR_UNAUTHORIZED = 4100;\nexport const JSONRPC_ERR_UNSUPPORTED_METHOD = 4200;\nexport const JSONRPC_ERR_DISCONNECTED = 4900;\nexport const JSONRPC_ERR_CHAIN_DISCONNECTED = 4901;\n\n// ENS error codes\nexport const ERR_ENS_CHECK_INTERFACE_SUPPORT = 901;\nexport const ERR_ENS_UNSUPPORTED_NETWORK = 902;\nexport const ERR_ENS_NETWORK_NOT_SYNCED = 903;\n\n// Utils error codes\nexport const ERR_INVALID_STRING = 1001;\nexport const ERR_INVALID_BYTES = 1002;\nexport const ERR_INVALID_NUMBER = 1003;\nexport const ERR_INVALID_UNIT = 1004;\nexport const ERR_INVALID_ADDRESS = 1005;\nexport const ERR_INVALID_HEX = 1006;\nexport const ERR_INVALID_TYPE = 1007;\nexport const ERR_INVALID_BOOLEAN = 1008;\nexport const ERR_INVALID_UNSIGNED_INTEGER = 1009;\nexport const ERR_INVALID_SIZE = 1010;\nexport const ERR_INVALID_LARGE_VALUE = 1011;\nexport const ERR_INVALID_BLOCK = 1012;\nexport const ERR_INVALID_TYPE_ABI = 1013;\nexport const ERR_INVALID_NIBBLE_WIDTH = 1014;\nexport const ERR_INVALID_INTEGER = 1015;\n\n// Validation error codes\nexport const ERR_VALIDATION = 1100;\n\n\n// Core error codes\nexport const ERR_CORE_HARDFORK_MISMATCH = 1101;\nexport const ERR_CORE_CHAIN_MISMATCH = 1102;\n\n// Schema error codes\nexport const ERR_SCHEMA_FORMAT = 1200;\n\n// RPC error codes (EIP-1474)\n// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1474.md\nexport const ERR_RPC_INVALID_JSON = -32700;\nexport const ERR_RPC_INVALID_REQUEST = -32600;\nexport const ERR_RPC_INVALID_METHOD = -32601;\nexport const ERR_RPC_INVALID_PARAMS = -32602;\nexport const ERR_RPC_INTERNAL_ERROR = -32603;\nexport const ERR_RPC_INVALID_INPUT = -32000;\nexport const ERR_RPC_MISSING_RESOURCE = -32001;\nexport const ERR_RPC_UNAVAILABLE_RESOURCE = -32002;\nexport const ERR_RPC_TRANSACTION_REJECTED = -32003;\nexport const ERR_RPC_UNSUPPORTED_METHOD = -32004;\nexport const ERR_RPC_LIMIT_EXCEEDED = -32005;\nexport const ERR_RPC_NOT_SUPPORTED = -32006;\n","/*\nThis file is part of web3.js.\n\nweb3.js is free software: you can redistribute it and/or modify\nit under the terms of the GNU Lesser General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nweb3.js is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU Lesser General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public License\nalong with web3.js. If not, see .\n*/\n\n/* eslint-disable max-classes-per-file */\n\nimport { Web3Error } from 'web3-types';\nimport { ERR_MULTIPLE_ERRORS } from './error_codes.js';\n\n/**\n * Base class for Web3 errors.\n */\nexport abstract class BaseWeb3Error extends Error implements Web3Error {\n\tpublic readonly name: string;\n\tpublic abstract readonly code: number;\n\tpublic stack: string | undefined;\n\n\tpublic cause: Error | undefined;\n\n\t/**\n\t * @deprecated Use the `cause` property instead.\n\t */\n\tpublic get innerError(): Error | Error[] | undefined {\n\t\t// eslint-disable-next-line no-use-before-define\n\t\tif (this.cause instanceof MultipleErrors) {\n\t\t\treturn this.cause.errors;\n\t\t}\n\t\treturn this.cause;\n\t}\n\t/**\n\t * @deprecated Use the `cause` property instead.\n\t */\n\tpublic set innerError(cause: Error | Error[] | undefined) {\n\t\tif (Array.isArray(cause)) {\n\t\t\t// eslint-disable-next-line no-use-before-define\n\t\t\tthis.cause = new MultipleErrors(cause);\n\t\t} else {\n\t\t\tthis.cause = cause;\n\t\t}\n\t}\n\n\tpublic constructor(msg?: string, cause?: Error | Error[]) {\n\t\tsuper(msg);\n\n\t\tif (Array.isArray(cause)) {\n\t\t\t// eslint-disable-next-line no-use-before-define\n\t\t\tthis.cause = new MultipleErrors(cause);\n\t\t} else {\n\t\t\tthis.cause = cause;\n\t\t}\n\n\t\tthis.name = this.constructor.name;\n\n\t\tif (typeof Error.captureStackTrace === 'function') {\n\t\t\tError.captureStackTrace(new.target.constructor);\n\t\t} else {\n\t\t\tthis.stack = new Error().stack;\n\t\t}\n\t}\n\n\tpublic static convertToString(value: unknown, unquotValue = false) {\n\t\t// Using \"null\" value intentionally for validation\n\t\t// eslint-disable-next-line no-null/no-null\n\t\tif (value === null || value === undefined) return 'undefined';\n\n\t\tconst result = JSON.stringify(\n\t\t\tvalue,\n\t\t\t(_, v) => (typeof v === 'bigint' ? v.toString() : v) as unknown,\n\t\t);\n\n\t\treturn unquotValue && ['bigint', 'string'].includes(typeof value)\n\t\t\t? result.replace(/['\\\\\"]+/g, '')\n\t\t\t: result;\n\t}\n\n\tpublic toJSON() {\n\t\treturn {\n\t\t\tname: this.name,\n\t\t\tcode: this.code,\n\t\t\tmessage: this.message,\n\t\t\tcause: this.cause,\n\t\t\t// deprecated\n\t\t\tinnerError: this.cause,\n\t\t};\n\t}\n}\n\nexport class MultipleErrors extends BaseWeb3Error {\n\tpublic code = ERR_MULTIPLE_ERRORS;\n\tpublic errors: Error[];\n\n\tpublic constructor(errors: Error[]) {\n\t\tsuper(`Multiple errors occurred: [${errors.map(e => e.message).join('], [')}]`);\n\t\tthis.errors = errors;\n\t}\n}\n\nexport abstract class InvalidValueError extends BaseWeb3Error {\n\tpublic readonly name: string;\n\n\tpublic constructor(value: unknown, msg: string) {\n\t\tsuper(\n\t\t\t`Invalid value given \"${BaseWeb3Error.convertToString(value, true)}\". Error: ${msg}.`,\n\t\t);\n\t\tthis.name = this.constructor.name;\n\t}\n}\n","/*\nThis file is part of web3.js.\n\nweb3.js is free software: you can redistribute it and/or modify\nit under the terms of the GNU Lesser General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nweb3.js is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU Lesser General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public License\nalong with web3.js. If not, see .\n*/\n\n/* eslint-disable max-classes-per-file */\n\nimport {\n\tERR_PRIVATE_KEY_LENGTH,\n\tERR_INVALID_PRIVATE_KEY,\n\tERR_INVALID_SIGNATURE,\n\tERR_UNSUPPORTED_KDF,\n\tERR_KEY_DERIVATION_FAIL,\n\tERR_KEY_VERSION_UNSUPPORTED,\n\tERR_INVALID_PASSWORD,\n\tERR_IV_LENGTH,\n\tERR_PBKDF2_ITERATIONS,\n} from '../error_codes.js';\nimport { BaseWeb3Error } from '../web3_error_base.js';\n\nexport class PrivateKeyLengthError extends BaseWeb3Error {\n\tpublic code = ERR_PRIVATE_KEY_LENGTH;\n\tpublic constructor() {\n\t\tsuper(`Private key must be 32 bytes.`);\n\t}\n}\n\nexport class InvalidPrivateKeyError extends BaseWeb3Error {\n\tpublic code = ERR_INVALID_PRIVATE_KEY;\n\tpublic constructor() {\n\t\tsuper(`Invalid Private Key, Not a valid string or uint8Array`);\n\t}\n}\n\nexport class InvalidSignatureError extends BaseWeb3Error {\n\tpublic code = ERR_INVALID_SIGNATURE;\n\tpublic constructor(errorDetails: string) {\n\t\tsuper(`\"${errorDetails}\"`);\n\t}\n}\n\nexport class InvalidKdfError extends BaseWeb3Error {\n\tpublic code = ERR_UNSUPPORTED_KDF;\n\tpublic constructor() {\n\t\tsuper(`Invalid key derivation function`);\n\t}\n}\n\nexport class KeyDerivationError extends BaseWeb3Error {\n\tpublic code = ERR_KEY_DERIVATION_FAIL;\n\tpublic constructor() {\n\t\tsuper(`Key derivation failed - possibly wrong password`);\n\t}\n}\n\nexport class KeyStoreVersionError extends BaseWeb3Error {\n\tpublic code = ERR_KEY_VERSION_UNSUPPORTED;\n\tpublic constructor() {\n\t\tsuper('Unsupported key store version');\n\t}\n}\n\nexport class InvalidPasswordError extends BaseWeb3Error {\n\tpublic code = ERR_INVALID_PASSWORD;\n\tpublic constructor() {\n\t\tsuper('Password cannot be empty');\n\t}\n}\n\nexport class IVLengthError extends BaseWeb3Error {\n\tpublic code = ERR_IV_LENGTH;\n\tpublic constructor() {\n\t\tsuper('Initialization vector must be 16 bytes');\n\t}\n}\n\nexport class PBKDF2IterationsError extends BaseWeb3Error {\n\tpublic code = ERR_PBKDF2_ITERATIONS;\n\tpublic constructor() {\n\t\tsuper('c > 1000, pbkdf2 is less secure with less iterations');\n\t}\n}\n","/*\nThis file is part of web3.js.\n\nweb3.js is free software: you can redistribute it and/or modify\nit under the terms of the GNU Lesser General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nweb3.js is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU Lesser General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public License\nalong with web3.js. If not, see .\n*/\n\n/* eslint-disable max-classes-per-file */\n\nimport { ConnectionEvent } from 'web3-types';\nimport {\n\tERR_CONN,\n\tERR_CONN_INVALID,\n\tERR_CONN_TIMEOUT,\n\tERR_CONN_NOT_OPEN,\n\tERR_CONN_CLOSE,\n\tERR_CONN_MAX_ATTEMPTS,\n\tERR_CONN_PENDING_REQUESTS,\n\tERR_REQ_ALREADY_SENT,\n} from '../error_codes.js';\nimport { BaseWeb3Error } from '../web3_error_base.js';\n\nexport class ConnectionError extends BaseWeb3Error {\n\tpublic code = ERR_CONN;\n\tpublic errorCode?: number;\n\tpublic errorReason?: string;\n\n\tpublic constructor(message: string, event?: ConnectionEvent) {\n\t\tsuper(message);\n\n\t\tif (event) {\n\t\t\tthis.errorCode = event.code;\n\t\t\tthis.errorReason = event.reason;\n\t\t}\n\t}\n\n\tpublic toJSON() {\n\t\treturn { ...super.toJSON(), errorCode: this.errorCode, errorReason: this.errorReason };\n\t}\n}\n\nexport class InvalidConnectionError extends ConnectionError {\n\tpublic constructor(public host: string, event?: ConnectionEvent) {\n\t\tsuper(`CONNECTION ERROR: Couldn't connect to node ${host}.`, event);\n\t\tthis.code = ERR_CONN_INVALID;\n\t}\n\n\tpublic toJSON() {\n\t\treturn { ...super.toJSON(), host: this.host };\n\t}\n}\n\nexport class ConnectionTimeoutError extends ConnectionError {\n\tpublic constructor(public duration: number) {\n\t\tsuper(`CONNECTION TIMEOUT: timeout of ${duration}ms achieved`);\n\t\tthis.code = ERR_CONN_TIMEOUT;\n\t}\n\n\tpublic toJSON() {\n\t\treturn { ...super.toJSON(), duration: this.duration };\n\t}\n}\n\nexport class ConnectionNotOpenError extends ConnectionError {\n\tpublic constructor(event?: ConnectionEvent) {\n\t\tsuper('Connection not open', event);\n\t\tthis.code = ERR_CONN_NOT_OPEN;\n\t}\n}\n\nexport class ConnectionCloseError extends ConnectionError {\n\tpublic constructor(event?: ConnectionEvent) {\n\t\tsuper(\n\t\t\t`CONNECTION ERROR: The connection got closed with the close code ${\n\t\t\t\tevent?.code ?? ''\n\t\t\t} and the following reason string ${event?.reason ?? ''}`,\n\t\t\tevent,\n\t\t);\n\t\tthis.code = ERR_CONN_CLOSE;\n\t}\n}\n\nexport class MaxAttemptsReachedOnReconnectingError extends ConnectionError {\n\tpublic constructor(numberOfAttempts: number) {\n\t\tsuper(`Maximum number of reconnect attempts reached! (${numberOfAttempts})`);\n\t\tthis.code = ERR_CONN_MAX_ATTEMPTS;\n\t}\n}\n\nexport class PendingRequestsOnReconnectingError extends ConnectionError {\n\tpublic constructor() {\n\t\tsuper('CONNECTION ERROR: Provider started to reconnect before the response got received!');\n\t\tthis.code = ERR_CONN_PENDING_REQUESTS;\n\t}\n}\n\nexport class RequestAlreadySentError extends ConnectionError {\n\tpublic constructor(id: number | string) {\n\t\tsuper(`Request already sent with following id: ${id}`);\n\t\tthis.code = ERR_REQ_ALREADY_SENT;\n\t}\n}\n","/*\nThis file is part of web3.js.\n\nweb3.js is free software: you can redistribute it and/or modify\nit under the terms of the GNU Lesser General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nweb3.js is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU Lesser General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public License\nalong with web3.js. If not, see .\n*/\n\n/* eslint-disable max-classes-per-file */\n\nimport { JsonRpcError, TransactionReceipt, HexString } from 'web3-types';\nimport {\n\tERR_CONTRACT,\n\tERR_CONTRACT_ABI_MISSING,\n\tERR_CONTRACT_EXECUTION_REVERTED,\n\tERR_CONTRACT_EVENT_NOT_EXISTS,\n\tERR_CONTRACT_INSTANTIATION,\n\tERR_CONTRACT_MISSING_ADDRESS,\n\tERR_CONTRACT_MISSING_DEPLOY_DATA,\n\tERR_CONTRACT_MISSING_FROM_ADDRESS,\n\tERR_CONTRACT_REQUIRED_CALLBACK,\n\tERR_CONTRACT_RESERVED_EVENT,\n\tERR_CONTRACT_RESOLVER_MISSING,\n\tERR_CONTRACT_TX_DATA_AND_INPUT,\n} from '../error_codes.js';\nimport { BaseWeb3Error, InvalidValueError } from '../web3_error_base.js';\n\nexport class Web3ContractError extends BaseWeb3Error {\n\tpublic code = ERR_CONTRACT;\n\tpublic receipt?: TransactionReceipt;\n\n\tpublic constructor(message: string, receipt?: TransactionReceipt) {\n\t\tsuper(message);\n\n\t\tthis.receipt = receipt;\n\t}\n}\nexport class ResolverMethodMissingError extends BaseWeb3Error {\n\tpublic code = ERR_CONTRACT_RESOLVER_MISSING;\n\n\tpublic constructor(public address: string, public name: string) {\n\t\tsuper(`The resolver at ${address} does not implement requested method: \"${name}\".`);\n\t}\n\n\tpublic toJSON() {\n\t\treturn { ...super.toJSON(), address: this.address, name: this.name };\n\t}\n}\n\nexport class ContractMissingABIError extends BaseWeb3Error {\n\tpublic code = ERR_CONTRACT_ABI_MISSING;\n\n\tpublic constructor() {\n\t\tsuper(\n\t\t\t'You must provide the json interface of the contract when instantiating a contract object.',\n\t\t);\n\t}\n}\n\nexport class ContractOnceRequiresCallbackError extends BaseWeb3Error {\n\tpublic code = ERR_CONTRACT_REQUIRED_CALLBACK;\n\n\tpublic constructor() {\n\t\tsuper('Once requires a callback as the second parameter.');\n\t}\n}\n\nexport class ContractEventDoesNotExistError extends BaseWeb3Error {\n\tpublic code = ERR_CONTRACT_EVENT_NOT_EXISTS;\n\n\tpublic constructor(public eventName: string) {\n\t\tsuper(`Event \"${eventName}\" doesn't exist in this contract.`);\n\t}\n\n\tpublic toJSON() {\n\t\treturn { ...super.toJSON(), eventName: this.eventName };\n\t}\n}\n\nexport class ContractReservedEventError extends BaseWeb3Error {\n\tpublic code = ERR_CONTRACT_RESERVED_EVENT;\n\n\tpublic constructor(public type: string) {\n\t\tsuper(`Event \"${type}\" doesn't exist in this contract.`);\n\t}\n\n\tpublic toJSON() {\n\t\treturn { ...super.toJSON(), type: this.type };\n\t}\n}\n\nexport class ContractMissingDeployDataError extends BaseWeb3Error {\n\tpublic code = ERR_CONTRACT_MISSING_DEPLOY_DATA;\n\n\tpublic constructor() {\n\t\tsuper(`No \"data\" specified in neither the given options, nor the default options.`);\n\t}\n}\n\nexport class ContractNoAddressDefinedError extends BaseWeb3Error {\n\tpublic code = ERR_CONTRACT_MISSING_ADDRESS;\n\n\tpublic constructor() {\n\t\tsuper(\"This contract object doesn't have address set yet, please set an address first.\");\n\t}\n}\n\nexport class ContractNoFromAddressDefinedError extends BaseWeb3Error {\n\tpublic code = ERR_CONTRACT_MISSING_FROM_ADDRESS;\n\n\tpublic constructor() {\n\t\tsuper('No \"from\" address specified in neither the given options, nor the default options.');\n\t}\n}\n\nexport class ContractInstantiationError extends BaseWeb3Error {\n\tpublic code = ERR_CONTRACT_INSTANTIATION;\n}\n\nexport type ProviderErrorData =\n\t| HexString\n\t| { data: HexString }\n\t| { originalError: { data: HexString } };\n\n/**\n * This class is expected to be set as an `cause` inside ContractExecutionError\n * The properties would be typically decoded from the `data` if it was encoded according to EIP-838\n */\nexport class Eip838ExecutionError extends Web3ContractError {\n\tpublic readonly name: string;\n\tpublic code: number;\n\tpublic data?: HexString;\n\tpublic errorName?: string;\n\tpublic errorSignature?: string;\n\tpublic errorArgs?: { [K in string]: unknown };\n\n\t// eslint-disable-next-line no-use-before-define\n\tpublic cause: Eip838ExecutionError | undefined;\n\n\tpublic constructor(error: JsonRpcError | Eip838ExecutionError) {\n\t\tsuper(error.message || 'Error');\n\n\t\tthis.name = ('name' in error && error.name) || this.constructor.name;\n\t\tthis.stack = ('stack' in error && error.stack) || undefined;\n\t\tthis.code = error.code;\n\n\t\t// get embedded error details got from some providers like MetaMask\n\t\t// and set this.data from the inner error data for easier read.\n\t\t// note: the data is a hex string inside either:\n\t\t//\t error.data, error.data.data or error.data.originalError.data (https://github.com/web3/web3.js/issues/4454#issuecomment-1485953455)\n\t\tif (typeof error.data === 'object') {\n\t\t\tlet originalError: { data: string };\n\t\t\tif (error.data && 'originalError' in error.data) {\n\t\t\t\toriginalError = error.data.originalError;\n\t\t\t} else {\n\t\t\t\t// Ganache has no `originalError` sub-object unlike others\n\t\t\t\toriginalError = error.data;\n\t\t\t}\n\t\t\tthis.data = originalError.data;\n\t\t\tthis.cause = new Eip838ExecutionError(originalError as JsonRpcError);\n\t\t} else {\n\t\t\tthis.data = error.data;\n\t\t}\n\t}\n\n\tpublic setDecodedProperties(\n\t\terrorName: string,\n\t\terrorSignature?: string,\n\t\terrorArgs?: { [K in string]: unknown },\n\t) {\n\t\tthis.errorName = errorName;\n\t\tthis.errorSignature = errorSignature;\n\t\tthis.errorArgs = errorArgs;\n\t}\n\n\tpublic toJSON() {\n\t\tlet json = {\n\t\t\t...super.toJSON(),\n\t\t\tdata: this.data,\n\t\t} as {\n\t\t\tname: string;\n\t\t\tcode: number;\n\t\t\tmessage: string;\n\t\t\tinnerError: Eip838ExecutionError | undefined;\n\t\t\tcause: Eip838ExecutionError | undefined;\n\t\t\tdata: string;\n\t\t\terrorName?: string;\n\t\t\terrorSignature?: string;\n\t\t\terrorArgs?: { [K in string]: unknown };\n\t\t};\n\n\t\tif (this.errorName) {\n\t\t\tjson = {\n\t\t\t\t...json,\n\t\t\t\terrorName: this.errorName,\n\t\t\t\terrorSignature: this.errorSignature,\n\t\t\t\terrorArgs: this.errorArgs,\n\t\t\t};\n\t\t}\n\t\treturn json;\n\t}\n}\n\n/**\n * Used when an error is raised while executing a function inside a smart contract.\n * The data is expected to be encoded according to EIP-848.\n */\nexport class ContractExecutionError extends Web3ContractError {\n\tpublic cause: Eip838ExecutionError;\n\n\tpublic constructor(rpcError: JsonRpcError) {\n\t\tsuper('Error happened while trying to execute a function inside a smart contract');\n\t\tthis.code = ERR_CONTRACT_EXECUTION_REVERTED;\n\t\tthis.cause = new Eip838ExecutionError(rpcError as JsonRpcError);\n\t}\n}\n\nexport class ContractTransactionDataAndInputError extends InvalidValueError {\n\tpublic code = ERR_CONTRACT_TX_DATA_AND_INPUT;\n\n\tpublic constructor(value: { data: HexString | undefined; input: HexString | undefined }) {\n\t\tsuper(\n\t\t\t`data: ${value.data ?? 'undefined'}, input: ${value.input ?? 'undefined'}`,\n\t\t\t'You can\\'t have \"data\" and \"input\" as properties of a contract at the same time, please use either \"data\" or \"input\" instead.',\n\t\t);\n\t}\n}\n","/*\nThis file is part of web3.js.\n\nweb3.js is free software: you can redistribute it and/or modify\nit under the terms of the GNU Lesser General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nweb3.js is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU Lesser General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public License\nalong with web3.js. If not, see .\n*/\n\n/* eslint-disable max-classes-per-file */\n\nimport {\n\tERR_ENS_CHECK_INTERFACE_SUPPORT,\n\tERR_ENS_NETWORK_NOT_SYNCED,\n\tERR_ENS_UNSUPPORTED_NETWORK,\n} from '../error_codes.js';\nimport { BaseWeb3Error } from '../web3_error_base.js';\n\nexport class ENSCheckInterfaceSupportError extends BaseWeb3Error {\n\tpublic code = ERR_ENS_CHECK_INTERFACE_SUPPORT;\n\tpublic constructor(errorDetails: string) {\n\t\tsuper(`ENS resolver check interface support error. \"${errorDetails}\"`);\n\t}\n}\n\nexport class ENSUnsupportedNetworkError extends BaseWeb3Error {\n\tpublic code = ERR_ENS_UNSUPPORTED_NETWORK;\n\tpublic constructor(networkType: string) {\n\t\tsuper(`ENS is not supported on network ${networkType}`);\n\t}\n}\n\nexport class ENSNetworkNotSyncedError extends BaseWeb3Error {\n\tpublic code = ERR_ENS_NETWORK_NOT_SYNCED;\n\tpublic constructor() {\n\t\tsuper(`Network not synced`);\n\t}\n}\n","/*\nThis file is part of web3.js.\n\nweb3.js is free software: you can redistribute it and/or modify\nit under the terms of the GNU Lesser General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nweb3.js is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU Lesser General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public License\nalong with web3.js. If not, see .\n*/\n\n/* eslint-disable max-classes-per-file */\n\nimport {\n\tERR_ABI_ENCODING,\n\tERR_FORMATTERS,\n\tERR_METHOD_NOT_IMPLEMENTED,\n\tERR_OPERATION_ABORT,\n\tERR_OPERATION_TIMEOUT,\n\tERR_PARAM,\n\tERR_EXISTING_PLUGIN_NAMESPACE,\n\tERR_INVALID_METHOD_PARAMS,\n} from '../error_codes.js';\nimport { BaseWeb3Error } from '../web3_error_base.js';\n\nexport class InvalidNumberOfParamsError extends BaseWeb3Error {\n\tpublic code = ERR_PARAM;\n\n\tpublic constructor(public got: number, public expected: number, public method: string) {\n\t\tsuper(`Invalid number of parameters for \"${method}\". Got \"${got}\" expected \"${expected}\"!`);\n\t}\n\n\tpublic toJSON() {\n\t\treturn {\n\t\t\t...super.toJSON(),\n\t\t\tgot: this.got,\n\t\t\texpected: this.expected,\n\t\t\tmethod: this.method,\n\t\t};\n\t}\n}\n\nexport class InvalidMethodParamsError extends BaseWeb3Error {\n\tpublic code = ERR_INVALID_METHOD_PARAMS;\n\n\tpublic constructor(public hint?: string) {\n\t\tsuper(`Invalid parameters passed. \"${typeof hint !== 'undefined' ? hint : ''}\"`);\n\t}\n\n\tpublic toJSON() {\n\t\treturn {\n\t\t\t...super.toJSON(),\n\t\t\thint: this.hint,\n\t\t};\n\t}\n}\n\nexport class FormatterError extends BaseWeb3Error {\n\tpublic code = ERR_FORMATTERS;\n}\n\nexport class MethodNotImplementedError extends BaseWeb3Error {\n\tpublic code = ERR_METHOD_NOT_IMPLEMENTED;\n\n\tpublic constructor() {\n\t\tsuper(\"The method you're trying to call is not implemented.\");\n\t}\n}\n\nexport class OperationTimeoutError extends BaseWeb3Error {\n\tpublic code = ERR_OPERATION_TIMEOUT;\n}\n\nexport class OperationAbortError extends BaseWeb3Error {\n\tpublic code = ERR_OPERATION_ABORT;\n}\n\nexport class AbiError extends BaseWeb3Error {\n\tpublic code = ERR_ABI_ENCODING;\n\tpublic readonly props: Record & { name?: string };\n\n\tpublic constructor(message: string, props?: Record & { name?: string }) {\n\t\tsuper(message);\n\t\tthis.props = props ?? {};\n\t}\n}\n\nexport class ExistingPluginNamespaceError extends BaseWeb3Error {\n\tpublic code = ERR_EXISTING_PLUGIN_NAMESPACE;\n\n\tpublic constructor(pluginNamespace: string) {\n\t\tsuper(`A plugin with the namespace: ${pluginNamespace} has already been registered.`);\n\t}\n}\n","/*\nThis file is part of web3.js.\n\nweb3.js is free software: you can redistribute it and/or modify\nit under the terms of the GNU Lesser General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nweb3.js is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU Lesser General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public License\nalong with web3.js. If not, see .\n*/\n\n/* eslint-disable max-classes-per-file */\n\nimport {\n\tERR_PROVIDER,\n\tERR_INVALID_PROVIDER,\n\tERR_INVALID_CLIENT,\n\tERR_SUBSCRIPTION,\n\tERR_WS_PROVIDER,\n} from '../error_codes.js';\nimport { BaseWeb3Error } from '../web3_error_base.js';\n\nexport class ProviderError extends BaseWeb3Error {\n\tpublic code = ERR_PROVIDER;\n}\n\nexport class InvalidProviderError extends BaseWeb3Error {\n\tpublic code = ERR_INVALID_PROVIDER;\n\n\tpublic constructor(public clientUrl: string) {\n\t\tsuper(`Provider with url \"${clientUrl}\" is not set or invalid`);\n\t}\n}\n\nexport class InvalidClientError extends BaseWeb3Error {\n\tpublic code = ERR_INVALID_CLIENT;\n\n\tpublic constructor(clientUrl: string) {\n\t\tsuper(`Client URL \"${clientUrl}\" is invalid.`);\n\t}\n}\n\nexport class SubscriptionError extends BaseWeb3Error {\n\tpublic code = ERR_SUBSCRIPTION;\n}\n\nexport class Web3WSProviderError extends BaseWeb3Error {\n\tpublic code = ERR_WS_PROVIDER; // this had duplicate code with generic provider\n}\n","/*\nThis file is part of web3.js.\n\nweb3.js is free software: you can redistribute it and/or modify\nit under the terms of the GNU Lesser General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nweb3.js is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU Lesser General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public License\nalong with web3.js. If not, see .\n*/\n\nimport { ERR_SIGNATURE_FAILED } from '../error_codes.js';\nimport { InvalidValueError } from '../web3_error_base.js';\n\nexport class SignatureError extends InvalidValueError {\n\tpublic code = ERR_SIGNATURE_FAILED;\n}\n","/*\nThis file is part of web3.js.\n\nweb3.js is free software: you can redistribute it and/or modify\nit under the terms of the GNU Lesser General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nweb3.js is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU Lesser General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public License\nalong with web3.js. If not, see .\n*/\n\n/* eslint-disable max-classes-per-file */\n\nimport {\n\tBytes,\n\tHexString,\n\tNumbers,\n\tTransactionReceipt,\n\tWeb3ValidationErrorObject,\n} from 'web3-types';\nimport {\n\tERR_RAW_TX_UNDEFINED,\n\tERR_TX,\n\tERR_TX_BLOCK_TIMEOUT,\n\tERR_TX_CONTRACT_NOT_STORED,\n\tERR_TX_CHAIN_ID_MISMATCH,\n\tERR_TX_DATA_AND_INPUT,\n\tERR_TX_GAS_MISMATCH,\n\tERR_TX_CHAIN_MISMATCH,\n\tERR_TX_HARDFORK_MISMATCH,\n\tERR_TX_INVALID_CALL,\n\tERR_TX_INVALID_CHAIN_INFO,\n\tERR_TX_INVALID_FEE_MARKET_GAS,\n\tERR_TX_INVALID_FEE_MARKET_GAS_PRICE,\n\tERR_TX_INVALID_LEGACY_FEE_MARKET,\n\tERR_TX_INVALID_LEGACY_GAS,\n\tERR_TX_INVALID_NONCE_OR_CHAIN_ID,\n\tERR_TX_INVALID_OBJECT,\n\tERR_TX_INVALID_SENDER,\n\tERR_TX_INVALID_RECEIVER,\n\tERR_TX_LOCAL_WALLET_NOT_AVAILABLE,\n\tERR_TX_MISSING_CHAIN_INFO,\n\tERR_TX_MISSING_CUSTOM_CHAIN,\n\tERR_TX_MISSING_CUSTOM_CHAIN_ID,\n\tERR_TX_MISSING_GAS,\n\tERR_TX_NO_CONTRACT_ADDRESS,\n\tERR_TX_NOT_FOUND,\n\tERR_TX_OUT_OF_GAS,\n\tERR_TX_POLLING_TIMEOUT,\n\tERR_TX_RECEIPT_MISSING_BLOCK_NUMBER,\n\tERR_TX_RECEIPT_MISSING_OR_BLOCKHASH_NULL,\n\tERR_TX_REVERT_INSTRUCTION,\n\tERR_TX_REVERT_TRANSACTION,\n\tERR_TX_REVERT_WITHOUT_REASON,\n\tERR_TX_SEND_TIMEOUT,\n\tERR_TX_SIGNING,\n\tERR_TX_UNABLE_TO_POPULATE_NONCE,\n\tERR_TX_UNSUPPORTED_EIP_1559,\n\tERR_TX_UNSUPPORTED_TYPE,\n\tERR_TX_REVERT_TRANSACTION_CUSTOM_ERROR,\n\tERR_TX_INVALID_PROPERTIES_FOR_TYPE,\n\tERR_TX_MISSING_GAS_INNER_ERROR,\n\tERR_TX_GAS_MISMATCH_INNER_ERROR,\n} from '../error_codes.js';\nimport { InvalidValueError, BaseWeb3Error } from '../web3_error_base.js';\n\nexport class TransactionError extends BaseWeb3Error {\n\tpublic code = ERR_TX;\n\n\tpublic constructor(message: string, public receipt?: ReceiptType) {\n\t\tsuper(message);\n\t}\n\n\tpublic toJSON() {\n\t\treturn { ...super.toJSON(), receipt: this.receipt };\n\t}\n}\n\nexport class RevertInstructionError extends BaseWeb3Error {\n\tpublic code = ERR_TX_REVERT_INSTRUCTION;\n\n\tpublic constructor(public reason: string, public signature: string) {\n\t\tsuper(`Your request got reverted with the following reason string: ${reason}`);\n\t}\n\n\tpublic toJSON() {\n\t\treturn { ...super.toJSON(), reason: this.reason, signature: this.signature };\n\t}\n}\n\nexport class TransactionRevertInstructionError<\n\tReceiptType = TransactionReceipt,\n> extends BaseWeb3Error {\n\tpublic code = ERR_TX_REVERT_TRANSACTION;\n\n\tpublic constructor(\n\t\tpublic reason: string,\n\t\tpublic signature?: string,\n\t\tpublic receipt?: ReceiptType,\n\t\tpublic data?: string,\n\t) {\n\t\tsuper(\n\t\t\t`Transaction has been reverted by the EVM${\n\t\t\t\treceipt === undefined ? '' : `:\\n ${BaseWeb3Error.convertToString(receipt)}`\n\t\t\t}`,\n\t\t);\n\t}\n\n\tpublic toJSON() {\n\t\treturn {\n\t\t\t...super.toJSON(),\n\t\t\treason: this.reason,\n\t\t\tsignature: this.signature,\n\t\t\treceipt: this.receipt,\n\t\t\tdata: this.data,\n\t\t};\n\t}\n}\n\n/**\n * This error is used when a transaction to a smart contract fails and\n * a custom user error (https://blog.soliditylang.org/2021/04/21/custom-errors/)\n * is able to be parsed from the revert reason\n */\nexport class TransactionRevertWithCustomError<\n\tReceiptType = TransactionReceipt,\n> extends TransactionRevertInstructionError {\n\tpublic code = ERR_TX_REVERT_TRANSACTION_CUSTOM_ERROR;\n\n\tpublic constructor(\n\t\tpublic reason: string,\n\t\tpublic customErrorName: string,\n\t\tpublic customErrorDecodedSignature: string,\n\t\tpublic customErrorArguments: Record,\n\t\tpublic signature?: string,\n\t\tpublic receipt?: ReceiptType,\n\t\tpublic data?: string,\n\t) {\n\t\tsuper(reason);\n\t}\n\n\tpublic toJSON() {\n\t\treturn {\n\t\t\t...super.toJSON(),\n\t\t\treason: this.reason,\n\t\t\tcustomErrorName: this.customErrorName,\n\t\t\tcustomErrorDecodedSignature: this.customErrorDecodedSignature,\n\t\t\tcustomErrorArguments: this.customErrorArguments,\n\t\t\tsignature: this.signature,\n\t\t\treceipt: this.receipt,\n\t\t\tdata: this.data,\n\t\t};\n\t}\n}\n\nexport class NoContractAddressFoundError extends TransactionError {\n\tpublic constructor(receipt: TransactionReceipt) {\n\t\tsuper(\"The transaction receipt didn't contain a contract address.\", receipt);\n\t\tthis.code = ERR_TX_NO_CONTRACT_ADDRESS;\n\t}\n\n\tpublic toJSON() {\n\t\treturn { ...super.toJSON(), receipt: this.receipt };\n\t}\n}\n\nexport class ContractCodeNotStoredError extends TransactionError {\n\tpublic constructor(receipt: TransactionReceipt) {\n\t\tsuper(\"The contract code couldn't be stored, please check your gas limit.\", receipt);\n\t\tthis.code = ERR_TX_CONTRACT_NOT_STORED;\n\t}\n}\n\nexport class TransactionRevertedWithoutReasonError<\n\tReceiptType = TransactionReceipt,\n> extends TransactionError {\n\tpublic constructor(receipt?: ReceiptType) {\n\t\tsuper(\n\t\t\t`Transaction has been reverted by the EVM${\n\t\t\t\treceipt === undefined ? '' : `:\\n ${BaseWeb3Error.convertToString(receipt)}`\n\t\t\t}`,\n\t\t\treceipt,\n\t\t);\n\t\tthis.code = ERR_TX_REVERT_WITHOUT_REASON;\n\t}\n}\n\nexport class TransactionOutOfGasError extends TransactionError {\n\tpublic constructor(receipt: TransactionReceipt) {\n\t\tsuper(\n\t\t\t`Transaction ran out of gas. Please provide more gas:\\n ${JSON.stringify(\n\t\t\t\treceipt,\n\t\t\t\tundefined,\n\t\t\t\t2,\n\t\t\t)}`,\n\t\t\treceipt,\n\t\t);\n\t\tthis.code = ERR_TX_OUT_OF_GAS;\n\t}\n}\n\nexport class UndefinedRawTransactionError extends TransactionError {\n\tpublic constructor() {\n\t\tsuper(`Raw transaction undefined`);\n\t\tthis.code = ERR_RAW_TX_UNDEFINED;\n\t}\n}\nexport class TransactionNotFound extends TransactionError {\n\tpublic constructor() {\n\t\tsuper('Transaction not found');\n\t\tthis.code = ERR_TX_NOT_FOUND;\n\t}\n}\n\nexport class InvalidTransactionWithSender extends InvalidValueError {\n\tpublic code = ERR_TX_INVALID_SENDER;\n\n\tpublic constructor(value: unknown) {\n\t\tsuper(value, 'invalid transaction with invalid sender');\n\t}\n}\nexport class InvalidTransactionWithReceiver extends InvalidValueError {\n\tpublic code = ERR_TX_INVALID_RECEIVER;\n\n\tpublic constructor(value: unknown) {\n\t\tsuper(value, 'invalid transaction with invalid receiver');\n\t}\n}\nexport class InvalidTransactionCall extends InvalidValueError {\n\tpublic code = ERR_TX_INVALID_CALL;\n\n\tpublic constructor(value: unknown) {\n\t\tsuper(value, 'invalid transaction call');\n\t}\n}\n\nexport class MissingCustomChainError extends InvalidValueError {\n\tpublic code = ERR_TX_MISSING_CUSTOM_CHAIN;\n\n\tpublic constructor() {\n\t\tsuper(\n\t\t\t'MissingCustomChainError',\n\t\t\t'If tx.common is provided it must have tx.common.customChain',\n\t\t);\n\t}\n}\n\nexport class MissingCustomChainIdError extends InvalidValueError {\n\tpublic code = ERR_TX_MISSING_CUSTOM_CHAIN_ID;\n\n\tpublic constructor() {\n\t\tsuper(\n\t\t\t'MissingCustomChainIdError',\n\t\t\t'If tx.common is provided it must have tx.common.customChain and tx.common.customChain.chainId',\n\t\t);\n\t}\n}\n\nexport class ChainIdMismatchError extends InvalidValueError {\n\tpublic code = ERR_TX_CHAIN_ID_MISMATCH;\n\n\tpublic constructor(value: { txChainId: unknown; customChainId: unknown }) {\n\t\tsuper(\n\t\t\tJSON.stringify(value),\n\t\t\t// https://github.com/ChainSafe/web3.js/blob/8783f4d64e424456bdc53b34ef1142d0a7cee4d7/packages/web3-eth-accounts/src/index.js#L176\n\t\t\t'Chain Id doesnt match in tx.chainId tx.common.customChain.chainId',\n\t\t);\n\t}\n}\n\nexport class ChainMismatchError extends InvalidValueError {\n\tpublic code = ERR_TX_CHAIN_MISMATCH;\n\n\tpublic constructor(value: { txChain: unknown; baseChain: unknown }) {\n\t\tsuper(JSON.stringify(value), 'Chain doesnt match in tx.chain tx.common.basechain');\n\t}\n}\n\nexport class HardforkMismatchError extends InvalidValueError {\n\tpublic code = ERR_TX_HARDFORK_MISMATCH;\n\n\tpublic constructor(value: { txHardfork: unknown; commonHardfork: unknown }) {\n\t\tsuper(JSON.stringify(value), 'hardfork doesnt match in tx.hardfork tx.common.hardfork');\n\t}\n}\n\nexport class CommonOrChainAndHardforkError extends InvalidValueError {\n\tpublic code = ERR_TX_INVALID_CHAIN_INFO;\n\n\tpublic constructor() {\n\t\tsuper(\n\t\t\t'CommonOrChainAndHardforkError',\n\t\t\t'Please provide the common object or the chain and hardfork property but not all together.',\n\t\t);\n\t}\n}\n\nexport class MissingChainOrHardforkError extends InvalidValueError {\n\tpublic code = ERR_TX_MISSING_CHAIN_INFO;\n\n\tpublic constructor(value: { chain: string | undefined; hardfork: string | undefined }) {\n\t\tsuper(\n\t\t\t'MissingChainOrHardforkError',\n\t\t\t`When specifying chain and hardfork, both values must be defined. Received \"chain\": ${\n\t\t\t\tvalue.chain ?? 'undefined'\n\t\t\t}, \"hardfork\": ${value.hardfork ?? 'undefined'}`,\n\t\t);\n\t}\n}\n\nexport class MissingGasInnerError extends BaseWeb3Error {\n\tpublic code = ERR_TX_MISSING_GAS_INNER_ERROR;\n\n\tpublic constructor() {\n\t\tsuper(\n\t\t\t'Missing properties in transaction, either define \"gas\" and \"gasPrice\" for type 0 transactions or \"gas\", \"maxPriorityFeePerGas\" and \"maxFeePerGas\" for type 2 transactions',\n\t\t);\n\t}\n}\n\nexport class MissingGasError extends InvalidValueError {\n\tpublic code = ERR_TX_MISSING_GAS;\n\n\tpublic constructor(value: {\n\t\tgas: Numbers | undefined;\n\t\tgasPrice: Numbers | undefined;\n\t\tmaxPriorityFeePerGas: Numbers | undefined;\n\t\tmaxFeePerGas: Numbers | undefined;\n\t}) {\n\t\tsuper(\n\t\t\t`gas: ${value.gas ?? 'undefined'}, gasPrice: ${\n\t\t\t\tvalue.gasPrice ?? 'undefined'\n\t\t\t}, maxPriorityFeePerGas: ${value.maxPriorityFeePerGas ?? 'undefined'}, maxFeePerGas: ${\n\t\t\t\tvalue.maxFeePerGas ?? 'undefined'\n\t\t\t}`,\n\t\t\t'\"gas\" is missing',\n\t\t);\n\t\tthis.cause = new MissingGasInnerError();\n\t}\n}\n\nexport class TransactionGasMismatchInnerError extends BaseWeb3Error {\n\tpublic code = ERR_TX_GAS_MISMATCH_INNER_ERROR;\n\n\tpublic constructor() {\n\t\tsuper(\n\t\t\t'Missing properties in transaction, either define \"gas\" and \"gasPrice\" for type 0 transactions or \"gas\", \"maxPriorityFeePerGas\" and \"maxFeePerGas\" for type 2 transactions, not both',\n\t\t);\n\t}\n}\n\nexport class TransactionGasMismatchError extends InvalidValueError {\n\tpublic code = ERR_TX_GAS_MISMATCH;\n\n\tpublic constructor(value: {\n\t\tgas: Numbers | undefined;\n\t\tgasPrice: Numbers | undefined;\n\t\tmaxPriorityFeePerGas: Numbers | undefined;\n\t\tmaxFeePerGas: Numbers | undefined;\n\t}) {\n\t\tsuper(\n\t\t\t`gas: ${value.gas ?? 'undefined'}, gasPrice: ${\n\t\t\t\tvalue.gasPrice ?? 'undefined'\n\t\t\t}, maxPriorityFeePerGas: ${value.maxPriorityFeePerGas ?? 'undefined'}, maxFeePerGas: ${\n\t\t\t\tvalue.maxFeePerGas ?? 'undefined'\n\t\t\t}`,\n\t\t\t'transaction must specify legacy or fee market gas properties, not both',\n\t\t);\n\t\tthis.cause = new TransactionGasMismatchInnerError();\n\t}\n}\n\nexport class InvalidGasOrGasPrice extends InvalidValueError {\n\tpublic code = ERR_TX_INVALID_LEGACY_GAS;\n\n\tpublic constructor(value: { gas: Numbers | undefined; gasPrice: Numbers | undefined }) {\n\t\tsuper(\n\t\t\t`gas: ${value.gas ?? 'undefined'}, gasPrice: ${value.gasPrice ?? 'undefined'}`,\n\t\t\t'Gas or gasPrice is lower than 0',\n\t\t);\n\t}\n}\n\nexport class InvalidMaxPriorityFeePerGasOrMaxFeePerGas extends InvalidValueError {\n\tpublic code = ERR_TX_INVALID_FEE_MARKET_GAS;\n\n\tpublic constructor(value: {\n\t\tmaxPriorityFeePerGas: Numbers | undefined;\n\t\tmaxFeePerGas: Numbers | undefined;\n\t}) {\n\t\tsuper(\n\t\t\t`maxPriorityFeePerGas: ${value.maxPriorityFeePerGas ?? 'undefined'}, maxFeePerGas: ${\n\t\t\t\tvalue.maxFeePerGas ?? 'undefined'\n\t\t\t}`,\n\t\t\t'maxPriorityFeePerGas or maxFeePerGas is lower than 0',\n\t\t);\n\t}\n}\n\nexport class Eip1559GasPriceError extends InvalidValueError {\n\tpublic code = ERR_TX_INVALID_FEE_MARKET_GAS_PRICE;\n\n\tpublic constructor(value: unknown) {\n\t\tsuper(value, \"eip-1559 transactions don't support gasPrice\");\n\t}\n}\n\nexport class UnsupportedFeeMarketError extends InvalidValueError {\n\tpublic code = ERR_TX_INVALID_LEGACY_FEE_MARKET;\n\n\tpublic constructor(value: {\n\t\tmaxPriorityFeePerGas: Numbers | undefined;\n\t\tmaxFeePerGas: Numbers | undefined;\n\t}) {\n\t\tsuper(\n\t\t\t`maxPriorityFeePerGas: ${value.maxPriorityFeePerGas ?? 'undefined'}, maxFeePerGas: ${\n\t\t\t\tvalue.maxFeePerGas ?? 'undefined'\n\t\t\t}`,\n\t\t\t\"pre-eip-1559 transaction don't support maxFeePerGas/maxPriorityFeePerGas\",\n\t\t);\n\t}\n}\n\nexport class InvalidTransactionObjectError extends InvalidValueError {\n\tpublic code = ERR_TX_INVALID_OBJECT;\n\n\tpublic constructor(value: unknown) {\n\t\tsuper(value, 'invalid transaction object');\n\t}\n}\n\nexport class InvalidNonceOrChainIdError extends InvalidValueError {\n\tpublic code = ERR_TX_INVALID_NONCE_OR_CHAIN_ID;\n\n\tpublic constructor(value: { nonce: Numbers | undefined; chainId: Numbers | undefined }) {\n\t\tsuper(\n\t\t\t`nonce: ${value.nonce ?? 'undefined'}, chainId: ${value.chainId ?? 'undefined'}`,\n\t\t\t'Nonce or chainId is lower than 0',\n\t\t);\n\t}\n}\n\nexport class UnableToPopulateNonceError extends InvalidValueError {\n\tpublic code = ERR_TX_UNABLE_TO_POPULATE_NONCE;\n\n\tpublic constructor() {\n\t\tsuper('UnableToPopulateNonceError', 'unable to populate nonce, no from address available');\n\t}\n}\n\nexport class Eip1559NotSupportedError extends InvalidValueError {\n\tpublic code = ERR_TX_UNSUPPORTED_EIP_1559;\n\n\tpublic constructor() {\n\t\tsuper('Eip1559NotSupportedError', \"Network doesn't support eip-1559\");\n\t}\n}\n\nexport class UnsupportedTransactionTypeError extends InvalidValueError {\n\tpublic code = ERR_TX_UNSUPPORTED_TYPE;\n\n\tpublic constructor(value: unknown) {\n\t\tsuper(value, 'unsupported transaction type');\n\t}\n}\n\nexport class TransactionDataAndInputError extends InvalidValueError {\n\tpublic code = ERR_TX_DATA_AND_INPUT;\n\n\tpublic constructor(value: { data: HexString | undefined; input: HexString | undefined }) {\n\t\tsuper(\n\t\t\t`data: ${value.data ?? 'undefined'}, input: ${value.input ?? 'undefined'}`,\n\t\t\t'You can\\'t have \"data\" and \"input\" as properties of transactions at the same time, please use either \"data\" or \"input\" instead.',\n\t\t);\n\t}\n}\n\nexport class TransactionSendTimeoutError extends BaseWeb3Error {\n\tpublic code = ERR_TX_SEND_TIMEOUT;\n\n\tpublic constructor(value: { numberOfSeconds: number; transactionHash?: Bytes }) {\n\t\tsuper(\n\t\t\t`The connected Ethereum Node did not respond within ${\n\t\t\t\tvalue.numberOfSeconds\n\t\t\t} seconds, please make sure your transaction was properly sent and you are connected to a healthy Node. Be aware that transaction might still be pending or mined!\\n\\tTransaction Hash: ${\n\t\t\t\tvalue.transactionHash ? value.transactionHash.toString() : 'not available'\n\t\t\t}`,\n\t\t);\n\t}\n}\n\nfunction transactionTimeoutHint(transactionHash?: Bytes) {\n\treturn `Please make sure your transaction was properly sent and there are no previous pending transaction for the same account. However, be aware that it might still be mined!\\n\\tTransaction Hash: ${\n\t\ttransactionHash ? transactionHash.toString() : 'not available'\n\t}`;\n}\n\nexport class TransactionPollingTimeoutError extends BaseWeb3Error {\n\tpublic code = ERR_TX_POLLING_TIMEOUT;\n\n\tpublic constructor(value: { numberOfSeconds: number; transactionHash: Bytes }) {\n\t\tsuper(\n\t\t\t`Transaction was not mined within ${\n\t\t\t\tvalue.numberOfSeconds\n\t\t\t} seconds. ${transactionTimeoutHint(value.transactionHash)}`,\n\t\t);\n\t}\n}\n\nexport class TransactionBlockTimeoutError extends BaseWeb3Error {\n\tpublic code = ERR_TX_BLOCK_TIMEOUT;\n\n\tpublic constructor(value: {\n\t\tstarterBlockNumber: number;\n\t\tnumberOfBlocks: number;\n\t\ttransactionHash?: Bytes;\n\t}) {\n\t\tsuper(\n\t\t\t`Transaction started at ${value.starterBlockNumber} but was not mined within ${\n\t\t\t\tvalue.numberOfBlocks\n\t\t\t} blocks. ${transactionTimeoutHint(value.transactionHash)}`,\n\t\t);\n\t}\n}\n\nexport class TransactionMissingReceiptOrBlockHashError extends InvalidValueError {\n\tpublic code = ERR_TX_RECEIPT_MISSING_OR_BLOCKHASH_NULL;\n\n\tpublic constructor(value: {\n\t\treceipt: TransactionReceipt;\n\t\tblockHash: Bytes;\n\t\ttransactionHash: Bytes;\n\t}) {\n\t\tsuper(\n\t\t\t`receipt: ${JSON.stringify(\n\t\t\t\tvalue.receipt,\n\t\t\t)}, blockHash: ${value.blockHash?.toString()}, transactionHash: ${value.transactionHash?.toString()}`,\n\t\t\t`Receipt missing or blockHash null`,\n\t\t);\n\t}\n}\n\nexport class TransactionReceiptMissingBlockNumberError extends InvalidValueError {\n\tpublic code = ERR_TX_RECEIPT_MISSING_BLOCK_NUMBER;\n\n\tpublic constructor(value: { receipt: TransactionReceipt }) {\n\t\tsuper(`receipt: ${JSON.stringify(value.receipt)}`, `Receipt missing block number`);\n\t}\n}\n\nexport class TransactionSigningError extends BaseWeb3Error {\n\tpublic code = ERR_TX_SIGNING;\n\tpublic constructor(errorDetails: string) {\n\t\tsuper(`Invalid signature. \"${errorDetails}\"`);\n\t}\n}\n\nexport class LocalWalletNotAvailableError extends InvalidValueError {\n\tpublic code = ERR_TX_LOCAL_WALLET_NOT_AVAILABLE;\n\n\tpublic constructor() {\n\t\tsuper(\n\t\t\t'LocalWalletNotAvailableError',\n\t\t\t`Attempted to index account in local wallet, but no wallet is available`,\n\t\t);\n\t}\n}\nexport class InvalidPropertiesForTransactionTypeError extends BaseWeb3Error {\n\tpublic code = ERR_TX_INVALID_PROPERTIES_FOR_TYPE;\n\n\tpublic constructor(\n\t\tvalidationError: Web3ValidationErrorObject[],\n\t\ttxType: '0x0' | '0x1' | '0x2',\n\t) {\n\t\tconst invalidPropertyNames: string[] = [];\n\t\tvalidationError.forEach(error => invalidPropertyNames.push(error.keyword));\n\t\tsuper(\n\t\t\t`The following properties are invalid for the transaction type ${txType}: ${invalidPropertyNames.join(\n\t\t\t\t', ',\n\t\t\t)}`,\n\t\t);\n\t}\n}\n","/*\nThis file is part of web3.js.\n\nweb3.js is free software: you can redistribute it and/or modify\nit under the terms of the GNU Lesser General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nweb3.js is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU Lesser General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public License\nalong with web3.js. If not, see .\n*/\n\n/* eslint-disable max-classes-per-file */\n\nimport {\n\tERR_INVALID_BYTES,\n\tERR_INVALID_NUMBER,\n\tERR_INVALID_ADDRESS,\n\tERR_INVALID_BLOCK,\n\tERR_INVALID_BOOLEAN,\n\tERR_INVALID_HEX,\n\tERR_INVALID_LARGE_VALUE,\n\tERR_INVALID_NIBBLE_WIDTH,\n\tERR_INVALID_SIZE,\n\tERR_INVALID_STRING,\n\tERR_INVALID_TYPE,\n\tERR_INVALID_TYPE_ABI,\n\tERR_INVALID_UNIT,\n\tERR_INVALID_INTEGER,\n\tERR_INVALID_UNSIGNED_INTEGER,\n} from '../error_codes.js';\nimport { InvalidValueError } from '../web3_error_base.js';\n\nexport class InvalidBytesError extends InvalidValueError {\n\tpublic code = ERR_INVALID_BYTES;\n\n\tpublic constructor(value: unknown) {\n\t\tsuper(value, 'can not parse as byte data');\n\t}\n}\n\nexport class InvalidNumberError extends InvalidValueError {\n\tpublic code = ERR_INVALID_NUMBER;\n\n\tpublic constructor(value: unknown) {\n\t\tsuper(value, 'can not parse as number data');\n\t}\n}\n\nexport class InvalidAddressError extends InvalidValueError {\n\tpublic code = ERR_INVALID_ADDRESS;\n\n\tpublic constructor(value: unknown) {\n\t\tsuper(value, 'invalid ethereum address');\n\t}\n}\n\nexport class InvalidStringError extends InvalidValueError {\n\tpublic code = ERR_INVALID_STRING;\n\n\tpublic constructor(value: unknown) {\n\t\tsuper(value, 'not a valid string');\n\t}\n}\n\nexport class InvalidUnitError extends InvalidValueError {\n\tpublic code = ERR_INVALID_UNIT;\n\n\tpublic constructor(value: unknown) {\n\t\tsuper(value, 'invalid unit');\n\t}\n}\n\nexport class InvalidIntegerError extends InvalidValueError {\n\tpublic code = ERR_INVALID_INTEGER;\n\n\tpublic constructor(value: unknown) {\n\t\tsuper(value, 'not a valid unit. Must be a positive integer');\n\t\n\t}\n}\n\nexport class HexProcessingError extends InvalidValueError {\n\tpublic code = ERR_INVALID_HEX;\n\n\tpublic constructor(value: unknown) {\n\t\tsuper(value, 'can not be converted to hex');\n\t}\n}\n\nexport class NibbleWidthError extends InvalidValueError {\n\tpublic code = ERR_INVALID_NIBBLE_WIDTH;\n\n\tpublic constructor(value: string) {\n\t\tsuper(value, 'value greater than the nibble width');\n\t}\n}\n\nexport class InvalidTypeError extends InvalidValueError {\n\tpublic code = ERR_INVALID_TYPE;\n\n\tpublic constructor(value: unknown) {\n\t\tsuper(value, 'invalid type, type not supported');\n\t}\n}\n\nexport class InvalidBooleanError extends InvalidValueError {\n\tpublic code = ERR_INVALID_BOOLEAN;\n\n\tpublic constructor(value: unknown) {\n\t\tsuper(value, 'not a valid boolean.');\n\t}\n}\n\nexport class InvalidUnsignedIntegerError extends InvalidValueError {\n\tpublic code = ERR_INVALID_UNSIGNED_INTEGER;\n\n\tpublic constructor(value: unknown) {\n\t\tsuper(value, 'not a valid unsigned integer.');\n\t}\n}\n\nexport class InvalidSizeError extends InvalidValueError {\n\tpublic code = ERR_INVALID_SIZE;\n\n\tpublic constructor(value: unknown) {\n\t\tsuper(value, 'invalid size given.');\n\t}\n}\n\nexport class InvalidLargeValueError extends InvalidValueError {\n\tpublic code = ERR_INVALID_LARGE_VALUE;\n\n\tpublic constructor(value: unknown) {\n\t\tsuper(value, 'value is larger than size.');\n\t}\n}\n\nexport class InvalidBlockError extends InvalidValueError {\n\tpublic code = ERR_INVALID_BLOCK;\n\n\tpublic constructor(value: string) {\n\t\tsuper(value, 'invalid string given');\n\t}\n}\n\nexport class InvalidTypeAbiInputError extends InvalidValueError {\n\tpublic code = ERR_INVALID_TYPE_ABI;\n\n\tpublic constructor(value: string) {\n\t\tsuper(value, 'components found but type is not tuple');\n\t}\n}\n","/*\nThis file is part of web3.js.\n\nweb3.js is free software: you can redistribute it and/or modify\nit under the terms of the GNU Lesser General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nweb3.js is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU Lesser General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public License\nalong with web3.js. If not, see .\n*/\n\n// eslint-disable-next-line max-classes-per-file\nimport {\n\tJsonRpcError,\n\tJsonRpcPayload,\n\tJsonRpcResponse,\n\tJsonRpcResponseWithError,\n} from 'web3-types';\nimport { BaseWeb3Error, MultipleErrors } from '../web3_error_base.js';\nimport { ERR_INVALID_RESPONSE, ERR_RESPONSE } from '../error_codes.js';\n\n// To avoid circular package dependency, copied to code here. If you update this please update same function in `json_rpc.ts`\nconst isResponseWithError = (\n\tresponse: JsonRpcResponse,\n): response is JsonRpcResponseWithError =>\n\t!Array.isArray(response) &&\n\tresponse.jsonrpc === '2.0' &&\n\t!!response &&\n\t// eslint-disable-next-line no-null/no-null\n\t(response.result === undefined || response.result === null) &&\n\t// JSON RPC consider \"null\" as valid response\n\t'error' in response &&\n\t(typeof response.id === 'number' || typeof response.id === 'string');\n\nconst buildErrorMessage = (response: JsonRpcResponse): string =>\n\tisResponseWithError(response) ? response.error.message : '';\n\nexport class ResponseError extends BaseWeb3Error {\n\tpublic code = ERR_RESPONSE;\n\tpublic data?: ErrorType | ErrorType[];\n\tpublic request?: JsonRpcPayload;\n\tpublic statusCode?: number;\n\n\tpublic constructor(\n\t\tresponse: JsonRpcResponse,\n\t\tmessage?: string,\n\t\trequest?: JsonRpcPayload,\n\t\tstatusCode?: number\n\t) {\n\t\tsuper(\n\t\t\tmessage ??\n\t\t\t\t`Returned error: ${\n\t\t\t\t\tArray.isArray(response)\n\t\t\t\t\t\t? response.map(r => buildErrorMessage(r)).join(',')\n\t\t\t\t\t\t: buildErrorMessage(response)\n\t\t\t\t}`,\n\t\t);\n\n\t\tif (!message) {\n\t\t\tthis.data = Array.isArray(response)\n\t\t\t\t? response.map(r => r.error?.data as ErrorType)\n\t\t\t\t: response?.error?.data;\n\t\t}\n\n\t\tthis.statusCode = statusCode;\n\t\tthis.request = request;\n\t\tlet errorOrErrors: JsonRpcError | JsonRpcError[] | undefined;\n\t\tif (`error` in response) {\n\t\t\terrorOrErrors = response.error as JsonRpcError;\n\t\t} else if (response instanceof Array) {\n\t\t\terrorOrErrors = response.filter(r => r.error).map(r => r.error) as JsonRpcError[];\n\t\t}\n\n\t\tif (Array.isArray(errorOrErrors) && errorOrErrors.length > 0) {\n\t\t\tthis.cause = new MultipleErrors(errorOrErrors as unknown as Error[]);\n\t\t} else {\n\t\t\tthis.cause = errorOrErrors as Error | undefined;\n\t\t}\n\t}\n\n\tpublic toJSON() {\n\t\treturn { ...super.toJSON(), data: this.data, request: this.request, statusCode: this.statusCode };\n\t}\n}\n\nexport class InvalidResponseError extends ResponseError<\n\tErrorType,\n\tRequestType\n> {\n\tpublic constructor(\n\t\tresult: JsonRpcResponse,\n\t\trequest?: JsonRpcPayload,\n\t) {\n\t\tsuper(result, undefined, request);\n\t\tthis.code = ERR_INVALID_RESPONSE;\n\t\tlet errorOrErrors: JsonRpcError | JsonRpcError[] | undefined;\n\t\tif (`error` in result) {\n\t\t\terrorOrErrors = result.error as JsonRpcError;\n\t\t} else if (result instanceof Array) {\n\t\t\terrorOrErrors = result.map(r => r.error) as JsonRpcError[];\n\t\t}\n\t\tif (Array.isArray(errorOrErrors)) {\n\t\t\tthis.cause = new MultipleErrors(errorOrErrors as unknown as Error[]);\n\t\t} else {\n\t\t\tthis.cause = errorOrErrors as Error | undefined;\n\t\t}\n\t}\n}","/*\nThis file is part of web3.js.\n\nweb3.js is free software: you can redistribute it and/or modify\nit under the terms of the GNU Lesser General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nweb3.js is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU Lesser General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public License\nalong with web3.js. If not, see .\n*/\n\n/* eslint-disable max-classes-per-file */\n\nimport { BaseWeb3Error } from '../web3_error_base.js';\nimport { ERR_CORE_HARDFORK_MISMATCH } from '../error_codes.js';\n\nexport class ConfigHardforkMismatchError extends BaseWeb3Error {\n\tpublic code = ERR_CORE_HARDFORK_MISMATCH;\n\n\tpublic constructor(defaultHardfork: string, commonHardFork: string) {\n\t\tsuper(\n\t\t\t`Web3Config hardfork doesnt match in defaultHardfork ${defaultHardfork} and common.hardfork ${commonHardFork}`,\n\t\t);\n\t}\n}\n\nexport class ConfigChainMismatchError extends BaseWeb3Error {\n\tpublic code = ERR_CORE_HARDFORK_MISMATCH;\n\n\tpublic constructor(defaultHardfork: string, commonHardFork: string) {\n\t\tsuper(\n\t\t\t`Web3Config chain doesnt match in defaultHardfork ${defaultHardfork} and common.hardfork ${commonHardFork}`,\n\t\t);\n\t}\n}\n","/*\nThis file is part of web3.js.\n\nweb3.js is free software: you can redistribute it and/or modify\nit under the terms of the GNU Lesser General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nweb3.js is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU Lesser General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public License\nalong with web3.js. If not, see .\n*/\n\nimport {\n\tERR_RPC_INTERNAL_ERROR,\n\tERR_RPC_INVALID_INPUT,\n\tERR_RPC_INVALID_JSON,\n\tERR_RPC_INVALID_METHOD,\n\tERR_RPC_INVALID_PARAMS,\n\tERR_RPC_INVALID_REQUEST,\n\tERR_RPC_LIMIT_EXCEEDED,\n\tERR_RPC_MISSING_RESOURCE,\n\tERR_RPC_NOT_SUPPORTED,\n\tERR_RPC_TRANSACTION_REJECTED,\n\tERR_RPC_UNAVAILABLE_RESOURCE,\n\tERR_RPC_UNSUPPORTED_METHOD,\n\tJSONRPC_ERR_CHAIN_DISCONNECTED,\n\tJSONRPC_ERR_DISCONNECTED,\n\tJSONRPC_ERR_REJECTED_REQUEST,\n\tJSONRPC_ERR_UNAUTHORIZED,\n\tJSONRPC_ERR_UNSUPPORTED_METHOD,\n} from '../error_codes.js';\n\n/**\n * A template string for a generic Rpc Error. The `*code*` will be replaced with the code number.\n * Note: consider in next version that a spelling mistake could be corrected for `occured` and the value could be:\n * \t`An Rpc error has occurred with a code of *code*`\n */\nexport const genericRpcErrorMessageTemplate = 'An Rpc error has occured with a code of *code*';\n\n/* eslint-disable @typescript-eslint/naming-convention */\nexport const RpcErrorMessages: {\n\t[key: number | string]: { name?: string; message: string; description?: string };\n} = {\n\t// EIP-1474 & JSON RPC 2.0\n\t// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1474.md\n\t[ERR_RPC_INVALID_JSON]: {\n\t\tmessage: 'Parse error',\n\t\tdescription: 'Invalid JSON',\n\t},\n\t[ERR_RPC_INVALID_REQUEST]: {\n\t\tmessage: 'Invalid request',\n\t\tdescription: 'JSON is not a valid request object\t',\n\t},\n\t[ERR_RPC_INVALID_METHOD]: {\n\t\tmessage: 'Method not found',\n\t\tdescription: 'Method does not exist\t',\n\t},\n\t[ERR_RPC_INVALID_PARAMS]: {\n\t\tmessage: 'Invalid params',\n\t\tdescription: 'Invalid method parameters',\n\t},\n\t[ERR_RPC_INTERNAL_ERROR]: {\n\t\tmessage: 'Internal error',\n\t\tdescription: 'Internal JSON-RPC error',\n\t},\n\n\t[ERR_RPC_INVALID_INPUT]: {\n\t\tmessage: 'Invalid input',\n\t\tdescription: 'Missing or invalid parameters',\n\t},\n\t[ERR_RPC_MISSING_RESOURCE]: {\n\t\tmessage: 'Resource not found',\n\t\tdescription: 'Requested resource not found',\n\t},\n\t[ERR_RPC_UNAVAILABLE_RESOURCE]: {\n\t\tmessage: 'Resource unavailable',\n\t\tdescription: 'Requested resource not available',\n\t},\n\t[ERR_RPC_TRANSACTION_REJECTED]: {\n\t\tmessage: 'Transaction rejected',\n\t\tdescription: 'Transaction creation failed',\n\t},\n\t[ERR_RPC_UNSUPPORTED_METHOD]: {\n\t\tmessage: 'Method not supported',\n\t\tdescription: 'Method is not implemented',\n\t},\n\t[ERR_RPC_LIMIT_EXCEEDED]: {\n\t\tmessage: 'Limit exceeded',\n\t\tdescription: 'Request exceeds defined limit',\n\t},\n\t[ERR_RPC_NOT_SUPPORTED]: {\n\t\tmessage: 'JSON-RPC version not supported',\n\t\tdescription: 'Version of JSON-RPC protocol is not supported',\n\t},\n\n\t// EIP-1193\n\t// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1193.md#provider-errors\n\t[JSONRPC_ERR_REJECTED_REQUEST]: {\n\t\tname: 'User Rejected Request',\n\t\tmessage: 'The user rejected the request.',\n\t},\n\t[JSONRPC_ERR_UNAUTHORIZED]: {\n\t\tname: 'Unauthorized',\n\t\tmessage: 'The requested method and/or account has not been authorized by the user.',\n\t},\n\t[JSONRPC_ERR_UNSUPPORTED_METHOD]: {\n\t\tname: 'Unsupported Method',\n\t\tmessage: 'The Provider does not support the requested method.',\n\t},\n\t[JSONRPC_ERR_DISCONNECTED]: {\n\t\tname: 'Disconnected',\n\t\tmessage: 'The Provider is disconnected from all chains.',\n\t},\n\t[JSONRPC_ERR_CHAIN_DISCONNECTED]: {\n\t\tname: 'Chain Disconnected',\n\t\tmessage: 'The Provider is not connected to the requested chain.',\n\t},\n\n\t// EIP-1193 - CloseEvent\n\t// https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent/code\n\t'0-999': {\n\t\tname: '',\n\t\tmessage: 'Not used.',\n\t},\n\t1000: {\n\t\tname: 'Normal Closure',\n\t\tmessage: 'The connection successfully completed the purpose for which it was created.',\n\t},\n\t1001: {\n\t\tname: 'Going Away',\n\t\tmessage:\n\t\t\t'The endpoint is going away, either because of a server failure or because the browser is navigating away from the page that opened the connection.',\n\t},\n\t1002: {\n\t\tname: 'Protocol error',\n\t\tmessage: 'The endpoint is terminating the connection due to a protocol error.',\n\t},\n\t1003: {\n\t\tname: 'Unsupported Data',\n\t\tmessage:\n\t\t\t'The connection is being terminated because the endpoint received data of a type it cannot accept. (For example, a text-only endpoint received binary data.)',\n\t},\n\t1004: {\n\t\tname: 'Reserved',\n\t\tmessage: 'Reserved. A meaning might be defined in the future.',\n\t},\n\t1005: {\n\t\tname: 'No Status Rcvd',\n\t\tmessage:\n\t\t\t'Reserved. Indicates that no status code was provided even though one was expected.',\n\t},\n\t1006: {\n\t\tname: 'Abnormal Closure',\n\t\tmessage:\n\t\t\t'Reserved. Indicates that a connection was closed abnormally (that is, with no close frame being sent) when a status code is expected.',\n\t},\n\t1007: {\n\t\tname: 'Invalid frame payload data',\n\t\tmessage:\n\t\t\t'The endpoint is terminating the connection because a message was received that contained inconsistent data (e.g., non-UTF-8 data within a text message).',\n\t},\n\t1008: {\n\t\tname: 'Policy Violation',\n\t\tmessage:\n\t\t\t'The endpoint is terminating the connection because it received a message that violates its policy. This is a generic status code, used when codes 1003 and 1009 are not suitable.',\n\t},\n\t1009: {\n\t\tname: 'Message Too Big',\n\t\tmessage:\n\t\t\t'The endpoint is terminating the connection because a data frame was received that is too large.',\n\t},\n\t1010: {\n\t\tname: 'Mandatory Ext.',\n\t\tmessage:\n\t\t\t\"The client is terminating the connection because it expected the server to negotiate one or more extension, but the server didn't.\",\n\t},\n\t1011: {\n\t\tname: 'Internal Error',\n\t\tmessage:\n\t\t\t'The server is terminating the connection because it encountered an unexpected condition that prevented it from fulfilling the request.',\n\t},\n\t1012: {\n\t\tname: 'Service Restart',\n\t\tmessage: 'The server is terminating the connection because it is restarting.',\n\t},\n\t1013: {\n\t\tname: 'Try Again Later',\n\t\tmessage:\n\t\t\t'The server is terminating the connection due to a temporary condition, e.g. it is overloaded and is casting off some of its clients.',\n\t},\n\t1014: {\n\t\tname: 'Bad Gateway',\n\t\tmessage:\n\t\t\t'The server was acting as a gateway or proxy and received an invalid response from the upstream server. This is similar to 502 HTTP Status Code.',\n\t},\n\t1015: {\n\t\tname: 'TLS handshake',\n\t\tmessage:\n\t\t\t\"Reserved. Indicates that the connection was closed due to a failure to perform a TLS handshake (e.g., the server certificate can't be verified).\",\n\t},\n\t'1016-2999': {\n\t\tname: '',\n\t\tmessage:\n\t\t\t'For definition by future revisions of the WebSocket Protocol specification, and for definition by extension specifications.',\n\t},\n\t'3000-3999': {\n\t\tname: '',\n\t\tmessage:\n\t\t\t'For use by libraries, frameworks, and applications. These status codes are registered directly with IANA. The interpretation of these codes is undefined by the WebSocket protocol.',\n\t},\n\t'4000-4999': {\n\t\tname: '',\n\t\tmessage:\n\t\t\t\"For private use, and thus can't be registered. Such codes can be used by prior agreements between WebSocket applications. The interpretation of these codes is undefined by the WebSocket protocol.\",\n\t},\n};\n","/*\nThis file is part of web3.js.\n\nweb3.js is free software: you can redistribute it and/or modify\nit under the terms of the GNU Lesser General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nweb3.js is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU Lesser General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public License\nalong with web3.js. If not, see .\n*/\n\n/* eslint-disable max-classes-per-file */\n\nimport { JsonRpcResponseWithError, JsonRpcId, JsonRpcError } from 'web3-types';\nimport { BaseWeb3Error } from '../web3_error_base.js';\nimport {\n\tERR_RPC_INTERNAL_ERROR,\n\tERR_RPC_INVALID_INPUT,\n\tERR_RPC_INVALID_JSON,\n\tERR_RPC_INVALID_METHOD,\n\tERR_RPC_INVALID_PARAMS,\n\tERR_RPC_INVALID_REQUEST,\n\tERR_RPC_LIMIT_EXCEEDED,\n\tERR_RPC_MISSING_RESOURCE,\n\tERR_RPC_NOT_SUPPORTED,\n\tERR_RPC_TRANSACTION_REJECTED,\n\tERR_RPC_UNAVAILABLE_RESOURCE,\n\tERR_RPC_UNSUPPORTED_METHOD,\n} from '../error_codes.js';\nimport { RpcErrorMessages, genericRpcErrorMessageTemplate } from './rpc_error_messages.js';\n\nexport class RpcError extends BaseWeb3Error {\n\tpublic code: number;\n\tpublic id: JsonRpcId;\n\tpublic jsonrpc: string;\n\tpublic jsonRpcError: JsonRpcError;\n\tpublic constructor(rpcError: JsonRpcResponseWithError, message?: string) {\n\t\tsuper(\n\t\t\tmessage ??\n\t\t\t\tgenericRpcErrorMessageTemplate.replace('*code*', rpcError.error.code.toString()),\n\t\t);\n\t\tthis.code = rpcError.error.code;\n\t\tthis.id = rpcError.id;\n\t\tthis.jsonrpc = rpcError.jsonrpc;\n\t\tthis.jsonRpcError = rpcError.error;\n\t}\n\n\tpublic toJSON() {\n\t\treturn { ...super.toJSON(), error: this.jsonRpcError, id: this.id, jsonRpc: this.jsonrpc };\n\t}\n}\n\nexport class EIP1193ProviderRpcError extends BaseWeb3Error {\n\tpublic code: number;\n\tpublic data?: unknown;\n\n\tpublic constructor(code: number, data?: unknown) {\n\t\tif (!code) {\n\t\t\t// this case should ideally not happen\n\t\t\tsuper();\n\t\t} else if (RpcErrorMessages[code]?.message) {\n\t\t\tsuper(RpcErrorMessages[code].message);\n\t\t} else {\n\t\t\t// Retrieve the status code object for the given code from the table, by searching through the appropriate range\n\t\t\tconst statusCodeRange = Object.keys(RpcErrorMessages).find(\n\t\t\t\tstatusCode =>\n\t\t\t\t\ttypeof statusCode === 'string' &&\n\t\t\t\t\tcode >= parseInt(statusCode.split('-')[0], 10) &&\n\t\t\t\t\tcode <= parseInt(statusCode.split('-')[1], 10),\n\t\t\t);\n\t\t\tsuper(\n\t\t\t\tRpcErrorMessages[statusCodeRange ?? '']?.message ??\n\t\t\t\t\tgenericRpcErrorMessageTemplate.replace('*code*', code?.toString() ?? '\"\"'),\n\t\t\t);\n\t\t}\n\t\tthis.code = code;\n\t\tthis.data = data;\n\t}\n}\n\nexport class ParseError extends RpcError {\n\tpublic code = ERR_RPC_INVALID_JSON;\n\tpublic constructor(rpcError: JsonRpcResponseWithError) {\n\t\tsuper(rpcError, RpcErrorMessages[ERR_RPC_INVALID_JSON].message);\n\t}\n}\n\nexport class InvalidRequestError extends RpcError {\n\tpublic code = ERR_RPC_INVALID_REQUEST;\n\tpublic constructor(rpcError: JsonRpcResponseWithError) {\n\t\tsuper(rpcError, RpcErrorMessages[ERR_RPC_INVALID_REQUEST].message);\n\t}\n}\n\nexport class MethodNotFoundError extends RpcError {\n\tpublic code = ERR_RPC_INVALID_METHOD;\n\tpublic constructor(rpcError: JsonRpcResponseWithError) {\n\t\tsuper(rpcError, RpcErrorMessages[ERR_RPC_INVALID_METHOD].message);\n\t}\n}\n\nexport class InvalidParamsError extends RpcError {\n\tpublic code = ERR_RPC_INVALID_PARAMS;\n\tpublic constructor(rpcError: JsonRpcResponseWithError) {\n\t\tsuper(rpcError, RpcErrorMessages[ERR_RPC_INVALID_PARAMS].message);\n\t}\n}\n\nexport class InternalError extends RpcError {\n\tpublic code = ERR_RPC_INTERNAL_ERROR;\n\tpublic constructor(rpcError: JsonRpcResponseWithError) {\n\t\tsuper(rpcError, RpcErrorMessages[ERR_RPC_INTERNAL_ERROR].message);\n\t}\n}\n\nexport class InvalidInputError extends RpcError {\n\tpublic code = ERR_RPC_INVALID_INPUT;\n\tpublic constructor(rpcError: JsonRpcResponseWithError) {\n\t\tsuper(rpcError, RpcErrorMessages[ERR_RPC_INVALID_INPUT].message);\n\t}\n}\n\nexport class MethodNotSupported extends RpcError {\n\tpublic code = ERR_RPC_UNSUPPORTED_METHOD;\n\tpublic constructor(rpcError: JsonRpcResponseWithError) {\n\t\tsuper(rpcError, RpcErrorMessages[ERR_RPC_UNSUPPORTED_METHOD].message);\n\t}\n}\n\nexport class ResourceUnavailableError extends RpcError {\n\tpublic code = ERR_RPC_UNAVAILABLE_RESOURCE;\n\tpublic constructor(rpcError: JsonRpcResponseWithError) {\n\t\tsuper(rpcError, RpcErrorMessages[ERR_RPC_UNAVAILABLE_RESOURCE].message);\n\t}\n}\n\nexport class ResourcesNotFoundError extends RpcError {\n\tpublic code = ERR_RPC_MISSING_RESOURCE;\n\tpublic constructor(rpcError: JsonRpcResponseWithError) {\n\t\tsuper(rpcError, RpcErrorMessages[ERR_RPC_MISSING_RESOURCE].message);\n\t}\n}\n\nexport class VersionNotSupportedError extends RpcError {\n\tpublic code = ERR_RPC_NOT_SUPPORTED;\n\tpublic constructor(rpcError: JsonRpcResponseWithError) {\n\t\tsuper(rpcError, RpcErrorMessages[ERR_RPC_NOT_SUPPORTED].message);\n\t}\n}\n\nexport class TransactionRejectedError extends RpcError {\n\tpublic code = ERR_RPC_TRANSACTION_REJECTED;\n\tpublic constructor(rpcError: JsonRpcResponseWithError) {\n\t\tsuper(rpcError, RpcErrorMessages[ERR_RPC_TRANSACTION_REJECTED].message);\n\t}\n}\n\nexport class LimitExceededError extends RpcError {\n\tpublic code = ERR_RPC_LIMIT_EXCEEDED;\n\tpublic constructor(rpcError: JsonRpcResponseWithError) {\n\t\tsuper(rpcError, RpcErrorMessages[ERR_RPC_LIMIT_EXCEEDED].message);\n\t}\n}\n\nexport const rpcErrorsMap = new Map();\nrpcErrorsMap.set(ERR_RPC_INVALID_JSON, { error: ParseError });\nrpcErrorsMap.set(ERR_RPC_INVALID_REQUEST, {\n\terror: InvalidRequestError,\n});\nrpcErrorsMap.set(ERR_RPC_INVALID_METHOD, {\n\terror: MethodNotFoundError,\n});\nrpcErrorsMap.set(ERR_RPC_INVALID_PARAMS, { error: InvalidParamsError });\nrpcErrorsMap.set(ERR_RPC_INTERNAL_ERROR, { error: InternalError });\nrpcErrorsMap.set(ERR_RPC_INVALID_INPUT, { error: InvalidInputError });\nrpcErrorsMap.set(ERR_RPC_UNSUPPORTED_METHOD, {\n\terror: MethodNotSupported,\n});\nrpcErrorsMap.set(ERR_RPC_UNAVAILABLE_RESOURCE, {\n\terror: ResourceUnavailableError,\n});\nrpcErrorsMap.set(ERR_RPC_TRANSACTION_REJECTED, {\n\terror: TransactionRejectedError,\n});\nrpcErrorsMap.set(ERR_RPC_MISSING_RESOURCE, {\n\terror: ResourcesNotFoundError,\n});\nrpcErrorsMap.set(ERR_RPC_NOT_SUPPORTED, {\n\terror: VersionNotSupportedError,\n});\nrpcErrorsMap.set(ERR_RPC_LIMIT_EXCEEDED, { error: LimitExceededError });\n","/*\nThis file is part of web3.js.\n\nweb3.js is free software: you can redistribute it and/or modify\nit under the terms of the GNU Lesser General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nweb3.js is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU Lesser General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public License\nalong with web3.js. If not, see .\n*/\n\nimport { ERR_SCHEMA_FORMAT } from '../error_codes.js';\nimport { BaseWeb3Error } from '../web3_error_base.js';\n\nexport class SchemaFormatError extends BaseWeb3Error {\n\tpublic code = ERR_SCHEMA_FORMAT;\n\n\tpublic constructor(public type: string) {\n\t\tsuper(`Format for the type ${type} is unsupported`);\n\t}\n\n\tpublic toJSON() {\n\t\treturn { ...super.toJSON(), type: this.type };\n\t}\n\n}\n","var util;\n(function (util) {\n util.assertEqual = (val) => val;\n function assertIs(_arg) { }\n util.assertIs = assertIs;\n function assertNever(_x) {\n throw new Error();\n }\n util.assertNever = assertNever;\n util.arrayToEnum = (items) => {\n const obj = {};\n for (const item of items) {\n obj[item] = item;\n }\n return obj;\n };\n util.getValidEnumValues = (obj) => {\n const validKeys = util.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== \"number\");\n const filtered = {};\n for (const k of validKeys) {\n filtered[k] = obj[k];\n }\n return util.objectValues(filtered);\n };\n util.objectValues = (obj) => {\n return util.objectKeys(obj).map(function (e) {\n return obj[e];\n });\n };\n util.objectKeys = typeof Object.keys === \"function\" // eslint-disable-line ban/ban\n ? (obj) => Object.keys(obj) // eslint-disable-line ban/ban\n : (object) => {\n const keys = [];\n for (const key in object) {\n if (Object.prototype.hasOwnProperty.call(object, key)) {\n keys.push(key);\n }\n }\n return keys;\n };\n util.find = (arr, checker) => {\n for (const item of arr) {\n if (checker(item))\n return item;\n }\n return undefined;\n };\n util.isInteger = typeof Number.isInteger === \"function\"\n ? (val) => Number.isInteger(val) // eslint-disable-line ban/ban\n : (val) => typeof val === \"number\" && isFinite(val) && Math.floor(val) === val;\n function joinValues(array, separator = \" | \") {\n return array\n .map((val) => (typeof val === \"string\" ? `'${val}'` : val))\n .join(separator);\n }\n util.joinValues = joinValues;\n util.jsonStringifyReplacer = (_, value) => {\n if (typeof value === \"bigint\") {\n return value.toString();\n }\n return value;\n };\n})(util || (util = {}));\nvar objectUtil;\n(function (objectUtil) {\n objectUtil.mergeShapes = (first, second) => {\n return {\n ...first,\n ...second, // second overwrites first\n };\n };\n})(objectUtil || (objectUtil = {}));\nconst ZodParsedType = util.arrayToEnum([\n \"string\",\n \"nan\",\n \"number\",\n \"integer\",\n \"float\",\n \"boolean\",\n \"date\",\n \"bigint\",\n \"symbol\",\n \"function\",\n \"undefined\",\n \"null\",\n \"array\",\n \"object\",\n \"unknown\",\n \"promise\",\n \"void\",\n \"never\",\n \"map\",\n \"set\",\n]);\nconst getParsedType = (data) => {\n const t = typeof data;\n switch (t) {\n case \"undefined\":\n return ZodParsedType.undefined;\n case \"string\":\n return ZodParsedType.string;\n case \"number\":\n return isNaN(data) ? ZodParsedType.nan : ZodParsedType.number;\n case \"boolean\":\n return ZodParsedType.boolean;\n case \"function\":\n return ZodParsedType.function;\n case \"bigint\":\n return ZodParsedType.bigint;\n case \"symbol\":\n return ZodParsedType.symbol;\n case \"object\":\n if (Array.isArray(data)) {\n return ZodParsedType.array;\n }\n if (data === null) {\n return ZodParsedType.null;\n }\n if (data.then &&\n typeof data.then === \"function\" &&\n data.catch &&\n typeof data.catch === \"function\") {\n return ZodParsedType.promise;\n }\n if (typeof Map !== \"undefined\" && data instanceof Map) {\n return ZodParsedType.map;\n }\n if (typeof Set !== \"undefined\" && data instanceof Set) {\n return ZodParsedType.set;\n }\n if (typeof Date !== \"undefined\" && data instanceof Date) {\n return ZodParsedType.date;\n }\n return ZodParsedType.object;\n default:\n return ZodParsedType.unknown;\n }\n};\n\nconst ZodIssueCode = util.arrayToEnum([\n \"invalid_type\",\n \"invalid_literal\",\n \"custom\",\n \"invalid_union\",\n \"invalid_union_discriminator\",\n \"invalid_enum_value\",\n \"unrecognized_keys\",\n \"invalid_arguments\",\n \"invalid_return_type\",\n \"invalid_date\",\n \"invalid_string\",\n \"too_small\",\n \"too_big\",\n \"invalid_intersection_types\",\n \"not_multiple_of\",\n \"not_finite\",\n]);\nconst quotelessJson = (obj) => {\n const json = JSON.stringify(obj, null, 2);\n return json.replace(/\"([^\"]+)\":/g, \"$1:\");\n};\nclass ZodError extends Error {\n constructor(issues) {\n super();\n this.issues = [];\n this.addIssue = (sub) => {\n this.issues = [...this.issues, sub];\n };\n this.addIssues = (subs = []) => {\n this.issues = [...this.issues, ...subs];\n };\n const actualProto = new.target.prototype;\n if (Object.setPrototypeOf) {\n // eslint-disable-next-line ban/ban\n Object.setPrototypeOf(this, actualProto);\n }\n else {\n this.__proto__ = actualProto;\n }\n this.name = \"ZodError\";\n this.issues = issues;\n }\n get errors() {\n return this.issues;\n }\n format(_mapper) {\n const mapper = _mapper ||\n function (issue) {\n return issue.message;\n };\n const fieldErrors = { _errors: [] };\n const processError = (error) => {\n for (const issue of error.issues) {\n if (issue.code === \"invalid_union\") {\n issue.unionErrors.map(processError);\n }\n else if (issue.code === \"invalid_return_type\") {\n processError(issue.returnTypeError);\n }\n else if (issue.code === \"invalid_arguments\") {\n processError(issue.argumentsError);\n }\n else if (issue.path.length === 0) {\n fieldErrors._errors.push(mapper(issue));\n }\n else {\n let curr = fieldErrors;\n let i = 0;\n while (i < issue.path.length) {\n const el = issue.path[i];\n const terminal = i === issue.path.length - 1;\n if (!terminal) {\n curr[el] = curr[el] || { _errors: [] };\n // if (typeof el === \"string\") {\n // curr[el] = curr[el] || { _errors: [] };\n // } else if (typeof el === \"number\") {\n // const errorArray: any = [];\n // errorArray._errors = [];\n // curr[el] = curr[el] || errorArray;\n // }\n }\n else {\n curr[el] = curr[el] || { _errors: [] };\n curr[el]._errors.push(mapper(issue));\n }\n curr = curr[el];\n i++;\n }\n }\n }\n };\n processError(this);\n return fieldErrors;\n }\n static assert(value) {\n if (!(value instanceof ZodError)) {\n throw new Error(`Not a ZodError: ${value}`);\n }\n }\n toString() {\n return this.message;\n }\n get message() {\n return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2);\n }\n get isEmpty() {\n return this.issues.length === 0;\n }\n flatten(mapper = (issue) => issue.message) {\n const fieldErrors = {};\n const formErrors = [];\n for (const sub of this.issues) {\n if (sub.path.length > 0) {\n fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || [];\n fieldErrors[sub.path[0]].push(mapper(sub));\n }\n else {\n formErrors.push(mapper(sub));\n }\n }\n return { formErrors, fieldErrors };\n }\n get formErrors() {\n return this.flatten();\n }\n}\nZodError.create = (issues) => {\n const error = new ZodError(issues);\n return error;\n};\n\nconst errorMap = (issue, _ctx) => {\n let message;\n switch (issue.code) {\n case ZodIssueCode.invalid_type:\n if (issue.received === ZodParsedType.undefined) {\n message = \"Required\";\n }\n else {\n message = `Expected ${issue.expected}, received ${issue.received}`;\n }\n break;\n case ZodIssueCode.invalid_literal:\n message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.jsonStringifyReplacer)}`;\n break;\n case ZodIssueCode.unrecognized_keys:\n message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, \", \")}`;\n break;\n case ZodIssueCode.invalid_union:\n message = `Invalid input`;\n break;\n case ZodIssueCode.invalid_union_discriminator:\n message = `Invalid discriminator value. Expected ${util.joinValues(issue.options)}`;\n break;\n case ZodIssueCode.invalid_enum_value:\n message = `Invalid enum value. Expected ${util.joinValues(issue.options)}, received '${issue.received}'`;\n break;\n case ZodIssueCode.invalid_arguments:\n message = `Invalid function arguments`;\n break;\n case ZodIssueCode.invalid_return_type:\n message = `Invalid function return type`;\n break;\n case ZodIssueCode.invalid_date:\n message = `Invalid date`;\n break;\n case ZodIssueCode.invalid_string:\n if (typeof issue.validation === \"object\") {\n if (\"includes\" in issue.validation) {\n message = `Invalid input: must include \"${issue.validation.includes}\"`;\n if (typeof issue.validation.position === \"number\") {\n message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`;\n }\n }\n else if (\"startsWith\" in issue.validation) {\n message = `Invalid input: must start with \"${issue.validation.startsWith}\"`;\n }\n else if (\"endsWith\" in issue.validation) {\n message = `Invalid input: must end with \"${issue.validation.endsWith}\"`;\n }\n else {\n util.assertNever(issue.validation);\n }\n }\n else if (issue.validation !== \"regex\") {\n message = `Invalid ${issue.validation}`;\n }\n else {\n message = \"Invalid\";\n }\n break;\n case ZodIssueCode.too_small:\n if (issue.type === \"array\")\n message = `Array must contain ${issue.exact ? \"exactly\" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`;\n else if (issue.type === \"string\")\n message = `String must contain ${issue.exact ? \"exactly\" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`;\n else if (issue.type === \"number\")\n message = `Number must be ${issue.exact\n ? `exactly equal to `\n : issue.inclusive\n ? `greater than or equal to `\n : `greater than `}${issue.minimum}`;\n else if (issue.type === \"date\")\n message = `Date must be ${issue.exact\n ? `exactly equal to `\n : issue.inclusive\n ? `greater than or equal to `\n : `greater than `}${new Date(Number(issue.minimum))}`;\n else\n message = \"Invalid input\";\n break;\n case ZodIssueCode.too_big:\n if (issue.type === \"array\")\n message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`;\n else if (issue.type === \"string\")\n message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`;\n else if (issue.type === \"number\")\n message = `Number must be ${issue.exact\n ? `exactly`\n : issue.inclusive\n ? `less than or equal to`\n : `less than`} ${issue.maximum}`;\n else if (issue.type === \"bigint\")\n message = `BigInt must be ${issue.exact\n ? `exactly`\n : issue.inclusive\n ? `less than or equal to`\n : `less than`} ${issue.maximum}`;\n else if (issue.type === \"date\")\n message = `Date must be ${issue.exact\n ? `exactly`\n : issue.inclusive\n ? `smaller than or equal to`\n : `smaller than`} ${new Date(Number(issue.maximum))}`;\n else\n message = \"Invalid input\";\n break;\n case ZodIssueCode.custom:\n message = `Invalid input`;\n break;\n case ZodIssueCode.invalid_intersection_types:\n message = `Intersection results could not be merged`;\n break;\n case ZodIssueCode.not_multiple_of:\n message = `Number must be a multiple of ${issue.multipleOf}`;\n break;\n case ZodIssueCode.not_finite:\n message = \"Number must be finite\";\n break;\n default:\n message = _ctx.defaultError;\n util.assertNever(issue);\n }\n return { message };\n};\n\nlet overrideErrorMap = errorMap;\nfunction setErrorMap(map) {\n overrideErrorMap = map;\n}\nfunction getErrorMap() {\n return overrideErrorMap;\n}\n\nconst makeIssue = (params) => {\n const { data, path, errorMaps, issueData } = params;\n const fullPath = [...path, ...(issueData.path || [])];\n const fullIssue = {\n ...issueData,\n path: fullPath,\n };\n if (issueData.message !== undefined) {\n return {\n ...issueData,\n path: fullPath,\n message: issueData.message,\n };\n }\n let errorMessage = \"\";\n const maps = errorMaps\n .filter((m) => !!m)\n .slice()\n .reverse();\n for (const map of maps) {\n errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message;\n }\n return {\n ...issueData,\n path: fullPath,\n message: errorMessage,\n };\n};\nconst EMPTY_PATH = [];\nfunction addIssueToContext(ctx, issueData) {\n const overrideMap = getErrorMap();\n const issue = makeIssue({\n issueData: issueData,\n data: ctx.data,\n path: ctx.path,\n errorMaps: [\n ctx.common.contextualErrorMap,\n ctx.schemaErrorMap,\n overrideMap,\n overrideMap === errorMap ? undefined : errorMap, // then global default map\n ].filter((x) => !!x),\n });\n ctx.common.issues.push(issue);\n}\nclass ParseStatus {\n constructor() {\n this.value = \"valid\";\n }\n dirty() {\n if (this.value === \"valid\")\n this.value = \"dirty\";\n }\n abort() {\n if (this.value !== \"aborted\")\n this.value = \"aborted\";\n }\n static mergeArray(status, results) {\n const arrayValue = [];\n for (const s of results) {\n if (s.status === \"aborted\")\n return INVALID;\n if (s.status === \"dirty\")\n status.dirty();\n arrayValue.push(s.value);\n }\n return { status: status.value, value: arrayValue };\n }\n static async mergeObjectAsync(status, pairs) {\n const syncPairs = [];\n for (const pair of pairs) {\n const key = await pair.key;\n const value = await pair.value;\n syncPairs.push({\n key,\n value,\n });\n }\n return ParseStatus.mergeObjectSync(status, syncPairs);\n }\n static mergeObjectSync(status, pairs) {\n const finalObject = {};\n for (const pair of pairs) {\n const { key, value } = pair;\n if (key.status === \"aborted\")\n return INVALID;\n if (value.status === \"aborted\")\n return INVALID;\n if (key.status === \"dirty\")\n status.dirty();\n if (value.status === \"dirty\")\n status.dirty();\n if (key.value !== \"__proto__\" &&\n (typeof value.value !== \"undefined\" || pair.alwaysSet)) {\n finalObject[key.value] = value.value;\n }\n }\n return { status: status.value, value: finalObject };\n }\n}\nconst INVALID = Object.freeze({\n status: \"aborted\",\n});\nconst DIRTY = (value) => ({ status: \"dirty\", value });\nconst OK = (value) => ({ status: \"valid\", value });\nconst isAborted = (x) => x.status === \"aborted\";\nconst isDirty = (x) => x.status === \"dirty\";\nconst isValid = (x) => x.status === \"valid\";\nconst isAsync = (x) => typeof Promise !== \"undefined\" && x instanceof Promise;\n\n/******************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n\r\nfunction __classPrivateFieldGet(receiver, state, kind, f) {\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\r\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\r\n}\r\n\r\nfunction __classPrivateFieldSet(receiver, state, value, kind, f) {\r\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\r\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\r\n}\r\n\r\ntypeof SuppressedError === \"function\" ? SuppressedError : function (error, suppressed, message) {\r\n var e = new Error(message);\r\n return e.name = \"SuppressedError\", e.error = error, e.suppressed = suppressed, e;\r\n};\n\nvar errorUtil;\n(function (errorUtil) {\n errorUtil.errToObj = (message) => typeof message === \"string\" ? { message } : message || {};\n errorUtil.toString = (message) => typeof message === \"string\" ? message : message === null || message === void 0 ? void 0 : message.message;\n})(errorUtil || (errorUtil = {}));\n\nvar _ZodEnum_cache, _ZodNativeEnum_cache;\nclass ParseInputLazyPath {\n constructor(parent, value, path, key) {\n this._cachedPath = [];\n this.parent = parent;\n this.data = value;\n this._path = path;\n this._key = key;\n }\n get path() {\n if (!this._cachedPath.length) {\n if (this._key instanceof Array) {\n this._cachedPath.push(...this._path, ...this._key);\n }\n else {\n this._cachedPath.push(...this._path, this._key);\n }\n }\n return this._cachedPath;\n }\n}\nconst handleResult = (ctx, result) => {\n if (isValid(result)) {\n return { success: true, data: result.value };\n }\n else {\n if (!ctx.common.issues.length) {\n throw new Error(\"Validation failed but no issues detected.\");\n }\n return {\n success: false,\n get error() {\n if (this._error)\n return this._error;\n const error = new ZodError(ctx.common.issues);\n this._error = error;\n return this._error;\n },\n };\n }\n};\nfunction processCreateParams(params) {\n if (!params)\n return {};\n const { errorMap, invalid_type_error, required_error, description } = params;\n if (errorMap && (invalid_type_error || required_error)) {\n throw new Error(`Can't use \"invalid_type_error\" or \"required_error\" in conjunction with custom error map.`);\n }\n if (errorMap)\n return { errorMap: errorMap, description };\n const customMap = (iss, ctx) => {\n var _a, _b;\n const { message } = params;\n if (iss.code === \"invalid_enum_value\") {\n return { message: message !== null && message !== void 0 ? message : ctx.defaultError };\n }\n if (typeof ctx.data === \"undefined\") {\n return { message: (_a = message !== null && message !== void 0 ? message : required_error) !== null && _a !== void 0 ? _a : ctx.defaultError };\n }\n if (iss.code !== \"invalid_type\")\n return { message: ctx.defaultError };\n return { message: (_b = message !== null && message !== void 0 ? message : invalid_type_error) !== null && _b !== void 0 ? _b : ctx.defaultError };\n };\n return { errorMap: customMap, description };\n}\nclass ZodType {\n constructor(def) {\n /** Alias of safeParseAsync */\n this.spa = this.safeParseAsync;\n this._def = def;\n this.parse = this.parse.bind(this);\n this.safeParse = this.safeParse.bind(this);\n this.parseAsync = this.parseAsync.bind(this);\n this.safeParseAsync = this.safeParseAsync.bind(this);\n this.spa = this.spa.bind(this);\n this.refine = this.refine.bind(this);\n this.refinement = this.refinement.bind(this);\n this.superRefine = this.superRefine.bind(this);\n this.optional = this.optional.bind(this);\n this.nullable = this.nullable.bind(this);\n this.nullish = this.nullish.bind(this);\n this.array = this.array.bind(this);\n this.promise = this.promise.bind(this);\n this.or = this.or.bind(this);\n this.and = this.and.bind(this);\n this.transform = this.transform.bind(this);\n this.brand = this.brand.bind(this);\n this.default = this.default.bind(this);\n this.catch = this.catch.bind(this);\n this.describe = this.describe.bind(this);\n this.pipe = this.pipe.bind(this);\n this.readonly = this.readonly.bind(this);\n this.isNullable = this.isNullable.bind(this);\n this.isOptional = this.isOptional.bind(this);\n }\n get description() {\n return this._def.description;\n }\n _getType(input) {\n return getParsedType(input.data);\n }\n _getOrReturnCtx(input, ctx) {\n return (ctx || {\n common: input.parent.common,\n data: input.data,\n parsedType: getParsedType(input.data),\n schemaErrorMap: this._def.errorMap,\n path: input.path,\n parent: input.parent,\n });\n }\n _processInputParams(input) {\n return {\n status: new ParseStatus(),\n ctx: {\n common: input.parent.common,\n data: input.data,\n parsedType: getParsedType(input.data),\n schemaErrorMap: this._def.errorMap,\n path: input.path,\n parent: input.parent,\n },\n };\n }\n _parseSync(input) {\n const result = this._parse(input);\n if (isAsync(result)) {\n throw new Error(\"Synchronous parse encountered promise.\");\n }\n return result;\n }\n _parseAsync(input) {\n const result = this._parse(input);\n return Promise.resolve(result);\n }\n parse(data, params) {\n const result = this.safeParse(data, params);\n if (result.success)\n return result.data;\n throw result.error;\n }\n safeParse(data, params) {\n var _a;\n const ctx = {\n common: {\n issues: [],\n async: (_a = params === null || params === void 0 ? void 0 : params.async) !== null && _a !== void 0 ? _a : false,\n contextualErrorMap: params === null || params === void 0 ? void 0 : params.errorMap,\n },\n path: (params === null || params === void 0 ? void 0 : params.path) || [],\n schemaErrorMap: this._def.errorMap,\n parent: null,\n data,\n parsedType: getParsedType(data),\n };\n const result = this._parseSync({ data, path: ctx.path, parent: ctx });\n return handleResult(ctx, result);\n }\n async parseAsync(data, params) {\n const result = await this.safeParseAsync(data, params);\n if (result.success)\n return result.data;\n throw result.error;\n }\n async safeParseAsync(data, params) {\n const ctx = {\n common: {\n issues: [],\n contextualErrorMap: params === null || params === void 0 ? void 0 : params.errorMap,\n async: true,\n },\n path: (params === null || params === void 0 ? void 0 : params.path) || [],\n schemaErrorMap: this._def.errorMap,\n parent: null,\n data,\n parsedType: getParsedType(data),\n };\n const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx });\n const result = await (isAsync(maybeAsyncResult)\n ? maybeAsyncResult\n : Promise.resolve(maybeAsyncResult));\n return handleResult(ctx, result);\n }\n refine(check, message) {\n const getIssueProperties = (val) => {\n if (typeof message === \"string\" || typeof message === \"undefined\") {\n return { message };\n }\n else if (typeof message === \"function\") {\n return message(val);\n }\n else {\n return message;\n }\n };\n return this._refinement((val, ctx) => {\n const result = check(val);\n const setError = () => ctx.addIssue({\n code: ZodIssueCode.custom,\n ...getIssueProperties(val),\n });\n if (typeof Promise !== \"undefined\" && result instanceof Promise) {\n return result.then((data) => {\n if (!data) {\n setError();\n return false;\n }\n else {\n return true;\n }\n });\n }\n if (!result) {\n setError();\n return false;\n }\n else {\n return true;\n }\n });\n }\n refinement(check, refinementData) {\n return this._refinement((val, ctx) => {\n if (!check(val)) {\n ctx.addIssue(typeof refinementData === \"function\"\n ? refinementData(val, ctx)\n : refinementData);\n return false;\n }\n else {\n return true;\n }\n });\n }\n _refinement(refinement) {\n return new ZodEffects({\n schema: this,\n typeName: ZodFirstPartyTypeKind.ZodEffects,\n effect: { type: \"refinement\", refinement },\n });\n }\n superRefine(refinement) {\n return this._refinement(refinement);\n }\n optional() {\n return ZodOptional.create(this, this._def);\n }\n nullable() {\n return ZodNullable.create(this, this._def);\n }\n nullish() {\n return this.nullable().optional();\n }\n array() {\n return ZodArray.create(this, this._def);\n }\n promise() {\n return ZodPromise.create(this, this._def);\n }\n or(option) {\n return ZodUnion.create([this, option], this._def);\n }\n and(incoming) {\n return ZodIntersection.create(this, incoming, this._def);\n }\n transform(transform) {\n return new ZodEffects({\n ...processCreateParams(this._def),\n schema: this,\n typeName: ZodFirstPartyTypeKind.ZodEffects,\n effect: { type: \"transform\", transform },\n });\n }\n default(def) {\n const defaultValueFunc = typeof def === \"function\" ? def : () => def;\n return new ZodDefault({\n ...processCreateParams(this._def),\n innerType: this,\n defaultValue: defaultValueFunc,\n typeName: ZodFirstPartyTypeKind.ZodDefault,\n });\n }\n brand() {\n return new ZodBranded({\n typeName: ZodFirstPartyTypeKind.ZodBranded,\n type: this,\n ...processCreateParams(this._def),\n });\n }\n catch(def) {\n const catchValueFunc = typeof def === \"function\" ? def : () => def;\n return new ZodCatch({\n ...processCreateParams(this._def),\n innerType: this,\n catchValue: catchValueFunc,\n typeName: ZodFirstPartyTypeKind.ZodCatch,\n });\n }\n describe(description) {\n const This = this.constructor;\n return new This({\n ...this._def,\n description,\n });\n }\n pipe(target) {\n return ZodPipeline.create(this, target);\n }\n readonly() {\n return ZodReadonly.create(this);\n }\n isOptional() {\n return this.safeParse(undefined).success;\n }\n isNullable() {\n return this.safeParse(null).success;\n }\n}\nconst cuidRegex = /^c[^\\s-]{8,}$/i;\nconst cuid2Regex = /^[0-9a-z]+$/;\nconst ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/;\n// const uuidRegex =\n// /^([a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[a-f0-9]{4}-[a-f0-9]{12}|00000000-0000-0000-0000-000000000000)$/i;\nconst uuidRegex = /^[0-9a-fA-F]{8}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{12}$/i;\nconst nanoidRegex = /^[a-z0-9_-]{21}$/i;\nconst durationRegex = /^[-+]?P(?!$)(?:(?:[-+]?\\d+Y)|(?:[-+]?\\d+[.,]\\d+Y$))?(?:(?:[-+]?\\d+M)|(?:[-+]?\\d+[.,]\\d+M$))?(?:(?:[-+]?\\d+W)|(?:[-+]?\\d+[.,]\\d+W$))?(?:(?:[-+]?\\d+D)|(?:[-+]?\\d+[.,]\\d+D$))?(?:T(?=[\\d+-])(?:(?:[-+]?\\d+H)|(?:[-+]?\\d+[.,]\\d+H$))?(?:(?:[-+]?\\d+M)|(?:[-+]?\\d+[.,]\\d+M$))?(?:[-+]?\\d+(?:[.,]\\d+)?S)?)??$/;\n// from https://stackoverflow.com/a/46181/1550155\n// old version: too slow, didn't support unicode\n// const emailRegex = /^((([a-z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])+(\\.([a-z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])+)*)|((\\x22)((((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(([\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x7f]|\\x21|[\\x23-\\x5b]|[\\x5d-\\x7e]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(\\\\([\\x01-\\x09\\x0b\\x0c\\x0d-\\x7f]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]))))*(((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(\\x22)))@((([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])*([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])))\\.)+(([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])*([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])))$/i;\n//old email regex\n// const emailRegex = /^(([^<>()[\\].,;:\\s@\"]+(\\.[^<>()[\\].,;:\\s@\"]+)*)|(\".+\"))@((?!-)([^<>()[\\].,;:\\s@\"]+\\.)+[^<>()[\\].,;:\\s@\"]{1,})[^-<>()[\\].,;:\\s@\"]$/i;\n// eslint-disable-next-line\n// const emailRegex =\n// /^(([^<>()[\\]\\\\.,;:\\s@\\\"]+(\\.[^<>()[\\]\\\\.,;:\\s@\\\"]+)*)|(\\\".+\\\"))@((\\[(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\\])|(\\[IPv6:(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))\\])|([A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])*(\\.[A-Za-z]{2,})+))$/;\n// const emailRegex =\n// /^[a-zA-Z0-9\\.\\!\\#\\$\\%\\&\\'\\*\\+\\/\\=\\?\\^\\_\\`\\{\\|\\}\\~\\-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;\n// const emailRegex =\n// /^(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])$/i;\nconst emailRegex = /^(?!\\.)(?!.*\\.\\.)([A-Z0-9_'+\\-\\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\\-]*\\.)+[A-Z]{2,}$/i;\n// const emailRegex =\n// /^[a-z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-z0-9-]+(?:\\.[a-z0-9\\-]+)*$/i;\n// from https://thekevinscott.com/emojis-in-javascript/#writing-a-regular-expression\nconst _emojiRegex = `^(\\\\p{Extended_Pictographic}|\\\\p{Emoji_Component})+$`;\nlet emojiRegex;\n// faster, simpler, safer\nconst ipv4Regex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;\nconst ipv6Regex = /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/;\n// https://stackoverflow.com/questions/7860392/determine-if-string-is-in-base64-using-javascript\nconst base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;\n// simple\n// const dateRegexSource = `\\\\d{4}-\\\\d{2}-\\\\d{2}`;\n// no leap year validation\n// const dateRegexSource = `\\\\d{4}-((0[13578]|10|12)-31|(0[13-9]|1[0-2])-30|(0[1-9]|1[0-2])-(0[1-9]|1\\\\d|2\\\\d))`;\n// with leap year validation\nconst dateRegexSource = `((\\\\d\\\\d[2468][048]|\\\\d\\\\d[13579][26]|\\\\d\\\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\\\d|30)|(02)-(0[1-9]|1\\\\d|2[0-8])))`;\nconst dateRegex = new RegExp(`^${dateRegexSource}$`);\nfunction timeRegexSource(args) {\n // let regex = `\\\\d{2}:\\\\d{2}:\\\\d{2}`;\n let regex = `([01]\\\\d|2[0-3]):[0-5]\\\\d:[0-5]\\\\d`;\n if (args.precision) {\n regex = `${regex}\\\\.\\\\d{${args.precision}}`;\n }\n else if (args.precision == null) {\n regex = `${regex}(\\\\.\\\\d+)?`;\n }\n return regex;\n}\nfunction timeRegex(args) {\n return new RegExp(`^${timeRegexSource(args)}$`);\n}\n// Adapted from https://stackoverflow.com/a/3143231\nfunction datetimeRegex(args) {\n let regex = `${dateRegexSource}T${timeRegexSource(args)}`;\n const opts = [];\n opts.push(args.local ? `Z?` : `Z`);\n if (args.offset)\n opts.push(`([+-]\\\\d{2}:?\\\\d{2})`);\n regex = `${regex}(${opts.join(\"|\")})`;\n return new RegExp(`^${regex}$`);\n}\nfunction isValidIP(ip, version) {\n if ((version === \"v4\" || !version) && ipv4Regex.test(ip)) {\n return true;\n }\n if ((version === \"v6\" || !version) && ipv6Regex.test(ip)) {\n return true;\n }\n return false;\n}\nclass ZodString extends ZodType {\n _parse(input) {\n if (this._def.coerce) {\n input.data = String(input.data);\n }\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.string) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.string,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const status = new ParseStatus();\n let ctx = undefined;\n for (const check of this._def.checks) {\n if (check.kind === \"min\") {\n if (input.data.length < check.value) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: check.value,\n type: \"string\",\n inclusive: true,\n exact: false,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"max\") {\n if (input.data.length > check.value) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: check.value,\n type: \"string\",\n inclusive: true,\n exact: false,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"length\") {\n const tooBig = input.data.length > check.value;\n const tooSmall = input.data.length < check.value;\n if (tooBig || tooSmall) {\n ctx = this._getOrReturnCtx(input, ctx);\n if (tooBig) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: check.value,\n type: \"string\",\n inclusive: true,\n exact: true,\n message: check.message,\n });\n }\n else if (tooSmall) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: check.value,\n type: \"string\",\n inclusive: true,\n exact: true,\n message: check.message,\n });\n }\n status.dirty();\n }\n }\n else if (check.kind === \"email\") {\n if (!emailRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"email\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"emoji\") {\n if (!emojiRegex) {\n emojiRegex = new RegExp(_emojiRegex, \"u\");\n }\n if (!emojiRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"emoji\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"uuid\") {\n if (!uuidRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"uuid\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"nanoid\") {\n if (!nanoidRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"nanoid\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"cuid\") {\n if (!cuidRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"cuid\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"cuid2\") {\n if (!cuid2Regex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"cuid2\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"ulid\") {\n if (!ulidRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"ulid\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"url\") {\n try {\n new URL(input.data);\n }\n catch (_a) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"url\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"regex\") {\n check.regex.lastIndex = 0;\n const testResult = check.regex.test(input.data);\n if (!testResult) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"regex\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"trim\") {\n input.data = input.data.trim();\n }\n else if (check.kind === \"includes\") {\n if (!input.data.includes(check.value, check.position)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: { includes: check.value, position: check.position },\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"toLowerCase\") {\n input.data = input.data.toLowerCase();\n }\n else if (check.kind === \"toUpperCase\") {\n input.data = input.data.toUpperCase();\n }\n else if (check.kind === \"startsWith\") {\n if (!input.data.startsWith(check.value)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: { startsWith: check.value },\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"endsWith\") {\n if (!input.data.endsWith(check.value)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: { endsWith: check.value },\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"datetime\") {\n const regex = datetimeRegex(check);\n if (!regex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: \"datetime\",\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"date\") {\n const regex = dateRegex;\n if (!regex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: \"date\",\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"time\") {\n const regex = timeRegex(check);\n if (!regex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: \"time\",\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"duration\") {\n if (!durationRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"duration\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"ip\") {\n if (!isValidIP(input.data, check.version)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"ip\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"base64\") {\n if (!base64Regex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"base64\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else {\n util.assertNever(check);\n }\n }\n return { status: status.value, value: input.data };\n }\n _regex(regex, validation, message) {\n return this.refinement((data) => regex.test(data), {\n validation,\n code: ZodIssueCode.invalid_string,\n ...errorUtil.errToObj(message),\n });\n }\n _addCheck(check) {\n return new ZodString({\n ...this._def,\n checks: [...this._def.checks, check],\n });\n }\n email(message) {\n return this._addCheck({ kind: \"email\", ...errorUtil.errToObj(message) });\n }\n url(message) {\n return this._addCheck({ kind: \"url\", ...errorUtil.errToObj(message) });\n }\n emoji(message) {\n return this._addCheck({ kind: \"emoji\", ...errorUtil.errToObj(message) });\n }\n uuid(message) {\n return this._addCheck({ kind: \"uuid\", ...errorUtil.errToObj(message) });\n }\n nanoid(message) {\n return this._addCheck({ kind: \"nanoid\", ...errorUtil.errToObj(message) });\n }\n cuid(message) {\n return this._addCheck({ kind: \"cuid\", ...errorUtil.errToObj(message) });\n }\n cuid2(message) {\n return this._addCheck({ kind: \"cuid2\", ...errorUtil.errToObj(message) });\n }\n ulid(message) {\n return this._addCheck({ kind: \"ulid\", ...errorUtil.errToObj(message) });\n }\n base64(message) {\n return this._addCheck({ kind: \"base64\", ...errorUtil.errToObj(message) });\n }\n ip(options) {\n return this._addCheck({ kind: \"ip\", ...errorUtil.errToObj(options) });\n }\n datetime(options) {\n var _a, _b;\n if (typeof options === \"string\") {\n return this._addCheck({\n kind: \"datetime\",\n precision: null,\n offset: false,\n local: false,\n message: options,\n });\n }\n return this._addCheck({\n kind: \"datetime\",\n precision: typeof (options === null || options === void 0 ? void 0 : options.precision) === \"undefined\" ? null : options === null || options === void 0 ? void 0 : options.precision,\n offset: (_a = options === null || options === void 0 ? void 0 : options.offset) !== null && _a !== void 0 ? _a : false,\n local: (_b = options === null || options === void 0 ? void 0 : options.local) !== null && _b !== void 0 ? _b : false,\n ...errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message),\n });\n }\n date(message) {\n return this._addCheck({ kind: \"date\", message });\n }\n time(options) {\n if (typeof options === \"string\") {\n return this._addCheck({\n kind: \"time\",\n precision: null,\n message: options,\n });\n }\n return this._addCheck({\n kind: \"time\",\n precision: typeof (options === null || options === void 0 ? void 0 : options.precision) === \"undefined\" ? null : options === null || options === void 0 ? void 0 : options.precision,\n ...errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message),\n });\n }\n duration(message) {\n return this._addCheck({ kind: \"duration\", ...errorUtil.errToObj(message) });\n }\n regex(regex, message) {\n return this._addCheck({\n kind: \"regex\",\n regex: regex,\n ...errorUtil.errToObj(message),\n });\n }\n includes(value, options) {\n return this._addCheck({\n kind: \"includes\",\n value: value,\n position: options === null || options === void 0 ? void 0 : options.position,\n ...errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message),\n });\n }\n startsWith(value, message) {\n return this._addCheck({\n kind: \"startsWith\",\n value: value,\n ...errorUtil.errToObj(message),\n });\n }\n endsWith(value, message) {\n return this._addCheck({\n kind: \"endsWith\",\n value: value,\n ...errorUtil.errToObj(message),\n });\n }\n min(minLength, message) {\n return this._addCheck({\n kind: \"min\",\n value: minLength,\n ...errorUtil.errToObj(message),\n });\n }\n max(maxLength, message) {\n return this._addCheck({\n kind: \"max\",\n value: maxLength,\n ...errorUtil.errToObj(message),\n });\n }\n length(len, message) {\n return this._addCheck({\n kind: \"length\",\n value: len,\n ...errorUtil.errToObj(message),\n });\n }\n /**\n * @deprecated Use z.string().min(1) instead.\n * @see {@link ZodString.min}\n */\n nonempty(message) {\n return this.min(1, errorUtil.errToObj(message));\n }\n trim() {\n return new ZodString({\n ...this._def,\n checks: [...this._def.checks, { kind: \"trim\" }],\n });\n }\n toLowerCase() {\n return new ZodString({\n ...this._def,\n checks: [...this._def.checks, { kind: \"toLowerCase\" }],\n });\n }\n toUpperCase() {\n return new ZodString({\n ...this._def,\n checks: [...this._def.checks, { kind: \"toUpperCase\" }],\n });\n }\n get isDatetime() {\n return !!this._def.checks.find((ch) => ch.kind === \"datetime\");\n }\n get isDate() {\n return !!this._def.checks.find((ch) => ch.kind === \"date\");\n }\n get isTime() {\n return !!this._def.checks.find((ch) => ch.kind === \"time\");\n }\n get isDuration() {\n return !!this._def.checks.find((ch) => ch.kind === \"duration\");\n }\n get isEmail() {\n return !!this._def.checks.find((ch) => ch.kind === \"email\");\n }\n get isURL() {\n return !!this._def.checks.find((ch) => ch.kind === \"url\");\n }\n get isEmoji() {\n return !!this._def.checks.find((ch) => ch.kind === \"emoji\");\n }\n get isUUID() {\n return !!this._def.checks.find((ch) => ch.kind === \"uuid\");\n }\n get isNANOID() {\n return !!this._def.checks.find((ch) => ch.kind === \"nanoid\");\n }\n get isCUID() {\n return !!this._def.checks.find((ch) => ch.kind === \"cuid\");\n }\n get isCUID2() {\n return !!this._def.checks.find((ch) => ch.kind === \"cuid2\");\n }\n get isULID() {\n return !!this._def.checks.find((ch) => ch.kind === \"ulid\");\n }\n get isIP() {\n return !!this._def.checks.find((ch) => ch.kind === \"ip\");\n }\n get isBase64() {\n return !!this._def.checks.find((ch) => ch.kind === \"base64\");\n }\n get minLength() {\n let min = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"min\") {\n if (min === null || ch.value > min)\n min = ch.value;\n }\n }\n return min;\n }\n get maxLength() {\n let max = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"max\") {\n if (max === null || ch.value < max)\n max = ch.value;\n }\n }\n return max;\n }\n}\nZodString.create = (params) => {\n var _a;\n return new ZodString({\n checks: [],\n typeName: ZodFirstPartyTypeKind.ZodString,\n coerce: (_a = params === null || params === void 0 ? void 0 : params.coerce) !== null && _a !== void 0 ? _a : false,\n ...processCreateParams(params),\n });\n};\n// https://stackoverflow.com/questions/3966484/why-does-modulus-operator-return-fractional-number-in-javascript/31711034#31711034\nfunction floatSafeRemainder(val, step) {\n const valDecCount = (val.toString().split(\".\")[1] || \"\").length;\n const stepDecCount = (step.toString().split(\".\")[1] || \"\").length;\n const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;\n const valInt = parseInt(val.toFixed(decCount).replace(\".\", \"\"));\n const stepInt = parseInt(step.toFixed(decCount).replace(\".\", \"\"));\n return (valInt % stepInt) / Math.pow(10, decCount);\n}\nclass ZodNumber extends ZodType {\n constructor() {\n super(...arguments);\n this.min = this.gte;\n this.max = this.lte;\n this.step = this.multipleOf;\n }\n _parse(input) {\n if (this._def.coerce) {\n input.data = Number(input.data);\n }\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.number) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.number,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n let ctx = undefined;\n const status = new ParseStatus();\n for (const check of this._def.checks) {\n if (check.kind === \"int\") {\n if (!util.isInteger(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: \"integer\",\n received: \"float\",\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"min\") {\n const tooSmall = check.inclusive\n ? input.data < check.value\n : input.data <= check.value;\n if (tooSmall) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: check.value,\n type: \"number\",\n inclusive: check.inclusive,\n exact: false,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"max\") {\n const tooBig = check.inclusive\n ? input.data > check.value\n : input.data >= check.value;\n if (tooBig) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: check.value,\n type: \"number\",\n inclusive: check.inclusive,\n exact: false,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"multipleOf\") {\n if (floatSafeRemainder(input.data, check.value) !== 0) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.not_multiple_of,\n multipleOf: check.value,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"finite\") {\n if (!Number.isFinite(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.not_finite,\n message: check.message,\n });\n status.dirty();\n }\n }\n else {\n util.assertNever(check);\n }\n }\n return { status: status.value, value: input.data };\n }\n gte(value, message) {\n return this.setLimit(\"min\", value, true, errorUtil.toString(message));\n }\n gt(value, message) {\n return this.setLimit(\"min\", value, false, errorUtil.toString(message));\n }\n lte(value, message) {\n return this.setLimit(\"max\", value, true, errorUtil.toString(message));\n }\n lt(value, message) {\n return this.setLimit(\"max\", value, false, errorUtil.toString(message));\n }\n setLimit(kind, value, inclusive, message) {\n return new ZodNumber({\n ...this._def,\n checks: [\n ...this._def.checks,\n {\n kind,\n value,\n inclusive,\n message: errorUtil.toString(message),\n },\n ],\n });\n }\n _addCheck(check) {\n return new ZodNumber({\n ...this._def,\n checks: [...this._def.checks, check],\n });\n }\n int(message) {\n return this._addCheck({\n kind: \"int\",\n message: errorUtil.toString(message),\n });\n }\n positive(message) {\n return this._addCheck({\n kind: \"min\",\n value: 0,\n inclusive: false,\n message: errorUtil.toString(message),\n });\n }\n negative(message) {\n return this._addCheck({\n kind: \"max\",\n value: 0,\n inclusive: false,\n message: errorUtil.toString(message),\n });\n }\n nonpositive(message) {\n return this._addCheck({\n kind: \"max\",\n value: 0,\n inclusive: true,\n message: errorUtil.toString(message),\n });\n }\n nonnegative(message) {\n return this._addCheck({\n kind: \"min\",\n value: 0,\n inclusive: true,\n message: errorUtil.toString(message),\n });\n }\n multipleOf(value, message) {\n return this._addCheck({\n kind: \"multipleOf\",\n value: value,\n message: errorUtil.toString(message),\n });\n }\n finite(message) {\n return this._addCheck({\n kind: \"finite\",\n message: errorUtil.toString(message),\n });\n }\n safe(message) {\n return this._addCheck({\n kind: \"min\",\n inclusive: true,\n value: Number.MIN_SAFE_INTEGER,\n message: errorUtil.toString(message),\n })._addCheck({\n kind: \"max\",\n inclusive: true,\n value: Number.MAX_SAFE_INTEGER,\n message: errorUtil.toString(message),\n });\n }\n get minValue() {\n let min = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"min\") {\n if (min === null || ch.value > min)\n min = ch.value;\n }\n }\n return min;\n }\n get maxValue() {\n let max = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"max\") {\n if (max === null || ch.value < max)\n max = ch.value;\n }\n }\n return max;\n }\n get isInt() {\n return !!this._def.checks.find((ch) => ch.kind === \"int\" ||\n (ch.kind === \"multipleOf\" && util.isInteger(ch.value)));\n }\n get isFinite() {\n let max = null, min = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"finite\" ||\n ch.kind === \"int\" ||\n ch.kind === \"multipleOf\") {\n return true;\n }\n else if (ch.kind === \"min\") {\n if (min === null || ch.value > min)\n min = ch.value;\n }\n else if (ch.kind === \"max\") {\n if (max === null || ch.value < max)\n max = ch.value;\n }\n }\n return Number.isFinite(min) && Number.isFinite(max);\n }\n}\nZodNumber.create = (params) => {\n return new ZodNumber({\n checks: [],\n typeName: ZodFirstPartyTypeKind.ZodNumber,\n coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false,\n ...processCreateParams(params),\n });\n};\nclass ZodBigInt extends ZodType {\n constructor() {\n super(...arguments);\n this.min = this.gte;\n this.max = this.lte;\n }\n _parse(input) {\n if (this._def.coerce) {\n input.data = BigInt(input.data);\n }\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.bigint) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.bigint,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n let ctx = undefined;\n const status = new ParseStatus();\n for (const check of this._def.checks) {\n if (check.kind === \"min\") {\n const tooSmall = check.inclusive\n ? input.data < check.value\n : input.data <= check.value;\n if (tooSmall) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n type: \"bigint\",\n minimum: check.value,\n inclusive: check.inclusive,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"max\") {\n const tooBig = check.inclusive\n ? input.data > check.value\n : input.data >= check.value;\n if (tooBig) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n type: \"bigint\",\n maximum: check.value,\n inclusive: check.inclusive,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"multipleOf\") {\n if (input.data % check.value !== BigInt(0)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.not_multiple_of,\n multipleOf: check.value,\n message: check.message,\n });\n status.dirty();\n }\n }\n else {\n util.assertNever(check);\n }\n }\n return { status: status.value, value: input.data };\n }\n gte(value, message) {\n return this.setLimit(\"min\", value, true, errorUtil.toString(message));\n }\n gt(value, message) {\n return this.setLimit(\"min\", value, false, errorUtil.toString(message));\n }\n lte(value, message) {\n return this.setLimit(\"max\", value, true, errorUtil.toString(message));\n }\n lt(value, message) {\n return this.setLimit(\"max\", value, false, errorUtil.toString(message));\n }\n setLimit(kind, value, inclusive, message) {\n return new ZodBigInt({\n ...this._def,\n checks: [\n ...this._def.checks,\n {\n kind,\n value,\n inclusive,\n message: errorUtil.toString(message),\n },\n ],\n });\n }\n _addCheck(check) {\n return new ZodBigInt({\n ...this._def,\n checks: [...this._def.checks, check],\n });\n }\n positive(message) {\n return this._addCheck({\n kind: \"min\",\n value: BigInt(0),\n inclusive: false,\n message: errorUtil.toString(message),\n });\n }\n negative(message) {\n return this._addCheck({\n kind: \"max\",\n value: BigInt(0),\n inclusive: false,\n message: errorUtil.toString(message),\n });\n }\n nonpositive(message) {\n return this._addCheck({\n kind: \"max\",\n value: BigInt(0),\n inclusive: true,\n message: errorUtil.toString(message),\n });\n }\n nonnegative(message) {\n return this._addCheck({\n kind: \"min\",\n value: BigInt(0),\n inclusive: true,\n message: errorUtil.toString(message),\n });\n }\n multipleOf(value, message) {\n return this._addCheck({\n kind: \"multipleOf\",\n value,\n message: errorUtil.toString(message),\n });\n }\n get minValue() {\n let min = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"min\") {\n if (min === null || ch.value > min)\n min = ch.value;\n }\n }\n return min;\n }\n get maxValue() {\n let max = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"max\") {\n if (max === null || ch.value < max)\n max = ch.value;\n }\n }\n return max;\n }\n}\nZodBigInt.create = (params) => {\n var _a;\n return new ZodBigInt({\n checks: [],\n typeName: ZodFirstPartyTypeKind.ZodBigInt,\n coerce: (_a = params === null || params === void 0 ? void 0 : params.coerce) !== null && _a !== void 0 ? _a : false,\n ...processCreateParams(params),\n });\n};\nclass ZodBoolean extends ZodType {\n _parse(input) {\n if (this._def.coerce) {\n input.data = Boolean(input.data);\n }\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.boolean) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.boolean,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n}\nZodBoolean.create = (params) => {\n return new ZodBoolean({\n typeName: ZodFirstPartyTypeKind.ZodBoolean,\n coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false,\n ...processCreateParams(params),\n });\n};\nclass ZodDate extends ZodType {\n _parse(input) {\n if (this._def.coerce) {\n input.data = new Date(input.data);\n }\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.date) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.date,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n if (isNaN(input.data.getTime())) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_date,\n });\n return INVALID;\n }\n const status = new ParseStatus();\n let ctx = undefined;\n for (const check of this._def.checks) {\n if (check.kind === \"min\") {\n if (input.data.getTime() < check.value) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n message: check.message,\n inclusive: true,\n exact: false,\n minimum: check.value,\n type: \"date\",\n });\n status.dirty();\n }\n }\n else if (check.kind === \"max\") {\n if (input.data.getTime() > check.value) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n message: check.message,\n inclusive: true,\n exact: false,\n maximum: check.value,\n type: \"date\",\n });\n status.dirty();\n }\n }\n else {\n util.assertNever(check);\n }\n }\n return {\n status: status.value,\n value: new Date(input.data.getTime()),\n };\n }\n _addCheck(check) {\n return new ZodDate({\n ...this._def,\n checks: [...this._def.checks, check],\n });\n }\n min(minDate, message) {\n return this._addCheck({\n kind: \"min\",\n value: minDate.getTime(),\n message: errorUtil.toString(message),\n });\n }\n max(maxDate, message) {\n return this._addCheck({\n kind: \"max\",\n value: maxDate.getTime(),\n message: errorUtil.toString(message),\n });\n }\n get minDate() {\n let min = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"min\") {\n if (min === null || ch.value > min)\n min = ch.value;\n }\n }\n return min != null ? new Date(min) : null;\n }\n get maxDate() {\n let max = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"max\") {\n if (max === null || ch.value < max)\n max = ch.value;\n }\n }\n return max != null ? new Date(max) : null;\n }\n}\nZodDate.create = (params) => {\n return new ZodDate({\n checks: [],\n coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false,\n typeName: ZodFirstPartyTypeKind.ZodDate,\n ...processCreateParams(params),\n });\n};\nclass ZodSymbol extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.symbol) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.symbol,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n}\nZodSymbol.create = (params) => {\n return new ZodSymbol({\n typeName: ZodFirstPartyTypeKind.ZodSymbol,\n ...processCreateParams(params),\n });\n};\nclass ZodUndefined extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.undefined) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.undefined,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n}\nZodUndefined.create = (params) => {\n return new ZodUndefined({\n typeName: ZodFirstPartyTypeKind.ZodUndefined,\n ...processCreateParams(params),\n });\n};\nclass ZodNull extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.null) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.null,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n}\nZodNull.create = (params) => {\n return new ZodNull({\n typeName: ZodFirstPartyTypeKind.ZodNull,\n ...processCreateParams(params),\n });\n};\nclass ZodAny extends ZodType {\n constructor() {\n super(...arguments);\n // to prevent instances of other classes from extending ZodAny. this causes issues with catchall in ZodObject.\n this._any = true;\n }\n _parse(input) {\n return OK(input.data);\n }\n}\nZodAny.create = (params) => {\n return new ZodAny({\n typeName: ZodFirstPartyTypeKind.ZodAny,\n ...processCreateParams(params),\n });\n};\nclass ZodUnknown extends ZodType {\n constructor() {\n super(...arguments);\n // required\n this._unknown = true;\n }\n _parse(input) {\n return OK(input.data);\n }\n}\nZodUnknown.create = (params) => {\n return new ZodUnknown({\n typeName: ZodFirstPartyTypeKind.ZodUnknown,\n ...processCreateParams(params),\n });\n};\nclass ZodNever extends ZodType {\n _parse(input) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.never,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n}\nZodNever.create = (params) => {\n return new ZodNever({\n typeName: ZodFirstPartyTypeKind.ZodNever,\n ...processCreateParams(params),\n });\n};\nclass ZodVoid extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.undefined) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.void,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n}\nZodVoid.create = (params) => {\n return new ZodVoid({\n typeName: ZodFirstPartyTypeKind.ZodVoid,\n ...processCreateParams(params),\n });\n};\nclass ZodArray extends ZodType {\n _parse(input) {\n const { ctx, status } = this._processInputParams(input);\n const def = this._def;\n if (ctx.parsedType !== ZodParsedType.array) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.array,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n if (def.exactLength !== null) {\n const tooBig = ctx.data.length > def.exactLength.value;\n const tooSmall = ctx.data.length < def.exactLength.value;\n if (tooBig || tooSmall) {\n addIssueToContext(ctx, {\n code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small,\n minimum: (tooSmall ? def.exactLength.value : undefined),\n maximum: (tooBig ? def.exactLength.value : undefined),\n type: \"array\",\n inclusive: true,\n exact: true,\n message: def.exactLength.message,\n });\n status.dirty();\n }\n }\n if (def.minLength !== null) {\n if (ctx.data.length < def.minLength.value) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: def.minLength.value,\n type: \"array\",\n inclusive: true,\n exact: false,\n message: def.minLength.message,\n });\n status.dirty();\n }\n }\n if (def.maxLength !== null) {\n if (ctx.data.length > def.maxLength.value) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: def.maxLength.value,\n type: \"array\",\n inclusive: true,\n exact: false,\n message: def.maxLength.message,\n });\n status.dirty();\n }\n }\n if (ctx.common.async) {\n return Promise.all([...ctx.data].map((item, i) => {\n return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i));\n })).then((result) => {\n return ParseStatus.mergeArray(status, result);\n });\n }\n const result = [...ctx.data].map((item, i) => {\n return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i));\n });\n return ParseStatus.mergeArray(status, result);\n }\n get element() {\n return this._def.type;\n }\n min(minLength, message) {\n return new ZodArray({\n ...this._def,\n minLength: { value: minLength, message: errorUtil.toString(message) },\n });\n }\n max(maxLength, message) {\n return new ZodArray({\n ...this._def,\n maxLength: { value: maxLength, message: errorUtil.toString(message) },\n });\n }\n length(len, message) {\n return new ZodArray({\n ...this._def,\n exactLength: { value: len, message: errorUtil.toString(message) },\n });\n }\n nonempty(message) {\n return this.min(1, message);\n }\n}\nZodArray.create = (schema, params) => {\n return new ZodArray({\n type: schema,\n minLength: null,\n maxLength: null,\n exactLength: null,\n typeName: ZodFirstPartyTypeKind.ZodArray,\n ...processCreateParams(params),\n });\n};\nfunction deepPartialify(schema) {\n if (schema instanceof ZodObject) {\n const newShape = {};\n for (const key in schema.shape) {\n const fieldSchema = schema.shape[key];\n newShape[key] = ZodOptional.create(deepPartialify(fieldSchema));\n }\n return new ZodObject({\n ...schema._def,\n shape: () => newShape,\n });\n }\n else if (schema instanceof ZodArray) {\n return new ZodArray({\n ...schema._def,\n type: deepPartialify(schema.element),\n });\n }\n else if (schema instanceof ZodOptional) {\n return ZodOptional.create(deepPartialify(schema.unwrap()));\n }\n else if (schema instanceof ZodNullable) {\n return ZodNullable.create(deepPartialify(schema.unwrap()));\n }\n else if (schema instanceof ZodTuple) {\n return ZodTuple.create(schema.items.map((item) => deepPartialify(item)));\n }\n else {\n return schema;\n }\n}\nclass ZodObject extends ZodType {\n constructor() {\n super(...arguments);\n this._cached = null;\n /**\n * @deprecated In most cases, this is no longer needed - unknown properties are now silently stripped.\n * If you want to pass through unknown properties, use `.passthrough()` instead.\n */\n this.nonstrict = this.passthrough;\n // extend<\n // Augmentation extends ZodRawShape,\n // NewOutput extends util.flatten<{\n // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation\n // ? Augmentation[k][\"_output\"]\n // : k extends keyof Output\n // ? Output[k]\n // : never;\n // }>,\n // NewInput extends util.flatten<{\n // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation\n // ? Augmentation[k][\"_input\"]\n // : k extends keyof Input\n // ? Input[k]\n // : never;\n // }>\n // >(\n // augmentation: Augmentation\n // ): ZodObject<\n // extendShape,\n // UnknownKeys,\n // Catchall,\n // NewOutput,\n // NewInput\n // > {\n // return new ZodObject({\n // ...this._def,\n // shape: () => ({\n // ...this._def.shape(),\n // ...augmentation,\n // }),\n // }) as any;\n // }\n /**\n * @deprecated Use `.extend` instead\n * */\n this.augment = this.extend;\n }\n _getCached() {\n if (this._cached !== null)\n return this._cached;\n const shape = this._def.shape();\n const keys = util.objectKeys(shape);\n return (this._cached = { shape, keys });\n }\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.object) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.object,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const { status, ctx } = this._processInputParams(input);\n const { shape, keys: shapeKeys } = this._getCached();\n const extraKeys = [];\n if (!(this._def.catchall instanceof ZodNever &&\n this._def.unknownKeys === \"strip\")) {\n for (const key in ctx.data) {\n if (!shapeKeys.includes(key)) {\n extraKeys.push(key);\n }\n }\n }\n const pairs = [];\n for (const key of shapeKeys) {\n const keyValidator = shape[key];\n const value = ctx.data[key];\n pairs.push({\n key: { status: \"valid\", value: key },\n value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)),\n alwaysSet: key in ctx.data,\n });\n }\n if (this._def.catchall instanceof ZodNever) {\n const unknownKeys = this._def.unknownKeys;\n if (unknownKeys === \"passthrough\") {\n for (const key of extraKeys) {\n pairs.push({\n key: { status: \"valid\", value: key },\n value: { status: \"valid\", value: ctx.data[key] },\n });\n }\n }\n else if (unknownKeys === \"strict\") {\n if (extraKeys.length > 0) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.unrecognized_keys,\n keys: extraKeys,\n });\n status.dirty();\n }\n }\n else if (unknownKeys === \"strip\") ;\n else {\n throw new Error(`Internal ZodObject error: invalid unknownKeys value.`);\n }\n }\n else {\n // run catchall validation\n const catchall = this._def.catchall;\n for (const key of extraKeys) {\n const value = ctx.data[key];\n pairs.push({\n key: { status: \"valid\", value: key },\n value: catchall._parse(new ParseInputLazyPath(ctx, value, ctx.path, key) //, ctx.child(key), value, getParsedType(value)\n ),\n alwaysSet: key in ctx.data,\n });\n }\n }\n if (ctx.common.async) {\n return Promise.resolve()\n .then(async () => {\n const syncPairs = [];\n for (const pair of pairs) {\n const key = await pair.key;\n const value = await pair.value;\n syncPairs.push({\n key,\n value,\n alwaysSet: pair.alwaysSet,\n });\n }\n return syncPairs;\n })\n .then((syncPairs) => {\n return ParseStatus.mergeObjectSync(status, syncPairs);\n });\n }\n else {\n return ParseStatus.mergeObjectSync(status, pairs);\n }\n }\n get shape() {\n return this._def.shape();\n }\n strict(message) {\n errorUtil.errToObj;\n return new ZodObject({\n ...this._def,\n unknownKeys: \"strict\",\n ...(message !== undefined\n ? {\n errorMap: (issue, ctx) => {\n var _a, _b, _c, _d;\n const defaultError = (_c = (_b = (_a = this._def).errorMap) === null || _b === void 0 ? void 0 : _b.call(_a, issue, ctx).message) !== null && _c !== void 0 ? _c : ctx.defaultError;\n if (issue.code === \"unrecognized_keys\")\n return {\n message: (_d = errorUtil.errToObj(message).message) !== null && _d !== void 0 ? _d : defaultError,\n };\n return {\n message: defaultError,\n };\n },\n }\n : {}),\n });\n }\n strip() {\n return new ZodObject({\n ...this._def,\n unknownKeys: \"strip\",\n });\n }\n passthrough() {\n return new ZodObject({\n ...this._def,\n unknownKeys: \"passthrough\",\n });\n }\n // const AugmentFactory =\n // (def: Def) =>\n // (\n // augmentation: Augmentation\n // ): ZodObject<\n // extendShape, Augmentation>,\n // Def[\"unknownKeys\"],\n // Def[\"catchall\"]\n // > => {\n // return new ZodObject({\n // ...def,\n // shape: () => ({\n // ...def.shape(),\n // ...augmentation,\n // }),\n // }) as any;\n // };\n extend(augmentation) {\n return new ZodObject({\n ...this._def,\n shape: () => ({\n ...this._def.shape(),\n ...augmentation,\n }),\n });\n }\n /**\n * Prior to zod@1.0.12 there was a bug in the\n * inferred type of merged objects. Please\n * upgrade if you are experiencing issues.\n */\n merge(merging) {\n const merged = new ZodObject({\n unknownKeys: merging._def.unknownKeys,\n catchall: merging._def.catchall,\n shape: () => ({\n ...this._def.shape(),\n ...merging._def.shape(),\n }),\n typeName: ZodFirstPartyTypeKind.ZodObject,\n });\n return merged;\n }\n // merge<\n // Incoming extends AnyZodObject,\n // Augmentation extends Incoming[\"shape\"],\n // NewOutput extends {\n // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation\n // ? Augmentation[k][\"_output\"]\n // : k extends keyof Output\n // ? Output[k]\n // : never;\n // },\n // NewInput extends {\n // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation\n // ? Augmentation[k][\"_input\"]\n // : k extends keyof Input\n // ? Input[k]\n // : never;\n // }\n // >(\n // merging: Incoming\n // ): ZodObject<\n // extendShape>,\n // Incoming[\"_def\"][\"unknownKeys\"],\n // Incoming[\"_def\"][\"catchall\"],\n // NewOutput,\n // NewInput\n // > {\n // const merged: any = new ZodObject({\n // unknownKeys: merging._def.unknownKeys,\n // catchall: merging._def.catchall,\n // shape: () =>\n // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),\n // typeName: ZodFirstPartyTypeKind.ZodObject,\n // }) as any;\n // return merged;\n // }\n setKey(key, schema) {\n return this.augment({ [key]: schema });\n }\n // merge(\n // merging: Incoming\n // ): //ZodObject = (merging) => {\n // ZodObject<\n // extendShape>,\n // Incoming[\"_def\"][\"unknownKeys\"],\n // Incoming[\"_def\"][\"catchall\"]\n // > {\n // // const mergedShape = objectUtil.mergeShapes(\n // // this._def.shape(),\n // // merging._def.shape()\n // // );\n // const merged: any = new ZodObject({\n // unknownKeys: merging._def.unknownKeys,\n // catchall: merging._def.catchall,\n // shape: () =>\n // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),\n // typeName: ZodFirstPartyTypeKind.ZodObject,\n // }) as any;\n // return merged;\n // }\n catchall(index) {\n return new ZodObject({\n ...this._def,\n catchall: index,\n });\n }\n pick(mask) {\n const shape = {};\n util.objectKeys(mask).forEach((key) => {\n if (mask[key] && this.shape[key]) {\n shape[key] = this.shape[key];\n }\n });\n return new ZodObject({\n ...this._def,\n shape: () => shape,\n });\n }\n omit(mask) {\n const shape = {};\n util.objectKeys(this.shape).forEach((key) => {\n if (!mask[key]) {\n shape[key] = this.shape[key];\n }\n });\n return new ZodObject({\n ...this._def,\n shape: () => shape,\n });\n }\n /**\n * @deprecated\n */\n deepPartial() {\n return deepPartialify(this);\n }\n partial(mask) {\n const newShape = {};\n util.objectKeys(this.shape).forEach((key) => {\n const fieldSchema = this.shape[key];\n if (mask && !mask[key]) {\n newShape[key] = fieldSchema;\n }\n else {\n newShape[key] = fieldSchema.optional();\n }\n });\n return new ZodObject({\n ...this._def,\n shape: () => newShape,\n });\n }\n required(mask) {\n const newShape = {};\n util.objectKeys(this.shape).forEach((key) => {\n if (mask && !mask[key]) {\n newShape[key] = this.shape[key];\n }\n else {\n const fieldSchema = this.shape[key];\n let newField = fieldSchema;\n while (newField instanceof ZodOptional) {\n newField = newField._def.innerType;\n }\n newShape[key] = newField;\n }\n });\n return new ZodObject({\n ...this._def,\n shape: () => newShape,\n });\n }\n keyof() {\n return createZodEnum(util.objectKeys(this.shape));\n }\n}\nZodObject.create = (shape, params) => {\n return new ZodObject({\n shape: () => shape,\n unknownKeys: \"strip\",\n catchall: ZodNever.create(),\n typeName: ZodFirstPartyTypeKind.ZodObject,\n ...processCreateParams(params),\n });\n};\nZodObject.strictCreate = (shape, params) => {\n return new ZodObject({\n shape: () => shape,\n unknownKeys: \"strict\",\n catchall: ZodNever.create(),\n typeName: ZodFirstPartyTypeKind.ZodObject,\n ...processCreateParams(params),\n });\n};\nZodObject.lazycreate = (shape, params) => {\n return new ZodObject({\n shape,\n unknownKeys: \"strip\",\n catchall: ZodNever.create(),\n typeName: ZodFirstPartyTypeKind.ZodObject,\n ...processCreateParams(params),\n });\n};\nclass ZodUnion extends ZodType {\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n const options = this._def.options;\n function handleResults(results) {\n // return first issue-free validation if it exists\n for (const result of results) {\n if (result.result.status === \"valid\") {\n return result.result;\n }\n }\n for (const result of results) {\n if (result.result.status === \"dirty\") {\n // add issues from dirty option\n ctx.common.issues.push(...result.ctx.common.issues);\n return result.result;\n }\n }\n // return invalid\n const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues));\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_union,\n unionErrors,\n });\n return INVALID;\n }\n if (ctx.common.async) {\n return Promise.all(options.map(async (option) => {\n const childCtx = {\n ...ctx,\n common: {\n ...ctx.common,\n issues: [],\n },\n parent: null,\n };\n return {\n result: await option._parseAsync({\n data: ctx.data,\n path: ctx.path,\n parent: childCtx,\n }),\n ctx: childCtx,\n };\n })).then(handleResults);\n }\n else {\n let dirty = undefined;\n const issues = [];\n for (const option of options) {\n const childCtx = {\n ...ctx,\n common: {\n ...ctx.common,\n issues: [],\n },\n parent: null,\n };\n const result = option._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: childCtx,\n });\n if (result.status === \"valid\") {\n return result;\n }\n else if (result.status === \"dirty\" && !dirty) {\n dirty = { result, ctx: childCtx };\n }\n if (childCtx.common.issues.length) {\n issues.push(childCtx.common.issues);\n }\n }\n if (dirty) {\n ctx.common.issues.push(...dirty.ctx.common.issues);\n return dirty.result;\n }\n const unionErrors = issues.map((issues) => new ZodError(issues));\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_union,\n unionErrors,\n });\n return INVALID;\n }\n }\n get options() {\n return this._def.options;\n }\n}\nZodUnion.create = (types, params) => {\n return new ZodUnion({\n options: types,\n typeName: ZodFirstPartyTypeKind.ZodUnion,\n ...processCreateParams(params),\n });\n};\n/////////////////////////////////////////////////////\n/////////////////////////////////////////////////////\n////////// //////////\n////////// ZodDiscriminatedUnion //////////\n////////// //////////\n/////////////////////////////////////////////////////\n/////////////////////////////////////////////////////\nconst getDiscriminator = (type) => {\n if (type instanceof ZodLazy) {\n return getDiscriminator(type.schema);\n }\n else if (type instanceof ZodEffects) {\n return getDiscriminator(type.innerType());\n }\n else if (type instanceof ZodLiteral) {\n return [type.value];\n }\n else if (type instanceof ZodEnum) {\n return type.options;\n }\n else if (type instanceof ZodNativeEnum) {\n // eslint-disable-next-line ban/ban\n return util.objectValues(type.enum);\n }\n else if (type instanceof ZodDefault) {\n return getDiscriminator(type._def.innerType);\n }\n else if (type instanceof ZodUndefined) {\n return [undefined];\n }\n else if (type instanceof ZodNull) {\n return [null];\n }\n else if (type instanceof ZodOptional) {\n return [undefined, ...getDiscriminator(type.unwrap())];\n }\n else if (type instanceof ZodNullable) {\n return [null, ...getDiscriminator(type.unwrap())];\n }\n else if (type instanceof ZodBranded) {\n return getDiscriminator(type.unwrap());\n }\n else if (type instanceof ZodReadonly) {\n return getDiscriminator(type.unwrap());\n }\n else if (type instanceof ZodCatch) {\n return getDiscriminator(type._def.innerType);\n }\n else {\n return [];\n }\n};\nclass ZodDiscriminatedUnion extends ZodType {\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.object) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.object,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const discriminator = this.discriminator;\n const discriminatorValue = ctx.data[discriminator];\n const option = this.optionsMap.get(discriminatorValue);\n if (!option) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_union_discriminator,\n options: Array.from(this.optionsMap.keys()),\n path: [discriminator],\n });\n return INVALID;\n }\n if (ctx.common.async) {\n return option._parseAsync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n }\n else {\n return option._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n }\n }\n get discriminator() {\n return this._def.discriminator;\n }\n get options() {\n return this._def.options;\n }\n get optionsMap() {\n return this._def.optionsMap;\n }\n /**\n * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor.\n * However, it only allows a union of objects, all of which need to share a discriminator property. This property must\n * have a different value for each object in the union.\n * @param discriminator the name of the discriminator property\n * @param types an array of object schemas\n * @param params\n */\n static create(discriminator, options, params) {\n // Get all the valid discriminator values\n const optionsMap = new Map();\n // try {\n for (const type of options) {\n const discriminatorValues = getDiscriminator(type.shape[discriminator]);\n if (!discriminatorValues.length) {\n throw new Error(`A discriminator value for key \\`${discriminator}\\` could not be extracted from all schema options`);\n }\n for (const value of discriminatorValues) {\n if (optionsMap.has(value)) {\n throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`);\n }\n optionsMap.set(value, type);\n }\n }\n return new ZodDiscriminatedUnion({\n typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion,\n discriminator,\n options,\n optionsMap,\n ...processCreateParams(params),\n });\n }\n}\nfunction mergeValues(a, b) {\n const aType = getParsedType(a);\n const bType = getParsedType(b);\n if (a === b) {\n return { valid: true, data: a };\n }\n else if (aType === ZodParsedType.object && bType === ZodParsedType.object) {\n const bKeys = util.objectKeys(b);\n const sharedKeys = util\n .objectKeys(a)\n .filter((key) => bKeys.indexOf(key) !== -1);\n const newObj = { ...a, ...b };\n for (const key of sharedKeys) {\n const sharedValue = mergeValues(a[key], b[key]);\n if (!sharedValue.valid) {\n return { valid: false };\n }\n newObj[key] = sharedValue.data;\n }\n return { valid: true, data: newObj };\n }\n else if (aType === ZodParsedType.array && bType === ZodParsedType.array) {\n if (a.length !== b.length) {\n return { valid: false };\n }\n const newArray = [];\n for (let index = 0; index < a.length; index++) {\n const itemA = a[index];\n const itemB = b[index];\n const sharedValue = mergeValues(itemA, itemB);\n if (!sharedValue.valid) {\n return { valid: false };\n }\n newArray.push(sharedValue.data);\n }\n return { valid: true, data: newArray };\n }\n else if (aType === ZodParsedType.date &&\n bType === ZodParsedType.date &&\n +a === +b) {\n return { valid: true, data: a };\n }\n else {\n return { valid: false };\n }\n}\nclass ZodIntersection extends ZodType {\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n const handleParsed = (parsedLeft, parsedRight) => {\n if (isAborted(parsedLeft) || isAborted(parsedRight)) {\n return INVALID;\n }\n const merged = mergeValues(parsedLeft.value, parsedRight.value);\n if (!merged.valid) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_intersection_types,\n });\n return INVALID;\n }\n if (isDirty(parsedLeft) || isDirty(parsedRight)) {\n status.dirty();\n }\n return { status: status.value, value: merged.data };\n };\n if (ctx.common.async) {\n return Promise.all([\n this._def.left._parseAsync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n }),\n this._def.right._parseAsync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n }),\n ]).then(([left, right]) => handleParsed(left, right));\n }\n else {\n return handleParsed(this._def.left._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n }), this._def.right._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n }));\n }\n }\n}\nZodIntersection.create = (left, right, params) => {\n return new ZodIntersection({\n left: left,\n right: right,\n typeName: ZodFirstPartyTypeKind.ZodIntersection,\n ...processCreateParams(params),\n });\n};\nclass ZodTuple extends ZodType {\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.array) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.array,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n if (ctx.data.length < this._def.items.length) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: this._def.items.length,\n inclusive: true,\n exact: false,\n type: \"array\",\n });\n return INVALID;\n }\n const rest = this._def.rest;\n if (!rest && ctx.data.length > this._def.items.length) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: this._def.items.length,\n inclusive: true,\n exact: false,\n type: \"array\",\n });\n status.dirty();\n }\n const items = [...ctx.data]\n .map((item, itemIndex) => {\n const schema = this._def.items[itemIndex] || this._def.rest;\n if (!schema)\n return null;\n return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex));\n })\n .filter((x) => !!x); // filter nulls\n if (ctx.common.async) {\n return Promise.all(items).then((results) => {\n return ParseStatus.mergeArray(status, results);\n });\n }\n else {\n return ParseStatus.mergeArray(status, items);\n }\n }\n get items() {\n return this._def.items;\n }\n rest(rest) {\n return new ZodTuple({\n ...this._def,\n rest,\n });\n }\n}\nZodTuple.create = (schemas, params) => {\n if (!Array.isArray(schemas)) {\n throw new Error(\"You must pass an array of schemas to z.tuple([ ... ])\");\n }\n return new ZodTuple({\n items: schemas,\n typeName: ZodFirstPartyTypeKind.ZodTuple,\n rest: null,\n ...processCreateParams(params),\n });\n};\nclass ZodRecord extends ZodType {\n get keySchema() {\n return this._def.keyType;\n }\n get valueSchema() {\n return this._def.valueType;\n }\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.object) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.object,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const pairs = [];\n const keyType = this._def.keyType;\n const valueType = this._def.valueType;\n for (const key in ctx.data) {\n pairs.push({\n key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)),\n value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)),\n alwaysSet: key in ctx.data,\n });\n }\n if (ctx.common.async) {\n return ParseStatus.mergeObjectAsync(status, pairs);\n }\n else {\n return ParseStatus.mergeObjectSync(status, pairs);\n }\n }\n get element() {\n return this._def.valueType;\n }\n static create(first, second, third) {\n if (second instanceof ZodType) {\n return new ZodRecord({\n keyType: first,\n valueType: second,\n typeName: ZodFirstPartyTypeKind.ZodRecord,\n ...processCreateParams(third),\n });\n }\n return new ZodRecord({\n keyType: ZodString.create(),\n valueType: first,\n typeName: ZodFirstPartyTypeKind.ZodRecord,\n ...processCreateParams(second),\n });\n }\n}\nclass ZodMap extends ZodType {\n get keySchema() {\n return this._def.keyType;\n }\n get valueSchema() {\n return this._def.valueType;\n }\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.map) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.map,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const keyType = this._def.keyType;\n const valueType = this._def.valueType;\n const pairs = [...ctx.data.entries()].map(([key, value], index) => {\n return {\n key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, \"key\"])),\n value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, \"value\"])),\n };\n });\n if (ctx.common.async) {\n const finalMap = new Map();\n return Promise.resolve().then(async () => {\n for (const pair of pairs) {\n const key = await pair.key;\n const value = await pair.value;\n if (key.status === \"aborted\" || value.status === \"aborted\") {\n return INVALID;\n }\n if (key.status === \"dirty\" || value.status === \"dirty\") {\n status.dirty();\n }\n finalMap.set(key.value, value.value);\n }\n return { status: status.value, value: finalMap };\n });\n }\n else {\n const finalMap = new Map();\n for (const pair of pairs) {\n const key = pair.key;\n const value = pair.value;\n if (key.status === \"aborted\" || value.status === \"aborted\") {\n return INVALID;\n }\n if (key.status === \"dirty\" || value.status === \"dirty\") {\n status.dirty();\n }\n finalMap.set(key.value, value.value);\n }\n return { status: status.value, value: finalMap };\n }\n }\n}\nZodMap.create = (keyType, valueType, params) => {\n return new ZodMap({\n valueType,\n keyType,\n typeName: ZodFirstPartyTypeKind.ZodMap,\n ...processCreateParams(params),\n });\n};\nclass ZodSet extends ZodType {\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.set) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.set,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const def = this._def;\n if (def.minSize !== null) {\n if (ctx.data.size < def.minSize.value) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: def.minSize.value,\n type: \"set\",\n inclusive: true,\n exact: false,\n message: def.minSize.message,\n });\n status.dirty();\n }\n }\n if (def.maxSize !== null) {\n if (ctx.data.size > def.maxSize.value) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: def.maxSize.value,\n type: \"set\",\n inclusive: true,\n exact: false,\n message: def.maxSize.message,\n });\n status.dirty();\n }\n }\n const valueType = this._def.valueType;\n function finalizeSet(elements) {\n const parsedSet = new Set();\n for (const element of elements) {\n if (element.status === \"aborted\")\n return INVALID;\n if (element.status === \"dirty\")\n status.dirty();\n parsedSet.add(element.value);\n }\n return { status: status.value, value: parsedSet };\n }\n const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i)));\n if (ctx.common.async) {\n return Promise.all(elements).then((elements) => finalizeSet(elements));\n }\n else {\n return finalizeSet(elements);\n }\n }\n min(minSize, message) {\n return new ZodSet({\n ...this._def,\n minSize: { value: minSize, message: errorUtil.toString(message) },\n });\n }\n max(maxSize, message) {\n return new ZodSet({\n ...this._def,\n maxSize: { value: maxSize, message: errorUtil.toString(message) },\n });\n }\n size(size, message) {\n return this.min(size, message).max(size, message);\n }\n nonempty(message) {\n return this.min(1, message);\n }\n}\nZodSet.create = (valueType, params) => {\n return new ZodSet({\n valueType,\n minSize: null,\n maxSize: null,\n typeName: ZodFirstPartyTypeKind.ZodSet,\n ...processCreateParams(params),\n });\n};\nclass ZodFunction extends ZodType {\n constructor() {\n super(...arguments);\n this.validate = this.implement;\n }\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.function) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.function,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n function makeArgsIssue(args, error) {\n return makeIssue({\n data: args,\n path: ctx.path,\n errorMaps: [\n ctx.common.contextualErrorMap,\n ctx.schemaErrorMap,\n getErrorMap(),\n errorMap,\n ].filter((x) => !!x),\n issueData: {\n code: ZodIssueCode.invalid_arguments,\n argumentsError: error,\n },\n });\n }\n function makeReturnsIssue(returns, error) {\n return makeIssue({\n data: returns,\n path: ctx.path,\n errorMaps: [\n ctx.common.contextualErrorMap,\n ctx.schemaErrorMap,\n getErrorMap(),\n errorMap,\n ].filter((x) => !!x),\n issueData: {\n code: ZodIssueCode.invalid_return_type,\n returnTypeError: error,\n },\n });\n }\n const params = { errorMap: ctx.common.contextualErrorMap };\n const fn = ctx.data;\n if (this._def.returns instanceof ZodPromise) {\n // Would love a way to avoid disabling this rule, but we need\n // an alias (using an arrow function was what caused 2651).\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const me = this;\n return OK(async function (...args) {\n const error = new ZodError([]);\n const parsedArgs = await me._def.args\n .parseAsync(args, params)\n .catch((e) => {\n error.addIssue(makeArgsIssue(args, e));\n throw error;\n });\n const result = await Reflect.apply(fn, this, parsedArgs);\n const parsedReturns = await me._def.returns._def.type\n .parseAsync(result, params)\n .catch((e) => {\n error.addIssue(makeReturnsIssue(result, e));\n throw error;\n });\n return parsedReturns;\n });\n }\n else {\n // Would love a way to avoid disabling this rule, but we need\n // an alias (using an arrow function was what caused 2651).\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const me = this;\n return OK(function (...args) {\n const parsedArgs = me._def.args.safeParse(args, params);\n if (!parsedArgs.success) {\n throw new ZodError([makeArgsIssue(args, parsedArgs.error)]);\n }\n const result = Reflect.apply(fn, this, parsedArgs.data);\n const parsedReturns = me._def.returns.safeParse(result, params);\n if (!parsedReturns.success) {\n throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]);\n }\n return parsedReturns.data;\n });\n }\n }\n parameters() {\n return this._def.args;\n }\n returnType() {\n return this._def.returns;\n }\n args(...items) {\n return new ZodFunction({\n ...this._def,\n args: ZodTuple.create(items).rest(ZodUnknown.create()),\n });\n }\n returns(returnType) {\n return new ZodFunction({\n ...this._def,\n returns: returnType,\n });\n }\n implement(func) {\n const validatedFunc = this.parse(func);\n return validatedFunc;\n }\n strictImplement(func) {\n const validatedFunc = this.parse(func);\n return validatedFunc;\n }\n static create(args, returns, params) {\n return new ZodFunction({\n args: (args\n ? args\n : ZodTuple.create([]).rest(ZodUnknown.create())),\n returns: returns || ZodUnknown.create(),\n typeName: ZodFirstPartyTypeKind.ZodFunction,\n ...processCreateParams(params),\n });\n }\n}\nclass ZodLazy extends ZodType {\n get schema() {\n return this._def.getter();\n }\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n const lazySchema = this._def.getter();\n return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx });\n }\n}\nZodLazy.create = (getter, params) => {\n return new ZodLazy({\n getter: getter,\n typeName: ZodFirstPartyTypeKind.ZodLazy,\n ...processCreateParams(params),\n });\n};\nclass ZodLiteral extends ZodType {\n _parse(input) {\n if (input.data !== this._def.value) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n received: ctx.data,\n code: ZodIssueCode.invalid_literal,\n expected: this._def.value,\n });\n return INVALID;\n }\n return { status: \"valid\", value: input.data };\n }\n get value() {\n return this._def.value;\n }\n}\nZodLiteral.create = (value, params) => {\n return new ZodLiteral({\n value: value,\n typeName: ZodFirstPartyTypeKind.ZodLiteral,\n ...processCreateParams(params),\n });\n};\nfunction createZodEnum(values, params) {\n return new ZodEnum({\n values,\n typeName: ZodFirstPartyTypeKind.ZodEnum,\n ...processCreateParams(params),\n });\n}\nclass ZodEnum extends ZodType {\n constructor() {\n super(...arguments);\n _ZodEnum_cache.set(this, void 0);\n }\n _parse(input) {\n if (typeof input.data !== \"string\") {\n const ctx = this._getOrReturnCtx(input);\n const expectedValues = this._def.values;\n addIssueToContext(ctx, {\n expected: util.joinValues(expectedValues),\n received: ctx.parsedType,\n code: ZodIssueCode.invalid_type,\n });\n return INVALID;\n }\n if (!__classPrivateFieldGet(this, _ZodEnum_cache, \"f\")) {\n __classPrivateFieldSet(this, _ZodEnum_cache, new Set(this._def.values), \"f\");\n }\n if (!__classPrivateFieldGet(this, _ZodEnum_cache, \"f\").has(input.data)) {\n const ctx = this._getOrReturnCtx(input);\n const expectedValues = this._def.values;\n addIssueToContext(ctx, {\n received: ctx.data,\n code: ZodIssueCode.invalid_enum_value,\n options: expectedValues,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n get options() {\n return this._def.values;\n }\n get enum() {\n const enumValues = {};\n for (const val of this._def.values) {\n enumValues[val] = val;\n }\n return enumValues;\n }\n get Values() {\n const enumValues = {};\n for (const val of this._def.values) {\n enumValues[val] = val;\n }\n return enumValues;\n }\n get Enum() {\n const enumValues = {};\n for (const val of this._def.values) {\n enumValues[val] = val;\n }\n return enumValues;\n }\n extract(values, newDef = this._def) {\n return ZodEnum.create(values, {\n ...this._def,\n ...newDef,\n });\n }\n exclude(values, newDef = this._def) {\n return ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), {\n ...this._def,\n ...newDef,\n });\n }\n}\n_ZodEnum_cache = new WeakMap();\nZodEnum.create = createZodEnum;\nclass ZodNativeEnum extends ZodType {\n constructor() {\n super(...arguments);\n _ZodNativeEnum_cache.set(this, void 0);\n }\n _parse(input) {\n const nativeEnumValues = util.getValidEnumValues(this._def.values);\n const ctx = this._getOrReturnCtx(input);\n if (ctx.parsedType !== ZodParsedType.string &&\n ctx.parsedType !== ZodParsedType.number) {\n const expectedValues = util.objectValues(nativeEnumValues);\n addIssueToContext(ctx, {\n expected: util.joinValues(expectedValues),\n received: ctx.parsedType,\n code: ZodIssueCode.invalid_type,\n });\n return INVALID;\n }\n if (!__classPrivateFieldGet(this, _ZodNativeEnum_cache, \"f\")) {\n __classPrivateFieldSet(this, _ZodNativeEnum_cache, new Set(util.getValidEnumValues(this._def.values)), \"f\");\n }\n if (!__classPrivateFieldGet(this, _ZodNativeEnum_cache, \"f\").has(input.data)) {\n const expectedValues = util.objectValues(nativeEnumValues);\n addIssueToContext(ctx, {\n received: ctx.data,\n code: ZodIssueCode.invalid_enum_value,\n options: expectedValues,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n get enum() {\n return this._def.values;\n }\n}\n_ZodNativeEnum_cache = new WeakMap();\nZodNativeEnum.create = (values, params) => {\n return new ZodNativeEnum({\n values: values,\n typeName: ZodFirstPartyTypeKind.ZodNativeEnum,\n ...processCreateParams(params),\n });\n};\nclass ZodPromise extends ZodType {\n unwrap() {\n return this._def.type;\n }\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.promise &&\n ctx.common.async === false) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.promise,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const promisified = ctx.parsedType === ZodParsedType.promise\n ? ctx.data\n : Promise.resolve(ctx.data);\n return OK(promisified.then((data) => {\n return this._def.type.parseAsync(data, {\n path: ctx.path,\n errorMap: ctx.common.contextualErrorMap,\n });\n }));\n }\n}\nZodPromise.create = (schema, params) => {\n return new ZodPromise({\n type: schema,\n typeName: ZodFirstPartyTypeKind.ZodPromise,\n ...processCreateParams(params),\n });\n};\nclass ZodEffects extends ZodType {\n innerType() {\n return this._def.schema;\n }\n sourceType() {\n return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects\n ? this._def.schema.sourceType()\n : this._def.schema;\n }\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n const effect = this._def.effect || null;\n const checkCtx = {\n addIssue: (arg) => {\n addIssueToContext(ctx, arg);\n if (arg.fatal) {\n status.abort();\n }\n else {\n status.dirty();\n }\n },\n get path() {\n return ctx.path;\n },\n };\n checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx);\n if (effect.type === \"preprocess\") {\n const processed = effect.transform(ctx.data, checkCtx);\n if (ctx.common.async) {\n return Promise.resolve(processed).then(async (processed) => {\n if (status.value === \"aborted\")\n return INVALID;\n const result = await this._def.schema._parseAsync({\n data: processed,\n path: ctx.path,\n parent: ctx,\n });\n if (result.status === \"aborted\")\n return INVALID;\n if (result.status === \"dirty\")\n return DIRTY(result.value);\n if (status.value === \"dirty\")\n return DIRTY(result.value);\n return result;\n });\n }\n else {\n if (status.value === \"aborted\")\n return INVALID;\n const result = this._def.schema._parseSync({\n data: processed,\n path: ctx.path,\n parent: ctx,\n });\n if (result.status === \"aborted\")\n return INVALID;\n if (result.status === \"dirty\")\n return DIRTY(result.value);\n if (status.value === \"dirty\")\n return DIRTY(result.value);\n return result;\n }\n }\n if (effect.type === \"refinement\") {\n const executeRefinement = (acc) => {\n const result = effect.refinement(acc, checkCtx);\n if (ctx.common.async) {\n return Promise.resolve(result);\n }\n if (result instanceof Promise) {\n throw new Error(\"Async refinement encountered during synchronous parse operation. Use .parseAsync instead.\");\n }\n return acc;\n };\n if (ctx.common.async === false) {\n const inner = this._def.schema._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n if (inner.status === \"aborted\")\n return INVALID;\n if (inner.status === \"dirty\")\n status.dirty();\n // return value is ignored\n executeRefinement(inner.value);\n return { status: status.value, value: inner.value };\n }\n else {\n return this._def.schema\n ._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx })\n .then((inner) => {\n if (inner.status === \"aborted\")\n return INVALID;\n if (inner.status === \"dirty\")\n status.dirty();\n return executeRefinement(inner.value).then(() => {\n return { status: status.value, value: inner.value };\n });\n });\n }\n }\n if (effect.type === \"transform\") {\n if (ctx.common.async === false) {\n const base = this._def.schema._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n if (!isValid(base))\n return base;\n const result = effect.transform(base.value, checkCtx);\n if (result instanceof Promise) {\n throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);\n }\n return { status: status.value, value: result };\n }\n else {\n return this._def.schema\n ._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx })\n .then((base) => {\n if (!isValid(base))\n return base;\n return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({ status: status.value, value: result }));\n });\n }\n }\n util.assertNever(effect);\n }\n}\nZodEffects.create = (schema, effect, params) => {\n return new ZodEffects({\n schema,\n typeName: ZodFirstPartyTypeKind.ZodEffects,\n effect,\n ...processCreateParams(params),\n });\n};\nZodEffects.createWithPreprocess = (preprocess, schema, params) => {\n return new ZodEffects({\n schema,\n effect: { type: \"preprocess\", transform: preprocess },\n typeName: ZodFirstPartyTypeKind.ZodEffects,\n ...processCreateParams(params),\n });\n};\nclass ZodOptional extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType === ZodParsedType.undefined) {\n return OK(undefined);\n }\n return this._def.innerType._parse(input);\n }\n unwrap() {\n return this._def.innerType;\n }\n}\nZodOptional.create = (type, params) => {\n return new ZodOptional({\n innerType: type,\n typeName: ZodFirstPartyTypeKind.ZodOptional,\n ...processCreateParams(params),\n });\n};\nclass ZodNullable extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType === ZodParsedType.null) {\n return OK(null);\n }\n return this._def.innerType._parse(input);\n }\n unwrap() {\n return this._def.innerType;\n }\n}\nZodNullable.create = (type, params) => {\n return new ZodNullable({\n innerType: type,\n typeName: ZodFirstPartyTypeKind.ZodNullable,\n ...processCreateParams(params),\n });\n};\nclass ZodDefault extends ZodType {\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n let data = ctx.data;\n if (ctx.parsedType === ZodParsedType.undefined) {\n data = this._def.defaultValue();\n }\n return this._def.innerType._parse({\n data,\n path: ctx.path,\n parent: ctx,\n });\n }\n removeDefault() {\n return this._def.innerType;\n }\n}\nZodDefault.create = (type, params) => {\n return new ZodDefault({\n innerType: type,\n typeName: ZodFirstPartyTypeKind.ZodDefault,\n defaultValue: typeof params.default === \"function\"\n ? params.default\n : () => params.default,\n ...processCreateParams(params),\n });\n};\nclass ZodCatch extends ZodType {\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n // newCtx is used to not collect issues from inner types in ctx\n const newCtx = {\n ...ctx,\n common: {\n ...ctx.common,\n issues: [],\n },\n };\n const result = this._def.innerType._parse({\n data: newCtx.data,\n path: newCtx.path,\n parent: {\n ...newCtx,\n },\n });\n if (isAsync(result)) {\n return result.then((result) => {\n return {\n status: \"valid\",\n value: result.status === \"valid\"\n ? result.value\n : this._def.catchValue({\n get error() {\n return new ZodError(newCtx.common.issues);\n },\n input: newCtx.data,\n }),\n };\n });\n }\n else {\n return {\n status: \"valid\",\n value: result.status === \"valid\"\n ? result.value\n : this._def.catchValue({\n get error() {\n return new ZodError(newCtx.common.issues);\n },\n input: newCtx.data,\n }),\n };\n }\n }\n removeCatch() {\n return this._def.innerType;\n }\n}\nZodCatch.create = (type, params) => {\n return new ZodCatch({\n innerType: type,\n typeName: ZodFirstPartyTypeKind.ZodCatch,\n catchValue: typeof params.catch === \"function\" ? params.catch : () => params.catch,\n ...processCreateParams(params),\n });\n};\nclass ZodNaN extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.nan) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.nan,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return { status: \"valid\", value: input.data };\n }\n}\nZodNaN.create = (params) => {\n return new ZodNaN({\n typeName: ZodFirstPartyTypeKind.ZodNaN,\n ...processCreateParams(params),\n });\n};\nconst BRAND = Symbol(\"zod_brand\");\nclass ZodBranded extends ZodType {\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n const data = ctx.data;\n return this._def.type._parse({\n data,\n path: ctx.path,\n parent: ctx,\n });\n }\n unwrap() {\n return this._def.type;\n }\n}\nclass ZodPipeline extends ZodType {\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.common.async) {\n const handleAsync = async () => {\n const inResult = await this._def.in._parseAsync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n if (inResult.status === \"aborted\")\n return INVALID;\n if (inResult.status === \"dirty\") {\n status.dirty();\n return DIRTY(inResult.value);\n }\n else {\n return this._def.out._parseAsync({\n data: inResult.value,\n path: ctx.path,\n parent: ctx,\n });\n }\n };\n return handleAsync();\n }\n else {\n const inResult = this._def.in._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n if (inResult.status === \"aborted\")\n return INVALID;\n if (inResult.status === \"dirty\") {\n status.dirty();\n return {\n status: \"dirty\",\n value: inResult.value,\n };\n }\n else {\n return this._def.out._parseSync({\n data: inResult.value,\n path: ctx.path,\n parent: ctx,\n });\n }\n }\n }\n static create(a, b) {\n return new ZodPipeline({\n in: a,\n out: b,\n typeName: ZodFirstPartyTypeKind.ZodPipeline,\n });\n }\n}\nclass ZodReadonly extends ZodType {\n _parse(input) {\n const result = this._def.innerType._parse(input);\n const freeze = (data) => {\n if (isValid(data)) {\n data.value = Object.freeze(data.value);\n }\n return data;\n };\n return isAsync(result)\n ? result.then((data) => freeze(data))\n : freeze(result);\n }\n unwrap() {\n return this._def.innerType;\n }\n}\nZodReadonly.create = (type, params) => {\n return new ZodReadonly({\n innerType: type,\n typeName: ZodFirstPartyTypeKind.ZodReadonly,\n ...processCreateParams(params),\n });\n};\nfunction custom(check, params = {}, \n/**\n * @deprecated\n *\n * Pass `fatal` into the params object instead:\n *\n * ```ts\n * z.string().custom((val) => val.length > 5, { fatal: false })\n * ```\n *\n */\nfatal) {\n if (check)\n return ZodAny.create().superRefine((data, ctx) => {\n var _a, _b;\n if (!check(data)) {\n const p = typeof params === \"function\"\n ? params(data)\n : typeof params === \"string\"\n ? { message: params }\n : params;\n const _fatal = (_b = (_a = p.fatal) !== null && _a !== void 0 ? _a : fatal) !== null && _b !== void 0 ? _b : true;\n const p2 = typeof p === \"string\" ? { message: p } : p;\n ctx.addIssue({ code: \"custom\", ...p2, fatal: _fatal });\n }\n });\n return ZodAny.create();\n}\nconst late = {\n object: ZodObject.lazycreate,\n};\nvar ZodFirstPartyTypeKind;\n(function (ZodFirstPartyTypeKind) {\n ZodFirstPartyTypeKind[\"ZodString\"] = \"ZodString\";\n ZodFirstPartyTypeKind[\"ZodNumber\"] = \"ZodNumber\";\n ZodFirstPartyTypeKind[\"ZodNaN\"] = \"ZodNaN\";\n ZodFirstPartyTypeKind[\"ZodBigInt\"] = \"ZodBigInt\";\n ZodFirstPartyTypeKind[\"ZodBoolean\"] = \"ZodBoolean\";\n ZodFirstPartyTypeKind[\"ZodDate\"] = \"ZodDate\";\n ZodFirstPartyTypeKind[\"ZodSymbol\"] = \"ZodSymbol\";\n ZodFirstPartyTypeKind[\"ZodUndefined\"] = \"ZodUndefined\";\n ZodFirstPartyTypeKind[\"ZodNull\"] = \"ZodNull\";\n ZodFirstPartyTypeKind[\"ZodAny\"] = \"ZodAny\";\n ZodFirstPartyTypeKind[\"ZodUnknown\"] = \"ZodUnknown\";\n ZodFirstPartyTypeKind[\"ZodNever\"] = \"ZodNever\";\n ZodFirstPartyTypeKind[\"ZodVoid\"] = \"ZodVoid\";\n ZodFirstPartyTypeKind[\"ZodArray\"] = \"ZodArray\";\n ZodFirstPartyTypeKind[\"ZodObject\"] = \"ZodObject\";\n ZodFirstPartyTypeKind[\"ZodUnion\"] = \"ZodUnion\";\n ZodFirstPartyTypeKind[\"ZodDiscriminatedUnion\"] = \"ZodDiscriminatedUnion\";\n ZodFirstPartyTypeKind[\"ZodIntersection\"] = \"ZodIntersection\";\n ZodFirstPartyTypeKind[\"ZodTuple\"] = \"ZodTuple\";\n ZodFirstPartyTypeKind[\"ZodRecord\"] = \"ZodRecord\";\n ZodFirstPartyTypeKind[\"ZodMap\"] = \"ZodMap\";\n ZodFirstPartyTypeKind[\"ZodSet\"] = \"ZodSet\";\n ZodFirstPartyTypeKind[\"ZodFunction\"] = \"ZodFunction\";\n ZodFirstPartyTypeKind[\"ZodLazy\"] = \"ZodLazy\";\n ZodFirstPartyTypeKind[\"ZodLiteral\"] = \"ZodLiteral\";\n ZodFirstPartyTypeKind[\"ZodEnum\"] = \"ZodEnum\";\n ZodFirstPartyTypeKind[\"ZodEffects\"] = \"ZodEffects\";\n ZodFirstPartyTypeKind[\"ZodNativeEnum\"] = \"ZodNativeEnum\";\n ZodFirstPartyTypeKind[\"ZodOptional\"] = \"ZodOptional\";\n ZodFirstPartyTypeKind[\"ZodNullable\"] = \"ZodNullable\";\n ZodFirstPartyTypeKind[\"ZodDefault\"] = \"ZodDefault\";\n ZodFirstPartyTypeKind[\"ZodCatch\"] = \"ZodCatch\";\n ZodFirstPartyTypeKind[\"ZodPromise\"] = \"ZodPromise\";\n ZodFirstPartyTypeKind[\"ZodBranded\"] = \"ZodBranded\";\n ZodFirstPartyTypeKind[\"ZodPipeline\"] = \"ZodPipeline\";\n ZodFirstPartyTypeKind[\"ZodReadonly\"] = \"ZodReadonly\";\n})(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));\nconst instanceOfType = (\n// const instanceOfType = any>(\ncls, params = {\n message: `Input not instance of ${cls.name}`,\n}) => custom((data) => data instanceof cls, params);\nconst stringType = ZodString.create;\nconst numberType = ZodNumber.create;\nconst nanType = ZodNaN.create;\nconst bigIntType = ZodBigInt.create;\nconst booleanType = ZodBoolean.create;\nconst dateType = ZodDate.create;\nconst symbolType = ZodSymbol.create;\nconst undefinedType = ZodUndefined.create;\nconst nullType = ZodNull.create;\nconst anyType = ZodAny.create;\nconst unknownType = ZodUnknown.create;\nconst neverType = ZodNever.create;\nconst voidType = ZodVoid.create;\nconst arrayType = ZodArray.create;\nconst objectType = ZodObject.create;\nconst strictObjectType = ZodObject.strictCreate;\nconst unionType = ZodUnion.create;\nconst discriminatedUnionType = ZodDiscriminatedUnion.create;\nconst intersectionType = ZodIntersection.create;\nconst tupleType = ZodTuple.create;\nconst recordType = ZodRecord.create;\nconst mapType = ZodMap.create;\nconst setType = ZodSet.create;\nconst functionType = ZodFunction.create;\nconst lazyType = ZodLazy.create;\nconst literalType = ZodLiteral.create;\nconst enumType = ZodEnum.create;\nconst nativeEnumType = ZodNativeEnum.create;\nconst promiseType = ZodPromise.create;\nconst effectsType = ZodEffects.create;\nconst optionalType = ZodOptional.create;\nconst nullableType = ZodNullable.create;\nconst preprocessType = ZodEffects.createWithPreprocess;\nconst pipelineType = ZodPipeline.create;\nconst ostring = () => stringType().optional();\nconst onumber = () => numberType().optional();\nconst oboolean = () => booleanType().optional();\nconst coerce = {\n string: ((arg) => ZodString.create({ ...arg, coerce: true })),\n number: ((arg) => ZodNumber.create({ ...arg, coerce: true })),\n boolean: ((arg) => ZodBoolean.create({\n ...arg,\n coerce: true,\n })),\n bigint: ((arg) => ZodBigInt.create({ ...arg, coerce: true })),\n date: ((arg) => ZodDate.create({ ...arg, coerce: true })),\n};\nconst NEVER = INVALID;\n\nvar z = /*#__PURE__*/Object.freeze({\n __proto__: null,\n defaultErrorMap: errorMap,\n setErrorMap: setErrorMap,\n getErrorMap: getErrorMap,\n makeIssue: makeIssue,\n EMPTY_PATH: EMPTY_PATH,\n addIssueToContext: addIssueToContext,\n ParseStatus: ParseStatus,\n INVALID: INVALID,\n DIRTY: DIRTY,\n OK: OK,\n isAborted: isAborted,\n isDirty: isDirty,\n isValid: isValid,\n isAsync: isAsync,\n get util () { return util; },\n get objectUtil () { return objectUtil; },\n ZodParsedType: ZodParsedType,\n getParsedType: getParsedType,\n ZodType: ZodType,\n datetimeRegex: datetimeRegex,\n ZodString: ZodString,\n ZodNumber: ZodNumber,\n ZodBigInt: ZodBigInt,\n ZodBoolean: ZodBoolean,\n ZodDate: ZodDate,\n ZodSymbol: ZodSymbol,\n ZodUndefined: ZodUndefined,\n ZodNull: ZodNull,\n ZodAny: ZodAny,\n ZodUnknown: ZodUnknown,\n ZodNever: ZodNever,\n ZodVoid: ZodVoid,\n ZodArray: ZodArray,\n ZodObject: ZodObject,\n ZodUnion: ZodUnion,\n ZodDiscriminatedUnion: ZodDiscriminatedUnion,\n ZodIntersection: ZodIntersection,\n ZodTuple: ZodTuple,\n ZodRecord: ZodRecord,\n ZodMap: ZodMap,\n ZodSet: ZodSet,\n ZodFunction: ZodFunction,\n ZodLazy: ZodLazy,\n ZodLiteral: ZodLiteral,\n ZodEnum: ZodEnum,\n ZodNativeEnum: ZodNativeEnum,\n ZodPromise: ZodPromise,\n ZodEffects: ZodEffects,\n ZodTransformer: ZodEffects,\n ZodOptional: ZodOptional,\n ZodNullable: ZodNullable,\n ZodDefault: ZodDefault,\n ZodCatch: ZodCatch,\n ZodNaN: ZodNaN,\n BRAND: BRAND,\n ZodBranded: ZodBranded,\n ZodPipeline: ZodPipeline,\n ZodReadonly: ZodReadonly,\n custom: custom,\n Schema: ZodType,\n ZodSchema: ZodType,\n late: late,\n get ZodFirstPartyTypeKind () { return ZodFirstPartyTypeKind; },\n coerce: coerce,\n any: anyType,\n array: arrayType,\n bigint: bigIntType,\n boolean: booleanType,\n date: dateType,\n discriminatedUnion: discriminatedUnionType,\n effect: effectsType,\n 'enum': enumType,\n 'function': functionType,\n 'instanceof': instanceOfType,\n intersection: intersectionType,\n lazy: lazyType,\n literal: literalType,\n map: mapType,\n nan: nanType,\n nativeEnum: nativeEnumType,\n never: neverType,\n 'null': nullType,\n nullable: nullableType,\n number: numberType,\n object: objectType,\n oboolean: oboolean,\n onumber: onumber,\n optional: optionalType,\n ostring: ostring,\n pipeline: pipelineType,\n preprocess: preprocessType,\n promise: promiseType,\n record: recordType,\n set: setType,\n strictObject: strictObjectType,\n string: stringType,\n symbol: symbolType,\n transformer: effectsType,\n tuple: tupleType,\n 'undefined': undefinedType,\n union: unionType,\n unknown: unknownType,\n 'void': voidType,\n NEVER: NEVER,\n ZodIssueCode: ZodIssueCode,\n quotelessJson: quotelessJson,\n ZodError: ZodError\n});\n\nexport { BRAND, DIRTY, EMPTY_PATH, INVALID, NEVER, OK, ParseStatus, ZodType as Schema, ZodAny, ZodArray, ZodBigInt, ZodBoolean, ZodBranded, ZodCatch, ZodDate, ZodDefault, ZodDiscriminatedUnion, ZodEffects, ZodEnum, ZodError, ZodFirstPartyTypeKind, ZodFunction, ZodIntersection, ZodIssueCode, ZodLazy, ZodLiteral, ZodMap, ZodNaN, ZodNativeEnum, ZodNever, ZodNull, ZodNullable, ZodNumber, ZodObject, ZodOptional, ZodParsedType, ZodPipeline, ZodPromise, ZodReadonly, ZodRecord, ZodType as ZodSchema, ZodSet, ZodString, ZodSymbol, ZodEffects as ZodTransformer, ZodTuple, ZodType, ZodUndefined, ZodUnion, ZodUnknown, ZodVoid, addIssueToContext, anyType as any, arrayType as array, bigIntType as bigint, booleanType as boolean, coerce, custom, dateType as date, datetimeRegex, z as default, errorMap as defaultErrorMap, discriminatedUnionType as discriminatedUnion, effectsType as effect, enumType as enum, functionType as function, getErrorMap, getParsedType, instanceOfType as instanceof, intersectionType as intersection, isAborted, isAsync, isDirty, isValid, late, lazyType as lazy, literalType as literal, makeIssue, mapType as map, nanType as nan, nativeEnumType as nativeEnum, neverType as never, nullType as null, nullableType as nullable, numberType as number, objectType as object, objectUtil, oboolean, onumber, optionalType as optional, ostring, pipelineType as pipeline, preprocessType as preprocess, promiseType as promise, quotelessJson, recordType as record, setType as set, setErrorMap, strictObjectType as strictObject, stringType as string, symbolType as symbol, effectsType as transformer, tupleType as tuple, undefinedType as undefined, unionType as union, unknownType as unknown, util, voidType as void, z };\n","/*\nThis file is part of web3.js.\n\nweb3.js is free software: you can redistribute it and/or modify\nit under the terms of the GNU Lesser General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nweb3.js is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU Lesser General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public License\nalong with web3.js. If not, see .\n*/\n\nimport { BaseWeb3Error, ERR_VALIDATION } from 'web3-errors';\nimport { Web3ValidationErrorObject } from 'web3-types';\n\nconst errorFormatter = (error: Web3ValidationErrorObject): string => {\n\tif (error.message) {\n\t\treturn error.message;\n\t}\n\n\treturn 'unspecified error';\n};\n\nexport class Web3ValidatorError extends BaseWeb3Error {\n\tpublic code = ERR_VALIDATION;\n\tpublic readonly errors: Web3ValidationErrorObject[];\n\n\tpublic constructor(errors: Web3ValidationErrorObject[]) {\n\t\tsuper();\n\n\t\tthis.errors = errors;\n\n\t\tsuper.message = `Web3 validator found ${\n\t\t\terrors.length\n\t\t} error[s]:\\n${this._compileErrors().join('\\n')}`;\n\t}\n\n\tprivate _compileErrors(): string[] {\n\t\treturn this.errors.map(errorFormatter);\n\t}\n}\n","/*\nThis file is part of web3.js.\n\nweb3.js is free software: you can redistribute it and/or modify\nit under the terms of the GNU Lesser General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nweb3.js is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU Lesser General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public License\nalong with web3.js. If not, see .\n*/\n\nexport const VALID_ETH_BASE_TYPES = ['bool', 'int', 'uint', 'bytes', 'string', 'address', 'tuple'];\n","/*\nThis file is part of web3.js.\n\nweb3.js is free software: you can redistribute it and/or modify\nit under the terms of the GNU Lesser General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nweb3.js is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU Lesser General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public License\nalong with web3.js. If not, see .\n*/\n\nimport { AbiParameter } from 'web3-types';\n// eslint-disable-next-line require-extensions/require-extensions\nimport { ShortValidationSchema } from '../types';\n\nexport const isAbiParameterSchema = (\n\tschema: string | ShortValidationSchema | AbiParameter,\n): schema is AbiParameter => typeof schema === 'object' && 'type' in schema && 'name' in schema;\n","/*\nThis file is part of web3.js.\n\nweb3.js is free software: you can redistribute it and/or modify\nit under the terms of the GNU Lesser General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nweb3.js is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU Lesser General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public License\nalong with web3.js. If not, see .\n*/\n\nimport { ValidInputTypes } from '../types.js';\n\n/**\n * checks input if typeof data is valid string input\n */\nexport const isString = (value: ValidInputTypes) => typeof value === 'string';\n\nexport const isHexStrict = (hex: ValidInputTypes) =>\n\ttypeof hex === 'string' && /^((-)?0x[0-9a-f]+|(0x))$/i.test(hex);\n\n/**\n * Is the string a hex string.\n *\n * @param value\n * @param length\n * @returns output the string is a hex string\n */\nexport function isHexString(value: string, length?: number): boolean {\n\tif (typeof value !== 'string' || !value.match(/^0x[0-9A-Fa-f]*$/)) return false;\n\n\tif (typeof length !== 'undefined' && length > 0 && value.length !== 2 + 2 * length)\n\t\treturn false;\n\n\treturn true;\n}\n\nexport const isHex = (hex: ValidInputTypes): boolean =>\n\ttypeof hex === 'number' ||\n\ttypeof hex === 'bigint' ||\n\t(typeof hex === 'string' && /^((-0x|0x|-)?[0-9a-f]+|(0x))$/i.test(hex));\n\nexport const isHexString8Bytes = (value: string, prefixed = true) =>\n\tprefixed ? isHexStrict(value) && value.length === 18 : isHex(value) && value.length === 16;\n\nexport const isHexString32Bytes = (value: string, prefixed = true) =>\n\tprefixed ? isHexStrict(value) && value.length === 66 : isHex(value) && value.length === 64;\n\n/**\n * Returns a `Boolean` on whether or not the a `String` starts with '0x'\n * @param str the string input value\n * @return a boolean if it is or is not hex prefixed\n * @throws if the str input is not a string\n */\nexport function isHexPrefixed(str: string): boolean {\n\tif (typeof str !== 'string') {\n\t\tthrow new Error(`[isHexPrefixed] input must be type 'string', received type ${typeof str}`);\n\t}\n\n\treturn str.startsWith('0x');\n}\n\n/**\n * Checks provided Uint8Array for leading zeroes and throws if found.\n *\n * Examples:\n *\n * Valid values: 0x1, 0x, 0x01, 0x1234\n * Invalid values: 0x0, 0x00, 0x001, 0x0001\n *\n * Note: This method is useful for validating that RLP encoded integers comply with the rule that all\n * integer values encoded to RLP must be in the most compact form and contain no leading zero bytes\n * @param values An object containing string keys and Uint8Array values\n * @throws if any provided value is found to have leading zero bytes\n */\nexport const validateNoLeadingZeroes = function (values: {\n\t[key: string]: Uint8Array | undefined;\n}) {\n\tfor (const [k, v] of Object.entries(values)) {\n\t\tif (v !== undefined && v.length > 0 && v[0] === 0) {\n\t\t\tthrow new Error(`${k} cannot have leading zeroes, received: ${v.toString()}`);\n\t\t}\n\t}\n};\n","/*\nThis file is part of web3.js.\n\nweb3.js is free software: you can redistribute it and/or modify\nit under the terms of the GNU Lesser General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nweb3.js is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU Lesser General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public License\nalong with web3.js. If not, see .\n*/\n\nimport { InvalidBytesError, InvalidNumberError } from 'web3-errors';\nimport { VALID_ETH_BASE_TYPES } from './constants.js';\nimport {\n\tFullValidationSchema,\n\tJsonSchema,\n\tShortValidationSchema,\n\tValidationSchemaInput,\n\tValidInputTypes,\n} from './types.js';\nimport { isAbiParameterSchema } from './validation/abi.js';\nimport { isHexStrict } from './validation/string.js';\nimport { Web3ValidatorError } from './errors.js';\n\nconst extraTypes = ['hex', 'number', 'blockNumber', 'blockNumberOrTag', 'filter', 'bloom'];\n\nexport const parseBaseType = (\n\ttype: string,\n): {\n\tbaseType?: T;\n\tbaseTypeSize: number | undefined;\n\tarraySizes: number[];\n\tisArray: boolean;\n} => {\n\t// Remove all empty spaces to avoid any parsing issue.\n\tlet strippedType = type.replace(/ /, '');\n\tlet baseTypeSize: number | undefined;\n\tlet isArray = false;\n\tlet arraySizes: number[] = [];\n\n\tif (type.includes('[')) {\n\t\t// Extract the array type\n\t\tstrippedType = strippedType.slice(0, strippedType.indexOf('['));\n\t\t// Extract array indexes\n\t\tarraySizes = [...type.matchAll(/(?:\\[(\\d*)\\])/g)]\n\t\t\t.map(match => parseInt(match[1], 10))\n\t\t\t.map(size => (Number.isNaN(size) ? -1 : size));\n\n\t\tisArray = arraySizes.length > 0;\n\t}\n\n\tif (VALID_ETH_BASE_TYPES.includes(strippedType)) {\n\t\treturn { baseType: strippedType as unknown as T, isArray, baseTypeSize, arraySizes };\n\t}\n\n\tif (strippedType.startsWith('int')) {\n\t\tbaseTypeSize = parseInt(strippedType.substring(3), 10);\n\t\tstrippedType = 'int';\n\t} else if (strippedType.startsWith('uint')) {\n\t\tbaseTypeSize = parseInt(type.substring(4), 10);\n\t\tstrippedType = 'uint';\n\t} else if (strippedType.startsWith('bytes')) {\n\t\tbaseTypeSize = parseInt(strippedType.substring(5), 10);\n\t\tstrippedType = 'bytes';\n\t} else {\n\t\treturn { baseType: undefined, isArray: false, baseTypeSize: undefined, arraySizes };\n\t}\n\n\treturn { baseType: strippedType as unknown as T, isArray, baseTypeSize, arraySizes };\n};\n\nconst convertEthType = (\n\ttype: string,\n\tparentSchema: JsonSchema = {},\n): { format?: string; required?: boolean } => {\n\tconst typePropertyPresent = Object.keys(parentSchema).includes('type');\n\n\tif (typePropertyPresent) {\n\t\tthrow new Web3ValidatorError([\n\t\t\t{\n\t\t\t\tkeyword: 'eth',\n\t\t\t\tmessage: 'Either \"eth\" or \"type\" can be presented in schema',\n\t\t\t\tparams: { eth: type },\n\t\t\t\tinstancePath: '',\n\t\t\t\tschemaPath: '',\n\t\t\t},\n\t\t]);\n\t}\n\n\tconst { baseType, baseTypeSize } = parseBaseType(type);\n\n\tif (!baseType && !extraTypes.includes(type)) {\n\t\tthrow new Web3ValidatorError([\n\t\t\t{\n\t\t\t\tkeyword: 'eth',\n\t\t\t\tmessage: `Eth data type \"${type}\" is not valid`,\n\t\t\t\tparams: { eth: type },\n\t\t\t\tinstancePath: '',\n\t\t\t\tschemaPath: '',\n\t\t\t},\n\t\t]);\n\t}\n\n\tif (baseType) {\n\t\tif (baseType === 'tuple') {\n\t\t\tthrow new Error('\"tuple\" type is not implemented directly.');\n\t\t}\n\t\treturn { format: `${baseType}${baseTypeSize ?? ''}`, required: true };\n\t}\n\tif (type) {\n\t\treturn { format: type, required: true };\n\t}\n\n\treturn {};\n};\n\nexport const abiSchemaToJsonSchema = (\n\tabis: ShortValidationSchema | FullValidationSchema,\n\tlevel = '/0',\n) => {\n\tconst schema: JsonSchema = {\n\t\ttype: 'array',\n\t\titems: [],\n\t\tmaxItems: abis.length,\n\t\tminItems: abis.length,\n\t};\n\n\tfor (const [index, abi] of abis.entries()) {\n\t\t// eslint-disable-next-line no-nested-ternary\n\t\tlet abiType!: string;\n\t\tlet abiName!: string;\n\t\tlet abiComponents: ShortValidationSchema | FullValidationSchema | undefined = [];\n\n\t\t// If it's a complete Abi Parameter\n\t\t// e.g. {name: 'a', type: 'uint'}\n\t\tif (isAbiParameterSchema(abi)) {\n\t\t\tabiType = abi.type;\n\t\t\tabiName = abi.name || `${level}/${index}`;\n\t\t\tabiComponents = abi.components as FullValidationSchema;\n\t\t\t// If its short form string value e.g. ['uint']\n\t\t} else if (typeof abi === 'string') {\n\t\t\tabiType = abi;\n\t\t\tabiName = `${level}/${index}`;\n\n\t\t\t// If it's provided in short form of tuple e.g. [['uint', 'string']]\n\t\t} else if (Array.isArray(abi)) {\n\t\t\t// If its custom tuple e.g. ['tuple[2]', ['uint', 'string']]\n\t\t\tif (\n\t\t\t\tabi[0] &&\n\t\t\t\ttypeof abi[0] === 'string' &&\n\t\t\t\tabi[0].startsWith('tuple') &&\n\t\t\t\t!Array.isArray(abi[0]) &&\n\t\t\t\tabi[1] &&\n\t\t\t\tArray.isArray(abi[1])\n\t\t\t) {\n\t\t\t\t// eslint-disable-next-line prefer-destructuring\n\t\t\t\tabiType = abi[0];\n\t\t\t\tabiName = `${level}/${index}`;\n\t\t\t\tabiComponents = abi[1] as ReadonlyArray;\n\t\t\t} else {\n\t\t\t\tabiType = 'tuple';\n\t\t\t\tabiName = `${level}/${index}`;\n\t\t\t\tabiComponents = abi;\n\t\t\t}\n\t\t}\n\n\t\tconst { baseType, isArray, arraySizes } = parseBaseType(abiType);\n\n\t\tlet childSchema: JsonSchema;\n\t\tlet lastSchema = schema;\n\t\tfor (let i = arraySizes.length - 1; i > 0; i -= 1) {\n\t\t\tchildSchema = {\n\t\t\t\ttype: 'array',\n\t\t\t\t$id: abiName,\n\t\t\t\titems: [],\n\t\t\t\tmaxItems: arraySizes[i],\n\t\t\t\tminItems: arraySizes[i],\n\t\t\t};\n\n\t\t\tif (arraySizes[i] < 0) {\n\t\t\t\tdelete childSchema.maxItems;\n\t\t\t\tdelete childSchema.minItems;\n\t\t\t}\n\n\t\t\t// lastSchema.items is a Schema, concat with 'childSchema'\n\t\t\tif (!Array.isArray(lastSchema.items)) {\n\t\t\t\tlastSchema.items = [lastSchema.items as JsonSchema, childSchema];\n\t\t\t} // lastSchema.items is an empty Scheme array, set it to 'childSchema'\n\t\t\telse if (lastSchema.items.length === 0) {\n\t\t\t\tlastSchema.items = [childSchema];\n\t\t\t} // lastSchema.items is a non-empty Scheme array, append 'childSchema'\n\t\t\telse {\n\t\t\t\tlastSchema.items.push(childSchema);\n\t\t\t}\n\t\t\tlastSchema = childSchema;\n\t\t}\n\n\t\tif (baseType === 'tuple' && !isArray) {\n\t\t\tconst nestedTuple = abiSchemaToJsonSchema(abiComponents, abiName);\n\t\t\tnestedTuple.$id = abiName;\n\t\t\t(lastSchema.items as JsonSchema[]).push(nestedTuple);\n\t\t} else if (baseType === 'tuple' && isArray) {\n const arraySize = arraySizes[0];\n const item: JsonSchema = {\n type: 'array',\n $id: abiName,\n items: abiSchemaToJsonSchema(abiComponents, abiName),\n ...(arraySize >= 0 && { minItems: arraySize, maxItems: arraySize }),\n };\n\n (lastSchema.items as JsonSchema[]).push(item);\n\t\t} else if (isArray) {\n\t\t const arraySize = arraySizes[0];\n const item: JsonSchema = {\n type: 'array',\n $id: abiName,\n items: convertEthType(abiType),\n ...(arraySize >= 0 && { minItems: arraySize, maxItems: arraySize }),\n };\n\n (lastSchema.items as JsonSchema[]).push(item);\n\t\t} else if (Array.isArray(lastSchema.items)) {\n\t\t\t// Array of non-tuple items\n\t\t\tlastSchema.items.push({ $id: abiName, ...convertEthType(abiType) });\n\t\t} else {\n\t\t\t// Nested object\n\t\t\t(lastSchema.items as JsonSchema[]).push({\n\t\t\t\t$id: abiName,\n\t\t\t\t...convertEthType(abiType),\n\t\t\t});\n\t\t}\n\t\tlastSchema = schema;\n\t}\n\n\treturn schema;\n};\n\nexport const ethAbiToJsonSchema = (abis: ValidationSchemaInput) => abiSchemaToJsonSchema(abis);\n\nexport const fetchArrayElement = (data: Array, level: number): unknown => {\n\tif (level === 1) {\n\t\treturn data;\n\t}\n\n\treturn fetchArrayElement(data[0] as Array, level - 1);\n};\n\nexport const transformJsonDataToAbiFormat = (\n\tabis: FullValidationSchema,\n\tdata: ReadonlyArray | Record,\n\ttransformedData?: Array,\n): Array => {\n\tconst newData: Array = [];\n\n\tfor (const [index, abi] of abis.entries()) {\n\t\t// eslint-disable-next-line no-nested-ternary\n\t\tlet abiType!: string;\n\t\tlet abiName!: string;\n\t\tlet abiComponents: ShortValidationSchema | FullValidationSchema | undefined = [];\n\n\t\t// If it's a complete Abi Parameter\n\t\t// e.g. {name: 'a', type: 'uint'}\n\t\tif (isAbiParameterSchema(abi)) {\n\t\t\tabiType = abi.type;\n\t\t\tabiName = abi.name;\n\t\t\tabiComponents = abi.components as FullValidationSchema;\n\t\t\t// If its short form string value e.g. ['uint']\n\t\t} else if (typeof abi === 'string') {\n\t\t\tabiType = abi;\n\n\t\t\t// If it's provided in short form of tuple e.g. [['uint', 'string']]\n\t\t} else if (Array.isArray(abi)) {\n\t\t\t// If its custom tuple e.g. ['tuple[2]', ['uint', 'string']]\n\t\t\tif (abi[1] && Array.isArray(abi[1])) {\n\t\t\t\tabiType = abi[0] as string;\n\t\t\t\tabiComponents = abi[1] as ReadonlyArray;\n\t\t\t} else {\n\t\t\t\tabiType = 'tuple';\n\t\t\t\tabiComponents = abi;\n\t\t\t}\n\t\t}\n\n\t\tconst { baseType, isArray, arraySizes } = parseBaseType(abiType);\n\t\tconst dataItem = Array.isArray(data)\n\t\t\t? (data as Array)[index]\n\t\t\t: (data as Record)[abiName];\n\n\t\tif (baseType === 'tuple' && !isArray) {\n\t\t\tnewData.push(\n\t\t\t\ttransformJsonDataToAbiFormat(\n\t\t\t\t\tabiComponents as FullValidationSchema,\n\t\t\t\t\tdataItem as Array,\n\t\t\t\t\ttransformedData,\n\t\t\t\t),\n\t\t\t);\n\t\t} else if (baseType === 'tuple' && isArray) {\n\t\t\tconst tupleData = [];\n\t\t\tfor (const tupleItem of dataItem as Array) {\n\t\t\t\t// Nested array\n\t\t\t\tif (arraySizes.length > 1) {\n\t\t\t\t\tconst nestedItems = fetchArrayElement(\n\t\t\t\t\t\ttupleItem as Array,\n\t\t\t\t\t\tarraySizes.length - 1,\n\t\t\t\t\t);\n\t\t\t\t\tconst nestedData = [];\n\n\t\t\t\t\tfor (const nestedItem of nestedItems as Array) {\n\t\t\t\t\t\tnestedData.push(\n\t\t\t\t\t\t\ttransformJsonDataToAbiFormat(\n\t\t\t\t\t\t\t\tabiComponents as FullValidationSchema,\n\t\t\t\t\t\t\t\tnestedItem as Array,\n\t\t\t\t\t\t\t\ttransformedData,\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\ttupleData.push(nestedData);\n\t\t\t\t} else {\n\t\t\t\t\ttupleData.push(\n\t\t\t\t\t\ttransformJsonDataToAbiFormat(\n\t\t\t\t\t\t\tabiComponents as FullValidationSchema,\n\t\t\t\t\t\t\ttupleItem as Array,\n\t\t\t\t\t\t\ttransformedData,\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t\tnewData.push(tupleData);\n\t\t} else {\n\t\t\tnewData.push(dataItem);\n\t\t}\n\t}\n\n\t// Have to reassign before pushing to transformedData\n\t// eslint-disable-next-line no-param-reassign\n\ttransformedData = transformedData ?? [];\n\ttransformedData.push(...newData);\n\n\treturn transformedData;\n};\n\n/**\n * Code points to int\n */\n\nexport const codePointToInt = (codePoint: number): number => {\n\tif (codePoint >= 48 && codePoint <= 57) {\n\t\t/* ['0'..'9'] -> [0..9] */\n\t\treturn codePoint - 48;\n\t}\n\n\tif (codePoint >= 65 && codePoint <= 70) {\n\t\t/* ['A'..'F'] -> [10..15] */\n\t\treturn codePoint - 55;\n\t}\n\n\tif (codePoint >= 97 && codePoint <= 102) {\n\t\t/* ['a'..'f'] -> [10..15] */\n\t\treturn codePoint - 87;\n\t}\n\n\tthrow new Error(`Invalid code point: ${codePoint}`);\n};\n\n/**\n * Converts value to it's number representation\n */\nexport const hexToNumber = (value: string): bigint | number => {\n\tif (!isHexStrict(value)) {\n\t\tthrow new Error('Invalid hex string');\n\t}\n\n\tconst [negative, hexValue] = value.startsWith('-') ? [true, value.slice(1)] : [false, value];\n\tconst num = BigInt(hexValue);\n\n\tif (num > Number.MAX_SAFE_INTEGER) {\n\t\treturn negative ? -num : num;\n\t}\n\n\tif (num < Number.MIN_SAFE_INTEGER) {\n\t\treturn num;\n\t}\n\n\treturn negative ? -1 * Number(num) : Number(num);\n};\n\n/**\n * Converts value to it's hex representation\n */\nexport const numberToHex = (value: ValidInputTypes): string => {\n\tif ((typeof value === 'number' || typeof value === 'bigint') && value < 0) {\n\t\treturn `-0x${value.toString(16).slice(1)}`;\n\t}\n\n\tif ((typeof value === 'number' || typeof value === 'bigint') && value >= 0) {\n\t\treturn `0x${value.toString(16)}`;\n\t}\n\n\tif (typeof value === 'string' && isHexStrict(value)) {\n\t\tconst [negative, hex] = value.startsWith('-') ? [true, value.slice(1)] : [false, value];\n\t\tconst hexValue = hex.split(/^(-)?0(x|X)/).slice(-1)[0];\n\t\treturn `${negative ? '-' : ''}0x${hexValue.replace(/^0+/, '').toLowerCase()}`;\n\t}\n\n\tif (typeof value === 'string' && !isHexStrict(value)) {\n\t\treturn numberToHex(BigInt(value));\n\t}\n\n\tthrow new InvalidNumberError(value);\n};\n\n/**\n * Adds a padding on the left of a string, if value is a integer or bigInt will be converted to a hex string.\n */\nexport const padLeft = (value: ValidInputTypes, characterAmount: number, sign = '0'): string => {\n\tif (typeof value === 'string' && !isHexStrict(value)) {\n\t\treturn value.padStart(characterAmount, sign);\n\t}\n\n\tconst hex = typeof value === 'string' && isHexStrict(value) ? value : numberToHex(value);\n\n\tconst [prefix, hexValue] = hex.startsWith('-') ? ['-0x', hex.slice(3)] : ['0x', hex.slice(2)];\n\n\treturn `${prefix}${hexValue.padStart(characterAmount, sign)}`;\n};\n\nexport function uint8ArrayToHexString(uint8Array: Uint8Array): string {\n\tlet hexString = '0x';\n\tfor (const e of uint8Array) {\n\t\tconst hex = e.toString(16);\n\t\thexString += hex.length === 1 ? `0${hex}` : hex;\n\t}\n\treturn hexString;\n}\n\n// for optimized technique for hex to bytes conversion\nconst charCodeMap = {\n\tzero: 48,\n\tnine: 57,\n\tA: 65,\n\tF: 70,\n\ta: 97,\n\tf: 102,\n } as const\n\n function charCodeToBase16(char: number) {\n\tif (char >= charCodeMap.zero && char <= charCodeMap.nine)\n\t return char - charCodeMap.zero\n\tif (char >= charCodeMap.A && char <= charCodeMap.F)\n\t return char - (charCodeMap.A - 10)\n\tif (char >= charCodeMap.a && char <= charCodeMap.f)\n\t return char - (charCodeMap.a - 10)\n\treturn undefined\n }\n\nexport function hexToUint8Array(hex: string): Uint8Array {\n\tlet offset = 0;\n\tif (hex.startsWith('0') && (hex[1] === 'x' || hex[1] === 'X')) {\n\t\toffset = 2;\n\t}\n\tif (hex.length % 2 !== 0) {\n\t\tthrow new InvalidBytesError(`hex string has odd length: ${hex}`);\n\t}\n\tconst length = (hex.length - offset) / 2;\n\tconst bytes = new Uint8Array(length);\n\tfor (let index = 0, j = offset; index < length; index+=1) {\n\t // eslint-disable-next-line no-plusplus\n\t const nibbleLeft = charCodeToBase16(hex.charCodeAt(j++))\n\t // eslint-disable-next-line no-plusplus\n\t const nibbleRight = charCodeToBase16(hex.charCodeAt(j++))\n\t if (nibbleLeft === undefined || nibbleRight === undefined) {\n\t\tthrow new InvalidBytesError(\n\t\t\t`Invalid byte sequence (\"${hex[j - 2]}${\n\t\t\t\thex[j - 1]\n\t\t\t }\" in \"${hex}\").`,\n\t\t)\n\t }\n\t bytes[index] = nibbleLeft * 16 + nibbleRight\n\t}\n\treturn bytes\n}\n\n// @TODO: Remove this function and its usages once all sub dependencies uses version 1.3.3 or above of @noble/hashes\nexport function ensureIfUint8Array(data: T) {\n\tif (\n\t\t!(data instanceof Uint8Array) &&\n\t\t(data as { constructor: { name: string } })?.constructor?.name === 'Uint8Array'\n\t) {\n\t\treturn Uint8Array.from(data as unknown as Uint8Array);\n\t}\n\treturn data;\n}\n","/*\nThis file is part of web3.js.\n\nweb3.js is free software: you can redistribute it and/or modify\nit under the terms of the GNU Lesser General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nweb3.js is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU Lesser General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public License\nalong with web3.js. If not, see .\n*/\n\nimport { ValidInputTypes } from '../types.js';\nimport { hexToUint8Array, parseBaseType } from '../utils.js';\nimport { isHexStrict } from './string.js';\n\n/**\n * checks input if typeof data is valid Uint8Array input\n */\nexport const isUint8Array = (data: ValidInputTypes): data is Uint8Array =>\n\tdata instanceof Uint8Array || data?.constructor?.name === 'Uint8Array' || data?.constructor?.name === 'Buffer';\n\nexport const isBytes = (\n\tvalue: ValidInputTypes | Uint8Array | number[],\n\toptions: { abiType: string; size?: never } | { size: number; abiType?: never } = {\n\t\tabiType: 'bytes',\n\t},\n) => {\n\tif (typeof value !== 'string' && !Array.isArray(value) && !isUint8Array(value)) {\n\t\treturn false;\n\t}\n\n\t// isHexStrict also accepts - prefix which can not exists in bytes\n\tif (typeof value === 'string' && isHexStrict(value) && value.startsWith('-')) {\n\t\treturn false;\n\t}\n\n\tif (typeof value === 'string' && !isHexStrict(value)) {\n\t\treturn false;\n\t}\n\n\tlet valueToCheck: Uint8Array;\n\n\tif (typeof value === 'string') {\n\t\tif (value.length % 2 !== 0) {\n\t\t\t// odd length hex\n\t\t\treturn false;\n\t\t}\n\t\tvalueToCheck = hexToUint8Array(value);\n\t} else if (Array.isArray(value)) {\n\t\tif (value.some(d => d < 0 || d > 255 || !Number.isInteger(d))) {\n\t\t\treturn false;\n\t\t}\n\t\tvalueToCheck = new Uint8Array(value);\n\t} else {\n\t\tvalueToCheck = value;\n\t}\n\n\tif (options?.abiType) {\n\t\tconst { baseTypeSize } = parseBaseType(options.abiType);\n\n\t\treturn baseTypeSize ? valueToCheck.length === baseTypeSize : true;\n\t}\n\n\tif (options?.size) {\n\t\treturn valueToCheck.length === options?.size;\n\t}\n\n\treturn true;\n};\n","/*\nThis file is part of web3.js.\n\nweb3.js is free software: you can redistribute it and/or modify\nit under the terms of the GNU Lesser General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nweb3.js is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU Lesser General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public License\nalong with web3.js. If not, see .\n*/\n\nimport { keccak256 } from 'ethereum-cryptography/keccak.js';\nimport { utf8ToBytes } from 'ethereum-cryptography/utils.js';\nimport { ValidInputTypes } from '../types.js';\nimport { ensureIfUint8Array, uint8ArrayToHexString } from '../utils.js';\nimport { isHexStrict } from './string.js';\nimport { isUint8Array } from './bytes.js';\n\n/**\n * Checks the checksum of a given address. Will also return false on non-checksum addresses.\n */\nexport const checkAddressCheckSum = (data: string): boolean => {\n\tif (!/^(0x)?[0-9a-f]{40}$/i.test(data)) return false;\n\tconst address = data.slice(2);\n\tconst updatedData = utf8ToBytes(address.toLowerCase());\n\n\tconst addressHash = uint8ArrayToHexString(keccak256(ensureIfUint8Array(updatedData))).slice(2);\n\n\tfor (let i = 0; i < 40; i += 1) {\n\t\t// the nth letter should be uppercase if the nth digit of casemap is 1\n\t\tif (\n\t\t\t(parseInt(addressHash[i], 16) > 7 && address[i].toUpperCase() !== address[i]) ||\n\t\t\t(parseInt(addressHash[i], 16) <= 7 && address[i].toLowerCase() !== address[i])\n\t\t) {\n\t\t\treturn false;\n\t\t}\n\t}\n\treturn true;\n};\n\n/**\n * Checks if a given string is a valid Ethereum address. It will also check the checksum, if the address has upper and lowercase letters.\n */\nexport const isAddress = (value: ValidInputTypes, checkChecksum = true) => {\n\tif (typeof value !== 'string' && !isUint8Array(value)) {\n\t\treturn false;\n\t}\n\n\tlet valueToCheck: string;\n\n\tif (isUint8Array(value)) {\n\t\tvalueToCheck = uint8ArrayToHexString(value);\n\t} else if (typeof value === 'string' && !isHexStrict(value)) {\n\t\tvalueToCheck = value.toLowerCase().startsWith('0x') ? value : `0x${value}`;\n\t} else {\n\t\tvalueToCheck = value;\n\t}\n\n\t// check if it has the basic requirements of an address\n\tif (!/^(0x)?[0-9a-f]{40}$/i.test(valueToCheck)) {\n\t\treturn false;\n\t}\n\t// If it's ALL lowercase or ALL upppercase\n\tif (\n\t\t/^(0x|0X)?[0-9a-f]{40}$/.test(valueToCheck) ||\n\t\t/^(0x|0X)?[0-9A-F]{40}$/.test(valueToCheck)\n\t) {\n\t\treturn true;\n\t\t// Otherwise check each case\n\t}\n\treturn checkChecksum ? checkAddressCheckSum(valueToCheck) : true;\n};\n","/*\nThis file is part of web3.js.\n\nweb3.js is free software: you can redistribute it and/or modify\nit under the terms of the GNU Lesser General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nweb3.js is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU Lesser General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public License\nalong with web3.js. If not, see .\n*/\n\nimport { ValidInputTypes } from '../types.js';\nimport { parseBaseType, hexToNumber } from '../utils.js';\nimport { isHexStrict } from './string.js';\n\n/**\n * Checks if a given value is a valid big int\n */\nexport const isBigInt = (value: ValidInputTypes): boolean => typeof value === 'bigint';\n\n// Note: this could be simplified using ** operator, but babel does not handle it well\n// \tyou can find more at: https://github.com/babel/babel/issues/13109 and https://github.com/web3/web3.js/issues/6187\n/** @internal */\nexport const bigintPower = (base: bigint, expo: bigint) => {\n\t// edge case\n\tif (expo === BigInt(0)) {\n\t\treturn BigInt(1);\n\t}\n\tlet res = base;\n\tfor (let index = 1; index < expo; index += 1) {\n\t\tres *= base;\n\t}\n\treturn res;\n};\n\nexport const isUInt = (\n\tvalue: ValidInputTypes,\n\toptions: { abiType: string; bitSize?: never } | { bitSize: number; abiType?: never } = {\n\t\tabiType: 'uint',\n\t},\n) => {\n\tif (\n\t\t!['number', 'string', 'bigint'].includes(typeof value) ||\n\t\t(typeof value === 'string' && value.length === 0)\n\t) {\n\t\treturn false;\n\t}\n\n\tlet size!: number;\n\n\tif (options?.abiType) {\n\t\tconst { baseTypeSize } = parseBaseType(options.abiType);\n\n\t\tif (baseTypeSize) {\n\t\t\tsize = baseTypeSize;\n\t\t}\n\t} else if (options.bitSize) {\n\t\tsize = options.bitSize;\n\t}\n\n\tconst maxSize = bigintPower(BigInt(2), BigInt(size ?? 256)) - BigInt(1);\n\n\ttry {\n\t\tconst valueToCheck =\n\t\t\ttypeof value === 'string' && isHexStrict(value)\n\t\t\t\t? BigInt(hexToNumber(value))\n\t\t\t\t: BigInt(value as number);\n\n\t\treturn valueToCheck >= 0 && valueToCheck <= maxSize;\n\t} catch (error) {\n\t\t// Some invalid number value given which can not be converted via BigInt\n\t\treturn false;\n\t}\n};\n\nexport const isInt = (\n\tvalue: ValidInputTypes,\n\toptions: { abiType: string; bitSize?: never } | { bitSize: number; abiType?: never } = {\n\t\tabiType: 'int',\n\t},\n) => {\n\tif (!['number', 'string', 'bigint'].includes(typeof value)) {\n\t\treturn false;\n\t}\n\n\tif (typeof value === 'number' && value > Number.MAX_SAFE_INTEGER) {\n\t\treturn false;\n\t}\n\n\tlet size!: number;\n\n\tif (options?.abiType) {\n\t\tconst { baseTypeSize, baseType } = parseBaseType(options.abiType);\n\n\t\tif (baseType !== 'int') {\n\t\t\treturn false;\n\t\t}\n\n\t\tif (baseTypeSize) {\n\t\t\tsize = baseTypeSize;\n\t\t}\n\t} else if (options.bitSize) {\n\t\tsize = options.bitSize;\n\t}\n\n\tconst maxSize = bigintPower(BigInt(2), BigInt((size ?? 256) - 1));\n\tconst minSize = BigInt(-1) * bigintPower(BigInt(2), BigInt((size ?? 256) - 1));\n\n\ttry {\n\t\tconst valueToCheck =\n\t\t\ttypeof value === 'string' && isHexStrict(value)\n\t\t\t\t? BigInt(hexToNumber(value))\n\t\t\t\t: BigInt(value as number);\n\n\t\treturn valueToCheck >= minSize && valueToCheck <= maxSize;\n\t} catch (error) {\n\t\t// Some invalid number value given which can not be converted via BigInt\n\t\treturn false;\n\t}\n};\n\nexport const isNumber = (value: ValidInputTypes) => {\n\tif (isInt(value)) {\n\t\treturn true;\n\t}\n\n\t// It would be a decimal number\n\tif (\n\t\ttypeof value === 'string' &&\n\t\t/[0-9.]/.test(value) &&\n\t\tvalue.indexOf('.') === value.lastIndexOf('.')\n\t) {\n\t\treturn true;\n\t}\n\n\tif (typeof value === 'number') {\n\t\treturn true;\n\t}\n\n\treturn false;\n};\n","/*\nThis file is part of web3.js.\n\nweb3.js is free software: you can redistribute it and/or modify\nit under the terms of the GNU Lesser General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nweb3.js is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU Lesser General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public License\nalong with web3.js. If not, see .\n*/\n\nimport { BlockTags } from 'web3-types';\nimport { isUInt } from './numbers.js';\n\nexport const isBlockNumber = (value: string | number | bigint): boolean => isUInt(value);\n\n/**\n * Returns true if the given blockNumber is 'latest', 'pending', 'earliest, 'safe' or 'finalized'\n */\nexport const isBlockTag = (value: string) => Object.values(BlockTags).includes(value as BlockTags);\n\n/**\n * Returns true if given value is valid hex string and not negative, or is a valid BlockTag\n */\nexport const isBlockNumberOrTag = (value: string | number | bigint) =>\n\tisBlockTag(value as string) || isBlockNumber(value);\n","/*\nThis file is part of web3.js.\n\nweb3.js is free software: you can redistribute it and/or modify\nit under the terms of the GNU Lesser General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nweb3.js is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU Lesser General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public License\nalong with web3.js. If not, see .\n*/\n\nimport { keccak256 } from 'ethereum-cryptography/keccak.js';\nimport { ValidInputTypes } from '../types.js';\nimport { codePointToInt, hexToUint8Array, padLeft, uint8ArrayToHexString } from '../utils.js';\nimport { isAddress } from './address.js';\nimport { isHexStrict } from './string.js';\n\n/**\n * Returns true if the bloom is a valid bloom\n * https://github.com/joshstevens19/ethereum-bloom-filters/blob/fbeb47b70b46243c3963fe1c2988d7461ef17236/src/index.ts#L7\n */\nexport const isBloom = (bloom: ValidInputTypes): boolean => {\n\tif (typeof bloom !== 'string') {\n\t\treturn false;\n\t}\n\n\tif (!/^(0x)?[0-9a-f]{512}$/i.test(bloom)) {\n\t\treturn false;\n\t}\n\n\tif (/^(0x)?[0-9a-f]{512}$/.test(bloom) || /^(0x)?[0-9A-F]{512}$/.test(bloom)) {\n\t\treturn true;\n\t}\n\n\treturn false;\n};\n\n/**\n * Returns true if the value is part of the given bloom\n * note: false positives are possible.\n */\nexport const isInBloom = (bloom: string, value: string | Uint8Array): boolean => {\n\tif (typeof value === 'string' && !isHexStrict(value)) {\n\t\treturn false;\n\t}\n\n\tif (!isBloom(bloom)) {\n\t\treturn false;\n\t}\n\n\tconst uint8Array = typeof value === 'string' ? hexToUint8Array(value) : value;\n\n\tconst hash = uint8ArrayToHexString(keccak256(uint8Array)).slice(2);\n\n\tfor (let i = 0; i < 12; i += 4) {\n\t\t// calculate bit position in bloom filter that must be active\n\t\tconst bitpos =\n\t\t\t// eslint-disable-next-line no-bitwise\n\t\t\t((parseInt(hash.slice(i, i + 2), 16) << 8) + parseInt(hash.slice(i + 2, i + 4), 16)) &\n\t\t\t2047;\n\n\t\t// test if bitpos in bloom is active\n\t\tconst code = codePointToInt(bloom.charCodeAt(bloom.length - 1 - Math.floor(bitpos / 4)));\n\n\t\t// eslint-disable-next-line no-bitwise\n\t\tconst offset = 1 << bitpos % 4;\n\n\t\t// eslint-disable-next-line no-bitwise\n\t\tif ((code & offset) !== offset) {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\treturn true;\n};\n\n/**\n * Returns true if the ethereum users address is part of the given bloom note: false positives are possible.\n */\nexport const isUserEthereumAddressInBloom = (bloom: string, ethereumAddress: string): boolean => {\n\tif (!isBloom(bloom)) {\n\t\treturn false;\n\t}\n\n\tif (!isAddress(ethereumAddress)) {\n\t\treturn false;\n\t}\n\n\t// you have to pad the ethereum address to 32 bytes\n\t// else the bloom filter does not work\n\t// this is only if your matching the USERS\n\t// ethereum address. Contract address do not need this\n\t// hence why we have 2 methods\n\t// (0x is not in the 2nd parameter of padleft so 64 chars is fine)\n\n\tconst address = padLeft(ethereumAddress, 64);\n\n\treturn isInBloom(bloom, address);\n};\n\n/**\n * Returns true if the contract address is part of the given bloom.\n * note: false positives are possible.\n */\nexport const isContractAddressInBloom = (bloom: string, contractAddress: string): boolean => {\n\tif (!isBloom(bloom)) {\n\t\treturn false;\n\t}\n\n\tif (!isAddress(contractAddress)) {\n\t\treturn false;\n\t}\n\n\treturn isInBloom(bloom, contractAddress);\n};\n","/*\nThis file is part of web3.js.\n\nweb3.js is free software: you can redistribute it and/or modify\nit under the terms of the GNU Lesser General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nweb3.js is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU Lesser General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public License\nalong with web3.js. If not, see .\n*/\n\nimport { TypedArray } from 'web3-types';\n\n// Explicitly check for the\n// eslint-disable-next-line @typescript-eslint/ban-types\nexport const isNullish = (item: unknown): item is undefined | null =>\n\t// Using \"null\" value intentionally for validation\n\t// eslint-disable-next-line no-null/no-null\n\titem === undefined || item === null;\n\nexport const isObject = (item: unknown): item is Record =>\n\ttypeof item === 'object' &&\n\t!isNullish(item) &&\n\t!Array.isArray(item) &&\n\t!(item instanceof TypedArray);\n","/*\nThis file is part of web3.js.\n\nweb3.js is free software: you can redistribute it and/or modify\nit under the terms of the GNU Lesser General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nweb3.js is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU Lesser General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public License\nalong with web3.js. If not, see .\n*/\n\nimport { isBloom, isInBloom } from './bloom.js';\n\n/**\n * Checks if its a valid topic\n */\nexport const isTopic = (topic: string): boolean => {\n\tif (typeof topic !== 'string') {\n\t\treturn false;\n\t}\n\n\tif (!/^(0x)?[0-9a-f]{64}$/i.test(topic)) {\n\t\treturn false;\n\t}\n\n\tif (/^(0x)?[0-9a-f]{64}$/.test(topic) || /^(0x)?[0-9A-F]{64}$/.test(topic)) {\n\t\treturn true;\n\t}\n\n\treturn false;\n};\n\n/**\n * Returns true if the topic is part of the given bloom.\n * note: false positives are possible.\n */\nexport const isTopicInBloom = (bloom: string, topic: string): boolean => {\n\tif (!isBloom(bloom)) {\n\t\treturn false;\n\t}\n\n\tif (!isTopic(topic)) {\n\t\treturn false;\n\t}\n\n\treturn isInBloom(bloom, topic);\n};\n","/*\nThis file is part of web3.js.\n\nweb3.js is free software: you can redistribute it and/or modify\nit under the terms of the GNU Lesser General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nweb3.js is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU Lesser General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public License\nalong with web3.js. If not, see .\n*/\nimport { Filter } from 'web3-types';\nimport { ValidInputTypes } from './types.js';\nimport { isAddress } from './validation/address.js';\nimport { isBlockNumber, isBlockNumberOrTag, isBlockTag } from './validation/block.js';\nimport { isBloom } from './validation/bloom.js';\nimport { isBoolean } from './validation/boolean.js';\nimport { isBytes } from './validation/bytes.js';\nimport { isFilterObject } from './validation/filter.js';\nimport { isHexStrict, isString } from './validation/string.js';\nimport { isNumber, isInt, isUInt } from './validation/numbers.js';\n\nconst formats: { [key: string]: (data: unknown) => boolean } = {\n\taddress: (data: unknown) => isAddress(data as ValidInputTypes),\n\tbloom: (data: unknown) => isBloom(data as ValidInputTypes),\n\tblockNumber: (data: unknown) => isBlockNumber(data as string | number | bigint),\n\tblockTag: (data: unknown) => isBlockTag(data as string),\n\tblockNumberOrTag: (data: unknown) => isBlockNumberOrTag(data as string | number | bigint),\n\tbool: (data: unknown) => isBoolean(data as ValidInputTypes),\n\tbytes: (data: unknown) => isBytes(data as ValidInputTypes | Uint8Array | number[]),\n\tfilter: (data: unknown) => isFilterObject(data as Filter),\n\thex: (data: unknown) => isHexStrict(data as ValidInputTypes),\n\tuint: (data: unknown) => isUInt(data as ValidInputTypes),\n\tint: (data: unknown) => isInt(data as ValidInputTypes),\n\tnumber: (data: unknown) => isNumber(data as ValidInputTypes),\n\tstring: (data: unknown) => isString(data as ValidInputTypes),\n};\n// generate formats for all numbers types\nfor (let bitSize = 8; bitSize <= 256; bitSize += 8) {\n\tformats[`int${bitSize}`] = data => isInt(data as ValidInputTypes, { bitSize });\n\tformats[`uint${bitSize}`] = data => isUInt(data as ValidInputTypes, { bitSize });\n}\n// generate bytes\nfor (let size = 1; size <= 32; size += 1) {\n\tformats[`bytes${size}`] = data =>\n\t\tisBytes(data as ValidInputTypes | Uint8Array | number[], { size });\n}\nformats.bytes256 = formats.bytes;\n\nexport default formats;\n","/*\nThis file is part of web3.js.\n\nweb3.js is free software: you can redistribute it and/or modify\nit under the terms of the GNU Lesser General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nweb3.js is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU Lesser General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public License\nalong with web3.js. If not, see .\n*/\n\nimport { ValidInputTypes } from '../types.js';\nimport { isHexStrict } from './string.js';\n\nexport const isBoolean = (value: ValidInputTypes) => {\n\tif (!['number', 'string', 'boolean'].includes(typeof value)) {\n\t\treturn false;\n\t}\n\n\tif (typeof value === 'boolean') {\n\t\treturn true;\n\t}\n\n\tif (typeof value === 'string' && !isHexStrict(value)) {\n\t\treturn value === '1' || value === '0';\n\t}\n\n\tif (typeof value === 'string' && isHexStrict(value)) {\n\t\treturn value === '0x1' || value === '0x0';\n\t}\n\n\t// type === number\n\treturn value === 1 || value === 0;\n};\n","/*\nThis file is part of web3.js.\n\nweb3.js is free software: you can redistribute it and/or modify\nit under the terms of the GNU Lesser General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nweb3.js is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU Lesser General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public License\nalong with web3.js. If not, see .\n*/\n\nimport { Filter } from 'web3-types';\nimport { isAddress } from './address.js';\nimport { isBlockNumberOrTag } from './block.js';\nimport { isNullish } from './object.js';\nimport { isTopic } from './topic.js';\n\n/**\n * First we check if all properties in the provided value are expected,\n * then because all Filter properties are optional, we check if the expected properties\n * are defined. If defined and they're not the expected type, we immediately return false,\n * otherwise we return true after all checks pass.\n */\nexport const isFilterObject = (value: Filter) => {\n\tconst expectedFilterProperties: (keyof Filter)[] = [\n\t\t'fromBlock',\n\t\t'toBlock',\n\t\t'address',\n\t\t'topics',\n\t\t'blockHash',\n\t];\n\tif (isNullish(value) || typeof value !== 'object') return false;\n\n\tif (\n\t\t!Object.keys(value).every(property =>\n\t\t\texpectedFilterProperties.includes(property as keyof Filter),\n\t\t)\n\t)\n\t\treturn false;\n\n\tif (\n\t\t(!isNullish(value.fromBlock) && !isBlockNumberOrTag(value.fromBlock)) ||\n\t\t(!isNullish(value.toBlock) && !isBlockNumberOrTag(value.toBlock))\n\t)\n\t\treturn false;\n\n\tif (!isNullish(value.address)) {\n\t\tif (Array.isArray(value.address)) {\n\t\t\tif (!value.address.every(address => isAddress(address))) return false;\n\t\t} else if (!isAddress(value.address)) return false;\n\t}\n\n\tif (!isNullish(value.topics)) {\n\t\tif (\n\t\t\t!value.topics.every(topic => {\n\t\t\t\tif (isNullish(topic)) return true;\n\n\t\t\t\tif (Array.isArray(topic)) {\n\t\t\t\t\treturn topic.every(nestedTopic => isTopic(nestedTopic));\n\t\t\t\t}\n\n\t\t\t\tif (isTopic(topic)) return true;\n\n\t\t\t\treturn false;\n\t\t\t})\n\t\t)\n\t\t\treturn false;\n\t}\n\n\treturn true;\n};\n","/*\nThis file is part of web3.js.\n\nweb3.js is free software: you can redistribute it and/or modify\nit under the terms of the GNU Lesser General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nweb3.js is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU Lesser General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public License\nalong with web3.js. If not, see .\n*/\nimport { SchemaFormatError } from 'web3-errors';\nimport { Web3ValidationErrorObject } from 'web3-types';\n\nimport { z, ZodType, ZodIssue, ZodIssueCode, ZodTypeAny } from 'zod';\n\nimport { RawCreateParams } from 'zod/lib/types';\nimport { Web3ValidatorError } from './errors.js';\nimport { Json, JsonSchema } from './types.js';\nimport formats from './formats.js';\n\nconst convertToZod = (schema: JsonSchema): ZodType => {\n\tif ((!schema?.type || schema?.type === 'object') && schema?.properties) {\n\t\tconst obj: { [key: string]: ZodType } = {};\n\t\tfor (const name of Object.keys(schema.properties)) {\n\t\t\tconst zItem = convertToZod(schema.properties[name]);\n\t\t\tif (zItem) {\n\t\t\t\tobj[name] = zItem;\n\t\t\t}\n\t\t}\n\n\t\tif (Array.isArray(schema.required)) {\n\t\t\treturn z\n\t\t\t\t.object(obj)\n\t\t\t\t.partial()\n\t\t\t\t.required(schema.required.reduce((acc, v: string) => ({ ...acc, [v]: true }), {}));\n\t\t}\n\t\treturn z.object(obj).partial();\n\t}\n\n\tif (schema?.type === 'array' && schema?.items) {\n\t\tif (Array.isArray(schema.items) && schema.items.length > 1\n\t\t && schema.maxItems !== undefined\n\t\t && new Set(schema.items.map((item: JsonSchema) => item.$id)).size === schema.items.length) {\n\t\t\tconst arr: Partial<[ZodTypeAny, ...ZodTypeAny[]]> = [];\n\t\t\tfor (const item of schema.items) {\n\t\t\t\tconst zItem = convertToZod(item);\n\t\t\t\tif (zItem) {\n\t\t\t\t\tarr.push(zItem);\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn z.tuple(arr as [ZodTypeAny, ...ZodTypeAny[]]);\n\t\t}\n\t\tconst nextSchema = Array.isArray(schema.items) ? schema.items[0] : schema.items;\n let zodArraySchema = z.array(convertToZod(nextSchema));\n\n zodArraySchema = schema.minItems !== undefined ? zodArraySchema.min(schema.minItems) : zodArraySchema;\n zodArraySchema = schema.maxItems !== undefined ? zodArraySchema.max(schema.maxItems) : zodArraySchema;\n\t\treturn zodArraySchema;\n\t}\n\n\tif (schema.oneOf && Array.isArray(schema.oneOf)) {\n\t\treturn z.union(\n\t\t\tschema.oneOf.map(oneOfSchema => convertToZod(oneOfSchema)) as [\n\t\t\t\tZodTypeAny,\n\t\t\t\tZodTypeAny,\n\t\t\t\t...ZodTypeAny[],\n\t\t\t],\n\t\t);\n\t}\n\n\tif (schema?.format) {\n\t\tif (!formats[schema.format]) {\n\t\t\tthrow new SchemaFormatError(schema.format);\n\t\t}\n\n\t\treturn z.any().refine(formats[schema.format], (value: unknown) => ({\n\t\t\tparams: { value, format: schema.format },\n\t\t}));\n\t}\n\n\tif (\n\t\tschema?.type &&\n\t\tschema?.type !== 'object' &&\n\t\ttypeof (z as unknown as { [key: string]: (params?: RawCreateParams) => ZodType })[\n\t\t\tString(schema.type)\n\t\t] === 'function'\n\t) {\n\t\treturn (z as unknown as { [key: string]: (params?: RawCreateParams) => ZodType })[\n\t\t\tString(schema.type)\n\t\t]();\n\t}\n\treturn z.object({ data: z.any() }).partial();\n};\n\nexport class Validator {\n\t// eslint-disable-next-line no-use-before-define\n\tprivate static validatorInstance?: Validator;\n\n\t// eslint-disable-next-line no-useless-constructor, @typescript-eslint/no-empty-function\n\tpublic static factory(): Validator {\n\t\tif (!Validator.validatorInstance) {\n\t\t\tValidator.validatorInstance = new Validator();\n\t\t}\n\t\treturn Validator.validatorInstance;\n\t}\n\n\tpublic validate(schema: JsonSchema, data: Json, options?: { silent?: boolean }) {\n\t\tconst zod = convertToZod(schema);\n\t\tconst result = zod.safeParse(data);\n\t\tif (!result.success) {\n\t\t\tconst errors = this.convertErrors(result.error?.issues ?? []);\n\t\t\tif (errors) {\n\t\t\t\tif (options?.silent) {\n\t\t\t\t\treturn errors;\n\t\t\t\t}\n\t\t\t\tthrow new Web3ValidatorError(errors);\n\t\t\t}\n\t\t}\n\t\treturn undefined;\n\t}\n\t// eslint-disable-next-line class-methods-use-this\n\tprivate convertErrors(errors: ZodIssue[] | undefined): Web3ValidationErrorObject[] | undefined {\n\t\tif (errors && Array.isArray(errors) && errors.length > 0) {\n\t\t\treturn errors.map((error: ZodIssue) => {\n\t\t\t\tlet message;\n\t\t\t\tlet keyword;\n\t\t\t\tlet params;\n\t\t\t\tlet schemaPath;\n\n\t\t\t\tschemaPath = error.path.join('/');\n\n\t\t\t\tconst field = String(error.path[error.path.length - 1]);\n\t\t\t\tconst instancePath = error.path.join('/');\n\t\t\t\tif (error.code === ZodIssueCode.too_big) {\n\t\t\t\t\tkeyword = 'maxItems';\n\t\t\t\t\tschemaPath = `${instancePath}/maxItems`;\n\t\t\t\t\tparams = { limit: error.maximum };\n\t\t\t\t\tmessage = `must NOT have more than ${error.maximum} items`;\n\t\t\t\t} else if (error.code === ZodIssueCode.too_small) {\n\t\t\t\t\tkeyword = 'minItems';\n\t\t\t\t\tschemaPath = `${instancePath}/minItems`;\n\t\t\t\t\tparams = { limit: error.minimum };\n\t\t\t\t\tmessage = `must NOT have fewer than ${error.minimum} items`;\n\t\t\t\t} else if (error.code === ZodIssueCode.custom) {\n\t\t\t\t\tconst { value, format } = (error.params ?? {}) as {\n\t\t\t\t\t\tvalue: unknown;\n\t\t\t\t\t\tformat: string;\n\t\t\t\t\t};\n\n\t\t\t\t\tif (typeof value === 'undefined') {\n\t\t\t\t\t\tmessage = `value at \"/${schemaPath}\" is required`;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tmessage = `value \"${\n\t\t\t\t\t\t\t// eslint-disable-next-line @typescript-eslint/restrict-template-expressions\n\t\t\t\t\t\t\ttypeof value === 'object' ? JSON.stringify(value) : value\n\t\t\t\t\t\t}\" at \"/${schemaPath}\" must pass \"${format}\" validation`;\n\t\t\t\t\t}\n\n\t\t\t\t\tparams = { value };\n\t\t\t\t}\n\n\t\t\t\treturn {\n\t\t\t\t\tkeyword: keyword ?? field,\n\t\t\t\t\tinstancePath: instancePath ? `/${instancePath}` : '',\n\t\t\t\t\tschemaPath: schemaPath ? `#${schemaPath}` : '#',\n\t\t\t\t\t// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n\t\t\t\t\tparams: params ?? { value: error.message },\n\t\t\t\t\tmessage: message ?? error.message,\n\t\t\t\t} as Web3ValidationErrorObject;\n\t\t\t});\n\t\t}\n\t\treturn undefined;\n\t}\n}\n","/*\nThis file is part of web3.js.\n\nweb3.js is free software: you can redistribute it and/or modify\nit under the terms of the GNU Lesser General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nweb3.js is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU Lesser General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public License\nalong with web3.js. If not, see .\n*/\n\nimport { Web3Validator } from './web3_validator.js';\n\nexport const validator = new Web3Validator();\n","/*\nThis file is part of web3.js.\n\nweb3.js is free software: you can redistribute it and/or modify\nit under the terms of the GNU Lesser General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nweb3.js is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU Lesser General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public License\nalong with web3.js. If not, see .\n*/\nimport { Web3ValidationErrorObject } from 'web3-types';\n\nimport { Validator } from './validator.js';\nimport { ethAbiToJsonSchema } from './utils.js';\nimport { Json, ValidationSchemaInput, Web3ValidationOptions } from './types.js';\nimport { Web3ValidatorError } from './errors.js';\n\nexport class Web3Validator {\n\tprivate readonly _validator: Validator;\n\tpublic constructor() {\n\t\tthis._validator = Validator.factory();\n\t}\n\tpublic validateJSONSchema(\n\t\tschema: object,\n\t\tdata: object,\n\t\toptions?: Web3ValidationOptions,\n\t): Web3ValidationErrorObject[] | undefined {\n\t\treturn this._validator.validate(schema, data as Json, options);\n\t}\n\tpublic validate(\n\t\tschema: ValidationSchemaInput,\n\t\tdata: ReadonlyArray,\n\t\toptions: Web3ValidationOptions = { silent: false },\n\t): Web3ValidationErrorObject[] | undefined {\n\t\tconst jsonSchema = ethAbiToJsonSchema(schema);\n\t\tif (\n\t\t\tArray.isArray(jsonSchema.items) &&\n\t\t\tjsonSchema.items?.length === 0 &&\n\t\t\tdata.length === 0\n\t\t) {\n\t\t\treturn undefined;\n\t\t}\n\n\t\tif (\n\t\t\tArray.isArray(jsonSchema.items) &&\n\t\t\tjsonSchema.items?.length === 0 &&\n\t\t\tdata.length !== 0\n\t\t) {\n\t\t\tthrow new Web3ValidatorError([\n\t\t\t\t{\n\t\t\t\t\tinstancePath: '/0',\n\t\t\t\t\tschemaPath: '/',\n\t\t\t\t\tkeyword: 'required',\n\t\t\t\t\tmessage: 'empty schema against data can not be validated',\n\t\t\t\t\tparams: data,\n\t\t\t\t},\n\t\t\t]);\n\t\t}\n\n\t\treturn this._validator.validate(jsonSchema, data as Json, options);\n\t}\n}\n","/*\nThis file is part of web3.js.\n\nweb3.js is free software: you can redistribute it and/or modify\nit under the terms of the GNU Lesser General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nweb3.js is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU Lesser General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public License\nalong with web3.js. If not, see .\n*/\n\nexport function isUint8Array(data: unknown | Uint8Array): data is Uint8Array {\n\treturn (\n\t\tdata instanceof Uint8Array ||\n\t\t(data as { constructor: { name: string } })?.constructor?.name === 'Uint8Array' ||\n\t\t(data as { constructor: { name: string } })?.constructor?.name === 'Buffer'\n\t);\n}\n\nexport function uint8ArrayConcat(...parts: Uint8Array[]): Uint8Array {\n\tconst length = parts.reduce((prev, part) => {\n\t\tconst agg = prev + part.length;\n\t\treturn agg;\n\t}, 0);\n\tconst result = new Uint8Array(length);\n\tlet offset = 0;\n\tfor (const part of parts) {\n\t\tresult.set(part, offset);\n\t\toffset += part.length;\n\t}\n\treturn result;\n}\n\n/**\n * Returns true if the two passed Uint8Arrays have the same content\n */\nexport function uint8ArrayEquals(a: Uint8Array, b: Uint8Array): boolean {\n\tif (a === b) {\n\t\treturn true;\n\t}\n\n\tif (a.byteLength !== b.byteLength) {\n\t\treturn false;\n\t}\n\n\tfor (let i = 0; i < a.byteLength; i += 1) {\n\t\tif (a[i] !== b[i]) {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\treturn true;\n}\n","/*\nThis file is part of web3.js.\n\nweb3.js is free software: you can redistribute it and/or modify\nit under the terms of the GNU Lesser General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nweb3.js is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU Lesser General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public License\nalong with web3.js. If not, see .\n*/\n\n/**\n * @module Utils\n */\n\nimport { keccak256 } from 'ethereum-cryptography/keccak.js';\nimport { bytesToUtf8, utf8ToBytes as ecUtf8ToBytes } from 'ethereum-cryptography/utils.js';\nimport { Address, Bytes, HexString, Numbers, ValueTypes } from 'web3-types';\nimport {\n\tisAddress,\n\tisHex,\n\tisHexStrict,\n\tisInt,\n\tisUInt,\n\tisNullish,\n\tutils,\n\tutils as validatorUtils,\n\tvalidator,\n\tbigintPower,\n} from 'web3-validator';\n\nimport {\n\tHexProcessingError,\n\tInvalidAddressError,\n\tInvalidBooleanError,\n\tInvalidBytesError,\n\tInvalidNumberError,\n\tInvalidUnitError,\n\tInvalidIntegerError,\n} from 'web3-errors';\nimport { isUint8Array } from './uint8array.js';\n\n// Ref: https://ethdocs.org/en/latest/ether.html\n// Note: this could be simplified using ** operator, but babel does not handle it well (https://github.com/babel/babel/issues/13109)\n/** @internal */\nexport const ethUnitMap = {\n\tnoether: BigInt(0),\n\twei: BigInt(1),\n\tkwei: BigInt(1000),\n\tKwei: BigInt(1000),\n\tbabbage: BigInt(1000),\n\tfemtoether: BigInt(1000),\n\tmwei: BigInt(1000000),\n\tMwei: BigInt(1000000),\n\tlovelace: BigInt(1000000),\n\tpicoether: BigInt(1000000),\n\tgwei: BigInt(1000000000),\n\tGwei: BigInt(1000000000),\n\tshannon: BigInt(1000000000),\n\tnanoether: BigInt(1000000000),\n\tnano: BigInt(1000000000),\n\tszabo: BigInt(1000000000000),\n\tmicroether: BigInt(1000000000000),\n\tmicro: BigInt(1000000000000),\n\tfinney: BigInt(1000000000000000),\n\tmilliether: BigInt(1000000000000000),\n\tmilli: BigInt(1000000000000000),\n\tether: BigInt('1000000000000000000'),\n\tkether: BigInt('1000000000000000000000'),\n\tgrand: BigInt('1000000000000000000000'),\n\tmether: BigInt('1000000000000000000000000'),\n\tgether: BigInt('1000000000000000000000000000'),\n\ttether: BigInt('1000000000000000000000000000000'),\n};\n\nconst PrecisionLossWarning =\n\t'Warning: Using type `number` with values that are large or contain many decimals may cause loss of precision, it is recommended to use type `string` or `BigInt` when using conversion methods';\n\nexport type EtherUnits = keyof typeof ethUnitMap;\n/**\n * Convert a value from bytes to Uint8Array\n * @param data - Data to be converted\n * @returns - The Uint8Array representation of the input data\n *\n * @example\n * ```ts\n * console.log(web3.utils.bytesToUint8Array(\"0xab\")));\n * > Uint8Array(1) [ 171 ]\n * ```\n */\nexport const bytesToUint8Array = (data: Bytes): Uint8Array | never => {\n\tvalidator.validate(['bytes'], [data]);\n\n\tif (isUint8Array(data)) {\n\t\treturn data;\n\t}\n\n\tif (Array.isArray(data)) {\n\t\treturn new Uint8Array(data);\n\t}\n\n\tif (typeof data === 'string') {\n\t\treturn validatorUtils.hexToUint8Array(data);\n\t}\n\n\tthrow new InvalidBytesError(data);\n};\n\n/**\n * @internal\n */\nconst { uint8ArrayToHexString } = validatorUtils;\n\n/**\n * Convert a byte array to a hex string\n * @param bytes - Byte array to be converted\n * @returns - The hex string representation of the input byte array\n *\n * @example\n * ```ts\n * console.log(web3.utils.bytesToHex(new Uint8Array([72, 12])));\n * > \"0x480c\"\n *\n */\nexport const bytesToHex = (bytes: Bytes): HexString =>\n\tuint8ArrayToHexString(bytesToUint8Array(bytes));\n\n/**\n * Convert a hex string to a byte array\n * @param hex - Hex string to be converted\n * @returns - The byte array representation of the input hex string\n *\n * @example\n * ```ts\n * console.log(web3.utils.hexToBytes('0x74657374'));\n * > Uint8Array(4) [ 116, 101, 115, 116 ]\n * ```\n */\nexport const hexToBytes = (bytes: HexString): Uint8Array => {\n\tif (typeof bytes === 'string' && bytes.slice(0, 2).toLowerCase() !== '0x') {\n\t\treturn bytesToUint8Array(`0x${bytes}`);\n\t}\n\treturn bytesToUint8Array(bytes);\n};\n\n/**\n * Converts value to it's number representation\n * @param value - Hex string to be converted\n * @returns - The number representation of the input value\n *\n * @example\n * ```ts\n * conoslle.log(web3.utils.hexToNumber('0xa'));\n * > 10\n * ```\n */\nexport const hexToNumber = (value: HexString): bigint | number => {\n\tvalidator.validate(['hex'], [value]);\n\n\t// To avoid duplicate code and circular dependency we will\n\t// use `hexToNumber` implementation from `web3-validator`\n\treturn validatorUtils.hexToNumber(value);\n};\n\n/**\n * Converts value to it's number representation @alias `hexToNumber`\n */\nexport const toDecimal = hexToNumber;\n\n/**\n * Converts value to it's hex representation\n * @param value - Value to be converted\n * @param hexstrict - Add padding to converted value if odd, to make it hexstrict\n * @returns - The hex representation of the input value\n *\n * @example\n * ```ts\n * console.log(web3.utils.numberToHex(10));\n * > \"0xa\"\n * ```\n */\nexport const numberToHex = (value: Numbers, hexstrict?: boolean): HexString => {\n\tif (typeof value !== 'bigint') validator.validate(['int'], [value]);\n\t// To avoid duplicate code and circular dependency we will\n\t// use `numberToHex` implementation from `web3-validator`\n\tlet updatedValue = validatorUtils.numberToHex(value);\n\tif (hexstrict) {\n\t\tif (!updatedValue.startsWith('-') && updatedValue.length % 2 === 1) {\n\t\t\t// To avoid duplicate a circular dependency we will not be using the padLeft method\n\t\t\tupdatedValue = '0x0'.concat(updatedValue.slice(2));\n\t\t} else if (updatedValue.length % 2 === 0 && updatedValue.startsWith('-'))\n\t\t\tupdatedValue = '-0x0'.concat(updatedValue.slice(3));\n\t}\n\treturn updatedValue;\n};\n/**\n * Converts value to it's hex representation @alias `numberToHex`\n *\n */\nexport const fromDecimal = numberToHex;\n\n/**\n * Converts value to it's decimal representation in string\n * @param value - Hex string to be converted\n * @returns - The decimal representation of the input value\n *\n * @example\n * ```ts\n * console.log(web3.utils.hexToNumberString('0xa'));\n * > \"10\"\n * ```\n */\nexport const hexToNumberString = (data: HexString): string => hexToNumber(data).toString();\n\n/**\n * Should be called to get hex representation (prefixed by 0x) of utf8 string\n * @param str - Utf8 string to be converted\n * @returns - The hex representation of the input string\n *\n * @example\n * ```ts\n * console.log(utf8ToHex('web3.js'));\n * > \"0x776562332e6a73\"\n * ```\n *\n */\nexport const utf8ToHex = (str: string): HexString => {\n\tvalidator.validate(['string'], [str]);\n\n\t// To be compatible with 1.x trim null character\n\t// eslint-disable-next-line no-control-regex\n\tlet strWithoutNullCharacter = str.replace(/^(?:\\u0000)/, '');\n\t// eslint-disable-next-line no-control-regex\n\tstrWithoutNullCharacter = strWithoutNullCharacter.replace(/(?:\\u0000)$/, '');\n\n\treturn bytesToHex(new TextEncoder().encode(strWithoutNullCharacter));\n};\n\n/**\n * @alias utf8ToHex\n */\n\nexport const fromUtf8 = utf8ToHex;\n/**\n * @alias utf8ToHex\n */\nexport const stringToHex = utf8ToHex;\n\n/**\n * Should be called to get utf8 from it's hex representation\n * @param str - Hex string to be converted\n * @returns - Utf8 string\n *\n * @example\n * ```ts\n * console.log(web3.utils.hexToUtf8('0x48656c6c6f20576f726c64'));\n * > Hello World\n * ```\n */\nexport const hexToUtf8 = (str: HexString): string => bytesToUtf8(hexToBytes(str));\n\n/**\n * @alias hexToUtf8\n */\nexport const toUtf8 = (input: HexString | Uint8Array) => {\n\tif (typeof input === 'string') {\n\t\treturn hexToUtf8(input);\n\t}\n\tvalidator.validate(['bytes'], [input]);\n\treturn bytesToUtf8(input);\n};\n\nexport const utf8ToBytes = ecUtf8ToBytes;\n\n/**\n * @alias hexToUtf8\n */\nexport const hexToString = hexToUtf8;\n\n/**\n * Should be called to get hex representation (prefixed by 0x) of ascii string\n * @param str - String to be converted to hex\n * @returns - Hex string\n *\n * @example\n * ```ts\n * console.log(web3.utils.asciiToHex('Hello World'));\n * > 0x48656c6c6f20576f726c64\n * ```\n */\nexport const asciiToHex = (str: string): HexString => {\n\tvalidator.validate(['string'], [str]);\n\tlet hexString = '';\n\tfor (let i = 0; i < str.length; i += 1) {\n\t\tconst hexCharCode = str.charCodeAt(i).toString(16);\n\t\t// might need a leading 0\n\t\thexString += hexCharCode.length % 2 !== 0 ? `0${hexCharCode}` : hexCharCode;\n\t}\n\treturn `0x${hexString}`;\n};\n\n/**\n * @alias asciiToHex\n */\nexport const fromAscii = asciiToHex;\n\n/**\n * Should be called to get ascii from it's hex representation\n * @param str - Hex string to be converted to ascii\n * @returns - Ascii string\n *\n * @example\n * ```ts\n * console.log(web3.utils.hexToAscii('0x48656c6c6f20576f726c64'));\n * > Hello World\n * ```\n */\nexport const hexToAscii = (str: HexString): string => {\n\tconst decoder = new TextDecoder('ascii');\n\treturn decoder.decode(hexToBytes(str));\n};\n\n/**\n * @alias hexToAscii\n */\nexport const toAscii = hexToAscii;\n\n/**\n * Auto converts any given value into it's hex representation.\n * @param value - Value to be converted to hex\n * @param returnType - If true, it will return the type of the value\n *\n * @example\n * ```ts\n * console.log(web3.utils.toHex(10));\n * > 0xa\n *\n * console.log(web3.utils.toHex('0x123', true));\n * > bytes\n *```\n */\nexport const toHex = (\n\tvalue: Numbers | Bytes | Address | boolean | object,\n\treturnType?: boolean,\n): HexString | ValueTypes => {\n\tif (typeof value === 'string' && isAddress(value)) {\n\t\treturn returnType ? 'address' : `0x${value.toLowerCase().replace(/^0x/i, '')}`;\n\t}\n\n\tif (typeof value === 'boolean') {\n\t\t// eslint-disable-next-line no-nested-ternary\n\t\treturn returnType ? 'bool' : value ? '0x01' : '0x00';\n\t}\n\n\tif (typeof value === 'number') {\n\t\t// eslint-disable-next-line no-nested-ternary\n\t\treturn returnType ? (value < 0 ? 'int256' : 'uint256') : numberToHex(value);\n\t}\n\n\tif (typeof value === 'bigint') {\n\t\treturn returnType ? 'bigint' : numberToHex(value);\n\t}\n\n\tif (isUint8Array(value)) {\n\t\treturn returnType ? 'bytes' : bytesToHex(value);\n\t}\n\n\tif (typeof value === 'object' && !!value) {\n\t\treturn returnType ? 'string' : utf8ToHex(JSON.stringify(value));\n\t}\n\n\tif (typeof value === 'string') {\n\t\tif (value.startsWith('-0x') || value.startsWith('-0X')) {\n\t\t\treturn returnType ? 'int256' : numberToHex(value);\n\t\t}\n\n\t\tif (isHexStrict(value)) {\n\t\t\treturn returnType ? 'bytes' : value;\n\t\t}\n\t\tif (isHex(value) && !isInt(value) && !isUInt(value)) {\n\t\t\treturn returnType ? 'bytes' : `0x${value}`;\n\t\t}\n\t\tif (isHex(value) && !isInt(value) && isUInt(value)) {\n\t\t\t// This condition seems problematic because meeting\n\t\t\t// both conditions `!isInt(value) && isUInt(value)` should be impossible.\n\t\t\t// But a value pass for those conditions: \"101611154195520776335741463917853444671577865378275924493376429267637792638729\"\n\t\t\t// Note that according to the docs: it is supposed to be treated as a string (https://docs.web3js.org/guides/web3_upgrade_guide/x/web3_utils_migration_guide#conversion-to-hex)\n\t\t\t// In short, the strange is that isInt(value) is false but isUInt(value) is true for the value above.\n\t\t\t// TODO: isUInt(value) should be investigated.\n\n\t\t\t// However, if `toHex('101611154195520776335741463917853444671577865378275924493376429267637792638729', true)` is called, it will return `true`.\n\t\t\t// But, if `toHex('101611154195520776335741463917853444671577865378275924493376429267637792638729')` is called, it will throw inside `numberToHex`.\n\t\t\treturn returnType ? 'uint' : numberToHex(value);\n\t\t}\n\n\t\tif (!Number.isFinite(value)) {\n\t\t\treturn returnType ? 'string' : utf8ToHex(value);\n\t\t}\n\t}\n\n\tthrow new HexProcessingError(value);\n};\n\n/**\n * Converts any given value into it's number representation, if possible, else into it's bigint representation.\n * @param value - The value to convert\n * @returns - Returns the value in number or bigint representation\n *\n * @example\n * ```ts\n * console.log(web3.utils.toNumber(1));\n * > 1\n * console.log(web3.utils.toNumber(Number.MAX_SAFE_INTEGER));\n * > 9007199254740991\n *\n * console.log(web3.utils.toNumber(BigInt(Number.MAX_SAFE_INTEGER)));\n * > 9007199254740991\n *\n * console.log(web3.utils.toNumber(BigInt(Number.MAX_SAFE_INTEGER) + BigInt(1)));\n * > 9007199254740992n\n *\n * ```\n */\nexport const toNumber = (value: Numbers): number | bigint => {\n\tif (typeof value === 'number') {\n\t\tif (value > 1e20) {\n\t\t\tconsole.warn(PrecisionLossWarning);\n\t\t\t// JavaScript converts numbers >= 10^21 to scientific notation when coerced to strings,\n\t\t\t// leading to potential parsing errors and incorrect representations.\n\t\t\t// For instance, String(10000000000000000000000) yields '1e+22'.\n\t\t\t// Using BigInt prevents this\n\t\t\treturn BigInt(value);\n\t\t}\n\t\treturn value;\n\t}\n\n\tif (typeof value === 'bigint') {\n\t\treturn value >= Number.MIN_SAFE_INTEGER && value <= Number.MAX_SAFE_INTEGER\n\t\t\t? Number(value)\n\t\t\t: value;\n\t}\n\n\tif (typeof value === 'string' && isHexStrict(value)) {\n\t\treturn hexToNumber(value);\n\t}\n\n\ttry {\n\t\treturn toNumber(BigInt(value));\n\t} catch {\n\t\tthrow new InvalidNumberError(value);\n\t}\n};\n\n/**\n * Auto converts any given value into it's bigint representation\n *\n * @param value - The value to convert\n * @returns - Returns the value in bigint representation\n\n * @example\n * ```ts\n * console.log(web3.utils.toBigInt(1));\n * > 1n\n * ```\n */\nexport const toBigInt = (value: unknown): bigint => {\n\tif (typeof value === 'number') {\n\t\treturn BigInt(value);\n\t}\n\n\tif (typeof value === 'bigint') {\n\t\treturn value;\n\t}\n\n\t// isHex passes for dec, too\n\tif (typeof value === 'string' && isHex(value)) {\n\t\tif (value.startsWith('-')) {\n\t\t\treturn -BigInt(value.substring(1));\n\t\t}\n\t\treturn BigInt(value);\n\t}\n\n\tthrow new InvalidNumberError(value);\n};\n\n/**\n * Takes a number of wei and converts it to any other ether unit.\n * @param number - The value in wei\n * @param unit - The unit to convert to\n * @returns - Returns the converted value in the given unit\n *\n * @example\n * ```ts\n * console.log(web3.utils.fromWei(\"1\", \"ether\"));\n * > 0.000000000000000001\n *\n * console.log(web3.utils.fromWei(\"1\", \"shannon\"));\n * > 0.000000001\n * ```\n */\nexport const fromWei = (number: Numbers, unit: EtherUnits | number): string => {\n\tlet denomination;\n\tif (typeof unit === 'string') {\n\t\tdenomination = ethUnitMap[unit];\n\n\t\tif (!denomination) {\n\t\t\tthrow new InvalidUnitError(unit);\n\t\t}\n\t} else {\n\t\tif (unit < 0 || !Number.isInteger(unit)) {\n\t\t\tthrow new InvalidIntegerError(unit);\n\t\t}\n\t\tdenomination = bigintPower(BigInt(10), BigInt(unit));\n\t}\n\n\t// value in wei would always be integer\n\t// 13456789, 1234\n\tconst value = String(toNumber(number));\n\n\t// count number of zeros in denomination\n\t// 1000000 -> 6\n\tconst numberOfZerosInDenomination = denomination.toString().length - 1;\n\n\tif (numberOfZerosInDenomination <= 0) {\n\t\treturn value.toString();\n\t}\n\n\t// pad the value with required zeros\n\t// 13456789 -> 13456789, 1234 -> 001234\n\tconst zeroPaddedValue = value.padStart(numberOfZerosInDenomination, '0');\n\n\t// get the integer part of value by counting number of zeros from start\n\t// 13456789 -> '13'\n\t// 001234 -> ''\n\tconst integer = zeroPaddedValue.slice(0, -numberOfZerosInDenomination);\n\n\t// get the fraction part of value by counting number of zeros backward\n\t// 13456789 -> '456789'\n\t// 001234 -> '001234'\n\tconst fraction = zeroPaddedValue.slice(-numberOfZerosInDenomination).replace(/\\.?0+$/, '');\n\n\tif (integer === '') {\n\t\treturn `0.${fraction}`;\n\t}\n\n\tif (fraction === '') {\n\t\treturn integer;\n\t}\n\tconst updatedValue = `${integer}.${fraction}`;\n\n\treturn updatedValue.slice(0, integer.length + numberOfZerosInDenomination + 1);\n};\n\n/**\n * Takes a number of a unit and converts it to wei.\n *\n * @param number - The number to convert.\n * @param unit - {@link EtherUnits} The unit of the number passed.\n * @returns The number converted to wei.\n *\n * @example\n * ```ts\n * console.log(web3.utils.toWei(\"0.001\", \"ether\"));\n * > 1000000000000000 //(wei)\n * ```\n */\n// todo in 1.x unit defaults to 'ether'\nexport const toWei = (number: Numbers, unit: EtherUnits | number): string => {\n\tvalidator.validate(['number'], [number]);\n\n\tlet denomination;\n\tif (typeof unit === 'string') {\n\t\tdenomination = ethUnitMap[unit];\n\t\tif (!denomination) {\n\t\t\tthrow new InvalidUnitError(unit);\n\t\t}\n\t} else {\n\t\tif (unit < 0 || !Number.isInteger(unit)) {\n\t\t\tthrow new InvalidIntegerError(unit);\n\t\t}\n\n\t\tdenomination = bigintPower(BigInt(10), BigInt(unit));\n\t}\n\n\tlet parsedNumber = number;\n\tif (typeof parsedNumber === 'number') {\n\t\tif (parsedNumber < 1e-15) {\n\t\t\tconsole.warn(PrecisionLossWarning);\n\t\t}\n\t\tif (parsedNumber > 1e20) {\n\t\t\tconsole.warn(PrecisionLossWarning);\n\n\t\t\tparsedNumber = BigInt(parsedNumber);\n\t\t} else {\n\t\t\t// in case there is a decimal point, we need to convert it to string\n\t\t\tparsedNumber = parsedNumber.toLocaleString('fullwide', {\n\t\t\t\tuseGrouping: false,\n\t\t\t\tmaximumFractionDigits: 20,\n\t\t\t});\n\t\t}\n\t}\n\n\t// if value is decimal e.g. 24.56 extract `integer` and `fraction` part\n\t// to avoid `fraction` to be null use `concat` with empty string\n\tconst [integer, fraction] = String(\n\t\ttypeof parsedNumber === 'string' && !isHexStrict(parsedNumber)\n\t\t\t? parsedNumber\n\t\t\t: toNumber(parsedNumber),\n\t)\n\t\t.split('.')\n\t\t.concat('');\n\n\t// join the value removing `.` from\n\t// 24.56 -> 2456\n\tconst value = BigInt(`${integer}${fraction}`);\n\n\t// multiply value with denomination\n\t// 2456 * 1000000 -> 2456000000\n\tconst updatedValue = value * denomination;\n\n\t// check if whole number was passed in\n\tconst decimals = fraction.length;\n\tif (decimals === 0) {\n\t\treturn updatedValue.toString();\n\t}\n\n\t// trim the value to remove extra zeros\n\treturn updatedValue.toString().slice(0, -decimals);\n};\n\n/**\n * Will convert an upper or lowercase Ethereum address to a checksum address.\n * @param address - An address string\n * @returns\tThe checksum address\n * @example\n * ```ts\n * web3.utils.toChecksumAddress('0xc1912fee45d61c87cc5ea59dae31190fffff232d');\n * > \"0xc1912fEE45d61C87Cc5EA59DaE31190FFFFf232d\"\n * ```\n */\nexport const toChecksumAddress = (address: Address): string => {\n\tif (!isAddress(address, false)) {\n\t\tthrow new InvalidAddressError(address);\n\t}\n\n\tconst lowerCaseAddress = address.toLowerCase().replace(/^0x/i, '');\n\n\t// calling `Uint8Array.from` because `noble-hashes` checks with `instanceof Uint8Array` that fails in some edge cases:\n\t// \thttps://github.com/paulmillr/noble-hashes/issues/25#issuecomment-1750106284\n\tconst hash = utils.uint8ArrayToHexString(\n\t\tkeccak256(validatorUtils.ensureIfUint8Array(utf8ToBytes(lowerCaseAddress))),\n\t);\n\n\tif (\n\t\tisNullish(hash) ||\n\t\thash === '0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470'\n\t)\n\t\treturn ''; // // EIP-1052 if hash is equal to c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470, keccak was given empty data\n\n\tlet checksumAddress = '0x';\n\n\tconst addressHash = hash.replace(/^0x/i, '');\n\n\tfor (let i = 0; i < lowerCaseAddress.length; i += 1) {\n\t\t// If ith character is 8 to f then make it uppercase\n\t\tif (parseInt(addressHash[i], 16) > 7) {\n\t\t\tchecksumAddress += lowerCaseAddress[i].toUpperCase();\n\t\t} else {\n\t\t\tchecksumAddress += lowerCaseAddress[i];\n\t\t}\n\t}\n\treturn checksumAddress;\n};\n\nexport const toBool = (value: boolean | string | number | unknown): boolean => {\n\tif (typeof value === 'boolean') {\n\t\treturn value;\n\t}\n\n\tif (typeof value === 'number' && (value === 0 || value === 1)) {\n\t\treturn Boolean(value);\n\t}\n\n\tif (typeof value === 'bigint' && (value === BigInt(0) || value === BigInt(1))) {\n\t\treturn Boolean(value);\n\t}\n\n\tif (\n\t\ttypeof value === 'string' &&\n\t\t!isHexStrict(value) &&\n\t\t(value === '1' || value === '0' || value === 'false' || value === 'true')\n\t) {\n\t\tif (value === 'true') {\n\t\t\treturn true;\n\t\t}\n\t\tif (value === 'false') {\n\t\t\treturn false;\n\t\t}\n\t\treturn Boolean(Number(value));\n\t}\n\n\tif (typeof value === 'string' && isHexStrict(value) && (value === '0x1' || value === '0x0')) {\n\t\treturn Boolean(toNumber(value));\n\t}\n\n\tthrow new InvalidBooleanError(value);\n};\n","/*\nThis file is part of web3.js.\n\nweb3.js is free software: you can redistribute it and/or modify\nit under the terms of the GNU Lesser General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nweb3.js is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU Lesser General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public License\nalong with web3.js. If not, see .\n*/\n/* eslint-disable max-classes-per-file */\n\nimport EventEmitter3 from 'eventemitter3';\n\n/**\n * This class copy the behavior of Node.js EventEmitter class.\n * It is used to provide the same interface for the browser environment.\n */\nexport class EventEmitter extends EventEmitter3 {\n\t// must be defined for backwards compatibility\n\tprivate maxListeners = Number.MAX_SAFE_INTEGER;\n\n\tpublic setMaxListeners(maxListeners: number) {\n\t\tthis.maxListeners = maxListeners;\n\t\treturn this;\n\t}\n\n\tpublic getMaxListeners(): number {\n\t\treturn this.maxListeners;\n\t}\n}\n","/*\nThis file is part of web3.js.\n\nweb3.js is free software: you can redistribute it and/or modify\nit under the terms of the GNU Lesser General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nweb3.js is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU Lesser General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public License\nalong with web3.js. If not, see .\n*/\n\n/**\n * @module Utils\n */\n\nimport { InvalidBlockError } from 'web3-errors';\nimport {\n\tcheckAddressCheckSum as checkAddressCheckSumValidator,\n\tisAddress as isAddressValidator,\n\tisBlockTag,\n\tisBloom as isBloomValidator,\n\tisContractAddressInBloom as isContractAddressInBloomValidator,\n\tisHex as isHexValidator,\n\tisHexStrict as isHexStrictValidator,\n\tisInBloom as isInBloomValidator,\n\tisNullish as isNullishValidator,\n\tisTopic as isTopicValidator,\n\tisTopicInBloom as isTopicInBloomValidator,\n\tisUserEthereumAddressInBloom as isUserEthereumAddressInBloomValidator,\n} from 'web3-validator';\nimport { BlockNumberOrTag, BlockTags, ContractInitOptions } from 'web3-types';\n\n/**\n * @deprecated Will be removed in next release. Please use `web3-validator` package instead.\n */\nexport const isHexStrict = isHexStrictValidator;\n\n/**\n * returns true if input is a hexstring, number or bigint\n *\n * @deprecated Will be removed in next release. Please use `web3-validator` package instead.\n */\nexport const isHex = isHexValidator;\n\n/**\n * Checks the checksum of a given address. Will also return false on non-checksum addresses.\n *\n * @deprecated Will be removed in next release. Please use `web3-validator` package instead.\n */\nexport const checkAddressCheckSum = checkAddressCheckSumValidator;\n\n/**\n * Checks if a given string is a valid Ethereum address. It will also check the checksum, if the address has upper and lowercase letters.\n *\n * @deprecated Will be removed in next release. Please use `web3-validator` package instead.\n */\nexport const isAddress = isAddressValidator;\n\n/**\n * Returns true if the bloom is a valid bloom\n * https://github.com/joshstevens19/ethereum-bloom-filters/blob/fbeb47b70b46243c3963fe1c2988d7461ef17236/src/index.ts#L7\n *\n * @deprecated Will be removed in next release. Please use `web3-validator` package instead.\n */\nexport const isBloom = isBloomValidator;\n\n/**\n * Returns true if the value is part of the given bloom\n * note: false positives are possible.\n *\n * @deprecated Will be removed in next release. Please use `web3-validator` package instead.\n */\nexport const isInBloom = isInBloomValidator;\n\n/**\n * Returns true if the ethereum users address is part of the given bloom note: false positives are possible.\n *\n * @deprecated Will be removed in next release. Please use `web3-validator` package instead.\n */\nexport const isUserEthereumAddressInBloom = isUserEthereumAddressInBloomValidator;\n\n/**\n * Returns true if the contract address is part of the given bloom.\n * note: false positives are possible.\n *\n * @deprecated Will be removed in next release. Please use `web3-validator` package instead.\n */\nexport const isContractAddressInBloom = isContractAddressInBloomValidator;\n\n/**\n * Checks if its a valid topic\n *\n * @deprecated Will be removed in next release. Please use `web3-validator` package instead.\n */\nexport const isTopic = isTopicValidator;\n\n/**\n * Returns true if the topic is part of the given bloom.\n * note: false positives are possible.\n *\n * @deprecated Will be removed in next release. Please use `web3-validator` package instead.\n */\nexport const isTopicInBloom = isTopicInBloomValidator;\n\n/**\n * Compares between block A and block B\n * @param blockA - Block number or string\n * @param blockB - Block number or string\n *\n * @returns - Returns -1 if a \\< b, returns 1 if a \\> b and returns 0 if a == b\n *\n * @example\n * ```ts\n * console.log(web3.utils.compareBlockNumbers('latest', 'pending'));\n * > -1\n *\n * console.log(web3.utils.compareBlockNumbers(12, 11));\n * > 1\n * ```\n */\nexport const compareBlockNumbers = (blockA: BlockNumberOrTag, blockB: BlockNumberOrTag) => {\n\tconst isABlockTag = typeof blockA === 'string' && isBlockTag(blockA);\n\tconst isBBlockTag = typeof blockB === 'string' && isBlockTag(blockB);\n\n\tif (\n\t\tblockA === blockB ||\n\t\t((blockA === 'earliest' || blockA === 0) && (blockB === 'earliest' || blockB === 0)) // only exception compare blocktag with number\n\t) {\n\t\treturn 0;\n\t}\n\tif (blockA === 'earliest' && blockB > 0) {\n\t\treturn -1;\n\t}\n\tif (blockB === 'earliest' && blockA > 0) {\n\t\treturn 1;\n\t}\n\n\tif (isABlockTag && isBBlockTag) {\n\t\t// Increasing order: earliest, finalized , safe, latest, pending\n\t\tconst tagsOrder = {\n\t\t\t[BlockTags.EARLIEST as string]: 1,\n\t\t\t[BlockTags.FINALIZED as string]: 2,\n\t\t\t[BlockTags.SAFE as string]: 3,\n\t\t\t[BlockTags.LATEST as string]: 4,\n\t\t\t[BlockTags.PENDING as string]: 5,\n\t\t};\n\n\t\tif (tagsOrder[blockA] < tagsOrder[blockB]) {\n\t\t\treturn -1;\n\t\t}\n\n\t\treturn 1;\n\t}\n\tif ((isABlockTag && !isBBlockTag) || (!isABlockTag && isBBlockTag)) {\n\t\tthrow new InvalidBlockError('Cannot compare blocktag with provided non-blocktag input.');\n\t}\n\n\tconst bigIntA = BigInt(blockA);\n\tconst bigIntB = BigInt(blockB);\n\n\tif (bigIntA < bigIntB) {\n\t\treturn -1;\n\t}\n\tif (bigIntA === bigIntB) {\n\t\treturn 0;\n\t}\n\treturn 1;\n};\n\nexport const isContractInitOptions = (options: unknown): options is ContractInitOptions =>\n\ttypeof options === 'object' &&\n\t!isNullishValidator(options) &&\n\tObject.keys(options).length !== 0 &&\n\t[\n\t\t'input',\n\t\t'data',\n\t\t'from',\n\t\t'gas',\n\t\t'gasPrice',\n\t\t'gasLimit',\n\t\t'address',\n\t\t'jsonInterface',\n\t\t'syncWithContext',\n\t\t'dataInputFill',\n\t].some(key => key in options);\n\nexport const isNullish = isNullishValidator;\n","/*\nThis file is part of web3.js.\n\nweb3.js is free software: you can redistribute it and/or modify\nit under the terms of the GNU Lesser General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nweb3.js is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU Lesser General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public License\nalong with web3.js. If not, see .\n*/\n\nimport { TypedArray } from 'web3-types';\nimport { isNullish } from 'web3-validator';\n\nconst isIterable = (item: unknown): item is Record =>\n\ttypeof item === 'object' &&\n\t!isNullish(item) &&\n\t!Array.isArray(item) &&\n\t!(item instanceof TypedArray);\n\n// The following code is a derivative work of the code from the \"LiskHQ/lisk-sdk\" project,\n// which is licensed under Apache version 2.\n/**\n * Deep merge two objects.\n * @param destination - The destination object.\n * @param sources - An array of source objects.\n * @returns - The merged object.\n */\nexport const mergeDeep = (\n\tdestination: Record,\n\t...sources: Record[]\n): Record => {\n\tif (!isIterable(destination)) {\n\t\treturn destination;\n\t}\n\tconst result = { ...destination }; // clone deep here\n\tfor (const src of sources) {\n\t\t// const src = { ..._src };\n\t\t// eslint-disable-next-line no-restricted-syntax\n\t\tfor (const key in src) {\n\t\t\tif (isIterable(src[key])) {\n\t\t\t\tif (!result[key]) {\n\t\t\t\t\tresult[key] = {};\n\t\t\t\t}\n\t\t\t\tresult[key] = mergeDeep(\n\t\t\t\t\tresult[key] as Record,\n\t\t\t\t\tsrc[key] as Record,\n\t\t\t\t);\n\t\t\t} else if (!isNullish(src[key]) && Object.hasOwnProperty.call(src, key)) {\n\t\t\t\tif (Array.isArray(src[key]) || src[key] instanceof TypedArray) {\n\t\t\t\t\tresult[key] = (src[key] as unknown[]).slice(0);\n\t\t\t\t} else {\n\t\t\t\t\tresult[key] = src[key];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn result;\n};\n","/*\nThis file is part of web3.js.\n\nweb3.js is free software: you can redistribute it and/or modify\nit under the terms of the GNU Lesser General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nweb3.js is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU Lesser General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public License\nalong with web3.js. If not, see .\n*/\n\n/**\n * @module Utils\n */\n\nimport { Numbers } from 'web3-types';\nimport { NibbleWidthError } from 'web3-errors';\nimport { isHexStrict, validator, utils as validatorUtils, bigintPower } from 'web3-validator';\nimport { numberToHex, toHex, toNumber } from './converters.js';\n\n/**\n * Adds a padding on the left of a string, if value is a integer or bigInt will be converted to a hex string.\n * @param value - The value to be padded.\n * @param characterAmount - The amount of characters the string should have.\n * @param sign - The sign to be added (default is 0).\n * @returns The padded string.\n *\n * @example\n * ```ts\n *\n * console.log(web3.utils.padLeft('0x123', 10));\n * >0x0000000123\n * ```\n */\nexport const padLeft = (value: Numbers, characterAmount: number, sign = '0'): string => {\n\t// To avoid duplicate code and circular dependency we will\n\t// use `padLeft` implementation from `web3-validator`\n\n\tif (typeof value === 'string') {\n\t\tif (!isHexStrict(value)) {\n\t\t\treturn value.padStart(characterAmount, sign);\n\t\t}\n\t\treturn validatorUtils.padLeft(value, characterAmount, sign);\n\t}\n\n\tvalidator.validate(['int'], [value]);\n\n\treturn validatorUtils.padLeft(value, characterAmount, sign);\n};\n\n/**\n * Adds a padding on the right of a string, if value is a integer or bigInt will be converted to a hex string.\n * @param value - The value to be padded.\n * @param characterAmount - The amount of characters the string should have.\n * @param sign - The sign to be added (default is 0).\n * @returns The padded string.\n *\n * @example\n * ```ts\n * console.log(web3.utils.padRight('0x123', 10));\n * > 0x1230000000\n *\n * console.log(web3.utils.padRight('0x123', 10, '1'));\n * > 0x1231111111\n * ```\n */\nexport const padRight = (value: Numbers, characterAmount: number, sign = '0'): string => {\n\tif (typeof value === 'string' && !isHexStrict(value)) {\n\t\treturn value.padEnd(characterAmount, sign);\n\t}\n\n\tvalidator.validate(['int'], [value]);\n\n\tconst hexString = typeof value === 'string' && isHexStrict(value) ? value : numberToHex(value);\n\n\tconst prefixLength = hexString.startsWith('-') ? 3 : 2;\n\treturn hexString.padEnd(characterAmount + prefixLength, sign);\n};\n\n/**\n * Adds a padding on the right of a string, if value is a integer or bigInt will be converted to a hex string. @alias `padRight`\n */\nexport const rightPad = padRight;\n\n/**\n * Adds a padding on the left of a string, if value is a integer or bigInt will be converted to a hex string. @alias `padLeft`\n */\nexport const leftPad = padLeft;\n\n/**\n * Converts a negative number into the two’s complement and return a hexstring of 64 nibbles.\n * @param value - The value to be converted.\n * @param nibbleWidth - The nibble width of the hex string (default is 64).\n *\n * @returns The hex string of the two’s complement.\n *\n * @example\n * ```ts\n * console.log(web3.utils.toTwosComplement(13, 32));\n * > 0x0000000000000000000000000000000d\n *\n * console.log(web3.utils.toTwosComplement('-0x1', 32));\n * > 0xffffffffffffffffffffffffffffffff\n *\n * console.log(web3.utils.toTwosComplement(BigInt('9007199254740992'), 32));\n * > 0x00000000000000000020000000000000\n * ```\n */\nexport const toTwosComplement = (value: Numbers, nibbleWidth = 64): string => {\n\tvalidator.validate(['int'], [value]);\n\n\tconst val = toNumber(value);\n\n\tif (val >= 0) return padLeft(toHex(val), nibbleWidth);\n\n\tconst largestBit = bigintPower(BigInt(2), BigInt(nibbleWidth * 4));\n\tif (-val >= largestBit) {\n\t\tthrow new NibbleWidthError(`value: ${value}, nibbleWidth: ${nibbleWidth}`);\n\t}\n\tconst updatedVal = BigInt(val);\n\n\tconst complement = updatedVal + largestBit;\n\n\treturn padLeft(numberToHex(complement), nibbleWidth);\n};\n\n/**\n * Converts the twos complement into a decimal number or big int.\n * @param value - The value to be converted.\n * @param nibbleWidth - The nibble width of the hex string (default is 64).\n * @returns The decimal number or big int.\n *\n * @example\n * ```ts\n * console.log(web3.utils.fromTwosComplement('0x0000000000000000000000000000000d', 32'));\n * > 13\n *\n * console.log(web3.utils.fromTwosComplement('0x00000000000000000020000000000000', 32));\n * > 9007199254740992n\n * ```\n */\nexport const fromTwosComplement = (value: Numbers, nibbleWidth = 64): number | bigint => {\n\tvalidator.validate(['int'], [value]);\n\n\tconst val = toNumber(value);\n\n\tif (val < 0) return val;\n\n\tconst largestBit = Math.ceil(Math.log(Number(val)) / Math.log(2));\n\n\tif (largestBit > nibbleWidth * 4)\n\t\tthrow new NibbleWidthError(`value: \"${value}\", nibbleWidth: \"${nibbleWidth}\"`);\n\n\t// check the largest bit to see if negative\n\tif (nibbleWidth * 4 !== largestBit) return val;\n\n\tconst complement = bigintPower(BigInt(2), BigInt(nibbleWidth) * BigInt(4));\n\n\treturn toNumber(BigInt(val) - complement);\n};\n","/*\nThis file is part of web3.js.\n\nweb3.js is free software: you can redistribute it and/or modify\nit under the terms of the GNU Lesser General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nweb3.js is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU Lesser General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public License\nalong with web3.js. If not, see .\n*/\nimport { FormatterError } from 'web3-errors';\nimport {\n\tBytes,\n\tDataFormat,\n\tFMT_BYTES,\n\tFMT_NUMBER,\n\tFormatType,\n\tDEFAULT_RETURN_FORMAT,\n} from 'web3-types';\nimport { isNullish, isObject, JsonSchema, utils, ValidationSchemaInput } from 'web3-validator';\nimport { bytesToUint8Array, bytesToHex, numberToHex, toBigInt } from './converters.js';\nimport { mergeDeep } from './objects.js';\nimport { padLeft } from './string_manipulation.js';\nimport { isUint8Array, uint8ArrayConcat } from './uint8array.js';\n\nconst { parseBaseType } = utils;\n\nexport const isDataFormat = (dataFormat: unknown): dataFormat is DataFormat =>\n\ttypeof dataFormat === 'object' &&\n\t!isNullish(dataFormat) &&\n\t'number' in dataFormat &&\n\t'bytes' in dataFormat;\n\n/**\n * Finds the schema that corresponds to a specific data path within a larger JSON schema.\n * It works by iterating over the dataPath array and traversing the JSON schema one step at a time until it reaches the end of the path.\n *\n * @param schema - represents a JSON schema, which is an object that describes the structure of JSON data\n * @param dataPath - represents an array of strings that specifies the path to the data within the JSON schema\n * @param oneOfPath - represents an optional array of two-element tuples that specifies the \"oneOf\" option to choose, if the schema has oneOf and the data path can match multiple subschemas\n * @returns the JSON schema that matches the data path\n *\n */\nconst findSchemaByDataPath = (\n\tschema: JsonSchema,\n\tdataPath: string[],\n\toneOfPath: [string, number][] = [],\n): JsonSchema | undefined => {\n\tlet result: JsonSchema = { ...schema } as JsonSchema;\n\tlet previousDataPath: string | undefined;\n\n\tfor (const dataPart of dataPath) {\n\t\tif (result.oneOf && previousDataPath) {\n\t\t\tconst currentDataPath = previousDataPath;\n\t\t\tconst path = oneOfPath.find(([key]) => key === currentDataPath);\n\t\t\tif (path && path[0] === previousDataPath) {\n\t\t\t\t// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access\n\t\t\t\tresult = result.oneOf[path[1]];\n\t\t\t}\n\t\t}\n\t\tif (!result.properties && !result.items) {\n\t\t\treturn undefined;\n\t\t}\n\n\t\tif (result.properties) {\n\t\t\tresult = (result.properties as Record)[dataPart];\n\t\t} else if (result.items && (result.items as JsonSchema).properties) {\n\t\t\tconst node = (result.items as JsonSchema).properties as Record;\n\n\t\t\tresult = node[dataPart];\n\t\t} else if (result.items && isObject(result.items)) {\n\t\t\tresult = result.items;\n\t\t} else if (result.items && Array.isArray(result.items)) {\n\t\t\tresult = result.items[parseInt(dataPart, 10)];\n\t\t}\n\n\t\tif (result && dataPart) previousDataPath = dataPart;\n\t}\n\n\treturn result;\n};\n/**\n * Converts a value depending on the format\n * @param value - value to convert\n * @param ethType - The type of the value to be parsed\n * @param format - The format to be converted to\n * @returns - The value converted to the specified format\n */\nexport const convertScalarValue = (value: unknown, ethType: string, format: DataFormat) => {\n\ttry {\n\t\tconst { baseType, baseTypeSize } = parseBaseType(ethType);\n\t\tif (baseType === 'int' || baseType === 'uint') {\n\t\t\tswitch (format.number) {\n\t\t\t\tcase FMT_NUMBER.NUMBER:\n\t\t\t\t\treturn Number(toBigInt(value));\n\t\t\t\tcase FMT_NUMBER.HEX:\n\t\t\t\t\treturn numberToHex(toBigInt(value));\n\t\t\t\tcase FMT_NUMBER.STR:\n\t\t\t\t\treturn toBigInt(value).toString();\n\t\t\t\tcase FMT_NUMBER.BIGINT:\n\t\t\t\t\treturn toBigInt(value);\n\t\t\t\tdefault:\n\t\t\t\t\tthrow new FormatterError(`Invalid format: ${String(format.number)}`);\n\t\t\t}\n\t\t}\n\t\tif (baseType === 'bytes') {\n\t\t\tlet paddedValue;\n\t\t\tif (baseTypeSize) {\n\t\t\t\tif (typeof value === 'string') paddedValue = padLeft(value, baseTypeSize * 2);\n\t\t\t\telse if (isUint8Array(value)) {\n\t\t\t\t\tpaddedValue = uint8ArrayConcat(\n\t\t\t\t\t\tnew Uint8Array(baseTypeSize - value.length),\n\t\t\t\t\t\tvalue,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tpaddedValue = value;\n\t\t\t}\n\t\t\tswitch (format.bytes) {\n\t\t\t\tcase FMT_BYTES.HEX:\n\t\t\t\t\treturn bytesToHex(bytesToUint8Array(paddedValue as Bytes));\n\t\t\t\tcase FMT_BYTES.UINT8ARRAY:\n\t\t\t\t\treturn bytesToUint8Array(paddedValue as Bytes);\n\t\t\t\tdefault:\n\t\t\t\t\tthrow new FormatterError(`Invalid format: ${String(format.bytes)}`);\n\t\t\t}\n\t\t}\n\t} catch (error) {\n\t\t// If someone didn't use `eth` keyword we can return original value\n\t\t// as the scope of this code is formatting not validation\n\t\treturn value;\n\t}\n\n\treturn value;\n};\n\nconst convertArray = ({\n\tvalue,\n\tschemaProp,\n\tschema,\n\tobject,\n\tkey,\n\tdataPath,\n\tformat,\n\toneOfPath = [],\n}: {\n\tvalue: unknown;\n\tschemaProp: JsonSchema;\n\tschema: JsonSchema;\n\tobject: Record;\n\tkey: string;\n\tdataPath: string[];\n\tformat: DataFormat;\n\toneOfPath: [string, number][];\n}) => {\n\t// If value is an array\n\tif (Array.isArray(value)) {\n\t\tlet _schemaProp = schemaProp;\n\n\t\t// TODO This is a naive approach to solving the issue of\n\t\t// a schema using oneOf. This chunk of code was intended to handle\n\t\t// BlockSchema.transactions\n\t\t// TODO BlockSchema.transactions are not being formatted\n\t\tif (schemaProp?.oneOf !== undefined) {\n\t\t\t// The following code is basically saying:\n\t\t\t// if the schema specifies oneOf, then we are to loop\n\t\t\t// over each possible schema and check if they type of the schema\n\t\t\t// matches the type of value[0], and if so we use the oneOfSchemaProp\n\t\t\t// as the schema for formatting\n\t\t\t// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-call\n\t\t\tschemaProp.oneOf.forEach((oneOfSchemaProp: JsonSchema, index: number) => {\n\t\t\t\tif (\n\t\t\t\t\t!Array.isArray(schemaProp?.items) &&\n\t\t\t\t\t((typeof value[0] === 'object' &&\n\t\t\t\t\t\t(oneOfSchemaProp?.items as JsonSchema)?.type === 'object') ||\n\t\t\t\t\t\t(typeof value[0] === 'string' &&\n\t\t\t\t\t\t\t(oneOfSchemaProp?.items as JsonSchema)?.type !== 'object'))\n\t\t\t\t) {\n\t\t\t\t\t_schemaProp = oneOfSchemaProp;\n\t\t\t\t\toneOfPath.push([key, index]);\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\n\t\tif (isNullish(_schemaProp?.items)) {\n\t\t\t// Can not find schema for array item, delete that item\n\t\t\t// eslint-disable-next-line no-param-reassign\n\t\t\tdelete object[key];\n\t\t\tdataPath.pop();\n\n\t\t\treturn true;\n\t\t}\n\n\t\t// If schema for array items is a single type\n\t\tif (isObject(_schemaProp.items) && !isNullish(_schemaProp.items.format)) {\n\t\t\tfor (let i = 0; i < value.length; i += 1) {\n\t\t\t\t// eslint-disable-next-line no-param-reassign\n\t\t\t\t(object[key] as unknown[])[i] = convertScalarValue(\n\t\t\t\t\tvalue[i],\n\t\t\t\t\t// eslint-disable-next-line @typescript-eslint/no-unsafe-argument\n\t\t\t\t\t_schemaProp?.items?.format,\n\t\t\t\t\tformat,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tdataPath.pop();\n\t\t\treturn true;\n\t\t}\n\n\t\t// If schema for array items is an object\n\t\tif (!Array.isArray(_schemaProp?.items) && _schemaProp?.items?.type === 'object') {\n\t\t\tfor (const arrObject of value) {\n\t\t\t\t// eslint-disable-next-line no-use-before-define\n\t\t\t\tconvert(\n\t\t\t\t\tarrObject as Record | unknown[],\n\t\t\t\t\tschema,\n\t\t\t\t\tdataPath,\n\t\t\t\t\tformat,\n\t\t\t\t\toneOfPath,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tdataPath.pop();\n\t\t\treturn true;\n\t\t}\n\n\t\t// If schema for array is a tuple\n\t\tif (Array.isArray(_schemaProp?.items)) {\n\t\t\tfor (let i = 0; i < value.length; i += 1) {\n\t\t\t\t// eslint-disable-next-line no-param-reassign\n\t\t\t\t(object[key] as unknown[])[i] = convertScalarValue(\n\t\t\t\t\tvalue[i],\n\t\t\t\t\t_schemaProp.items[i].format as string,\n\t\t\t\t\tformat,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tdataPath.pop();\n\t\t\treturn true;\n\t\t}\n\t}\n\treturn false;\n};\n\n/**\n * Converts the data to the specified format\n * @param data - data to convert\n * @param schema - The JSON schema that describes the structure of the data\n * @param dataPath - A string array that specifies the path to the data within the JSON schema\n * @param format - The format to be converted to\n * @param oneOfPath - An optional array of two-element tuples that specifies the \"oneOf\" option to choose, if the schema has oneOf and the data path can match multiple subschemas\n * @returns - The data converted to the specified format\n */\nexport const convert = (\n\tdata: Record | unknown[] | unknown,\n\tschema: JsonSchema,\n\tdataPath: string[],\n\tformat: DataFormat,\n\toneOfPath: [string, number][] = [],\n) => {\n\t// If it's a scalar value\n\tif (!isObject(data) && !Array.isArray(data)) {\n\t\treturn convertScalarValue(data, schema?.format as string, format);\n\t}\n\n\tconst object = data as Record;\n\t// case when schema is array and `items` is object\n\tif (\n\t\tArray.isArray(object) &&\n\t\tschema?.type === 'array' &&\n\t\t(schema?.items as JsonSchema)?.type === 'object'\n\t) {\n\t\tconvertArray({\n\t\t\tvalue: object,\n\t\t\tschemaProp: schema,\n\t\t\tschema,\n\t\t\tobject,\n\t\t\tkey: '',\n\t\t\tdataPath,\n\t\t\tformat,\n\t\t\toneOfPath,\n\t\t});\n\t} else {\n\t\tfor (const [key, value] of Object.entries(object)) {\n\t\t\tdataPath.push(key);\n\t\t\tconst schemaProp = findSchemaByDataPath(schema, dataPath, oneOfPath);\n\n\t\t\t// If value is a scaler value\n\t\t\tif (isNullish(schemaProp)) {\n\t\t\t\tdelete object[key];\n\t\t\t\tdataPath.pop();\n\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t// If value is an object, recurse into it\n\t\t\tif (isObject(value)) {\n\t\t\t\tconvert(value, schema, dataPath, format, oneOfPath);\n\t\t\t\tdataPath.pop();\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t// If value is an array\n\t\t\tif (\n\t\t\t\tconvertArray({\n\t\t\t\t\tvalue,\n\t\t\t\t\tschemaProp,\n\t\t\t\t\tschema,\n\t\t\t\t\tobject,\n\t\t\t\t\tkey,\n\t\t\t\t\tdataPath,\n\t\t\t\t\tformat,\n\t\t\t\t\toneOfPath,\n\t\t\t\t})\n\t\t\t) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tobject[key] = convertScalarValue(value, schemaProp.format as string, format);\n\n\t\t\tdataPath.pop();\n\t\t}\n\t}\n\n\treturn object;\n};\n\nexport const format = <\n\tDataType extends Record | unknown[] | unknown,\n\tReturnType extends DataFormat,\n>(\n\tschema: ValidationSchemaInput | JsonSchema,\n\tdata: DataType,\n\treturnFormat: ReturnType = DEFAULT_RETURN_FORMAT as ReturnType,\n): FormatType => {\n\tlet dataToParse: Record | unknown[] | unknown;\n\n\tif (isObject(data)) {\n\t\tdataToParse = mergeDeep({}, data);\n\t} else if (Array.isArray(data)) {\n\t\tdataToParse = [...data];\n\t} else {\n\t\tdataToParse = data;\n\t}\n\n\t// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n\tconst jsonSchema: JsonSchema = isObject(schema) ? schema : utils.ethAbiToJsonSchema(schema);\n\n\tif (!jsonSchema.properties && !jsonSchema.items && !jsonSchema.format) {\n\t\tthrow new FormatterError('Invalid json schema for formatting');\n\t}\n\n\treturn convert(dataToParse, jsonSchema, [], returnFormat) as FormatType<\n\t\ttypeof data,\n\t\tReturnType\n\t>;\n};\n","/*\nThis file is part of web3.js.\n\nweb3.js is free software: you can redistribute it and/or modify\nit under the terms of the GNU Lesser General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nweb3.js is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU Lesser General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public License\nalong with web3.js. If not, see .\n*/\n\n/**\n * This package provides utility functions for Ethereum dapps and other web3.js packages.\n *\n * For using Utils functions, first install Web3 package using `npm i web3` or `yarn add web3`.\n * After that, Web3 Utils functions will be available as mentioned below.\n * ```ts\n * import { Web3 } from 'web3';\n * const web3 = new Web3();\n *\n * const value = web3.utils.fromWei(\"1\", \"ether\")\n *\n * ```\n *\n * For using individual package install `web3-utils` package using `npm i web3-utils` or `yarn add web3-utils` and only import required functions.\n * This is more efficient approach for building lightweight applications.\n * ```ts\n * import { fromWei, soliditySha3Raw } from 'web3-utils';\n *\n * console.log(fromWei(\"1\", \"ether\"));\n * console.log(soliditySha3Raw({ type: \"string\", value: \"helloworld\" }))\n *\n * ```\n * @module Utils\n */\n\nimport { keccak256 } from 'ethereum-cryptography/keccak.js';\nimport { utf8ToBytes } from 'ethereum-cryptography/utils.js';\nimport {\n\tInvalidAddressError,\n\tInvalidBooleanError,\n\tInvalidBytesError,\n\tInvalidLargeValueError,\n\tInvalidSizeError,\n\tInvalidStringError,\n\tInvalidUnsignedIntegerError,\n} from 'web3-errors';\nimport {\n\tBytes,\n\tEncodingTypes,\n\tNumbers,\n\tSha3Input,\n\tTypedObject,\n\tTypedObjectAbbreviated,\n} from 'web3-types';\nimport { utils as validatorUtils, isAddress, isNullish, isHexStrict } from 'web3-validator';\nimport {\n\tbytesToUint8Array,\n\tbytesToHex,\n\thexToBytes,\n\ttoBigInt,\n\ttoHex,\n\ttoNumber,\n\tutf8ToHex,\n} from './converters.js';\nimport { leftPad, rightPad, toTwosComplement } from './string_manipulation.js';\n\nconst SHA3_EMPTY_BYTES = '0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470';\n\n/**\n * A wrapper for ethereum-cryptography/keccak256 to allow hashing a `string` and a `bigint` in addition to `UInt8Array`\n * @param data - the input to hash\n * @returns - the Keccak-256 hash of the input\n *\n * @example\n * ```ts\n * console.log(web3.utils.keccak256Wrapper('web3.js'));\n * > 0x63667efb1961039c9bb0d6ea7a5abdd223a3aca7daa5044ad894226e1f83919a\n *\n * console.log(web3.utils.keccak256Wrapper(1));\n * > 0xc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc6\n *\n * console.log(web3.utils.keccak256Wrapper(0xaf12fd));\n * > 0x358640fd4719fa923525d74ab5ae80a594301aba5543e3492b052bf4598b794c\n * ```\n */\nexport const keccak256Wrapper = (\n\tdata: Bytes | Numbers | string | ReadonlyArray,\n): string => {\n\tlet processedData;\n\tif (typeof data === 'bigint' || typeof data === 'number') {\n\t\tprocessedData = utf8ToBytes(data.toString());\n\t} else if (Array.isArray(data)) {\n\t\tprocessedData = new Uint8Array(data);\n\t} else if (typeof data === 'string' && !isHexStrict(data)) {\n\t\tprocessedData = utf8ToBytes(data);\n\t} else {\n\t\tprocessedData = bytesToUint8Array(data as Bytes);\n\t}\n\treturn bytesToHex(keccak256(validatorUtils.ensureIfUint8Array(processedData)));\n};\n\nexport { keccak256Wrapper as keccak256 };\n\n/**\n * computes the Keccak-256 hash of the input and returns a hexstring\n * @param data - the input to hash\n * @returns - the Keccak-256 hash of the input\n *\n * @example\n * ```ts\n * console.log(web3.utils.sha3('web3.js'));\n * > 0x63667efb1961039c9bb0d6ea7a5abdd223a3aca7daa5044ad894226e1f83919a\n *\n * console.log(web3.utils.sha3(''));\n * > undefined\n * ```\n */\nexport const sha3 = (data: Bytes): string | undefined => {\n\tlet updatedData: Uint8Array;\n\n\tif (typeof data === 'string') {\n\t\tif (data.startsWith('0x') && isHexStrict(data)) {\n\t\t\tupdatedData = hexToBytes(data);\n\t\t} else {\n\t\t\tupdatedData = utf8ToBytes(data);\n\t\t}\n\t} else {\n\t\tupdatedData = data;\n\t}\n\tconst hash = keccak256Wrapper(updatedData);\n\n\t// EIP-1052 if hash is equal to c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470, keccak was given empty data\n\treturn hash === SHA3_EMPTY_BYTES ? undefined : hash;\n};\n\n/**\n * Will calculate the sha3 of the input but does return the hash value instead of null if for example a empty string is passed.\n * @param data - the input to hash\n * @returns - the Keccak-256 hash of the input\n *\n * @example\n * ```ts\n * conosle.log(web3.utils.sha3Raw('web3.js'));\n * > 0x63667efb1961039c9bb0d6ea7a5abdd223a3aca7daa5044ad894226e1f83919a\n *\n * console.log(web3.utils.sha3Raw(''));\n * > 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470\n * ```\n */\nexport const sha3Raw = (data: Bytes): string => {\n\tconst hash = sha3(data);\n\tif (isNullish(hash)) {\n\t\treturn SHA3_EMPTY_BYTES;\n\t}\n\n\treturn hash;\n};\n\n/**\n * returns type and value\n * @param arg - the input to return the type and value\n * @returns - the type and value of the input\n */\nconst getType = (arg: Sha3Input): [string, EncodingTypes] => {\n\tif (Array.isArray(arg)) {\n\t\tthrow new Error('Autodetection of array types is not supported.');\n\t}\n\tlet type;\n\tlet value;\n\t// if type is given\n\tif (\n\t\ttypeof arg === 'object' &&\n\t\t('t' in arg || 'type' in arg) &&\n\t\t('v' in arg || 'value' in arg)\n\t) {\n\t\ttype = 't' in arg ? arg.t : arg.type;\n\t\tvalue = 'v' in arg ? arg.v : arg.value;\n\n\t\ttype = type.toLowerCase() === 'bigint' ? 'int' : type;\n\t} else if (typeof arg === 'bigint') {\n\t\treturn ['int', arg];\n\t}\n\t// otherwise try to guess the type\n\telse {\n\t\ttype = toHex(arg, true);\n\t\tvalue = toHex(arg);\n\n\t\tif (!type.startsWith('int') && !type.startsWith('uint')) {\n\t\t\ttype = 'bytes';\n\t\t}\n\t}\n\n\tif (\n\t\t(type.startsWith('int') || type.startsWith('uint')) &&\n\t\ttypeof value === 'string' &&\n\t\t!/^(-)?0x/i.test(value)\n\t) {\n\t\tvalue = toBigInt(value);\n\t}\n\treturn [type, value];\n};\n\n/**\n * returns the type with size if uint or int\n * @param name - the input to return the type with size\n * @returns - the type with size of the input\n */\nconst elementaryName = (name: string): string => {\n\tif (name.startsWith('int[')) {\n\t\treturn `int256${name.slice(3)}`;\n\t}\n\tif (name === 'int') {\n\t\treturn 'int256';\n\t}\n\tif (name.startsWith('uint[')) {\n\t\treturn `uint256'${name.slice(4)}`;\n\t}\n\tif (name === 'uint') {\n\t\treturn 'uint256';\n\t}\n\treturn name;\n};\n\n/**\n * returns the size of the value of type 'byte'\n */\nconst parseTypeN = (value: string, typeLength: number): number => {\n\tconst typesize = /^(\\d+).*$/.exec(value.slice(typeLength));\n\treturn typesize ? parseInt(typesize[1], 10) : 0;\n};\n\n/**\n * returns the bit length of the value\n * @param value - the input to return the bit length\n * @returns - the bit length of the input\n */\nconst bitLength = (value: bigint | number): number => {\n\tconst updatedVal = value.toString(2);\n\treturn updatedVal.length;\n};\n\n/**\n * Pads the value based on size and type\n * returns a string of the padded value\n * @param type - the input to pad\n * @returns = the padded value\n */\nconst solidityPack = (type: string, val: EncodingTypes): string => {\n\tconst value = val.toString();\n\tif (type === 'string') {\n\t\tif (typeof val === 'string') return utf8ToHex(val);\n\t\tthrow new InvalidStringError(val);\n\t}\n\tif (type === 'bool' || type === 'boolean') {\n\t\tif (typeof val === 'boolean') return val ? '01' : '00';\n\t\tthrow new InvalidBooleanError(val);\n\t}\n\n\tif (type === 'address') {\n\t\tif (!isAddress(value)) {\n\t\t\tthrow new InvalidAddressError(value);\n\t\t}\n\t\treturn value;\n\t}\n\tconst name = elementaryName(type);\n\tif (type.startsWith('uint')) {\n\t\tconst size = parseTypeN(name, 'uint'.length);\n\n\t\tif (size % 8 || size < 8 || size > 256) {\n\t\t\tthrow new InvalidSizeError(value);\n\t\t}\n\t\tconst num = toNumber(value);\n\t\tif (bitLength(num) > size) {\n\t\t\tthrow new InvalidLargeValueError(value);\n\t\t}\n\t\tif (num < BigInt(0)) {\n\t\t\tthrow new InvalidUnsignedIntegerError(value);\n\t\t}\n\n\t\treturn size ? leftPad(num.toString(16), (size / 8) * 2) : num.toString(16);\n\t}\n\n\tif (type.startsWith('int')) {\n\t\tconst size = parseTypeN(name, 'int'.length);\n\t\tif (size % 8 || size < 8 || size > 256) {\n\t\t\tthrow new InvalidSizeError(type);\n\t\t}\n\n\t\tconst num = toNumber(value);\n\t\tif (bitLength(num) > size) {\n\t\t\tthrow new InvalidLargeValueError(value);\n\t\t}\n\t\tif (num < BigInt(0)) {\n\t\t\treturn toTwosComplement(num.toString(), (size / 8) * 2);\n\t\t}\n\t\treturn size ? leftPad(num.toString(16), size / 4) : num.toString(16);\n\t}\n\n\tif (name === 'bytes') {\n\t\tif (value.replace(/^0x/i, '').length % 2 !== 0) {\n\t\t\tthrow new InvalidBytesError(value);\n\t\t}\n\t\treturn value;\n\t}\n\n\tif (type.startsWith('bytes')) {\n\t\tif (value.replace(/^0x/i, '').length % 2 !== 0) {\n\t\t\tthrow new InvalidBytesError(value);\n\t\t}\n\n\t\tconst size = parseTypeN(type, 'bytes'.length);\n\n\t\tif (!size || size < 1 || size > 64 || size < value.replace(/^0x/i, '').length / 2) {\n\t\t\tthrow new InvalidBytesError(value);\n\t\t}\n\n\t\treturn rightPad(value, size * 2);\n\t}\n\treturn '';\n};\n\n/**\n * returns a string of the tightly packed value given based on the type\n * @param arg - the input to return the tightly packed value\n * @returns - the tightly packed value\n */\nexport const processSolidityEncodePackedArgs = (arg: Sha3Input): string => {\n\tconst [type, val] = getType(arg);\n\n\t// array case\n\tif (Array.isArray(val)) {\n\t\t// go through each element of the array and use map function to create new hexarg list\n\t\tconst hexArg = val.map((v: Numbers | boolean) => solidityPack(type, v).replace('0x', ''));\n\t\treturn hexArg.join('');\n\t}\n\n\tconst hexArg = solidityPack(type, val);\n\treturn hexArg.replace('0x', '');\n};\n\n/**\n * Encode packed arguments to a hexstring\n */\nexport const encodePacked = (...values: Sha3Input[]): string => {\n\tconst hexArgs = values.map(processSolidityEncodePackedArgs);\n\treturn `0x${hexArgs.join('').toLowerCase()}`;\n};\n\n/**\n * Will tightly pack values given in the same way solidity would then hash.\n * returns a hash string, or null if input is empty\n * @param values - the input to return the tightly packed values\n * @returns - the keccack246 of the tightly packed values\n *\n * @example\n * ```ts\n * console.log(web3.utils.soliditySha3({ type: \"string\", value: \"31323334\" }));\n * > 0xf15f8da2ad27e486d632dc37d24912f634398918d6f9913a0a0ff84e388be62b\n * ```\n */\nexport const soliditySha3 = (...values: Sha3Input[]): string | undefined =>\n\tsha3(encodePacked(...values));\n\n/**\n * Will tightly pack values given in the same way solidity would then hash.\n * returns a hash string, if input is empty will return `0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470`\n * @param values - the input to return the tightly packed values\n * @returns - the keccack246 of the tightly packed values\n *\n * @example\n * ```ts\n * console.log(web3.utils.soliditySha3Raw({ type: \"string\", value: \"helloworld\" }))\n * > 0xfa26db7ca85ead399216e7c6316bc50ed24393c3122b582735e7f3b0f91b93f0\n * ```\n */\nexport const soliditySha3Raw = (...values: TypedObject[] | TypedObjectAbbreviated[]): string =>\n\tsha3Raw(encodePacked(...values));\n\n/**\n * Get slot number for storage long string in contract. Basically for getStorage method\n * returns slotNumber where will data placed\n * @param mainSlotNumber - the slot number where will be stored hash of long string\n * @returns - the slot number where will be stored long string\n */\nexport const getStorageSlotNumForLongString = (mainSlotNumber: number | string) =>\n\tsha3(\n\t\t`0x${(typeof mainSlotNumber === 'number'\n\t\t\t? mainSlotNumber.toString()\n\t\t\t: mainSlotNumber\n\t\t).padStart(64, '0')}`,\n\t);\n","/*\nThis file is part of web3.js.\n\nweb3.js is free software: you can redistribute it and/or modify\nit under the terms of the GNU Lesser General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nweb3.js is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU Lesser General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public License\nalong with web3.js. If not, see .\n*/\n\n/**\n * @module Utils\n */\n\nimport { getRandomBytesSync } from 'ethereum-cryptography/random.js';\nimport { bytesToHex } from './converters.js';\n\n/**\n * Returns a random byte array by the given bytes size\n * @param size - The size of the random byte array returned\n * @returns - random byte array\n *\n * @example\n * ```ts\n * console.log(web3.utils.randomBytes(32));\n * > Uint8Array(32) [\n * 93, 172, 226, 32, 33, 176, 156, 156,\n * 182, 30, 240, 2, 69, 96, 174, 197,\n * 33, 136, 194, 241, 197, 156, 110, 111,\n * 66, 87, 17, 88, 67, 48, 245, 183\n * ]\n * ```\n */\nexport const randomBytes = (size: number): Uint8Array => getRandomBytesSync(size);\n\n/**\n * Returns a random hex string by the given bytes size\n * @param byteSize - The size of the random hex string returned\n * @returns - random hex string\n *\n * ```ts\n * console.log(web3.utils.randomHex(32));\n * > 0x139f5b88b72a25eab053d3b57fe1f8a9dbc62a526b1cb1774d0d7db1c3e7ce9e\n * ```\n */\nexport const randomHex = (byteSize: number): string => bytesToHex(randomBytes(byteSize));\n","import { randomBytes } from \"@noble/hashes/utils\";\nexport function getRandomBytesSync(bytes) {\n return randomBytes(bytes);\n}\nexport async function getRandomBytes(bytes) {\n return randomBytes(bytes);\n}\n","/*\nThis file is part of web3.js.\n\nweb3.js is free software: you can redistribute it and/or modify\nit under the terms of the GNU Lesser General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nweb3.js is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU Lesser General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public License\nalong with web3.js. If not, see .\n*/\n\nimport { isNullish } from 'web3-validator';\n\nexport type Timer = ReturnType;\nexport type Timeout = ReturnType;\n\n/**\n * An alternative to the node function `isPromise` that exists in `util/types` because it is not available on the browser.\n * @param object - to check if it is a `Promise`\n * @returns `true` if it is an `object` or a `function` that has a `then` function. And returns `false` otherwise.\n */\nexport function isPromise(object: unknown): boolean {\n\treturn (\n\t\t(typeof object === 'object' || typeof object === 'function') &&\n\t\t// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n\t\ttypeof (object as { then: unknown }).then === 'function'\n\t);\n}\n\nexport type AsyncFunction = (...args: K[]) => Promise;\n\nexport function waitWithTimeout(\n\tawaitable: Promise | AsyncFunction,\n\ttimeout: number,\n\terror: Error,\n): Promise;\nexport function waitWithTimeout(\n\tawaitable: Promise | AsyncFunction,\n\ttimeout: number,\n): Promise;\n\n/**\n * Wait for a promise but interrupt it if it did not resolve within a given timeout.\n * If the timeout reached, before the promise code resolve, either throw an error if an error object was provided, or return `undefined`.\n * @param awaitable - The promise or function to wait for.\n * @param timeout - The timeout in milliseconds.\n * @param error - (Optional) The error to throw if the timeout reached.\n */\nexport async function waitWithTimeout(\n\tawaitable: Promise | AsyncFunction,\n\ttimeout: number,\n\terror?: Error,\n): Promise {\n\tlet timeoutId: Timeout | undefined;\n\tconst result = await Promise.race([\n\t\tawaitable instanceof Promise ? awaitable : awaitable(),\n\t\tnew Promise((resolve, reject) => {\n\t\t\ttimeoutId = setTimeout(() => (error ? reject(error) : resolve(undefined)), timeout);\n\t\t}),\n\t]);\n\tif (timeoutId) {\n\t\tclearTimeout(timeoutId);\n\t}\n\tif (result instanceof Error) {\n\t\tthrow result;\n\t}\n\treturn result;\n}\n\n/**\n * Repeatedly calls an async function with a given interval until the result of the function is defined (not undefined or null),\n * or until a timeout is reached. It returns promise and intervalId.\n * @param func - The function to call.\n * @param interval - The interval in milliseconds.\n */\nexport function pollTillDefinedAndReturnIntervalId(\n\tfunc: AsyncFunction,\n\tinterval: number,\n): [Promise>, Timer] {\n\tlet intervalId: Timer | undefined;\n\tconst polledRes = new Promise>((resolve, reject) => {\n\t\tintervalId = setInterval(\n\t\t\t(function intervalCallbackFunc() {\n\t\t\t\t(async () => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst res = await waitWithTimeout(func, interval);\n\n\t\t\t\t\t\tif (!isNullish(res)) {\n\t\t\t\t\t\t\tclearInterval(intervalId);\n\t\t\t\t\t\t\tresolve(res as unknown as Exclude);\n\t\t\t\t\t\t}\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tclearInterval(intervalId);\n\t\t\t\t\t\treject(error);\n\t\t\t\t\t}\n\t\t\t\t})() as unknown;\n\t\t\t\treturn intervalCallbackFunc;\n\t\t\t})(), // this will immediate invoke first call\n\t\t\tinterval,\n\t\t);\n\t});\n\n\treturn [polledRes as unknown as Promise>, intervalId!];\n}\n\n/**\n * Repeatedly calls an async function with a given interval until the result of the function is defined (not undefined or null),\n * or until a timeout is reached.\n * pollTillDefinedAndReturnIntervalId() function should be used instead of pollTillDefined if you need IntervalId in result.\n * This function will be deprecated in next major release so use pollTillDefinedAndReturnIntervalId().\n * @param func - The function to call.\n * @param interval - The interval in milliseconds.\n */\nexport async function pollTillDefined(\n\tfunc: AsyncFunction,\n\tinterval: number,\n): Promise> {\n\treturn pollTillDefinedAndReturnIntervalId(func, interval)[0];\n}\n/**\n * Enforce a timeout on a promise, so that it can be rejected if it takes too long to complete\n * @param timeout - The timeout to enforced in milliseconds.\n * @param error - The error to throw if the timeout is reached.\n * @returns A tuple of the timeout id and the promise that will be rejected if the timeout is reached.\n *\n * @example\n * ```ts\n * const [timerId, promise] = web3.utils.rejectIfTimeout(100, new Error('time out'));\n * ```\n */\nexport function rejectIfTimeout(timeout: number, error: Error): [Timer, Promise] {\n\tlet timeoutId: Timer | undefined;\n\tconst rejectOnTimeout = new Promise((_, reject) => {\n\t\ttimeoutId = setTimeout(() => {\n\t\t\treject(error);\n\t\t}, timeout);\n\t});\n\treturn [timeoutId!, rejectOnTimeout];\n}\n/**\n * Sets an interval that repeatedly executes the given cond function with the specified interval between each call.\n * If the condition is met, the interval is cleared and a Promise that rejects with the returned value is returned.\n * @param cond - The function/condition to call.\n * @param interval - The interval in milliseconds.\n * @returns - an array with the interval ID and the Promise.\n */\nexport function rejectIfConditionAtInterval(\n\tcond: AsyncFunction,\n\tinterval: number,\n): [Timer, Promise] {\n\tlet intervalId: Timer | undefined;\n\tconst rejectIfCondition = new Promise((_, reject) => {\n\t\tintervalId = setInterval(() => {\n\t\t\t(async () => {\n\t\t\t\tconst error = await cond();\n\t\t\t\tif (error) {\n\t\t\t\t\tclearInterval(intervalId);\n\t\t\t\t\treject(error);\n\t\t\t\t}\n\t\t\t})() as unknown;\n\t\t}, interval);\n\t});\n\treturn [intervalId!, rejectIfCondition];\n}\n","/*\nThis file is part of web3.js.\n\nweb3.js is free software: you can redistribute it and/or modify\nit under the terms of the GNU Lesser General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nweb3.js is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU Lesser General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public License\nalong with web3.js. If not, see .\n*/\n\n/**\n * @module Utils\n */\n\nimport { bytesToHex } from './converters.js';\nimport { randomBytes } from './random.js';\n\n/**\n * Generate a version 4 (random) uuid\n * https://github.com/uuidjs/uuid/blob/main/src/v4.js#L5\n * @returns - A version 4 uuid of the form xxxxxxxx-xxxx-4xxx-xxxx-xxxxxxxxxxxx\n * @example\n * ```ts\n * console.log(web3.utils.uuidV4());\n * > \"1b9d6bcd-bbfd-4b2d-9b5d-ab8dfbbd4bed\"\n * ```\n */\nexport const uuidV4 = (): string => {\n\tconst bytes = randomBytes(16);\n\n\t// https://github.com/ethers-io/ethers.js/blob/ce8f1e4015c0f27bf178238770b1325136e3351a/packages/json-wallets/src.ts/utils.ts#L54\n\t// Section: 4.1.3:\n\t// - time_hi_and_version[12:16] = 0b0100\n\t/* eslint-disable-next-line */\n\tbytes[6] = (bytes[6] & 0x0f) | 0x40;\n\n\t// Section 4.4\n\t// - clock_seq_hi_and_reserved[6] = 0b0\n\t// - clock_seq_hi_and_reserved[7] = 0b1\n\t/* eslint-disable-next-line */\n\tbytes[8] = (bytes[8] & 0x3f) | 0x80;\n\n\tconst hexString = bytesToHex(bytes);\n\n\treturn [\n\t\thexString.substring(2, 10),\n\t\thexString.substring(10, 14),\n\t\thexString.substring(14, 18),\n\t\thexString.substring(18, 22),\n\t\thexString.substring(22, 34),\n\t].join('-');\n};\n","/*\nThis file is part of web3.js.\n\nweb3.js is free software: you can redistribute it and/or modify\nit under the terms of the GNU Lesser General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nweb3.js is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU Lesser General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public License\nalong with web3.js. If not, see .\n*/\n\nimport { isNullish } from 'web3-validator';\nimport {\n\tJsonRpcPayload,\n\tJsonRpcResponse,\n\tJsonRpcResponseWithResult,\n\tJsonRpcResponseWithError,\n\tJsonRpcOptionalRequest,\n\tJsonRpcBatchRequest,\n\tJsonRpcNotification,\n\tJsonRpcRequest,\n\tJsonRpcBatchResponse,\n\tJsonRpcSubscriptionResult,\n} from 'web3-types';\nimport { rpcErrorsMap } from 'web3-errors';\nimport { uuidV4 } from './uuid.js';\n\n// check if code is a valid rpc server error code\nexport const isResponseRpcError = (rpcError: JsonRpcResponseWithError) => {\n\tconst errorCode = rpcError.error.code;\n\treturn rpcErrorsMap.has(errorCode) || (errorCode >= -32099 && errorCode <= -32000);\n};\n\nexport const isResponseWithResult = (\n\tresponse: JsonRpcResponse,\n): response is JsonRpcResponseWithResult =>\n\t!Array.isArray(response) &&\n\t!!response &&\n\tresponse.jsonrpc === '2.0' &&\n\t// JSON RPC consider \"null\" as valid response\n\t'result' in response &&\n\tisNullish(response.error) &&\n\t(typeof response.id === 'number' || typeof response.id === 'string');\n\n// To avoid circular package dependency, copied to code here. If you update this please update same function in `response_errors.ts`\nexport const isResponseWithError = (\n\tresponse: JsonRpcResponse,\n): response is JsonRpcResponseWithError =>\n\t!Array.isArray(response) &&\n\tresponse.jsonrpc === '2.0' &&\n\t!!response &&\n\tisNullish(response.result) &&\n\t// JSON RPC consider \"null\" as valid response\n\t'error' in response &&\n\t(typeof response.id === 'number' || typeof response.id === 'string');\n\nexport const isResponseWithNotification = (\n\tresponse: JsonRpcNotification | JsonRpcSubscriptionResult,\n): response is JsonRpcNotification =>\n\t!Array.isArray(response) &&\n\t!!response &&\n\tresponse.jsonrpc === '2.0' &&\n\t!isNullish(response.params) &&\n\t!isNullish(response.method);\n\nexport const isSubscriptionResult = (\n\tresponse: JsonRpcNotification | JsonRpcSubscriptionResult,\n): response is JsonRpcSubscriptionResult =>\n\t!Array.isArray(response) &&\n\t!!response &&\n\tresponse.jsonrpc === '2.0' &&\n\t'id' in response &&\n\t// JSON RPC consider \"null\" as valid response\n\t'result' in response;\n\nexport const validateResponse = (\n\tresponse: JsonRpcResponse,\n): boolean => isResponseWithResult(response) || isResponseWithError(response);\n\nexport const isValidResponse = (\n\tresponse: JsonRpcResponse,\n): boolean =>\n\tArray.isArray(response) ? response.every(validateResponse) : validateResponse(response);\n\nexport const isBatchResponse = (\n\tresponse: JsonRpcResponse,\n): response is JsonRpcBatchResponse =>\n\tArray.isArray(response) && response.length > 0 && isValidResponse(response);\n\n// internal optional variable to increment and use for the jsonrpc `id`\nlet requestIdSeed: number | undefined;\n\n/**\n * Optionally use to make the jsonrpc `id` start from a specific number.\n * Without calling this function, the `id` will be filled with a Uuid.\n * But after this being called with a number, the `id` will be a number starting from the provided `start` variable.\n * However, if `undefined` was passed to this function, the `id` will be a Uuid again.\n * @param start - a number to start incrementing from.\n * \tOr `undefined` to use a new Uuid (this is the default behavior)\n */\nexport const setRequestIdStart = (start: number | undefined) => {\n\trequestIdSeed = start;\n};\n\nexport const toPayload = (\n\trequest: JsonRpcOptionalRequest,\n): JsonRpcPayload => {\n\tif (typeof requestIdSeed !== 'undefined') {\n\t\trequestIdSeed += 1;\n\t}\n\treturn {\n\t\tjsonrpc: request.jsonrpc ?? '2.0',\n\t\tid: request.id ?? requestIdSeed ?? uuidV4(),\n\t\tmethod: request.method,\n\t\tparams: request.params ?? undefined,\n\t};\n};\n\nexport const toBatchPayload = (requests: JsonRpcOptionalRequest[]): JsonRpcBatchRequest =>\n\trequests.map(request => toPayload(request)) as JsonRpcBatchRequest;\n\nexport const isBatchRequest = (\n\trequest: JsonRpcBatchRequest | JsonRpcRequest | JsonRpcOptionalRequest,\n): request is JsonRpcBatchRequest => Array.isArray(request) && request.length > 0;\n","/*\nThis file is part of web3.js.\n\nweb3.js is free software: you can redistribute it and/or modify\nit under the terms of the GNU Lesser General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nweb3.js is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU Lesser General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public License\nalong with web3.js. If not, see .\n*/\n\nimport { OperationTimeoutError } from 'web3-errors';\nimport { Web3DeferredPromiseInterface } from 'web3-types';\nimport { Timeout } from './promise_helpers.js';\n\n/**\n * The class is a simple implementation of a deferred promise with optional timeout functionality,\n * which can be useful when dealing with asynchronous tasks.\n *\n */\nexport class Web3DeferredPromise implements Promise, Web3DeferredPromiseInterface {\n\t// public tag to treat object as promise by different libs\n\t// eslint-disable-next-line @typescript-eslint/prefer-as-const\n\tpublic [Symbol.toStringTag]: 'Promise' = 'Promise';\n\n\tprivate readonly _promise: Promise;\n\tprivate _resolve!: (value: T | PromiseLike) => void;\n\tprivate _reject!: (reason?: unknown) => void;\n\tprivate _state: 'pending' | 'fulfilled' | 'rejected' = 'pending';\n\tprivate _timeoutId?: Timeout;\n\tprivate readonly _timeoutInterval?: number;\n\tprivate readonly _timeoutMessage: string;\n\n\t/**\n\t *\n\t * @param timeout - (optional) The timeout in milliseconds.\n\t * @param eagerStart - (optional) If true, the timer starts as soon as the promise is created.\n\t * @param timeoutMessage - (optional) The message to include in the timeout erro that is thrown when the promise times out.\n\t */\n\tpublic constructor(\n\t\t{\n\t\t\ttimeout,\n\t\t\teagerStart,\n\t\t\ttimeoutMessage,\n\t\t}: { timeout: number; eagerStart: boolean; timeoutMessage: string } = {\n\t\t\ttimeout: 0,\n\t\t\teagerStart: false,\n\t\t\ttimeoutMessage: 'DeferredPromise timed out',\n\t\t},\n\t) {\n\t\tthis._promise = new Promise((resolve, reject) => {\n\t\t\tthis._resolve = resolve;\n\t\t\tthis._reject = reject;\n\t\t});\n\n\t\tthis._timeoutMessage = timeoutMessage;\n\t\tthis._timeoutInterval = timeout;\n\n\t\tif (eagerStart) {\n\t\t\tthis.startTimer();\n\t\t}\n\t}\n\t/**\n\t * Returns the current state of the promise.\n\t * @returns 'pending' | 'fulfilled' | 'rejected'\n\t */\n\tpublic get state(): 'pending' | 'fulfilled' | 'rejected' {\n\t\treturn this._state;\n\t}\n\t/**\n\t *\n\t * @param onfulfilled - (optional) The callback to execute when the promise is fulfilled.\n\t * @param onrejected - (optional) The callback to execute when the promise is rejected.\n\t * @returns\n\t */\n\tpublic async then