{"version":3,"sources":["../node_modules/viem/errors/version.ts","../node_modules/viem/errors/utils.ts","../node_modules/viem/errors/base.ts","../node_modules/viem/errors/encoding.ts","../node_modules/viem/utils/data/isHex.ts","../node_modules/viem/utils/data/size.ts","../node_modules/viem/utils/data/trim.ts","../node_modules/viem/errors/data.ts","../node_modules/viem/utils/data/pad.ts","../node_modules/viem/utils/encoding/toHex.ts","../node_modules/viem/utils/encoding/toBytes.ts","../node_modules/viem/utils/encoding/fromHex.ts","../node_modules/viem/utils/formatters/transactionRequest.ts","../node_modules/viem/errors/address.ts","../node_modules/viem/errors/chain.ts","../node_modules/viem/constants/unit.ts","../node_modules/viem/utils/unit/formatUnits.ts","../node_modules/viem/utils/unit/formatGwei.ts","../node_modules/viem/errors/node.ts","../node_modules/viem/utils/address/isAddress.ts","../node_modules/viem/utils/data/concat.ts","../node_modules/abitype/src/version.ts","../node_modules/abitype/src/errors.ts","../node_modules/abitype/src/regex.ts","../node_modules/abitype/src/human-readable/formatAbiParameter.ts","../node_modules/abitype/src/human-readable/formatAbiParameters.ts","../node_modules/abitype/src/human-readable/formatAbiItem.ts","../node_modules/abitype/src/human-readable/runtime/signatures.ts","../node_modules/abitype/src/human-readable/errors/abiItem.ts","../node_modules/abitype/src/human-readable/errors/abiParameter.ts","../node_modules/abitype/src/human-readable/errors/signature.ts","../node_modules/abitype/src/human-readable/errors/struct.ts","../node_modules/abitype/src/human-readable/errors/splitParameters.ts","../node_modules/abitype/src/human-readable/runtime/cache.ts","../node_modules/abitype/src/human-readable/runtime/utils.ts","../node_modules/abitype/src/human-readable/runtime/structs.ts","../node_modules/abitype/src/human-readable/parseAbi.ts","../node_modules/abitype/src/index.ts","../node_modules/viem/utils/abi/formatAbiItem.ts","../node_modules/viem/errors/abi.ts","../node_modules/viem/utils/hash/normalizeSignature.ts","../node_modules/viem/utils/hash/getFunctionSignature.ts","../node_modules/viem/utils/hash/getEventSignature.ts","../node_modules/@noble/hashes/src/_assert.ts","../node_modules/@noble/hashes/src/_u64.ts","../node_modules/@noble/hashes/src/cryptoNode.ts","../node_modules/@noble/hashes/src/utils.ts","../node_modules/@noble/hashes/src/sha3.ts","../node_modules/viem/utils/hash/keccak256.ts","../node_modules/viem/utils/hash/getEventSelector.ts","../node_modules/viem/utils/data/slice.ts","../node_modules/viem/utils/abi/encodeAbiParameters.ts","../node_modules/viem/utils/hash/getFunctionSelector.ts","../node_modules/viem/utils/abi/getAbiItem.ts","../node_modules/viem/accounts/utils/parseAccount.ts","../node_modules/viem/utils/abi/encodeFunctionData.ts","../node_modules/viem/constants/solidity.ts","../node_modules/viem/utils/address/getAddress.ts","../node_modules/viem/utils/abi/decodeAbiParameters.ts","../node_modules/viem/utils/abi/decodeErrorResult.ts","../node_modules/viem/utils/stringify.ts","../node_modules/viem/utils/abi/formatAbiItemWithArgs.ts","../node_modules/viem/utils/unit/formatEther.ts","../node_modules/viem/errors/transaction.ts","../node_modules/viem/errors/contract.ts","../node_modules/viem/errors/request.ts","../node_modules/viem/errors/rpc.ts","../node_modules/viem/utils/errors/getNodeError.ts","../node_modules/viem/utils/formatters/extract.ts","../node_modules/viem/utils/transaction/assertRequest.ts","../node_modules/viem/utils/abi/decodeFunctionResult.ts","../node_modules/viem/constants/abis.ts","../node_modules/viem/constants/contract.ts","../node_modules/viem/utils/chain/getChainContractAddress.ts","../node_modules/viem/utils/errors/getCallError.ts","../node_modules/viem/utils/promise/createBatchScheduler.ts","../node_modules/viem/errors/ccip.ts","../node_modules/viem/utils/address/isAddressEqual.ts","../node_modules/viem/utils/ccip.ts","../node_modules/viem/actions/public/call.ts","../node_modules/@noble/hashes/src/_sha2.ts","../node_modules/@noble/hashes/src/sha256.ts","../node_modules/@noble/curves/src/abstract/utils.ts","../node_modules/@noble/curves/src/abstract/modular.ts","../node_modules/@noble/curves/src/abstract/curve.ts","../node_modules/@noble/curves/src/abstract/weierstrass.ts","../node_modules/@noble/hashes/src/hmac.ts","../node_modules/@noble/curves/src/_shortw_utils.ts","../node_modules/@noble/curves/src/secp256k1.ts","../node_modules/viem/utils/chain/defineChain.ts","../node_modules/viem/utils/formatters/transaction.ts","../node_modules/viem/utils/formatters/block.ts","../node_modules/viem/utils/formatters/transactionReceipt.ts","../node_modules/viem/utils/formatters/log.ts","../node_modules/viem/index.ts","../node_modules/viem/utils/getAction.ts","../node_modules/viem/utils/abi/encodeEventTopics.ts","../node_modules/viem/errors/log.ts","../node_modules/viem/actions/public/createContractEventFilter.ts","../node_modules/viem/utils/filters/createFilterRequestScope.ts","../node_modules/viem/actions/public/estimateContractGas.ts","../node_modules/viem/utils/errors/getContractError.ts","../node_modules/viem/actions/public/estimateGas.ts","../node_modules/viem/errors/account.ts","../node_modules/viem/errors/estimateGas.ts","../node_modules/viem/utils/errors/getEstimateGasError.ts","../node_modules/viem/actions/wallet/prepareTransactionRequest.ts","../node_modules/viem/errors/fee.ts","../node_modules/viem/actions/public/estimateMaxPriorityFeePerGas.ts","../node_modules/viem/errors/block.ts","../node_modules/viem/actions/public/getBlock.ts","../node_modules/viem/actions/public/getGasPrice.ts","../node_modules/viem/actions/public/estimateFeesPerGas.ts","../node_modules/viem/actions/public/getTransactionCount.ts","../node_modules/viem/utils/transaction/getTransactionType.ts","../node_modules/viem/actions/public/getContractEvents.ts","../node_modules/viem/actions/public/getLogs.ts","../node_modules/viem/utils/abi/decodeEventLog.ts","../node_modules/viem/actions/public/readContract.ts","../node_modules/viem/actions/public/simulateContract.ts","../node_modules/viem/utils/observe.ts","../node_modules/viem/utils/wait.ts","../node_modules/viem/utils/poll.ts","../node_modules/viem/actions/public/watchContractEvent.ts","../node_modules/viem/utils/promise/withCache.ts","../node_modules/viem/actions/public/getBlockNumber.ts","../node_modules/viem/actions/public/getFilterChanges.ts","../node_modules/viem/actions/public/uninstallFilter.ts","../node_modules/viem/actions/wallet/writeContract.ts","../node_modules/viem/actions/wallet/sendTransaction.ts","../node_modules/viem/utils/chain/assertCurrentChain.ts","../node_modules/viem/utils/errors/getTransactionError.ts","../node_modules/viem/actions/public/getChainId.ts","../node_modules/viem/actions/wallet/sendRawTransaction.ts","../node_modules/viem/actions/wallet/addChain.ts","../node_modules/viem/utils/accounts.ts","../node_modules/viem/accounts/utils/publicKeyToAddress.ts","../node_modules/viem/utils/uid.ts","../node_modules/viem/clients/createClient.ts","../node_modules/viem/utils/buildRequest.ts","../node_modules/viem/utils/promise/withRetry.ts","../node_modules/viem/clients/transports/createTransport.ts","../node_modules/viem/clients/transports/http.ts","../node_modules/viem/errors/transport.ts","../node_modules/viem/utils/rpc.ts","../node_modules/viem/utils/promise/withTimeout.ts","../node_modules/viem/actions/ens/getEnsAddress.ts","../node_modules/viem/utils/ens/errors.ts","../node_modules/viem/utils/ens/namehash.ts","../node_modules/viem/utils/ens/encodedLabelToLabelhash.ts","../node_modules/viem/utils/ens/packetToBytes.ts","../node_modules/viem/utils/ens/encodeLabelhash.ts","../node_modules/viem/utils/ens/labelhash.ts","../node_modules/viem/errors/ens.ts","../node_modules/viem/utils/ens/avatar/utils.ts","../node_modules/viem/utils/ens/avatar/parseAvatarRecord.ts","../node_modules/viem/actions/ens/getEnsText.ts","../node_modules/viem/actions/ens/getEnsAvatar.ts","../node_modules/viem/actions/ens/getEnsName.ts","../node_modules/viem/actions/ens/getEnsResolver.ts","../node_modules/viem/clients/decorators/public.ts","../node_modules/viem/actions/public/createBlockFilter.ts","../node_modules/viem/actions/public/createEventFilter.ts","../node_modules/viem/actions/public/createPendingTransactionFilter.ts","../node_modules/viem/actions/public/getBalance.ts","../node_modules/viem/actions/public/getBlockTransactionCount.ts","../node_modules/viem/actions/public/getBytecode.ts","../node_modules/viem/actions/public/getFeeHistory.ts","../node_modules/viem/utils/formatters/feeHistory.ts","../node_modules/viem/actions/public/getFilterLogs.ts","../node_modules/viem/actions/public/getProof.ts","../node_modules/viem/utils/regex.ts","../node_modules/viem/utils/typedData.ts","../node_modules/viem/utils/signature/hashTypedData.ts","../node_modules/viem/utils/abi/encodeDeployData.ts","../node_modules/viem/utils/abi/encodePacked.ts","../node_modules/viem/utils/index.ts","../node_modules/viem/errors/cursor.ts","../node_modules/viem/utils/cursor.ts","../node_modules/viem/constants/strings.ts","../node_modules/viem/utils/signature/hashMessage.ts","../node_modules/viem/utils/transaction/assertTransaction.ts","../node_modules/viem/utils/transaction/serializeTransaction.ts","../node_modules/viem/utils/transaction/serializeAccessList.ts","../node_modules/viem/utils/formatters/proof.ts","../node_modules/viem/actions/public/getStorageAt.ts","../node_modules/viem/actions/public/getTransaction.ts","../node_modules/viem/actions/public/getTransactionConfirmations.ts","../node_modules/viem/actions/public/getTransactionReceipt.ts","../node_modules/viem/actions/public/multicall.ts","../node_modules/viem/actions/public/verifyHash.ts","../node_modules/viem/constants/contracts.ts","../node_modules/viem/utils/data/isBytesEqual.ts","../node_modules/viem/actions/public/verifyMessage.ts","../node_modules/viem/actions/public/verifyTypedData.ts","../node_modules/viem/actions/public/waitForTransactionReceipt.ts","../node_modules/viem/actions/public/watchBlockNumber.ts","../node_modules/viem/actions/public/watchBlocks.ts","../node_modules/viem/actions/public/watchEvent.ts","../node_modules/viem/actions/public/watchPendingTransactions.ts","../node_modules/viem/clients/createPublicClient.ts","../node_modules/viem/actions/wallet/deployContract.ts","../node_modules/viem/actions/wallet/getAddresses.ts","../node_modules/viem/actions/wallet/getPermissions.ts","../node_modules/viem/actions/wallet/requestAddresses.ts","../node_modules/viem/actions/wallet/requestPermissions.ts","../node_modules/viem/actions/wallet/signMessage.ts","../node_modules/viem/actions/wallet/signTransaction.ts","../node_modules/viem/actions/wallet/signTypedData.ts","../node_modules/viem/actions/wallet/switchChain.ts","../node_modules/viem/actions/wallet/watchAsset.ts","../node_modules/viem/clients/decorators/wallet.ts","../node_modules/viem/clients/createWalletClient.ts","../node_modules/viem/utils/signature/signatureToHex.ts","../node_modules/viem/utils/encoding/toRlp.ts","../node_modules/viem/chains/definitions/mainnet.ts","../src/support/currencies.ts","../node_modules/@scure/bip39/src/wordlists/czech.ts","../node_modules/@scure/bip39/src/wordlists/english.ts","../node_modules/@scure/bip39/src/wordlists/french.ts","../node_modules/@scure/bip39/src/wordlists/italian.ts","../node_modules/@scure/bip39/src/wordlists/japanese.ts","../node_modules/@scure/bip39/src/wordlists/korean.ts","../node_modules/@scure/bip39/src/wordlists/simplified-chinese.ts","../node_modules/@scure/bip39/src/wordlists/spanish.ts","../node_modules/@scure/bip39/src/wordlists/traditional-chinese.ts","../node_modules/viem/accounts/generatePrivateKey.ts","../node_modules/viem/accounts/privateKeyToAccount.ts","../node_modules/viem/accounts/toAccount.ts","../node_modules/viem/accounts/utils/sign.ts","../node_modules/viem/accounts/utils/signMessage.ts","../node_modules/viem/accounts/utils/signTransaction.ts","../node_modules/viem/accounts/utils/signTypedData.ts","../src/arcade/ArcadeClient.ts","../src/types.ts","../src/support/CollectionRegistry.ts","../src/helpers.ts","../src/arcade/support/mappers.ts","../src/arcade/api/offers.ts","../src/arcade/api/loans.ts","../src/nftfi/NFTfiClient.ts","../src/errors.ts","../src/nftfi/support/mappers.ts","../src/nftfi/api/offers.ts","../src/nftfi/api/loans.ts","../src/gondi/GondiClient.ts","../src/gondi/config.ts","../src/gondi/api/loans.ts","../src/gondi/api/offers.ts","../src/gondi/support/mappers.ts","../src/config.ts","../src/blur/GhostApi.ts","../src/blur/support/mappers.ts","../src/blur/BlurClient.ts","../src/deepnftvalue/DeepNftValueClient.ts","../src/reservoir/ReservoirClient.ts","../src/support/PortfolioClient.ts","../src/support/loaner.ts"],"names":["docsPath","size","bytes","index","encoder","version","init_version","BaseError","init_utils","formatAbiItem","init_formatAbiItem","hash","toBytes","concatBytes","pad","length","consumed","value","formatted","init_contract","cause","id","wait","args","split","init_ccip","data","offchainLookup","offchainLookupSignature","isLE","_32n","buffer","bytesToHex","hexToBytes","hexToNumber","utf8ToBytes","u8a","hexes","_0n","_1n","gen","_2n","number","Fp","bitLen","Point","_3n","a","randomBytes","sign","r","s","_4n","slice","config","err","event","listeners","cleanup","poll","cacheKey","eventName","request","key","response","body","http","res","bytesRegex","integerRegex","struct","v","result","block","encode","wordlist","signMessage","signTransaction","signTypedData","LendingPlatform","LoanStatus","OfferType","axios","Offers","Loans","mapError","url"],"mappings":";;;;;;;;;;;AAAA,IAAa;AAAb;;;AAAO,IAAM,UAAU;;;;;ACEvB,IAIa,oBACA,QACA;AANb;;;;AAIO,IAAM,qBAAqB,CAAC,YAAqB;AACjD,IAAM,SAAS,CAAC,QAAgB;AAChC,IAAM,aAAa,MAAM,QAAQ,OAAO;;;;;AC8D/C,SAAS,KAAK,KAAc,IAA8B;AACxD,MAAI,KAAK,GAAG;AAAG,WAAO;AACtB,MAAI,OAAO,OAAO,QAAQ,YAAY,WAAW;AAC/C,WAAO,KAAK,IAAI,OAAO,EAAE;AAC3B,SAAO,KAAK,OAAO;AACrB;AA3EA,IAkBa;AAlBb;;;;AAkBM,IAAO,YAAP,MAAO,mBAAkB,MAAK;MASlC,YAAY,cAAsB,OAA4B,CAAA,GAAE;AAC9D,cAAK;AATP,eAAA,eAAA,MAAA,WAAA;;;;;;AACA,eAAA,eAAA,MAAA,YAAA;;;;;;AACA,eAAA,eAAA,MAAA,gBAAA;;;;;;AACA,eAAA,eAAA,MAAA,gBAAA;;;;;;AAES,eAAA,eAAA,MAAA,QAAA;;;;iBAAO;;AAChB,eAAA,eAAA,MAAA,WAAA;;;;iBAAU,WAAU;;AAKlB,cAAM,UACJ,KAAK,iBAAiB,aAClB,KAAK,MAAM,UACX,KAAK,OAAO,UACV,KAAK,MAAM,UACX,KAAK;AACb,cAAMA,YACJ,KAAK,iBAAiB,aAClB,KAAK,MAAM,YAAY,KAAK,WAC5B,KAAK;AAEX,aAAK,UAAU;UACb,gBAAgB;UAChB;UACA,GAAI,KAAK,eAAe,CAAC,GAAG,KAAK,cAAc,EAAE,IAAI,CAAA;UACrD,GAAIA,YACA;YACE,wBAAwBA,SAAQ,QAC9B,KAAK,WAAW,IAAI,KAAK,QAAQ,KAAK,EACxC;cAEF,CAAA;UACJ,GAAI,UAAU,CAAC,YAAY,OA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,YACzB;AAAA,UACF;AAAA,UACA;AAAA,QACF;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF","sourcesContent":["export const version = '1.21.3'\n","import type { Address } from 'abitype'\n\nimport { version } from './version.js'\n\nexport type ErrorType<name extends string = 'Error'> = Error & { name: name }\n\nexport const getContractAddress = (address: Address) => address\nexport const getUrl = (url: string) => url\nexport const getVersion = () => `viem@${version}`\n","import { getVersion } from './utils.js'\n\ntype BaseErrorParameters = {\n  docsPath?: string\n  docsSlug?: string\n  metaMessages?: string[]\n} & (\n  | {\n      cause?: never\n      details?: string\n    }\n  | {\n      cause: BaseError | Error\n      details?: never\n    }\n)\n\nexport type BaseErrorType = BaseError & { name: 'ViemError' }\nexport class BaseError extends Error {\n  details: string\n  docsPath?: string\n  metaMessages?: string[]\n  shortMessage: string\n\n  override name = 'ViemError'\n  version = getVersion()\n\n  constructor(shortMessage: string, args: BaseErrorParameters = {}) {\n    super()\n\n    const details =\n      args.cause instanceof BaseError\n        ? args.cause.details\n        : args.cause?.message\n          ? args.cause.message\n          : args.details!\n    const docsPath =\n      args.cause instanceof BaseError\n        ? args.cause.docsPath || args.docsPath\n        : args.docsPath\n\n    this.message = [\n      shortMessage || 'An error occurred.',\n      '',\n      ...(args.metaMessages ? [...args.metaMessages, ''] : []),\n      ...(docsPath\n        ? [\n            `Docs: https://viem.sh${docsPath}.html${\n              args.docsSlug ? `#${args.docsSlug}` : ''\n            }`,\n          ]\n        : []),\n      ...(details ? [`Details: ${details}`] : []),\n      `Version: ${this.version}`,\n    ].join('\\n')\n\n    if (args.cause) this.cause = args.cause\n    this.details = details\n    this.docsPath = docsPath\n    this.metaMessages = args.metaMessages\n    this.shortMessage = shortMessage\n  }\n\n  walk(): Error\n  walk(fn: (err: unknown) => boolean): Error | null\n  walk(fn?: any): any {\n    return walk(this, fn)\n  }\n}\n\nfunction walk(err: unknown, fn?: (err: unknown) => boolean): unknown {\n  if (fn?.(err)) return err\n  if (err && typeof err === 'object' && 'cause' in err)\n    return walk(err.cause, fn)\n  return fn ? null : err\n}\n","import type { ByteArray, Hex } from '../types/misc.js'\n\nimport { BaseError } from './base.js'\n\nexport type DataLengthTooLongErrorType = DataLengthTooLongError & {\n  name: 'DataLengthTooLongError'\n}\n/** @deprecated */\nexport class DataLengthTooLongError extends BaseError {\n  override name = 'DataLengthTooLongError'\n  constructor({ consumed, length }: { consumed: number; length: number }) {\n    super(\n      `Consumed bytes (${consumed}) is shorter than data length (${\n        length - 1\n      }).`,\n    )\n  }\n}\n\nexport type DataLengthTooShortErrorType = DataLengthTooShortError & {\n  name: 'DataLengthTooShortError'\n}\n/** @deprecated */\nexport class DataLengthTooShortError extends BaseError {\n  override name = 'DataLengthTooShortError'\n  constructor({ length, dataLength }: { length: number; dataLength: number }) {\n    super(\n      `Data length (${dataLength - 1}) is shorter than consumed bytes length (${\n        length - 1\n      }).`,\n    )\n  }\n}\n\nexport type IntegerOutOfRangeErrorType = IntegerOutOfRangeError & {\n  name: 'IntegerOutOfRangeError'\n}\nexport class IntegerOutOfRangeError extends BaseError {\n  override name = 'IntegerOutOfRangeError'\n  constructor({\n    max,\n    min,\n    signed,\n    size,\n    value,\n  }: {\n    max?: string\n    min: string\n    signed?: boolean\n    size?: number\n    value: string\n  }) {\n    super(\n      `Number \"${value}\" is not in safe ${\n        size ? `${size * 8}-bit ${signed ? 'signed' : 'unsigned'} ` : ''\n      }integer range ${max ? `(${min} to ${max})` : `(above ${min})`}`,\n    )\n  }\n}\n\nexport type InvalidBytesBooleanErrorType = InvalidBytesBooleanError & {\n  name: 'InvalidBytesBooleanError'\n}\nexport class InvalidBytesBooleanError extends BaseError {\n  override name = 'InvalidBytesBooleanError'\n  constructor(bytes: ByteArray) {\n    super(\n      `Bytes value \"${bytes}\" is not a valid boolean. The bytes array must contain a single byte of either a 0 or 1 value.`,\n    )\n  }\n}\n\nexport type InvalidHexBooleanErrorType = InvalidHexBooleanError & {\n  name: 'InvalidHexBooleanError'\n}\nexport class InvalidHexBooleanError extends BaseError {\n  override name = 'InvalidHexBooleanError'\n  constructor(hex: Hex) {\n    super(\n      `Hex value \"${hex}\" is not a valid boolean. The hex value must be \"0x0\" (false) or \"0x1\" (true).`,\n    )\n  }\n}\n\nexport type InvalidHexValueErrorType = InvalidHexValueError & {\n  name: 'InvalidHexValueError'\n}\nexport class InvalidHexValueError extends BaseError {\n  override name = 'InvalidHexValueError'\n  constructor(value: Hex) {\n    super(\n      `Hex value \"${value}\" is an odd length (${value.length}). It must be an even length.`,\n    )\n  }\n}\n\nexport type OffsetOutOfBoundsErrorType = OffsetOutOfBoundsError & {\n  name: 'OffsetOutOfBoundsError'\n}\n/** @deprecated */\nexport class OffsetOutOfBoundsError extends BaseError {\n  override name = 'OffsetOutOfBoundsError' as const\n  constructor({ nextOffset, offset }: { nextOffset: number; offset: number }) {\n    super(\n      `Next offset (${nextOffset}) is greater than previous offset + consumed bytes (${offset})`,\n    )\n  }\n}\n\nexport type SizeOverflowErrorType = SizeOverflowError & {\n  name: 'SizeOverflowError'\n}\nexport class SizeOverflowError extends BaseError {\n  override name = 'SizeOverflowError' as const\n  constructor({ givenSize, maxSize }: { givenSize: number; maxSize: number }) {\n    super(\n      `Size cannot exceed ${maxSize} bytes. Given size: ${givenSize} bytes.`,\n    )\n  }\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { Hex } from '../../types/misc.js'\n\nexport type IsHexErrorType = ErrorType\n\nexport function isHex(\n  value: unknown,\n  { strict = true }: { strict?: boolean } = {},\n): value is Hex {\n  if (!value) return false\n  if (typeof value !== 'string') return false\n  return strict ? /^0x[0-9a-fA-F]*$/.test(value) : value.startsWith('0x')\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray, Hex } from '../../types/misc.js'\n\nimport { type IsHexErrorType, isHex } from './isHex.js'\n\nexport type SizeErrorType = IsHexErrorType | ErrorType\n\n/**\n * @description Retrieves the size of the value (in bytes).\n *\n * @param value The value (hex or byte array) to retrieve the size of.\n * @returns The size of the value (in bytes).\n */\nexport function size(value: Hex | ByteArray) {\n  if (isHex(value, { strict: false })) return Math.ceil((value.length - 2) / 2)\n  return value.length\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray, Hex } from '../../types/misc.js'\n\ntype TrimOptions = {\n  dir?: 'left' | 'right'\n}\nexport type TrimReturnType<TValue extends ByteArray | Hex> = TValue extends Hex\n  ? Hex\n  : ByteArray\n\nexport type TrimErrorType = ErrorType\n\nexport function trim<TValue extends ByteArray | Hex>(\n  hexOrBytes: TValue,\n  { dir = 'left' }: TrimOptions = {},\n): TrimReturnType<TValue> {\n  let data: any =\n    typeof hexOrBytes === 'string' ? hexOrBytes.replace('0x', '') : hexOrBytes\n\n  let sliceLength = 0\n  for (let i = 0; i < data.length - 1; i++) {\n    if (data[dir === 'left' ? i : data.length - i - 1].toString() === '0')\n      sliceLength++\n    else break\n  }\n  data =\n    dir === 'left'\n      ? data.slice(sliceLength)\n      : data.slice(0, data.length - sliceLength)\n\n  if (typeof hexOrBytes === 'string') {\n    if (data.length === 1 && dir === 'right') data = `${data}0`\n    return `0x${\n      data.length % 2 === 1 ? `0${data}` : data\n    }` as TrimReturnType<TValue>\n  }\n  return data as TrimReturnType<TValue>\n}\n","import { BaseError } from './base.js'\n\nexport type SliceOffsetOutOfBoundsErrorType = SliceOffsetOutOfBoundsError & {\n  name: 'SliceOffsetOutOfBoundsError'\n}\nexport class SliceOffsetOutOfBoundsError extends BaseError {\n  override name = 'SliceOffsetOutOfBoundsError'\n  constructor({\n    offset,\n    position,\n    size,\n  }: { offset: number; position: 'start' | 'end'; size: number }) {\n    super(\n      `Slice ${\n        position === 'start' ? 'starting' : 'ending'\n      } at offset \"${offset}\" is out-of-bounds (size: ${size}).`,\n    )\n  }\n}\n\nexport type SizeExceedsPaddingSizeErrorType = SizeExceedsPaddingSizeError & {\n  name: 'SizeExceedsPaddingSizeError'\n}\nexport class SizeExceedsPaddingSizeError extends BaseError {\n  override name = 'SizeExceedsPaddingSizeError'\n  constructor({\n    size,\n    targetSize,\n    type,\n  }: {\n    size: number\n    targetSize: number\n    type: 'hex' | 'bytes'\n  }) {\n    super(\n      `${type.charAt(0).toUpperCase()}${type\n        .slice(1)\n        .toLowerCase()} size (${size}) exceeds padding size (${targetSize}).`,\n    )\n  }\n}\n","import {\n  SizeExceedsPaddingSizeError,\n  type SizeExceedsPaddingSizeErrorType,\n} from '../../errors/data.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray, Hex } from '../../types/misc.js'\n\ntype PadOptions = {\n  dir?: 'left' | 'right'\n  size?: number | null\n}\nexport type PadReturnType<TValue extends ByteArray | Hex> = TValue extends Hex\n  ? Hex\n  : ByteArray\n\nexport type PadErrorType = PadHexErrorType | PadBytesErrorType | ErrorType\n\nexport function pad<TValue extends ByteArray | Hex>(\n  hexOrBytes: TValue,\n  { dir, size = 32 }: PadOptions = {},\n): PadReturnType<TValue> {\n  if (typeof hexOrBytes === 'string')\n    return padHex(hexOrBytes, { dir, size }) as PadReturnType<TValue>\n  return padBytes(hexOrBytes, { dir, size }) as PadReturnType<TValue>\n}\n\nexport type PadHexErrorType = SizeExceedsPaddingSizeErrorType | ErrorType\n\nexport function padHex(hex_: Hex, { dir, size = 32 }: PadOptions = {}) {\n  if (size === null) return hex_\n  const hex = hex_.replace('0x', '')\n  if (hex.length > size * 2)\n    throw new SizeExceedsPaddingSizeError({\n      size: Math.ceil(hex.length / 2),\n      targetSize: size,\n      type: 'hex',\n    })\n\n  return `0x${hex[dir === 'right' ? 'padEnd' : 'padStart'](\n    size * 2,\n    '0',\n  )}` as Hex\n}\n\nexport type PadBytesErrorType = SizeExceedsPaddingSizeErrorType | ErrorType\n\nexport function padBytes(\n  bytes: ByteArray,\n  { dir, size = 32 }: PadOptions = {},\n) {\n  if (size === null) return bytes\n  if (bytes.length > size)\n    throw new SizeExceedsPaddingSizeError({\n      size: bytes.length,\n      targetSize: size,\n      type: 'bytes',\n    })\n  const paddedBytes = new Uint8Array(size)\n  for (let i = 0; i < size; i++) {\n    const padEnd = dir === 'right'\n    paddedBytes[padEnd ? i : size - i - 1] =\n      bytes[padEnd ? i : bytes.length - i - 1]\n  }\n  return paddedBytes\n}\n","import {\n  IntegerOutOfRangeError,\n  type IntegerOutOfRangeErrorType,\n} from '../../errors/encoding.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray, Hex } from '../../types/misc.js'\nimport { type PadErrorType, pad } from '../data/pad.js'\n\nimport { type AssertSizeErrorType, assertSize } from './fromHex.js'\n\nconst hexes = /*#__PURE__*/ Array.from({ length: 256 }, (_v, i) =>\n  i.toString(16).padStart(2, '0'),\n)\n\nexport type ToHexParameters = {\n  /** The size (in bytes) of the output hex value. */\n  size?: number\n}\n\nexport type ToHexErrorType =\n  | BoolToHexErrorType\n  | BytesToHexErrorType\n  | NumberToHexErrorType\n  | StringToHexErrorType\n  | ErrorType\n\n/**\n * Encodes a string, number, bigint, or ByteArray into a hex string\n *\n * - Docs: https://viem.sh/docs/utilities/toHex.html\n * - Example: https://viem.sh/docs/utilities/toHex.html#usage\n *\n * @param value Value to encode.\n * @param opts Options.\n * @returns Hex value.\n *\n * @example\n * import { toHex } from 'viem'\n * const data = toHex('Hello world')\n * // '0x48656c6c6f20776f726c6421'\n *\n * @example\n * import { toHex } from 'viem'\n * const data = toHex(420)\n * // '0x1a4'\n *\n * @example\n * import { toHex } from 'viem'\n * const data = toHex('Hello world', { size: 32 })\n * // '0x48656c6c6f20776f726c64210000000000000000000000000000000000000000'\n */\nexport function toHex(\n  value: string | number | bigint | boolean | ByteArray,\n  opts: ToHexParameters = {},\n): Hex {\n  if (typeof value === 'number' || typeof value === 'bigint')\n    return numberToHex(value, opts)\n  if (typeof value === 'string') {\n    return stringToHex(value, opts)\n  }\n  if (typeof value === 'boolean') return boolToHex(value, opts)\n  return bytesToHex(value, opts)\n}\n\nexport type BoolToHexOpts = {\n  /** The size (in bytes) of the output hex value. */\n  size?: number\n}\n\nexport type BoolToHexErrorType = AssertSizeErrorType | PadErrorType | ErrorType\n\n/**\n * Encodes a boolean into a hex string\n *\n * - Docs: https://viem.sh/docs/utilities/toHex.html#booltohex\n *\n * @param value Value to encode.\n * @param opts Options.\n * @returns Hex value.\n *\n * @example\n * import { boolToHex } from 'viem'\n * const data = boolToHex(true)\n * // '0x1'\n *\n * @example\n * import { boolToHex } from 'viem'\n * const data = boolToHex(false)\n * // '0x0'\n *\n * @example\n * import { boolToHex } from 'viem'\n * const data = boolToHex(true, { size: 32 })\n * // '0x0000000000000000000000000000000000000000000000000000000000000001'\n */\nexport function boolToHex(value: boolean, opts: BoolToHexOpts = {}): Hex {\n  const hex: Hex = `0x${Number(value)}`\n  if (typeof opts.size === 'number') {\n    assertSize(hex, { size: opts.size })\n    return pad(hex, { size: opts.size })\n  }\n  return hex\n}\n\nexport type BytesToHexOpts = {\n  /** The size (in bytes) of the output hex value. */\n  size?: number\n}\n\nexport type BytesToHexErrorType = AssertSizeErrorType | PadErrorType | ErrorType\n\n/**\n * Encodes a bytes array into a hex string\n *\n * - Docs: https://viem.sh/docs/utilities/toHex.html#bytestohex\n *\n * @param value Value to encode.\n * @param opts Options.\n * @returns Hex value.\n *\n * @example\n * import { bytesToHex } from 'viem'\n * const data = bytesToHex(Uint8Array.from([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33])\n * // '0x48656c6c6f20576f726c6421'\n *\n * @example\n * import { bytesToHex } from 'viem'\n * const data = bytesToHex(Uint8Array.from([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33]), { size: 32 })\n * // '0x48656c6c6f20576f726c64210000000000000000000000000000000000000000'\n */\nexport function bytesToHex(value: ByteArray, opts: BytesToHexOpts = {}): Hex {\n  let string = ''\n  for (let i = 0; i < value.length; i++) {\n    string += hexes[value[i]]\n  }\n  const hex = `0x${string}` as const\n\n  if (typeof opts.size === 'number') {\n    assertSize(hex, { size: opts.size })\n    return pad(hex, { dir: 'right', size: opts.size })\n  }\n  return hex\n}\n\nexport type NumberToHexOpts =\n  | {\n      /** Whether or not the number of a signed representation. */\n      signed?: boolean\n      /** The size (in bytes) of the output hex value. */\n      size: number\n    }\n  | {\n      signed?: never\n      /** The size (in bytes) of the output hex value. */\n      size?: number\n    }\n\nexport type NumberToHexErrorType =\n  | IntegerOutOfRangeErrorType\n  | PadErrorType\n  | ErrorType\n\n/**\n * Encodes a number or bigint into a hex string\n *\n * - Docs: https://viem.sh/docs/utilities/toHex.html#numbertohex\n *\n * @param value Value to encode.\n * @param opts Options.\n * @returns Hex value.\n *\n * @example\n * import { numberToHex } from 'viem'\n * const data = numberToHex(420)\n * // '0x1a4'\n *\n * @example\n * import { numberToHex } from 'viem'\n * const data = numberToHex(420, { size: 32 })\n * // '0x00000000000000000000000000000000000000000000000000000000000001a4'\n */\nexport function numberToHex(\n  value_: number | bigint,\n  opts: NumberToHexOpts = {},\n): Hex {\n  const { signed, size } = opts\n\n  const value = BigInt(value_)\n\n  let maxValue\n  if (size) {\n    if (signed) maxValue = (1n << (BigInt(size) * 8n - 1n)) - 1n\n    else maxValue = 2n ** (BigInt(size) * 8n) - 1n\n  } else if (typeof value_ === 'number') {\n    maxValue = BigInt(Number.MAX_SAFE_INTEGER)\n  }\n\n  const minValue = typeof maxValue === 'bigint' && signed ? -maxValue - 1n : 0\n\n  if ((maxValue && value > maxValue) || value < minValue) {\n    const suffix = typeof value_ === 'bigint' ? 'n' : ''\n    throw new IntegerOutOfRangeError({\n      max: maxValue ? `${maxValue}${suffix}` : undefined,\n      min: `${minValue}${suffix}`,\n      signed,\n      size,\n      value: `${value_}${suffix}`,\n    })\n  }\n\n  const hex = `0x${(signed && value < 0\n    ? (1n << BigInt(size * 8)) + BigInt(value)\n    : value\n  ).toString(16)}` as Hex\n  if (size) return pad(hex, { size }) as Hex\n  return hex\n}\n\nexport type StringToHexOpts = {\n  /** The size (in bytes) of the output hex value. */\n  size?: number\n}\n\nexport type StringToHexErrorType = BytesToHexErrorType | ErrorType\n\nconst encoder = /*#__PURE__*/ new TextEncoder()\n\n/**\n * Encodes a UTF-8 string into a hex string\n *\n * - Docs: https://viem.sh/docs/utilities/toHex.html#stringtohex\n *\n * @param value Value to encode.\n * @param opts Options.\n * @returns Hex value.\n *\n * @example\n * import { stringToHex } from 'viem'\n * const data = stringToHex('Hello World!')\n * // '0x48656c6c6f20576f726c6421'\n *\n * @example\n * import { stringToHex } from 'viem'\n * const data = stringToHex('Hello World!', { size: 32 })\n * // '0x48656c6c6f20576f726c64210000000000000000000000000000000000000000'\n */\nexport function stringToHex(value_: string, opts: StringToHexOpts = {}): Hex {\n  const value = encoder.encode(value_)\n  return bytesToHex(value, opts)\n}\n","import { BaseError } from '../../errors/base.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray, Hex } from '../../types/misc.js'\nimport { type IsHexErrorType, isHex } from '../data/isHex.js'\nimport { type PadErrorType, pad } from '../data/pad.js'\n\nimport { type AssertSizeErrorType, assertSize } from './fromHex.js'\nimport {\n  type NumberToHexErrorType,\n  type NumberToHexOpts,\n  numberToHex,\n} from './toHex.js'\n\nconst encoder = /*#__PURE__*/ new TextEncoder()\n\nexport type ToBytesParameters = {\n  /** Size of the output bytes. */\n  size?: number\n}\n\nexport type ToBytesErrorType =\n  | NumberToBytesErrorType\n  | BoolToBytesErrorType\n  | HexToBytesErrorType\n  | StringToBytesErrorType\n  | IsHexErrorType\n  | ErrorType\n\n/**\n * Encodes a UTF-8 string, hex value, bigint, number or boolean to a byte array.\n *\n * - Docs: https://viem.sh/docs/utilities/toBytes.html\n * - Example: https://viem.sh/docs/utilities/toBytes.html#usage\n *\n * @param value Value to encode.\n * @param opts Options.\n * @returns Byte array value.\n *\n * @example\n * import { toBytes } from 'viem'\n * const data = toBytes('Hello world')\n * // Uint8Array([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33])\n *\n * @example\n * import { toBytes } from 'viem'\n * const data = toBytes(420)\n * // Uint8Array([1, 164])\n *\n * @example\n * import { toBytes } from 'viem'\n * const data = toBytes(420, { size: 4 })\n * // Uint8Array([0, 0, 1, 164])\n */\nexport function toBytes(\n  value: string | bigint | number | boolean | Hex,\n  opts: ToBytesParameters = {},\n): ByteArray {\n  if (typeof value === 'number' || typeof value === 'bigint')\n    return numberToBytes(value, opts)\n  if (typeof value === 'boolean') return boolToBytes(value, opts)\n  if (isHex(value)) return hexToBytes(value, opts)\n  return stringToBytes(value, opts)\n}\n\nexport type BoolToBytesOpts = {\n  /** Size of the output bytes. */\n  size?: number\n}\n\nexport type BoolToBytesErrorType =\n  | AssertSizeErrorType\n  | PadErrorType\n  | ErrorType\n\n/**\n * Encodes a boolean into a byte array.\n *\n * - Docs: https://viem.sh/docs/utilities/toBytes.html#booltobytes\n *\n * @param value Boolean value to encode.\n * @param opts Options.\n * @returns Byte array value.\n *\n * @example\n * import { boolToBytes } from 'viem'\n * const data = boolToBytes(true)\n * // Uint8Array([1])\n *\n * @example\n * import { boolToBytes } from 'viem'\n * const data = boolToBytes(true, { size: 32 })\n * // Uint8Array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1])\n */\nexport function boolToBytes(value: boolean, opts: BoolToBytesOpts = {}) {\n  const bytes = new Uint8Array(1)\n  bytes[0] = Number(value)\n  if (typeof opts.size === 'number') {\n    assertSize(bytes, { size: opts.size })\n    return pad(bytes, { size: opts.size })\n  }\n  return bytes\n}\n\n// We use very optimized technique to convert hex string to byte array\nconst charCodeMap = {\n  zero: 48,\n  nine: 57,\n  A: 65,\n  F: 70,\n  a: 97,\n  f: 102,\n} as const\n\nfunction charCodeToBase16(char: number) {\n  if (char >= charCodeMap.zero && char <= charCodeMap.nine)\n    return char - charCodeMap.zero\n  if (char >= charCodeMap.A && char <= charCodeMap.F)\n    return char - (charCodeMap.A - 10)\n  if (char >= charCodeMap.a && char <= charCodeMap.f)\n    return char - (charCodeMap.a - 10)\n  return undefined\n}\n\nexport type HexToBytesOpts = {\n  /** Size of the output bytes. */\n  size?: number\n}\n\nexport type HexToBytesErrorType = AssertSizeErrorType | PadErrorType | ErrorType\n\n/**\n * Encodes a hex string into a byte array.\n *\n * - Docs: https://viem.sh/docs/utilities/toBytes.html#hextobytes\n *\n * @param hex Hex string to encode.\n * @param opts Options.\n * @returns Byte array value.\n *\n * @example\n * import { hexToBytes } from 'viem'\n * const data = hexToBytes('0x48656c6c6f20776f726c6421')\n * // Uint8Array([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33])\n *\n * @example\n * import { hexToBytes } from 'viem'\n * const data = hexToBytes('0x48656c6c6f20776f726c6421', { size: 32 })\n * // Uint8Array([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])\n */\nexport function hexToBytes(hex_: Hex, opts: HexToBytesOpts = {}): ByteArray {\n  let hex = hex_\n  if (opts.size) {\n    assertSize(hex, { size: opts.size })\n    hex = pad(hex, { dir: 'right', size: opts.size })\n  }\n\n  let hexString = hex.slice(2) as string\n  if (hexString.length % 2) hexString = `0${hexString}`\n\n  const length = hexString.length / 2\n  const bytes = new Uint8Array(length)\n  for (let index = 0, j = 0; index < length; index++) {\n    const nibbleLeft = charCodeToBase16(hexString.charCodeAt(j++))\n    const nibbleRight = charCodeToBase16(hexString.charCodeAt(j++))\n    if (nibbleLeft === undefined || nibbleRight === undefined) {\n      throw new BaseError(\n        `Invalid byte sequence (\"${hexString[j - 2]}${\n          hexString[j - 1]\n        }\" in \"${hexString}\").`,\n      )\n    }\n    bytes[index] = nibbleLeft * 16 + nibbleRight\n  }\n  return bytes\n}\n\nexport type NumberToBytesErrorType =\n  | NumberToHexErrorType\n  | HexToBytesErrorType\n  | ErrorType\n\n/**\n * Encodes a number into a byte array.\n *\n * - Docs: https://viem.sh/docs/utilities/toBytes.html#numbertobytes\n *\n * @param value Number to encode.\n * @param opts Options.\n * @returns Byte array value.\n *\n * @example\n * import { numberToBytes } from 'viem'\n * const data = numberToBytes(420)\n * // Uint8Array([1, 164])\n *\n * @example\n * import { numberToBytes } from 'viem'\n * const data = numberToBytes(420, { size: 4 })\n * // Uint8Array([0, 0, 1, 164])\n */\nexport function numberToBytes(value: bigint | number, opts?: NumberToHexOpts) {\n  const hex = numberToHex(value, opts)\n  return hexToBytes(hex)\n}\n\nexport type StringToBytesOpts = {\n  /** Size of the output bytes. */\n  size?: number\n}\n\nexport type StringToBytesErrorType =\n  | AssertSizeErrorType\n  | PadErrorType\n  | ErrorType\n\n/**\n * Encodes a UTF-8 string into a byte array.\n *\n * - Docs: https://viem.sh/docs/utilities/toBytes.html#stringtobytes\n *\n * @param value String to encode.\n * @param opts Options.\n * @returns Byte array value.\n *\n * @example\n * import { stringToBytes } from 'viem'\n * const data = stringToBytes('Hello world!')\n * // Uint8Array([72, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100, 33])\n *\n * @example\n * import { stringToBytes } from 'viem'\n * const data = stringToBytes('Hello world!', { size: 32 })\n * // Uint8Array([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])\n */\nexport function stringToBytes(\n  value: string,\n  opts: StringToBytesOpts = {},\n): ByteArray {\n  const bytes = encoder.encode(value)\n  if (typeof opts.size === 'number') {\n    assertSize(bytes, { size: opts.size })\n    return pad(bytes, { dir: 'right', size: opts.size })\n  }\n  return bytes\n}\n","import {\n  InvalidHexBooleanError,\n  type InvalidHexBooleanErrorType,\n  SizeOverflowError,\n  type SizeOverflowErrorType,\n} from '../../errors/encoding.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray, Hex } from '../../types/misc.js'\nimport { type SizeErrorType, size as size_ } from '../data/size.js'\nimport { type TrimErrorType, trim } from '../data/trim.js'\n\nimport { type HexToBytesErrorType, hexToBytes } from './toBytes.js'\n\nexport type AssertSizeErrorType =\n  | SizeOverflowErrorType\n  | SizeErrorType\n  | ErrorType\n\nexport function assertSize(\n  hexOrBytes: Hex | ByteArray,\n  { size }: { size: number },\n): void {\n  if (size_(hexOrBytes) > size)\n    throw new SizeOverflowError({\n      givenSize: size_(hexOrBytes),\n      maxSize: size,\n    })\n}\n\nexport type FromHexParameters<\n  TTo extends 'string' | 'bigint' | 'number' | 'bytes' | 'boolean',\n> =\n  | TTo\n  | {\n      /** Size (in bytes) of the hex value. */\n      size?: number\n      /** Type to convert to. */\n      to: TTo\n    }\n\nexport type FromHexReturnType<TTo> = TTo extends 'string'\n  ? string\n  : TTo extends 'bigint'\n    ? bigint\n    : TTo extends 'number'\n      ? number\n      : TTo extends 'bytes'\n        ? ByteArray\n        : TTo extends 'boolean'\n          ? boolean\n          : never\n\nexport type FromHexErrorType =\n  | HexToNumberErrorType\n  | HexToBigIntErrorType\n  | HexToBoolErrorType\n  | HexToStringErrorType\n  | HexToBytesErrorType\n  | ErrorType\n\n/**\n * Decodes a hex string into a string, number, bigint, boolean, or byte array.\n *\n * - Docs: https://viem.sh/docs/utilities/fromHex.html\n * - Example: https://viem.sh/docs/utilities/fromHex.html#usage\n *\n * @param hex Hex string to decode.\n * @param toOrOpts Type to convert to or options.\n * @returns Decoded value.\n *\n * @example\n * import { fromHex } from 'viem'\n * const data = fromHex('0x1a4', 'number')\n * // 420\n *\n * @example\n * import { fromHex } from 'viem'\n * const data = fromHex('0x48656c6c6f20576f726c6421', 'string')\n * // 'Hello world'\n *\n * @example\n * import { fromHex } from 'viem'\n * const data = fromHex('0x48656c6c6f20576f726c64210000000000000000000000000000000000000000', {\n *   size: 32,\n *   to: 'string'\n * })\n * // 'Hello world'\n */\nexport function fromHex<\n  TTo extends 'string' | 'bigint' | 'number' | 'bytes' | 'boolean',\n>(hex: Hex, toOrOpts: FromHexParameters<TTo>): FromHexReturnType<TTo> {\n  const opts = typeof toOrOpts === 'string' ? { to: toOrOpts } : toOrOpts\n  const to = opts.to\n\n  if (to === 'number') return hexToNumber(hex, opts) as FromHexReturnType<TTo>\n  if (to === 'bigint') return hexToBigInt(hex, opts) as FromHexReturnType<TTo>\n  if (to === 'string') return hexToString(hex, opts) as FromHexReturnType<TTo>\n  if (to === 'boolean') return hexToBool(hex, opts) as FromHexReturnType<TTo>\n  return hexToBytes(hex, opts) as FromHexReturnType<TTo>\n}\n\nexport type HexToBigIntOpts = {\n  /** Whether or not the number of a signed representation. */\n  signed?: boolean\n  /** Size (in bytes) of the hex value. */\n  size?: number\n}\n\nexport type HexToBigIntErrorType = AssertSizeErrorType | ErrorType\n\n/**\n * Decodes a hex value into a bigint.\n *\n * - Docs: https://viem.sh/docs/utilities/fromHex.html#hextobigint\n *\n * @param hex Hex value to decode.\n * @param opts Options.\n * @returns BigInt value.\n *\n * @example\n * import { hexToBigInt } from 'viem'\n * const data = hexToBigInt('0x1a4', { signed: true })\n * // 420n\n *\n * @example\n * import { hexToBigInt } from 'viem'\n * const data = hexToBigInt('0x00000000000000000000000000000000000000000000000000000000000001a4', { size: 32 })\n * // 420n\n */\nexport function hexToBigInt(hex: Hex, opts: HexToBigIntOpts = {}): bigint {\n  const { signed } = opts\n\n  if (opts.size) assertSize(hex, { size: opts.size })\n\n  const value = BigInt(hex)\n  if (!signed) return value\n\n  const size = (hex.length - 2) / 2\n  const max = (1n << (BigInt(size) * 8n - 1n)) - 1n\n  if (value <= max) return value\n\n  return value - BigInt(`0x${'f'.padStart(size * 2, 'f')}`) - 1n\n}\n\nexport type HexToBoolOpts = {\n  /** Size (in bytes) of the hex value. */\n  size?: number\n}\n\nexport type HexToBoolErrorType =\n  | AssertSizeErrorType\n  | InvalidHexBooleanErrorType\n  | TrimErrorType\n  | ErrorType\n\n/**\n * Decodes a hex value into a boolean.\n *\n * - Docs: https://viem.sh/docs/utilities/fromHex.html#hextobool\n *\n * @param hex Hex value to decode.\n * @param opts Options.\n * @returns Boolean value.\n *\n * @example\n * import { hexToBool } from 'viem'\n * const data = hexToBool('0x01')\n * // true\n *\n * @example\n * import { hexToBool } from 'viem'\n * const data = hexToBool('0x0000000000000000000000000000000000000000000000000000000000000001', { size: 32 })\n * // true\n */\nexport function hexToBool(hex_: Hex, opts: HexToBoolOpts = {}): boolean {\n  let hex = hex_\n  if (opts.size) {\n    assertSize(hex, { size: opts.size })\n    hex = trim(hex)\n  }\n  if (trim(hex) === '0x00') return false\n  if (trim(hex) === '0x01') return true\n  throw new InvalidHexBooleanError(hex)\n}\n\nexport type HexToNumberOpts = HexToBigIntOpts\n\nexport type HexToNumberErrorType = HexToBigIntErrorType | ErrorType\n\n/**\n * Decodes a hex string into a number.\n *\n * - Docs: https://viem.sh/docs/utilities/fromHex.html#hextonumber\n *\n * @param hex Hex value to decode.\n * @param opts Options.\n * @returns Number value.\n *\n * @example\n * import { hexToNumber } from 'viem'\n * const data = hexToNumber('0x1a4')\n * // 420\n *\n * @example\n * import { hexToNumber } from 'viem'\n * const data = hexToBigInt('0x00000000000000000000000000000000000000000000000000000000000001a4', { size: 32 })\n * // 420\n */\nexport function hexToNumber(hex: Hex, opts: HexToNumberOpts = {}): number {\n  return Number(hexToBigInt(hex, opts))\n}\n\nexport type HexToStringOpts = {\n  /** Size (in bytes) of the hex value. */\n  size?: number\n}\n\nexport type HexToStringErrorType =\n  | AssertSizeErrorType\n  | HexToBytesErrorType\n  | TrimErrorType\n  | ErrorType\n\n/**\n * Decodes a hex value into a UTF-8 string.\n *\n * - Docs: https://viem.sh/docs/utilities/fromHex.html#hextostring\n *\n * @param hex Hex value to decode.\n * @param opts Options.\n * @returns String value.\n *\n * @example\n * import { hexToString } from 'viem'\n * const data = hexToString('0x48656c6c6f20576f726c6421')\n * // 'Hello world!'\n *\n * @example\n * import { hexToString } from 'viem'\n * const data = hexToString('0x48656c6c6f20576f726c64210000000000000000000000000000000000000000', {\n *  size: 32,\n * })\n * // 'Hello world'\n */\nexport function hexToString(hex: Hex, opts: HexToStringOpts = {}): string {\n  let bytes = hexToBytes(hex)\n  if (opts.size) {\n    assertSize(bytes, { size: opts.size })\n    bytes = trim(bytes, { dir: 'right' })\n  }\n  return new TextDecoder().decode(bytes)\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type {\n  Chain,\n  ExtractChainFormatterParameters,\n} from '../../types/chain.js'\nimport type { RpcTransactionRequest } from '../../types/rpc.js'\nimport type { TransactionRequest } from '../../types/transaction.js'\nimport { numberToHex } from '../encoding/toHex.js'\nimport { type DefineFormatterErrorType, defineFormatter } from './formatter.js'\n\nexport type FormattedTransactionRequest<\n  TChain extends Chain | undefined = Chain | undefined,\n> = ExtractChainFormatterParameters<\n  TChain,\n  'transactionRequest',\n  TransactionRequest\n>\n\nexport const rpcTransactionType = {\n  legacy: '0x0',\n  eip2930: '0x1',\n  eip1559: '0x2',\n} as const\n\nexport type FormatTransactionRequestErrorType = ErrorType\n\nexport function formatTransactionRequest(\n  transactionRequest: Partial<TransactionRequest>,\n) {\n  return {\n    ...transactionRequest,\n    gas:\n      typeof transactionRequest.gas !== 'undefined'\n        ? numberToHex(transactionRequest.gas)\n        : undefined,\n    gasPrice:\n      typeof transactionRequest.gasPrice !== 'undefined'\n        ? numberToHex(transactionRequest.gasPrice)\n        : undefined,\n    maxFeePerGas:\n      typeof transactionRequest.maxFeePerGas !== 'undefined'\n        ? numberToHex(transactionRequest.maxFeePerGas)\n        : undefined,\n    maxPriorityFeePerGas:\n      typeof transactionRequest.maxPriorityFeePerGas !== 'undefined'\n        ? numberToHex(transactionRequest.maxPriorityFeePerGas)\n        : undefined,\n    nonce:\n      typeof transactionRequest.nonce !== 'undefined'\n        ? numberToHex(transactionRequest.nonce)\n        : undefined,\n    type:\n      typeof transactionRequest.type !== 'undefined'\n        ? rpcTransactionType[transactionRequest.type]\n        : undefined,\n    value:\n      typeof transactionRequest.value !== 'undefined'\n        ? numberToHex(transactionRequest.value)\n        : undefined,\n  } as RpcTransactionRequest\n}\n\nexport type DefineTransactionRequestErrorType =\n  | DefineFormatterErrorType\n  | ErrorType\n\nexport const defineTransactionRequest = /*#__PURE__*/ defineFormatter(\n  'transactionRequest',\n  formatTransactionRequest,\n)\n","import { BaseError } from './base.js'\n\nexport type InvalidAddressErrorType = InvalidAddressError & {\n  name: 'InvalidAddressError'\n}\nexport class InvalidAddressError extends BaseError {\n  override name = 'InvalidAddressError'\n  constructor({ address }: { address: string }) {\n    super(`Address \"${address}\" is invalid.`)\n  }\n}\n","import type { Chain } from '../types/chain.js'\n\nimport { BaseError } from './base.js'\n\nexport type ChainDoesNotSupportContractErrorType =\n  ChainDoesNotSupportContract & {\n    name: 'ChainDoesNotSupportContract'\n  }\nexport class ChainDoesNotSupportContract extends BaseError {\n  override name = 'ChainDoesNotSupportContract'\n  constructor({\n    blockNumber,\n    chain,\n    contract,\n  }: {\n    blockNumber?: bigint\n    chain: Chain\n    contract: { name: string; blockCreated?: number }\n  }) {\n    super(\n      `Chain \"${chain.name}\" does not support contract \"${contract.name}\".`,\n      {\n        metaMessages: [\n          'This could be due to any of the following:',\n          ...(blockNumber &&\n          contract.blockCreated &&\n          contract.blockCreated > blockNumber\n            ? [\n                `- The contract \"${contract.name}\" was not deployed until block ${contract.blockCreated} (current block ${blockNumber}).`,\n              ]\n            : [\n                `- The chain does not have the contract \"${contract.name}\" configured.`,\n              ]),\n        ],\n      },\n    )\n  }\n}\n\nexport type ChainMismatchErrorType = ChainMismatchError & {\n  name: 'ChainMismatchError'\n}\nexport class ChainMismatchError extends BaseError {\n  override name = 'ChainMismatchError'\n\n  constructor({\n    chain,\n    currentChainId,\n  }: {\n    chain: Chain\n    currentChainId: number\n  }) {\n    super(\n      `The current chain of the wallet (id: ${currentChainId}) does not match the target chain for the transaction (id: ${chain.id} – ${chain.name}).`,\n      {\n        metaMessages: [\n          `Current Chain ID:  ${currentChainId}`,\n          `Expected Chain ID: ${chain.id} – ${chain.name}`,\n        ],\n      },\n    )\n  }\n}\n\nexport type ChainNotFoundErrorType = ChainNotFoundError & {\n  name: 'ChainNotFoundError'\n}\nexport class ChainNotFoundError extends BaseError {\n  override name = 'ChainNotFoundError'\n\n  constructor() {\n    super(\n      [\n        'No chain was provided to the request.',\n        'Please provide a chain with the `chain` argument on the Action, or by supplying a `chain` to WalletClient.',\n      ].join('\\n'),\n    )\n  }\n}\n\nexport type ClientChainNotConfiguredErrorType =\n  ClientChainNotConfiguredError & {\n    name: 'ClientChainNotConfiguredError'\n  }\nexport class ClientChainNotConfiguredError extends BaseError {\n  override name = 'ClientChainNotConfiguredError'\n\n  constructor() {\n    super('No chain was provided to the Client.')\n  }\n}\n\nexport type InvalidChainIdErrorType = InvalidChainIdError & {\n  name: 'InvalidChainIdError'\n}\nexport class InvalidChainIdError extends BaseError {\n  override name = 'InvalidChainIdError'\n\n  constructor({ chainId }: { chainId: number }) {\n    super(`Chain ID \"${chainId}\" is invalid.`)\n  }\n}\n","export const etherUnits = {\n  gwei: 9,\n  wei: 18,\n}\nexport const gweiUnits = {\n  ether: -9,\n  wei: 9,\n}\nexport const weiUnits = {\n  ether: -18,\n  gwei: -9,\n}\n","import type { ErrorType } from '../../errors/utils.js'\n\nexport type FormatUnitsErrorType = ErrorType\n\n/**\n *  Divides a number by a given exponent of base 10 (10exponent), and formats it into a string representation of the number..\n *\n * - Docs: https://viem.sh/docs/utilities/formatUnits.html\n *\n * @example\n * import { formatUnits } from 'viem'\n *\n * formatUnits(420000000000n, 9)\n * // '420'\n */\nexport function formatUnits(value: bigint, decimals: number) {\n  let display = value.toString()\n\n  const negative = display.startsWith('-')\n  if (negative) display = display.slice(1)\n\n  display = display.padStart(decimals, '0')\n\n  let [integer, fraction] = [\n    display.slice(0, display.length - decimals),\n    display.slice(display.length - decimals),\n  ]\n  fraction = fraction.replace(/(0+)$/, '')\n  return `${negative ? '-' : ''}${integer || '0'}${\n    fraction ? `.${fraction}` : ''\n  }`\n}\n","import { gweiUnits } from '../../constants/unit.js'\n\nimport { type FormatUnitsErrorType, formatUnits } from './formatUnits.js'\n\nexport type FormatGweiErrorType = FormatUnitsErrorType\n\n/**\n * Converts numerical wei to a string representation of gwei.\n *\n * - Docs: https://viem.sh/docs/utilities/formatGwei.html\n *\n * @example\n * import { formatGwei } from 'viem'\n *\n * formatGwei(1000000000n)\n * // '1'\n */\nexport function formatGwei(wei: bigint, unit: 'wei' = 'wei') {\n  return formatUnits(wei, gweiUnits[unit])\n}\n","import { formatGwei } from '../utils/unit/formatGwei.js'\n\nimport { BaseError } from './base.js'\n\n/**\n * geth:    https://github.com/ethereum/go-ethereum/blob/master/core/error.go\n *          https://github.com/ethereum/go-ethereum/blob/master/core/types/transaction.go#L34-L41\n *\n * erigon:  https://github.com/ledgerwatch/erigon/blob/master/core/error.go\n *          https://github.com/ledgerwatch/erigon/blob/master/core/types/transaction.go#L41-L46\n *\n * anvil:   https://github.com/foundry-rs/foundry/blob/master/anvil/src/eth/error.rs#L108\n */\nexport type ExecutionRevertedErrorType = ExecutionRevertedError & {\n  code: 3\n  name: 'ExecutionRevertedError'\n}\nexport class ExecutionRevertedError extends BaseError {\n  static code = 3\n  static nodeMessage = /execution reverted/\n\n  override name = 'ExecutionRevertedError'\n\n  constructor({\n    cause,\n    message,\n  }: { cause?: BaseError; message?: string } = {}) {\n    const reason = message\n      ?.replace('execution reverted: ', '')\n      ?.replace('execution reverted', '')\n    super(\n      `Execution reverted ${\n        reason ? `with reason: ${reason}` : 'for an unknown reason'\n      }.`,\n      {\n        cause,\n      },\n    )\n  }\n}\n\nexport type FeeCapTooHighErrorType = FeeCapTooHighError & {\n  name: 'FeeCapTooHighError'\n}\nexport class FeeCapTooHighError extends BaseError {\n  static nodeMessage =\n    /max fee per gas higher than 2\\^256-1|fee cap higher than 2\\^256-1/\n  override name = 'FeeCapTooHigh'\n  constructor({\n    cause,\n    maxFeePerGas,\n  }: { cause?: BaseError; maxFeePerGas?: bigint } = {}) {\n    super(\n      `The fee cap (\\`maxFeePerGas\\`${\n        maxFeePerGas ? ` = ${formatGwei(maxFeePerGas)} gwei` : ''\n      }) cannot be higher than the maximum allowed value (2^256-1).`,\n      {\n        cause,\n      },\n    )\n  }\n}\n\nexport type FeeCapTooLowErrorType = FeeCapTooLowError & {\n  name: 'FeeCapTooLowError'\n}\nexport class FeeCapTooLowError extends BaseError {\n  static nodeMessage =\n    /max fee per gas less than block base fee|fee cap less than block base fee|transaction is outdated/\n  override name = 'FeeCapTooLow'\n  constructor({\n    cause,\n    maxFeePerGas,\n  }: { cause?: BaseError; maxFeePerGas?: bigint } = {}) {\n    super(\n      `The fee cap (\\`maxFeePerGas\\`${\n        maxFeePerGas ? ` = ${formatGwei(maxFeePerGas)}` : ''\n      } gwei) cannot be lower than the block base fee.`,\n      {\n        cause,\n      },\n    )\n  }\n}\n\nexport type NonceTooHighErrorType = NonceTooHighError & {\n  name: 'NonceTooHighError'\n}\nexport class NonceTooHighError extends BaseError {\n  static nodeMessage = /nonce too high/\n  override name = 'NonceTooHighError'\n  constructor({ cause, nonce }: { cause?: BaseError; nonce?: number } = {}) {\n    super(\n      `Nonce provided for the transaction ${\n        nonce ? `(${nonce}) ` : ''\n      }is higher than the next one expected.`,\n      { cause },\n    )\n  }\n}\n\nexport type NonceTooLowErrorType = NonceTooLowError & {\n  name: 'NonceTooLowError'\n}\nexport class NonceTooLowError extends BaseError {\n  static nodeMessage =\n    /nonce too low|transaction already imported|already known/\n  override name = 'NonceTooLowError'\n  constructor({ cause, nonce }: { cause?: BaseError; nonce?: number } = {}) {\n    super(\n      [\n        `Nonce provided for the transaction ${\n          nonce ? `(${nonce}) ` : ''\n        }is lower than the current nonce of the account.`,\n        'Try increasing the nonce or find the latest nonce with `getTransactionCount`.',\n      ].join('\\n'),\n      { cause },\n    )\n  }\n}\n\nexport type NonceMaxValueErrorType = NonceMaxValueError & {\n  name: 'NonceMaxValueError'\n}\nexport class NonceMaxValueError extends BaseError {\n  static nodeMessage = /nonce has max value/\n  override name = 'NonceMaxValueError'\n  constructor({ cause, nonce }: { cause?: BaseError; nonce?: number } = {}) {\n    super(\n      `Nonce provided for the transaction ${\n        nonce ? `(${nonce}) ` : ''\n      }exceeds the maximum allowed nonce.`,\n      { cause },\n    )\n  }\n}\n\nexport type InsufficientFundsErrorType = InsufficientFundsError & {\n  name: 'InsufficientFundsError'\n}\nexport class InsufficientFundsError extends BaseError {\n  static nodeMessage = /insufficient funds/\n  override name = 'InsufficientFundsError'\n  constructor({ cause }: { cause?: BaseError } = {}) {\n    super(\n      [\n        'The total cost (gas * gas fee + value) of executing this transaction exceeds the balance of the account.',\n      ].join('\\n'),\n      {\n        cause,\n        metaMessages: [\n          'This error could arise when the account does not have enough funds to:',\n          ' - pay for the total gas fee,',\n          ' - pay for the value to send.',\n          ' ',\n          'The cost of the transaction is calculated as `gas * gas fee + value`, where:',\n          ' - `gas` is the amount of gas needed for transaction to execute,',\n          ' - `gas fee` is the gas fee,',\n          ' - `value` is the amount of ether to send to the recipient.',\n        ],\n      },\n    )\n  }\n}\n\nexport type IntrinsicGasTooHighErrorType = IntrinsicGasTooHighError & {\n  name: 'IntrinsicGasTooHighError'\n}\nexport class IntrinsicGasTooHighError extends BaseError {\n  static nodeMessage = /intrinsic gas too high|gas limit reached/\n  override name = 'IntrinsicGasTooHighError'\n  constructor({ cause, gas }: { cause?: BaseError; gas?: bigint } = {}) {\n    super(\n      `The amount of gas ${\n        gas ? `(${gas}) ` : ''\n      }provided for the transaction exceeds the limit allowed for the block.`,\n      {\n        cause,\n      },\n    )\n  }\n}\n\nexport type IntrinsicGasTooLowErrorType = IntrinsicGasTooLowError & {\n  name: 'IntrinsicGasTooLowError'\n}\nexport class IntrinsicGasTooLowError extends BaseError {\n  static nodeMessage = /intrinsic gas too low/\n  override name = 'IntrinsicGasTooLowError'\n  constructor({ cause, gas }: { cause?: BaseError; gas?: bigint } = {}) {\n    super(\n      `The amount of gas ${\n        gas ? `(${gas}) ` : ''\n      }provided for the transaction is too low.`,\n      {\n        cause,\n      },\n    )\n  }\n}\n\nexport type TransactionTypeNotSupportedErrorType =\n  TransactionTypeNotSupportedError & {\n    name: 'TransactionTypeNotSupportedError'\n  }\nexport class TransactionTypeNotSupportedError extends BaseError {\n  static nodeMessage = /transaction type not valid/\n  override name = 'TransactionTypeNotSupportedError'\n  constructor({ cause }: { cause?: BaseError }) {\n    super('The transaction type is not supported for this chain.', {\n      cause,\n    })\n  }\n}\n\nexport type TipAboveFeeCapErrorType = TipAboveFeeCapError & {\n  name: 'TipAboveFeeCapError'\n}\nexport class TipAboveFeeCapError extends BaseError {\n  static nodeMessage =\n    /max priority fee per gas higher than max fee per gas|tip higher than fee cap/\n  override name = 'TipAboveFeeCapError'\n  constructor({\n    cause,\n    maxPriorityFeePerGas,\n    maxFeePerGas,\n  }: {\n    cause?: BaseError\n    maxPriorityFeePerGas?: bigint\n    maxFeePerGas?: bigint\n  } = {}) {\n    super(\n      [\n        `The provided tip (\\`maxPriorityFeePerGas\\`${\n          maxPriorityFeePerGas\n            ? ` = ${formatGwei(maxPriorityFeePerGas)} gwei`\n            : ''\n        }) cannot be higher than the fee cap (\\`maxFeePerGas\\`${\n          maxFeePerGas ? ` = ${formatGwei(maxFeePerGas)} gwei` : ''\n        }).`,\n      ].join('\\n'),\n      {\n        cause,\n      },\n    )\n  }\n}\n\nexport type UnknownNodeErrorType = UnknownNodeError & {\n  name: 'UnknownNodeError'\n}\nexport class UnknownNodeError extends BaseError {\n  override name = 'UnknownNodeError'\n\n  constructor({ cause }: { cause?: BaseError }) {\n    super(`An error occurred while executing: ${cause?.shortMessage}`, {\n      cause,\n    })\n  }\n}\n","import type { Address } from 'abitype'\nimport type { ErrorType } from '../../errors/utils.js'\n\nconst addressRegex = /^0x[a-fA-F0-9]{40}$/\n\nexport type IsAddressErrorType = ErrorType\n\nexport function isAddress(address: string): address is Address {\n  return addressRegex.test(address)\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray, Hex } from '../../types/misc.js'\n\nexport type ConcatReturnType<TValue extends Hex | ByteArray> =\n  TValue extends Hex ? Hex : ByteArray\n\nexport type ConcatErrorType =\n  | ConcatBytesErrorType\n  | ConcatHexErrorType\n  | ErrorType\n\nexport function concat<TValue extends Hex | ByteArray>(\n  values: readonly TValue[],\n): ConcatReturnType<TValue> {\n  if (typeof values[0] === 'string')\n    return concatHex(values as readonly Hex[]) as ConcatReturnType<TValue>\n  return concatBytes(values as readonly ByteArray[]) as ConcatReturnType<TValue>\n}\n\nexport type ConcatBytesErrorType = ErrorType\n\nexport function concatBytes(values: readonly ByteArray[]): ByteArray {\n  let length = 0\n  for (const arr of values) {\n    length += arr.length\n  }\n  const result = new Uint8Array(length)\n  let offset = 0\n  for (const arr of values) {\n    result.set(arr, offset)\n    offset += arr.length\n  }\n  return result\n}\n\nexport type ConcatHexErrorType = ErrorType\n\nexport function concatHex(values: readonly Hex[]): Hex {\n  return `0x${(values as Hex[]).reduce(\n    (acc, x) => acc + x.replace('0x', ''),\n    '',\n  )}`\n}\n","export const version = '0.9.8'\n","import type { OneOf, Pretty } from './types.js'\nimport { version } from './version.js'\n\ntype BaseErrorArgs = Pretty<\n  {\n    docsPath?: string | undefined\n    metaMessages?: string[] | undefined\n  } & OneOf<{ details?: string | undefined } | { cause?: BaseError | Error }>\n>\n\nexport class BaseError extends Error {\n  details: string\n  docsPath?: string | undefined\n  metaMessages?: string[] | undefined\n  shortMessage: string\n\n  override name = 'AbiTypeError'\n\n  constructor(shortMessage: string, args: BaseErrorArgs = {}) {\n    const details =\n      args.cause instanceof BaseError\n        ? args.cause.details\n        : args.cause?.message\n        ? args.cause.message\n        : args.details!\n    const docsPath =\n      args.cause instanceof BaseError\n        ? args.cause.docsPath || args.docsPath\n        : args.docsPath\n    const message = [\n      shortMessage || 'An error occurred.',\n      '',\n      ...(args.metaMessages ? [...args.metaMessages, ''] : []),\n      ...(docsPath ? [`Docs: https://abitype.dev${docsPath}`] : []),\n      ...(details ? [`Details: ${details}`] : []),\n      `Version: abitype@${version}`,\n    ].join('\\n')\n\n    super(message)\n\n    if (args.cause) this.cause = args.cause\n    this.details = details\n    this.docsPath = docsPath\n    this.metaMessages = args.metaMessages\n    this.shortMessage = shortMessage\n  }\n}\n","// TODO: This looks cool. Need to check the performance of `new RegExp` versus defined inline though.\n// https://twitter.com/GabrielVergnaud/status/1622906834343366657\nexport function execTyped<T>(regex: RegExp, string: string) {\n  const match = regex.exec(string)\n  return match?.groups as T | undefined\n}\n\n// `bytes<M>`: binary type of `M` bytes, `0 < M <= 32`\n// https://regexr.com/6va55\nexport const bytesRegex = /^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/\n\n// `(u)int<M>`: (un)signed integer type of `M` bits, `0 < M <= 256`, `M % 8 == 0`\n// https://regexr.com/6v8hp\nexport const integerRegex =\n  /^u?int(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/\n\nexport const isTupleRegex = /^\\(.+?\\).*?$/\n","import type { AbiEventParameter, AbiParameter } from '../abi.js'\nimport { execTyped } from '../regex.js'\nimport type { IsNarrowable, Join } from '../types.js'\nimport type { AssertName } from './types/signatures.js'\n\n/**\n * Formats {@link AbiParameter} to human-readable ABI parameter.\n *\n * @param TAbiParameter - ABI parameter\n * @returns Human-readable ABI parameter\n *\n * @example\n * type Result = FormatAbiParameter<{ type: 'address'; name: 'from'; }>\n * //   ^? type Result = 'address from'\n */\nexport type FormatAbiParameter<\n  TAbiParameter extends AbiParameter | AbiEventParameter,\n> = TAbiParameter extends {\n  name?: infer Name extends string\n  type: `tuple${infer Array}`\n  components: infer Components extends readonly AbiParameter[]\n  indexed?: infer Indexed extends boolean\n}\n  ? FormatAbiParameter<\n      {\n        type: `(${Join<\n          {\n            [K in keyof Components]: FormatAbiParameter<\n              {\n                type: Components[K]['type']\n              } & (IsNarrowable<Components[K]['name'], string> extends true\n                ? { name: Components[K]['name'] }\n                : unknown) &\n                (Components[K] extends { components: readonly AbiParameter[] }\n                  ? { components: Components[K]['components'] }\n                  : unknown)\n            >\n          },\n          ', '\n        >})${Array}`\n      } & (IsNarrowable<Name, string> extends true ? { name: Name } : unknown) &\n        (IsNarrowable<Indexed, boolean> extends true\n          ? { indexed: Indexed }\n          : unknown)\n    >\n  : `${TAbiParameter['type']}${TAbiParameter extends { indexed: true }\n      ? ' indexed'\n      : ''}${TAbiParameter['name'] extends infer Name extends string\n      ? Name extends ''\n        ? ''\n        : ` ${AssertName<Name>}`\n      : ''}`\n\n// https://regexr.com/7f7rv\nconst tupleRegex = /^tuple(?<array>(\\[(\\d*)\\])*)$/\n\n/**\n * Formats {@link AbiParameter} to human-readable ABI parameter.\n *\n * @param abiParameter - ABI parameter\n * @returns Human-readable ABI parameter\n *\n * @example\n * const result = formatAbiParameter({ type: 'address', name: 'from' })\n * //    ^? const result: 'address from'\n */\nexport function formatAbiParameter<\n  const TAbiParameter extends AbiParameter | AbiEventParameter,\n>(abiParameter: TAbiParameter): FormatAbiParameter<TAbiParameter> {\n  type Result = FormatAbiParameter<TAbiParameter>\n\n  let type = abiParameter.type\n  if (tupleRegex.test(abiParameter.type) && 'components' in abiParameter) {\n    type = '('\n    const length = abiParameter.components.length as number\n    for (let i = 0; i < length; i++) {\n      const component = abiParameter.components[i]!\n      type += formatAbiParameter(component)\n      if (i < length - 1) type += ', '\n    }\n    const result = execTyped<{ array?: string }>(tupleRegex, abiParameter.type)\n    type += `)${result?.array ?? ''}`\n    return formatAbiParameter({\n      ...abiParameter,\n      type,\n    }) as Result\n  }\n  // Add `indexed` to type if in `abiParameter`\n  if ('indexed' in abiParameter && abiParameter.indexed)\n    type = `${type} indexed`\n  // Return human-readable ABI parameter\n  if (abiParameter.name) return `${type} ${abiParameter.name}` as Result\n  return type as Result\n}\n","import type { AbiEventParameter, AbiParameter } from '../abi.js'\nimport type { Join } from '../types.js'\nimport {\n  type FormatAbiParameter,\n  formatAbiParameter,\n} from './formatAbiParameter.js'\n\n/**\n * Formats {@link AbiParameter}s to human-readable ABI parameter.\n *\n * @param TAbiParameters - ABI parameters\n * @returns Human-readable ABI parameters\n *\n * @example\n * type Result = FormatAbiParameters<[\n *   // ^? type Result = 'address from, uint256 tokenId'\n *   { type: 'address'; name: 'from'; },\n *   { type: 'uint256'; name: 'tokenId'; },\n * ]>\n */\nexport type FormatAbiParameters<\n  TAbiParameters extends readonly [\n    AbiParameter | AbiEventParameter,\n    ...(readonly (AbiParameter | AbiEventParameter)[]),\n  ],\n> = Join<\n  {\n    [K in keyof TAbiParameters]: FormatAbiParameter<TAbiParameters[K]>\n  },\n  ', '\n>\n\n/**\n * Formats {@link AbiParameter}s to human-readable ABI parameters.\n *\n * @param abiParameters - ABI parameters\n * @returns Human-readable ABI parameters\n *\n * @example\n * const result = formatAbiParameters([\n *   //  ^? const result: 'address from, uint256 tokenId'\n *   { type: 'address', name: 'from' },\n *   { type: 'uint256', name: 'tokenId' },\n * ])\n */\nexport function formatAbiParameters<\n  const TAbiParameters extends readonly [\n    AbiParameter | AbiEventParameter,\n    ...(readonly (AbiParameter | AbiEventParameter)[]),\n  ],\n>(abiParameters: TAbiParameters): FormatAbiParameters<TAbiParameters> {\n  let params = ''\n  const length = abiParameters.length\n  for (let i = 0; i < length; i++) {\n    const abiParameter = abiParameters[i]!\n    params += formatAbiParameter(abiParameter)\n    if (i !== length - 1) params += ', '\n  }\n  return params as FormatAbiParameters<TAbiParameters>\n}\n","import type {\n  Abi,\n  AbiConstructor,\n  AbiError,\n  AbiEvent,\n  AbiEventParameter,\n  AbiFallback,\n  AbiFunction,\n  AbiParameter,\n  AbiReceive,\n  AbiStateMutability,\n} from '../abi.js'\nimport {\n  type FormatAbiParameters as FormatAbiParameters_,\n  formatAbiParameters,\n} from './formatAbiParameters.js'\nimport type { AssertName } from './types/signatures.js'\n\n/**\n * Formats ABI item (e.g. error, event, function) into human-readable ABI item\n *\n * @param TAbiItem - ABI item\n * @returns Human-readable ABI item\n */\nexport type FormatAbiItem<TAbiItem extends Abi[number]> =\n  Abi[number] extends TAbiItem\n    ? string\n    :\n        | (TAbiItem extends AbiFunction\n            ? AbiFunction extends TAbiItem\n              ? string\n              : `function ${AssertName<TAbiItem['name']>}(${FormatAbiParameters<\n                  TAbiItem['inputs']\n                >})${TAbiItem['stateMutability'] extends Exclude<\n                  AbiStateMutability,\n                  'nonpayable'\n                >\n                  ? ` ${TAbiItem['stateMutability']}`\n                  : ''}${TAbiItem['outputs']['length'] extends 0\n                  ? ''\n                  : ` returns (${FormatAbiParameters<TAbiItem['outputs']>})`}`\n            : never)\n        | (TAbiItem extends AbiEvent\n            ? AbiEvent extends TAbiItem\n              ? string\n              : `event ${AssertName<TAbiItem['name']>}(${FormatAbiParameters<\n                  TAbiItem['inputs']\n                >})`\n            : never)\n        | (TAbiItem extends AbiError\n            ? AbiError extends TAbiItem\n              ? string\n              : `error ${AssertName<TAbiItem['name']>}(${FormatAbiParameters<\n                  TAbiItem['inputs']\n                >})`\n            : never)\n        | (TAbiItem extends AbiConstructor\n            ? AbiConstructor extends TAbiItem\n              ? string\n              : `constructor(${FormatAbiParameters<\n                  TAbiItem['inputs']\n                >})${TAbiItem['stateMutability'] extends 'payable'\n                  ? ' payable'\n                  : ''}`\n            : never)\n        | (TAbiItem extends AbiFallback\n            ? AbiFallback extends TAbiItem\n              ? string\n              : 'fallback()'\n            : never)\n        | (TAbiItem extends AbiReceive\n            ? AbiReceive extends TAbiItem\n              ? string\n              : 'receive() external payable'\n            : never)\n\ntype FormatAbiParameters<\n  TAbiParameters extends readonly (AbiParameter | AbiEventParameter)[],\n> = TAbiParameters['length'] extends 0\n  ? ''\n  : FormatAbiParameters_<\n      TAbiParameters extends readonly [\n        AbiParameter | AbiEventParameter,\n        ...(readonly (AbiParameter | AbiEventParameter)[]),\n      ]\n        ? TAbiParameters\n        : never\n    >\n\n/**\n * Formats ABI item (e.g. error, event, function) into human-readable ABI item\n *\n * @param abiItem - ABI item\n * @returns Human-readable ABI item\n */\nexport function formatAbiItem<const TAbiItem extends Abi[number]>(\n  abiItem: TAbiItem,\n): FormatAbiItem<TAbiItem> {\n  type Result = FormatAbiItem<TAbiItem>\n  type Params = readonly [\n    AbiParameter | AbiEventParameter,\n    ...(readonly (AbiParameter | AbiEventParameter)[]),\n  ]\n\n  if (abiItem.type === 'function')\n    return `function ${abiItem.name}(${formatAbiParameters(\n      abiItem.inputs as Params,\n    )})${\n      abiItem.stateMutability && abiItem.stateMutability !== 'nonpayable'\n        ? ` ${abiItem.stateMutability}`\n        : ''\n    }${\n      abiItem.outputs.length\n        ? ` returns (${formatAbiParameters(abiItem.outputs as Params)})`\n        : ''\n    }`\n  else if (abiItem.type === 'event')\n    return `event ${abiItem.name}(${formatAbiParameters(\n      abiItem.inputs as Params,\n    )})`\n  else if (abiItem.type === 'error')\n    return `error ${abiItem.name}(${formatAbiParameters(\n      abiItem.inputs as Params,\n    )})`\n  else if (abiItem.type === 'constructor')\n    return `constructor(${formatAbiParameters(abiItem.inputs as Params)})${\n      abiItem.stateMutability === 'payable' ? ' payable' : ''\n    }`\n  else if (abiItem.type === 'fallback') return 'fallback()' as Result\n  return 'receive() external payable' as Result\n}\n","import type { AbiStateMutability } from '../../abi.js'\nimport { execTyped } from '../../regex.js'\nimport type {\n  EventModifier,\n  FunctionModifier,\n  Modifier,\n} from '../types/signatures.js'\n\n// https://regexr.com/7gmok\nconst errorSignatureRegex =\n  /^error (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*)\\((?<parameters>.*?)\\)$/\nexport function isErrorSignature(signature: string) {\n  return errorSignatureRegex.test(signature)\n}\nexport function execErrorSignature(signature: string) {\n  return execTyped<{ name: string; parameters: string }>(\n    errorSignatureRegex,\n    signature,\n  )\n}\n\n// https://regexr.com/7gmoq\nconst eventSignatureRegex =\n  /^event (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*)\\((?<parameters>.*?)\\)$/\nexport function isEventSignature(signature: string) {\n  return eventSignatureRegex.test(signature)\n}\nexport function execEventSignature(signature: string) {\n  return execTyped<{ name: string; parameters: string }>(\n    eventSignatureRegex,\n    signature,\n  )\n}\n\n// https://regexr.com/7gmot\nconst functionSignatureRegex =\n  /^function (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*)\\((?<parameters>.*?)\\)(?: (?<scope>external|public{1}))?(?: (?<stateMutability>pure|view|nonpayable|payable{1}))?(?: returns\\s?\\((?<returns>.*?)\\))?$/\nexport function isFunctionSignature(signature: string) {\n  return functionSignatureRegex.test(signature)\n}\nexport function execFunctionSignature(signature: string) {\n  return execTyped<{\n    name: string\n    parameters: string\n    stateMutability?: AbiStateMutability\n    returns?: string\n  }>(functionSignatureRegex, signature)\n}\n\n// https://regexr.com/7gmp3\nconst structSignatureRegex =\n  /^struct (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*) \\{(?<properties>.*?)\\}$/\nexport function isStructSignature(signature: string) {\n  return structSignatureRegex.test(signature)\n}\nexport function execStructSignature(signature: string) {\n  return execTyped<{ name: string; properties: string }>(\n    structSignatureRegex,\n    signature,\n  )\n}\n\n// https://regexr.com/78u01\nconst constructorSignatureRegex =\n  /^constructor\\((?<parameters>.*?)\\)(?:\\s(?<stateMutability>payable{1}))?$/\nexport function isConstructorSignature(signature: string) {\n  return constructorSignatureRegex.test(signature)\n}\nexport function execConstructorSignature(signature: string) {\n  return execTyped<{\n    parameters: string\n    stateMutability?: Extract<AbiStateMutability, 'payable'>\n  }>(constructorSignatureRegex, signature)\n}\n\n// https://regexr.com/78u18\nconst fallbackSignatureRegex = /^fallback\\(\\)$/\nexport function isFallbackSignature(signature: string) {\n  return fallbackSignatureRegex.test(signature)\n}\n\n// https://regexr.com/78u1k\nconst receiveSignatureRegex = /^receive\\(\\) external payable$/\nexport function isReceiveSignature(signature: string) {\n  return receiveSignatureRegex.test(signature)\n}\n\nexport const modifiers = new Set<Modifier>([\n  'memory',\n  'indexed',\n  'storage',\n  'calldata',\n])\nexport const eventModifiers = new Set<EventModifier>(['indexed'])\nexport const functionModifiers = new Set<FunctionModifier>([\n  'calldata',\n  'memory',\n  'storage',\n])\n","import { BaseError } from '../../errors.js'\n\nexport class InvalidAbiItemError extends BaseError {\n  override name = 'InvalidAbiItemError'\n\n  constructor({ signature }: { signature: string | object }) {\n    super('Failed to parse ABI item.', {\n      details: `parseAbiItem(${JSON.stringify(signature, null, 2)})`,\n      docsPath: '/api/human.html#parseabiitem-1',\n    })\n  }\n}\n\nexport class UnknownTypeError extends BaseError {\n  override name = 'UnknownTypeError'\n\n  constructor({ type }: { type: string }) {\n    super('Unknown type.', {\n      metaMessages: [\n        `Type \"${type}\" is not a valid ABI type. Perhaps you forgot to include a struct signature?`,\n      ],\n    })\n  }\n}\n\nexport class UnknownSolidityTypeError extends BaseError {\n  override name = 'UnknownSolidityTypeError'\n\n  constructor({ type }: { type: string }) {\n    super('Unknown type.', {\n      metaMessages: [`Type \"${type}\" is not a valid ABI type.`],\n    })\n  }\n}\n","import type { AbiItemType, AbiParameter } from '../../abi.js'\nimport { BaseError } from '../../errors.js'\nimport type { Modifier } from '../types/signatures.js'\n\nexport class InvalidAbiParameterError extends BaseError {\n  override name = 'InvalidAbiParameterError'\n\n  constructor({ param }: { param: string | object }) {\n    super('Failed to parse ABI parameter.', {\n      details: `parseAbiParameter(${JSON.stringify(param, null, 2)})`,\n      docsPath: '/api/human.html#parseabiparameter-1',\n    })\n  }\n}\n\nexport class InvalidAbiParametersError extends BaseError {\n  override name = 'InvalidAbiParametersError'\n\n  constructor({ params }: { params: string | object }) {\n    super('Failed to parse ABI parameters.', {\n      details: `parseAbiParameters(${JSON.stringify(params, null, 2)})`,\n      docsPath: '/api/human.html#parseabiparameters-1',\n    })\n  }\n}\n\nexport class InvalidParameterError extends BaseError {\n  override name = 'InvalidParameterError'\n\n  constructor({ param }: { param: string }) {\n    super('Invalid ABI parameter.', {\n      details: param,\n    })\n  }\n}\n\nexport class SolidityProtectedKeywordError extends BaseError {\n  override name = 'SolidityProtectedKeywordError'\n\n  constructor({ param, name }: { param: string; name: string }) {\n    super('Invalid ABI parameter.', {\n      details: param,\n      metaMessages: [\n        `\"${name}\" is a protected Solidity keyword. More info: https://docs.soliditylang.org/en/latest/cheatsheet.html`,\n      ],\n    })\n  }\n}\n\nexport class InvalidModifierError extends BaseError {\n  override name = 'InvalidModifierError'\n\n  constructor({\n    param,\n    type,\n    modifier,\n  }: {\n    param: string\n    type?: AbiItemType | 'struct' | undefined\n    modifier: Modifier\n  }) {\n    super('Invalid ABI parameter.', {\n      details: param,\n      metaMessages: [\n        `Modifier \"${modifier}\" not allowed${\n          type ? ` in \"${type}\" type` : ''\n        }.`,\n      ],\n    })\n  }\n}\n\nexport class InvalidFunctionModifierError extends BaseError {\n  override name = 'InvalidFunctionModifierError'\n\n  constructor({\n    param,\n    type,\n    modifier,\n  }: {\n    param: string\n    type?: AbiItemType | 'struct' | undefined\n    modifier: Modifier\n  }) {\n    super('Invalid ABI parameter.', {\n      details: param,\n      metaMessages: [\n        `Modifier \"${modifier}\" not allowed${\n          type ? ` in \"${type}\" type` : ''\n        }.`,\n        `Data location can only be specified for array, struct, or mapping types, but \"${modifier}\" was given.`,\n      ],\n    })\n  }\n}\n\nexport class InvalidAbiTypeParameterError extends BaseError {\n  override name = 'InvalidAbiTypeParameterError'\n\n  constructor({\n    abiParameter,\n  }: {\n    abiParameter: AbiParameter & { indexed?: boolean | undefined }\n  }) {\n    super('Invalid ABI parameter.', {\n      details: JSON.stringify(abiParameter, null, 2),\n      metaMessages: ['ABI parameter type is invalid.'],\n    })\n  }\n}\n","import type { AbiItemType } from '../../abi.js'\nimport { BaseError } from '../../errors.js'\n\nexport class InvalidSignatureError extends BaseError {\n  override name = 'InvalidSignatureError'\n\n  constructor({\n    signature,\n    type,\n  }: {\n    signature: string\n    type: AbiItemType | 'struct'\n  }) {\n    super(`Invalid ${type} signature.`, {\n      details: signature,\n    })\n  }\n}\n\nexport class UnknownSignatureError extends BaseError {\n  override name = 'UnknownSignatureError'\n\n  constructor({ signature }: { signature: string }) {\n    super('Unknown signature.', {\n      details: signature,\n    })\n  }\n}\n\nexport class InvalidStructSignatureError extends BaseError {\n  override name = 'InvalidStructSignatureError'\n\n  constructor({ signature }: { signature: string }) {\n    super('Invalid struct signature.', {\n      details: signature,\n      metaMessages: ['No properties exist.'],\n    })\n  }\n}\n","import { BaseError } from '../../errors.js'\n\nexport class CircularReferenceError extends BaseError {\n  override name = 'CircularReferenceError'\n\n  constructor({ type }: { type: string }) {\n    super('Circular reference detected.', {\n      metaMessages: [`Struct \"${type}\" is a circular reference.`],\n    })\n  }\n}\n","import { BaseError } from '../../errors.js'\n\nexport class InvalidParenthesisError extends BaseError {\n  override name = 'InvalidParenthesisError'\n\n  constructor({ current, depth }: { current: string; depth: number }) {\n    super('Unbalanced parentheses.', {\n      metaMessages: [\n        `\"${current.trim()}\" has too many ${\n          depth > 0 ? 'opening' : 'closing'\n        } parentheses.`,\n      ],\n      details: `Depth \"${depth}\"`,\n    })\n  }\n}\n","import type { AbiItemType, AbiParameter } from '../../abi.js'\n\n/**\n * Gets {@link parameterCache} cache key namespaced by {@link type}. This prevents parameters from being accessible to types that don't allow them (e.g. `string indexed foo` not allowed outside of `type: 'event'`).\n * @param param ABI parameter string\n * @param type ABI parameter type\n * @returns Cache key for {@link parameterCache}\n */\nexport function getParameterCacheKey(\n  param: string,\n  type?: AbiItemType | 'struct',\n) {\n  if (type) return `${type}:${param}`\n  return param\n}\n\n/**\n * Basic cache seeded with common ABI parameter strings.\n *\n * **Note: When seeding more parameters, make sure you benchmark performance. The current number is the ideal balance between performance and having an already existing cache.**\n */\nexport const parameterCache = new Map<\n  string,\n  AbiParameter & { indexed?: boolean }\n>([\n  // Unnamed\n  ['address', { type: 'address' }],\n  ['bool', { type: 'bool' }],\n  ['bytes', { type: 'bytes' }],\n  ['bytes32', { type: 'bytes32' }],\n  ['int', { type: 'int256' }],\n  ['int256', { type: 'int256' }],\n  ['string', { type: 'string' }],\n  ['uint', { type: 'uint256' }],\n  ['uint8', { type: 'uint8' }],\n  ['uint16', { type: 'uint16' }],\n  ['uint24', { type: 'uint24' }],\n  ['uint32', { type: 'uint32' }],\n  ['uint64', { type: 'uint64' }],\n  ['uint96', { type: 'uint96' }],\n  ['uint112', { type: 'uint112' }],\n  ['uint160', { type: 'uint160' }],\n  ['uint192', { type: 'uint192' }],\n  ['uint256', { type: 'uint256' }],\n\n  // Named\n  ['address owner', { type: 'address', name: 'owner' }],\n  ['address to', { type: 'address', name: 'to' }],\n  ['bool approved', { type: 'bool', name: 'approved' }],\n  ['bytes _data', { type: 'bytes', name: '_data' }],\n  ['bytes data', { type: 'bytes', name: 'data' }],\n  ['bytes signature', { type: 'bytes', name: 'signature' }],\n  ['bytes32 hash', { type: 'bytes32', name: 'hash' }],\n  ['bytes32 r', { type: 'bytes32', name: 'r' }],\n  ['bytes32 root', { type: 'bytes32', name: 'root' }],\n  ['bytes32 s', { type: 'bytes32', name: 's' }],\n  ['string name', { type: 'string', name: 'name' }],\n  ['string symbol', { type: 'string', name: 'symbol' }],\n  ['string tokenURI', { type: 'string', name: 'tokenURI' }],\n  ['uint tokenId', { type: 'uint256', name: 'tokenId' }],\n  ['uint8 v', { type: 'uint8', name: 'v' }],\n  ['uint256 balance', { type: 'uint256', name: 'balance' }],\n  ['uint256 tokenId', { type: 'uint256', name: 'tokenId' }],\n  ['uint256 value', { type: 'uint256', name: 'value' }],\n\n  // Indexed\n  [\n    'event:address indexed from',\n    { type: 'address', name: 'from', indexed: true },\n  ],\n  ['event:address indexed to', { type: 'address', name: 'to', indexed: true }],\n  [\n    'event:uint indexed tokenId',\n    { type: 'uint256', name: 'tokenId', indexed: true },\n  ],\n  [\n    'event:uint256 indexed tokenId',\n    { type: 'uint256', name: 'tokenId', indexed: true },\n  ],\n])\n","import type {\n  AbiItemType,\n  AbiType,\n  SolidityArray,\n  SolidityBytes,\n  SolidityString,\n  SolidityTuple,\n} from '../../abi.js'\nimport {\n  bytesRegex,\n  execTyped,\n  integerRegex,\n  isTupleRegex,\n} from '../../regex.js'\nimport { UnknownSolidityTypeError } from '../errors/abiItem.js'\nimport {\n  InvalidFunctionModifierError,\n  InvalidModifierError,\n  InvalidParameterError,\n  SolidityProtectedKeywordError,\n} from '../errors/abiParameter.js'\nimport {\n  InvalidSignatureError,\n  UnknownSignatureError,\n} from '../errors/signature.js'\nimport { InvalidParenthesisError } from '../errors/splitParameters.js'\nimport type { FunctionModifier, Modifier } from '../types/signatures.js'\nimport type { StructLookup } from '../types/structs.js'\nimport { getParameterCacheKey, parameterCache } from './cache.js'\nimport {\n  eventModifiers,\n  execConstructorSignature,\n  execErrorSignature,\n  execEventSignature,\n  execFunctionSignature,\n  functionModifiers,\n  isConstructorSignature,\n  isErrorSignature,\n  isEventSignature,\n  isFallbackSignature,\n  isFunctionSignature,\n  isReceiveSignature,\n} from './signatures.js'\n\nexport function parseSignature(signature: string, structs: StructLookup = {}) {\n  if (isFunctionSignature(signature)) {\n    const match = execFunctionSignature(signature)\n    if (!match) throw new InvalidSignatureError({ signature, type: 'function' })\n\n    const inputParams = splitParameters(match.parameters)\n    const inputs = []\n    const inputLength = inputParams.length\n    for (let i = 0; i < inputLength; i++) {\n      inputs.push(\n        parseAbiParameter(inputParams[i]!, {\n          modifiers: functionModifiers,\n          structs,\n          type: 'function',\n        }),\n      )\n    }\n\n    const outputs = []\n    if (match.returns) {\n      const outputParams = splitParameters(match.returns)\n      const outputLength = outputParams.length\n      for (let i = 0; i < outputLength; i++) {\n        outputs.push(\n          parseAbiParameter(outputParams[i]!, {\n            modifiers: functionModifiers,\n            structs,\n            type: 'function',\n          }),\n        )\n      }\n    }\n\n    return {\n      name: match.name,\n      type: 'function',\n      stateMutability: match.stateMutability ?? 'nonpayable',\n      inputs,\n      outputs,\n    }\n  }\n\n  if (isEventSignature(signature)) {\n    const match = execEventSignature(signature)\n    if (!match) throw new InvalidSignatureError({ signature, type: 'event' })\n\n    const params = splitParameters(match.parameters)\n    const abiParameters = []\n    const length = params.length\n    for (let i = 0; i < length; i++) {\n      abiParameters.push(\n        parseAbiParameter(params[i]!, {\n          modifiers: eventModifiers,\n          structs,\n          type: 'event',\n        }),\n      )\n    }\n    return { name: match.name, type: 'event', inputs: abiParameters }\n  }\n\n  if (isErrorSignature(signature)) {\n    const match = execErrorSignature(signature)\n    if (!match) throw new InvalidSignatureError({ signature, type: 'error' })\n\n    const params = splitParameters(match.parameters)\n    const abiParameters = []\n    const length = params.length\n    for (let i = 0; i < length; i++) {\n      abiParameters.push(\n        parseAbiParameter(params[i]!, { structs, type: 'error' }),\n      )\n    }\n    return { name: match.name, type: 'error', inputs: abiParameters }\n  }\n\n  if (isConstructorSignature(signature)) {\n    const match = execConstructorSignature(signature)\n    if (!match)\n      throw new InvalidSignatureError({ signature, type: 'constructor' })\n\n    const params = splitParameters(match.parameters)\n    const abiParameters = []\n    const length = params.length\n    for (let i = 0; i < length; i++) {\n      abiParameters.push(\n        parseAbiParameter(params[i]!, { structs, type: 'constructor' }),\n      )\n    }\n    return {\n      type: 'constructor',\n      stateMutability: match.stateMutability ?? 'nonpayable',\n      inputs: abiParameters,\n    }\n  }\n\n  if (isFallbackSignature(signature)) return { type: 'fallback' }\n  if (isReceiveSignature(signature))\n    return {\n      type: 'receive',\n      stateMutability: 'payable',\n    }\n\n  throw new UnknownSignatureError({ signature })\n}\n\nconst abiParameterWithoutTupleRegex =\n  /^(?<type>[a-zA-Z$_][a-zA-Z0-9$_]*)(?<array>(?:\\[\\d*?\\])+?)?(?:\\s(?<modifier>calldata|indexed|memory|storage{1}))?(?:\\s(?<name>[a-zA-Z$_][a-zA-Z0-9$_]*))?$/\nconst abiParameterWithTupleRegex =\n  /^\\((?<type>.+?)\\)(?<array>(?:\\[\\d*?\\])+?)?(?:\\s(?<modifier>calldata|indexed|memory|storage{1}))?(?:\\s(?<name>[a-zA-Z$_][a-zA-Z0-9$_]*))?$/\nconst dynamicIntegerRegex = /^u?int$/\n\ntype ParseOptions = {\n  modifiers?: Set<Modifier>\n  structs?: StructLookup\n  type?: AbiItemType | 'struct'\n}\n\nexport function parseAbiParameter(param: string, options?: ParseOptions) {\n  // optional namespace cache by `type`\n  const parameterCacheKey = getParameterCacheKey(param, options?.type)\n  if (parameterCache.has(parameterCacheKey))\n    return parameterCache.get(parameterCacheKey)!\n\n  const isTuple = isTupleRegex.test(param)\n  const match = execTyped<{\n    array?: string\n    modifier?: Modifier\n    name?: string\n    type: string\n  }>(\n    isTuple ? abiParameterWithTupleRegex : abiParameterWithoutTupleRegex,\n    param,\n  )\n  if (!match) throw new InvalidParameterError({ param })\n\n  if (match.name && isSolidityKeyword(match.name))\n    throw new SolidityProtectedKeywordError({ param, name: match.name })\n\n  const name = match.name ? { name: match.name } : {}\n  const indexed = match.modifier === 'indexed' ? { indexed: true } : {}\n  const structs = options?.structs ?? {}\n  let type: string\n  let components = {}\n  if (isTuple) {\n    type = 'tuple'\n    const params = splitParameters(match.type)\n    const components_ = []\n    const length = params.length\n    for (let i = 0; i < length; i++) {\n      // remove `modifiers` from `options` to prevent from being added to tuple components\n      components_.push(parseAbiParameter(params[i]!, { structs }))\n    }\n    components = { components: components_ }\n  } else if (match.type in structs) {\n    type = 'tuple'\n    components = { components: structs[match.type] }\n  } else if (dynamicIntegerRegex.test(match.type)) {\n    type = `${match.type}256`\n  } else {\n    type = match.type\n    if (!(options?.type === 'struct') && !isSolidityType(type))\n      throw new UnknownSolidityTypeError({ type })\n  }\n\n  if (match.modifier) {\n    // Check if modifier exists, but is not allowed (e.g. `indexed` in `functionModifiers`)\n    if (!options?.modifiers?.has?.(match.modifier))\n      throw new InvalidModifierError({\n        param,\n        type: options?.type,\n        modifier: match.modifier,\n      })\n\n    // Check if resolved `type` is valid if there is a function modifier\n    if (\n      functionModifiers.has(match.modifier as FunctionModifier) &&\n      !isValidDataLocation(type, !!match.array)\n    )\n      throw new InvalidFunctionModifierError({\n        param,\n        type: options?.type,\n        modifier: match.modifier,\n      })\n  }\n\n  const abiParameter = {\n    type: `${type}${match.array ?? ''}`,\n    ...name,\n    ...indexed,\n    ...components,\n  }\n  parameterCache.set(parameterCacheKey, abiParameter)\n  return abiParameter\n}\n\n// s/o latika for this\nexport function splitParameters(\n  params: string,\n  result: string[] = [],\n  current = '',\n  depth = 0,\n): readonly string[] {\n  if (params === '') {\n    if (current === '') return result\n    if (depth !== 0) throw new InvalidParenthesisError({ current, depth })\n\n    result.push(current.trim())\n    return result\n  }\n\n  const length = params.length\n  // rome-ignore lint/correctness/noUnreachable: recursive\n  for (let i = 0; i < length; i++) {\n    const char = params[i]\n    const tail = params.slice(i + 1)\n    switch (char) {\n      case ',':\n        return depth === 0\n          ? splitParameters(tail, [...result, current.trim()])\n          : splitParameters(tail, result, `${current}${char}`, depth)\n      case '(':\n        return splitParameters(tail, result, `${current}${char}`, depth + 1)\n      case ')':\n        return splitParameters(tail, result, `${current}${char}`, depth - 1)\n      default:\n        return splitParameters(tail, result, `${current}${char}`, depth)\n    }\n  }\n\n  return []\n}\n\nexport function isSolidityType(\n  type: string,\n): type is Exclude<AbiType, SolidityTuple | SolidityArray> {\n  return (\n    type === 'address' ||\n    type === 'bool' ||\n    type === 'function' ||\n    type === 'string' ||\n    bytesRegex.test(type) ||\n    integerRegex.test(type)\n  )\n}\n\nconst protectedKeywordsRegex =\n  /^(?:after|alias|anonymous|apply|auto|byte|calldata|case|catch|constant|copyof|default|defined|error|event|external|false|final|function|immutable|implements|in|indexed|inline|internal|let|mapping|match|memory|mutable|null|of|override|partial|private|promise|public|pure|reference|relocatable|return|returns|sizeof|static|storage|struct|super|supports|switch|this|true|try|typedef|typeof|var|view|virtual)$/\n\nexport function isSolidityKeyword(name: string) {\n  return (\n    name === 'address' ||\n    name === 'bool' ||\n    name === 'function' ||\n    name === 'string' ||\n    name === 'tuple' ||\n    bytesRegex.test(name) ||\n    integerRegex.test(name) ||\n    protectedKeywordsRegex.test(name)\n  )\n}\n\nexport function isValidDataLocation(\n  type: string,\n  isArray: boolean,\n): type is Exclude<\n  AbiType,\n  SolidityString | Extract<SolidityBytes, 'bytes'> | SolidityArray\n> {\n  return isArray || type === 'bytes' || type === 'string' || type === 'tuple'\n}\n","import type { AbiParameter } from '../../abi.js'\nimport { execTyped, isTupleRegex } from '../../regex.js'\nimport { UnknownTypeError } from '../errors/abiItem.js'\nimport { InvalidAbiTypeParameterError } from '../errors/abiParameter.js'\nimport {\n  InvalidSignatureError,\n  InvalidStructSignatureError,\n} from '../errors/signature.js'\nimport { CircularReferenceError } from '../errors/struct.js'\nimport type { StructLookup } from '../types/structs.js'\nimport { execStructSignature, isStructSignature } from './signatures.js'\nimport { isSolidityType, parseAbiParameter } from './utils.js'\n\nexport function parseStructs(signatures: readonly string[]) {\n  // Create \"shallow\" version of each struct (and filter out non-structs or invalid structs)\n  const shallowStructs: StructLookup = {}\n  const signaturesLength = signatures.length\n  for (let i = 0; i < signaturesLength; i++) {\n    const signature = signatures[i]!\n    if (!isStructSignature(signature)) continue\n\n    const match = execStructSignature(signature)\n    if (!match) throw new InvalidSignatureError({ signature, type: 'struct' })\n\n    const properties = match.properties.split(';')\n\n    const components: AbiParameter[] = []\n    const propertiesLength = properties.length\n    for (let k = 0; k < propertiesLength; k++) {\n      const property = properties[k]!\n      const trimmed = property.trim()\n      if (!trimmed) continue\n      const abiParameter = parseAbiParameter(trimmed, {\n        type: 'struct',\n      })\n      components.push(abiParameter)\n    }\n\n    if (!components.length) throw new InvalidStructSignatureError({ signature })\n    shallowStructs[match.name] = components\n  }\n\n  // Resolve nested structs inside each parameter\n  const resolvedStructs: StructLookup = {}\n  const entries = Object.entries(shallowStructs)\n  const entriesLength = entries.length\n  for (let i = 0; i < entriesLength; i++) {\n    const [name, parameters] = entries[i]!\n    resolvedStructs[name] = resolveStructs(parameters, shallowStructs)\n  }\n\n  return resolvedStructs\n}\n\nconst typeWithoutTupleRegex =\n  /^(?<type>[a-zA-Z$_][a-zA-Z0-9$_]*)(?<array>(?:\\[\\d*?\\])+?)?$/\n\nfunction resolveStructs(\n  abiParameters: readonly (AbiParameter & { indexed?: true })[],\n  structs: StructLookup,\n  ancestors = new Set<string>(),\n) {\n  const components: AbiParameter[] = []\n  const length = abiParameters.length\n  for (let i = 0; i < length; i++) {\n    const abiParameter = abiParameters[i]!\n    const isTuple = isTupleRegex.test(abiParameter.type)\n    if (isTuple) components.push(abiParameter)\n    else {\n      const match = execTyped<{ array?: string; type: string }>(\n        typeWithoutTupleRegex,\n        abiParameter.type,\n      )\n      if (!match?.type) throw new InvalidAbiTypeParameterError({ abiParameter })\n\n      const { array, type } = match\n      if (type in structs) {\n        if (ancestors.has(type)) throw new CircularReferenceError({ type })\n\n        components.push({\n          ...abiParameter,\n          type: `tuple${array ?? ''}`,\n          components: resolveStructs(\n            structs[type] ?? [],\n            structs,\n            new Set([...ancestors, type]),\n          ),\n        })\n      } else {\n        if (isSolidityType(type)) components.push(abiParameter)\n        else throw new UnknownTypeError({ type })\n      }\n    }\n  }\n\n  return components\n}\n","import type { Abi } from '../abi.js'\nimport type { Error, Filter } from '../types.js'\nimport { isStructSignature } from './runtime/signatures.js'\nimport { parseStructs } from './runtime/structs.js'\nimport { parseSignature } from './runtime/utils.js'\nimport type { Signatures } from './types/signatures.js'\nimport type { ParseStructs } from './types/structs.js'\nimport type { ParseSignature } from './types/utils.js'\n\n/**\n * Parses human-readable ABI into JSON {@link Abi}\n *\n * @param TSignatures - Human-readable ABI\n * @returns Parsed {@link Abi}\n *\n * @example\n * type Result = ParseAbi<\n *   // ^? type Result = readonly [{ name: \"balanceOf\"; type: \"function\"; stateMutability:...\n *   [\n *     'function balanceOf(address owner) view returns (uint256)',\n *     'event Transfer(address indexed from, address indexed to, uint256 amount)',\n *   ]\n * >\n */\nexport type ParseAbi<TSignatures extends readonly string[]> =\n  string[] extends TSignatures\n    ? Abi // If `T` was not able to be inferred (e.g. just `string[]`), return `Abi`\n    : TSignatures extends readonly string[]\n    ? TSignatures extends Signatures<TSignatures> // Validate signatures\n      ? ParseStructs<TSignatures> extends infer Structs\n        ? {\n            [K in keyof TSignatures]: TSignatures[K] extends string\n              ? ParseSignature<TSignatures[K], Structs>\n              : never\n          } extends infer Mapped extends readonly unknown[]\n          ? Filter<Mapped, never> extends infer Result\n            ? Result extends readonly []\n              ? never\n              : Result\n            : never\n          : never\n        : never\n      : never\n    : never\n\n/**\n * Parses human-readable ABI into JSON {@link Abi}\n *\n * @param signatures - Human-Readable ABI\n * @returns Parsed {@link Abi}\n *\n * @example\n * const abi = parseAbi([\n *   //  ^? const abi: readonly [{ name: \"balanceOf\"; type: \"function\"; stateMutability:...\n *   'function balanceOf(address owner) view returns (uint256)',\n *   'event Transfer(address indexed from, address indexed to, uint256 amount)',\n * ])\n */\nexport function parseAbi<const TSignatures extends readonly string[]>(\n  signatures: TSignatures['length'] extends 0\n    ? Error<'At least one signature required'>\n    : Signatures<TSignatures> extends TSignatures\n    ? TSignatures\n    : Signatures<TSignatures>,\n): ParseAbi<TSignatures> {\n  const structs = parseStructs(signatures as readonly string[])\n  const abi = []\n  const length = signatures.length as number\n  for (let i = 0; i < length; i++) {\n    const signature = (signatures as readonly string[])[i]!\n    if (isStructSignature(signature)) continue\n    abi.push(parseSignature(signature, structs))\n  }\n  return abi as unknown as ParseAbi<TSignatures>\n}\n","export type {\n  Abi,\n  AbiConstructor,\n  AbiError,\n  AbiEvent,\n  AbiEventParameter,\n  AbiFallback,\n  AbiFunction,\n  AbiInternalType,\n  AbiItemType,\n  AbiParameter,\n  AbiParameterKind,\n  AbiReceive,\n  AbiStateMutability,\n  AbiType,\n  Address,\n  SolidityAddress,\n  SolidityArray,\n  SolidityArrayWithoutTuple,\n  SolidityArrayWithTuple,\n  SolidityBool,\n  SolidityBytes,\n  SolidityFixedArrayRange,\n  SolidityFixedArraySizeLookup,\n  SolidityFunction,\n  SolidityInt,\n  SolidityString,\n  SolidityTuple,\n  TypedData,\n  TypedDataDomain,\n  TypedDataParameter,\n  TypedDataType,\n} from './abi.js'\n\nexport type { Config, DefaultConfig, ResolvedConfig } from './config.js'\n\nexport { BaseError } from './errors.js'\n\nexport type { Narrow } from './narrow.js'\nexport { narrow } from './narrow.js'\n\nexport type {\n  AbiParameterToPrimitiveType,\n  AbiParametersToPrimitiveTypes,\n  AbiTypeToPrimitiveType,\n  ExtractAbiError,\n  ExtractAbiErrorNames,\n  ExtractAbiErrors,\n  ExtractAbiEvent,\n  ExtractAbiEventNames,\n  ExtractAbiEvents,\n  ExtractAbiFunction,\n  ExtractAbiFunctionNames,\n  ExtractAbiFunctions,\n  IsAbi,\n  IsTypedData,\n  TypedDataToPrimitiveTypes,\n} from './utils.js'\n\n////////////////////////////////////////////////////////////////////////////////////////////////////\n// Human-Readable\n\nexport {\n  formatAbi,\n  type FormatAbi,\n} from './human-readable/formatAbi.js'\n\nexport {\n  formatAbiItem,\n  type FormatAbiItem,\n} from './human-readable/formatAbiItem.js'\n\nexport {\n  formatAbiParameter,\n  type FormatAbiParameter,\n} from './human-readable/formatAbiParameter.js'\n\nexport {\n  formatAbiParameters,\n  type FormatAbiParameters,\n} from './human-readable/formatAbiParameters.js'\n\nexport { parseAbi, type ParseAbi } from './human-readable/parseAbi.js'\n\nexport {\n  parseAbiItem,\n  type ParseAbiItem,\n} from './human-readable/parseAbiItem.js'\n\nexport {\n  parseAbiParameter,\n  type ParseAbiParameter,\n} from './human-readable/parseAbiParameter.js'\n\nexport {\n  parseAbiParameters,\n  type ParseAbiParameters,\n} from './human-readable/parseAbiParameters.js'\n\nexport {\n  UnknownTypeError,\n  InvalidAbiItemError,\n  UnknownSolidityTypeError,\n} from './human-readable/errors/abiItem.js'\n\nexport {\n  InvalidAbiTypeParameterError,\n  InvalidFunctionModifierError,\n  InvalidModifierError,\n  SolidityProtectedKeywordError,\n  InvalidParameterError,\n  InvalidAbiParametersError,\n  InvalidAbiParameterError,\n} from './human-readable/errors/abiParameter.js'\n\nexport {\n  InvalidStructSignatureError,\n  InvalidSignatureError,\n  UnknownSignatureError,\n} from './human-readable/errors/signature.js'\n\nexport { InvalidParenthesisError } from './human-readable/errors/splitParameters.js'\n\nexport { CircularReferenceError } from './human-readable/errors/struct.js'\n","import type { AbiParameter } from 'abitype'\n\nimport {\n  InvalidDefinitionTypeError,\n  type InvalidDefinitionTypeErrorType,\n} from '../../errors/abi.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { AbiItem } from '../../types/contract.js'\n\nexport type FormatAbiItemErrorType =\n  | FormatAbiParamsErrorType\n  | InvalidDefinitionTypeErrorType\n  | ErrorType\n\nexport function formatAbiItem(\n  abiItem: AbiItem,\n  { includeName = false }: { includeName?: boolean } = {},\n) {\n  if (\n    abiItem.type !== 'function' &&\n    abiItem.type !== 'event' &&\n    abiItem.type !== 'error'\n  )\n    throw new InvalidDefinitionTypeError(abiItem.type)\n\n  return `${abiItem.name}(${formatAbiParams(abiItem.inputs, { includeName })})`\n}\n\nexport type FormatAbiParamsErrorType = ErrorType\n\nexport function formatAbiParams(\n  params: readonly AbiParameter[] | undefined,\n  { includeName = false }: { includeName?: boolean } = {},\n): string {\n  if (!params) return ''\n  return params\n    .map((param) => formatAbiParam(param, { includeName }))\n    .join(includeName ? ', ' : ',')\n}\n\nexport type FormatAbiParamErrorType = ErrorType\n\nfunction formatAbiParam(\n  param: AbiParameter,\n  { includeName }: { includeName: boolean },\n): string {\n  if (param.type.startsWith('tuple')) {\n    return `(${formatAbiParams(\n      (param as unknown as { components: AbiParameter[] }).components,\n      { includeName },\n    )})${param.type.slice('tuple'.length)}`\n  }\n  return param.type + (includeName && param.name ? ` ${param.name}` : '')\n}\n","import type { Abi, AbiEvent, AbiParameter } from 'abitype'\n\nimport type { Hex } from '../types/misc.js'\nimport { formatAbiItem, formatAbiParams } from '../utils/abi/formatAbiItem.js'\nimport { size } from '../utils/data/size.js'\n\nimport { BaseError } from './base.js'\n\nexport type AbiConstructorNotFoundErrorType = AbiConstructorNotFoundError & {\n  name: 'AbiConstructorNotFoundError'\n}\nexport class AbiConstructorNotFoundError extends BaseError {\n  override name = 'AbiConstructorNotFoundError'\n  constructor({ docsPath }: { docsPath: string }) {\n    super(\n      [\n        'A constructor was not found on the ABI.',\n        'Make sure you are using the correct ABI and that the constructor exists on it.',\n      ].join('\\n'),\n      {\n        docsPath,\n      },\n    )\n  }\n}\n\nexport type AbiConstructorParamsNotFoundErrorType =\n  AbiConstructorParamsNotFoundError & {\n    name: 'AbiConstructorParamsNotFoundError'\n  }\n\nexport class AbiConstructorParamsNotFoundError extends BaseError {\n  override name = 'AbiConstructorParamsNotFoundError'\n  constructor({ docsPath }: { docsPath: string }) {\n    super(\n      [\n        'Constructor arguments were provided (`args`), but a constructor parameters (`inputs`) were not found on the ABI.',\n        'Make sure you are using the correct ABI, and that the `inputs` attribute on the constructor exists.',\n      ].join('\\n'),\n      {\n        docsPath,\n      },\n    )\n  }\n}\n\nexport type AbiDecodingDataSizeInvalidErrorType =\n  AbiDecodingDataSizeInvalidError & {\n    name: 'AbiDecodingDataSizeInvalidError'\n  }\nexport class AbiDecodingDataSizeInvalidError extends BaseError {\n  override name = 'AbiDecodingDataSizeInvalidError'\n  constructor({ data, size }: { data: Hex; size: number }) {\n    super(\n      [\n        `Data size of ${size} bytes is invalid.`,\n        'Size must be in increments of 32 bytes (size % 32 === 0).',\n      ].join('\\n'),\n      { metaMessages: [`Data: ${data} (${size} bytes)`] },\n    )\n  }\n}\n\nexport type AbiDecodingDataSizeTooSmallErrorType =\n  AbiDecodingDataSizeTooSmallError & {\n    name: 'AbiDecodingDataSizeTooSmallError'\n  }\nexport class AbiDecodingDataSizeTooSmallError extends BaseError {\n  override name = 'AbiDecodingDataSizeTooSmallError'\n\n  data: Hex\n  params: readonly AbiParameter[]\n  size: number\n\n  constructor({\n    data,\n    params,\n    size,\n  }: { data: Hex; params: readonly AbiParameter[]; size: number }) {\n    super(\n      [`Data size of ${size} bytes is too small for given parameters.`].join(\n        '\\n',\n      ),\n      {\n        metaMessages: [\n          `Params: (${formatAbiParams(params, { includeName: true })})`,\n          `Data:   ${data} (${size} bytes)`,\n        ],\n      },\n    )\n\n    this.data = data\n    this.params = params\n    this.size = size\n  }\n}\n\nexport type AbiDecodingZeroDataErrorType = AbiDecodingZeroDataError & {\n  name: 'AbiDecodingZeroDataError'\n}\nexport class AbiDecodingZeroDataError extends BaseError {\n  override name = 'AbiDecodingZeroDataError'\n  constructor() {\n    super('Cannot decode zero data (\"0x\") with ABI parameters.')\n  }\n}\n\nexport type AbiEncodingArrayLengthMismatchErrorType =\n  AbiEncodingArrayLengthMismatchError & {\n    name: 'AbiEncodingArrayLengthMismatchError'\n  }\nexport class AbiEncodingArrayLengthMismatchError extends BaseError {\n  override name = 'AbiEncodingArrayLengthMismatchError'\n  constructor({\n    expectedLength,\n    givenLength,\n    type,\n  }: { expectedLength: number; givenLength: number; type: string }) {\n    super(\n      [\n        `ABI encoding array length mismatch for type ${type}.`,\n        `Expected length: ${expectedLength}`,\n        `Given length: ${givenLength}`,\n      ].join('\\n'),\n    )\n  }\n}\n\nexport type AbiEncodingBytesSizeMismatchErrorType =\n  AbiEncodingBytesSizeMismatchError & {\n    name: 'AbiEncodingBytesSizeMismatchError'\n  }\nexport class AbiEncodingBytesSizeMismatchError extends BaseError {\n  override name = 'AbiEncodingBytesSizeMismatchError'\n  constructor({ expectedSize, value }: { expectedSize: number; value: Hex }) {\n    super(\n      `Size of bytes \"${value}\" (bytes${size(\n        value,\n      )}) does not match expected size (bytes${expectedSize}).`,\n    )\n  }\n}\n\nexport type AbiEncodingLengthMismatchErrorType =\n  AbiEncodingLengthMismatchError & {\n    name: 'AbiEncodingLengthMismatchError'\n  }\nexport class AbiEncodingLengthMismatchError extends BaseError {\n  override name = 'AbiEncodingLengthMismatchError'\n  constructor({\n    expectedLength,\n    givenLength,\n  }: { expectedLength: number; givenLength: number }) {\n    super(\n      [\n        'ABI encoding params/values length mismatch.',\n        `Expected length (params): ${expectedLength}`,\n        `Given length (values): ${givenLength}`,\n      ].join('\\n'),\n    )\n  }\n}\n\nexport type AbiErrorInputsNotFoundErrorType = AbiErrorInputsNotFoundError & {\n  name: 'AbiErrorInputsNotFoundError'\n}\nexport class AbiErrorInputsNotFoundError extends BaseError {\n  override name = 'AbiErrorInputsNotFoundError'\n  constructor(errorName: string, { docsPath }: { docsPath: string }) {\n    super(\n      [\n        `Arguments (\\`args\\`) were provided to \"${errorName}\", but \"${errorName}\" on the ABI does not contain any parameters (\\`inputs\\`).`,\n        'Cannot encode error result without knowing what the parameter types are.',\n        'Make sure you are using the correct ABI and that the inputs exist on it.',\n      ].join('\\n'),\n      {\n        docsPath,\n      },\n    )\n  }\n}\n\nexport type AbiErrorNotFoundErrorType = AbiErrorNotFoundError & {\n  name: 'AbiErrorNotFoundError'\n}\nexport class AbiErrorNotFoundError extends BaseError {\n  override name = 'AbiErrorNotFoundError'\n  constructor(errorName?: string, { docsPath }: { docsPath?: string } = {}) {\n    super(\n      [\n        `Error ${errorName ? `\"${errorName}\" ` : ''}not found on ABI.`,\n        'Make sure you are using the correct ABI and that the error exists on it.',\n      ].join('\\n'),\n      {\n        docsPath,\n      },\n    )\n  }\n}\n\nexport type AbiErrorSignatureNotFoundErrorType =\n  AbiErrorSignatureNotFoundError & {\n    name: 'AbiErrorSignatureNotFoundError'\n  }\nexport class AbiErrorSignatureNotFoundError extends BaseError {\n  override name = 'AbiErrorSignatureNotFoundError'\n\n  signature: Hex\n\n  constructor(signature: Hex, { docsPath }: { docsPath: string }) {\n    super(\n      [\n        `Encoded error signature \"${signature}\" not found on ABI.`,\n        'Make sure you are using the correct ABI and that the error exists on it.',\n        `You can look up the decoded signature here: https://openchain.xyz/signatures?query=${signature}.`,\n      ].join('\\n'),\n      {\n        docsPath,\n      },\n    )\n    this.signature = signature\n  }\n}\n\nexport type AbiEventSignatureEmptyTopicsErrorType =\n  AbiEventSignatureEmptyTopicsError & {\n    name: 'AbiEventSignatureEmptyTopicsError'\n  }\nexport class AbiEventSignatureEmptyTopicsError extends BaseError {\n  override name = 'AbiEventSignatureEmptyTopicsError'\n  constructor({ docsPath }: { docsPath: string }) {\n    super('Cannot extract event signature from empty topics.', {\n      docsPath,\n    })\n  }\n}\n\nexport type AbiEventSignatureNotFoundErrorType =\n  AbiEventSignatureNotFoundError & {\n    name: 'AbiEventSignatureNotFoundError'\n  }\nexport class AbiEventSignatureNotFoundError extends BaseError {\n  override name = 'AbiEventSignatureNotFoundError'\n  constructor(signature: Hex, { docsPath }: { docsPath: string }) {\n    super(\n      [\n        `Encoded event signature \"${signature}\" not found on ABI.`,\n        'Make sure you are using the correct ABI and that the event exists on it.',\n        `You can look up the signature here: https://openchain.xyz/signatures?query=${signature}.`,\n      ].join('\\n'),\n      {\n        docsPath,\n      },\n    )\n  }\n}\n\nexport type AbiEventNotFoundErrorType = AbiEventNotFoundError & {\n  name: 'AbiEventNotFoundError'\n}\nexport class AbiEventNotFoundError extends BaseError {\n  override name = 'AbiEventNotFoundError'\n  constructor(eventName?: string, { docsPath }: { docsPath?: string } = {}) {\n    super(\n      [\n        `Event ${eventName ? `\"${eventName}\" ` : ''}not found on ABI.`,\n        'Make sure you are using the correct ABI and that the event exists on it.',\n      ].join('\\n'),\n      {\n        docsPath,\n      },\n    )\n  }\n}\n\nexport type AbiFunctionNotFoundErrorType = AbiFunctionNotFoundError & {\n  name: 'AbiFunctionNotFoundError'\n}\nexport class AbiFunctionNotFoundError extends BaseError {\n  override name = 'AbiFunctionNotFoundError'\n  constructor(functionName?: string, { docsPath }: { docsPath?: string } = {}) {\n    super(\n      [\n        `Function ${functionName ? `\"${functionName}\" ` : ''}not found on ABI.`,\n        'Make sure you are using the correct ABI and that the function exists on it.',\n      ].join('\\n'),\n      {\n        docsPath,\n      },\n    )\n  }\n}\n\nexport type AbiFunctionOutputsNotFoundErrorType =\n  AbiFunctionOutputsNotFoundError & {\n    name: 'AbiFunctionOutputsNotFoundError'\n  }\nexport class AbiFunctionOutputsNotFoundError extends BaseError {\n  override name = 'AbiFunctionOutputsNotFoundError'\n  constructor(functionName: string, { docsPath }: { docsPath: string }) {\n    super(\n      [\n        `Function \"${functionName}\" does not contain any \\`outputs\\` on ABI.`,\n        'Cannot decode function result without knowing what the parameter types are.',\n        'Make sure you are using the correct ABI and that the function exists on it.',\n      ].join('\\n'),\n      {\n        docsPath,\n      },\n    )\n  }\n}\n\nexport type AbiFunctionSignatureNotFoundErrorType =\n  AbiFunctionSignatureNotFoundError & {\n    name: 'AbiFunctionSignatureNotFoundError'\n  }\nexport class AbiFunctionSignatureNotFoundError extends BaseError {\n  override name = 'AbiFunctionSignatureNotFoundError'\n  constructor(signature: Hex, { docsPath }: { docsPath: string }) {\n    super(\n      [\n        `Encoded function signature \"${signature}\" not found on ABI.`,\n        'Make sure you are using the correct ABI and that the function exists on it.',\n        `You can look up the signature here: https://openchain.xyz/signatures?query=${signature}.`,\n      ].join('\\n'),\n      {\n        docsPath,\n      },\n    )\n  }\n}\n\nexport type AbiItemAmbiguityErrorType = AbiItemAmbiguityError & {\n  name: 'AbiItemAmbiguityError'\n}\nexport class AbiItemAmbiguityError extends BaseError {\n  override name = 'AbiItemAmbiguityError'\n  constructor(\n    x: { abiItem: Abi[number]; type: string },\n    y: { abiItem: Abi[number]; type: string },\n  ) {\n    super('Found ambiguous types in overloaded ABI items.', {\n      metaMessages: [\n        `\\`${x.type}\\` in \\`${formatAbiItem(x.abiItem)}\\`, and`,\n        `\\`${y.type}\\` in \\`${formatAbiItem(y.abiItem)}\\``,\n        '',\n        'These types encode differently and cannot be distinguished at runtime.',\n        'Remove one of the ambiguous items in the ABI.',\n      ],\n    })\n  }\n}\n\nexport type BytesSizeMismatchErrorType = BytesSizeMismatchError & {\n  name: 'BytesSizeMismatchError'\n}\nexport class BytesSizeMismatchError extends BaseError {\n  override name = 'BytesSizeMismatchError'\n  constructor({\n    expectedSize,\n    givenSize,\n  }: { expectedSize: number; givenSize: number }) {\n    super(`Expected bytes${expectedSize}, got bytes${givenSize}.`)\n  }\n}\n\nexport type DecodeLogDataMismatchErrorType = DecodeLogDataMismatch & {\n  name: 'DecodeLogDataMismatch'\n}\nexport class DecodeLogDataMismatch extends BaseError {\n  override name = 'DecodeLogDataMismatch'\n\n  abiItem: AbiEvent\n  data: Hex\n  params: readonly AbiParameter[]\n  size: number\n\n  constructor({\n    abiItem,\n    data,\n    params,\n    size,\n  }: {\n    abiItem: AbiEvent\n    data: Hex\n    params: readonly AbiParameter[]\n    size: number\n  }) {\n    super(\n      [\n        `Data size of ${size} bytes is too small for non-indexed event parameters.`,\n      ].join('\\n'),\n      {\n        metaMessages: [\n          `Params: (${formatAbiParams(params, { includeName: true })})`,\n          `Data:   ${data} (${size} bytes)`,\n        ],\n      },\n    )\n\n    this.abiItem = abiItem\n    this.data = data\n    this.params = params\n    this.size = size\n  }\n}\n\nexport type DecodeLogTopicsMismatchErrorType = DecodeLogTopicsMismatch & {\n  name: 'DecodeLogTopicsMismatch'\n}\nexport class DecodeLogTopicsMismatch extends BaseError {\n  override name = 'DecodeLogTopicsMismatch'\n\n  abiItem: AbiEvent\n\n  constructor({\n    abiItem,\n    param,\n  }: {\n    abiItem: AbiEvent\n    param: AbiParameter & { indexed: boolean }\n  }) {\n    super(\n      [\n        `Expected a topic for indexed event parameter${\n          param.name ? ` \"${param.name}\"` : ''\n        } on event \"${formatAbiItem(abiItem, { includeName: true })}\".`,\n      ].join('\\n'),\n    )\n\n    this.abiItem = abiItem\n  }\n}\n\nexport type InvalidAbiEncodingTypeErrorType = InvalidAbiEncodingTypeError & {\n  name: 'InvalidAbiEncodingTypeError'\n}\nexport class InvalidAbiEncodingTypeError extends BaseError {\n  override name = 'InvalidAbiEncodingType'\n  constructor(type: string, { docsPath }: { docsPath: string }) {\n    super(\n      [\n        `Type \"${type}\" is not a valid encoding type.`,\n        'Please provide a valid ABI type.',\n      ].join('\\n'),\n      { docsPath },\n    )\n  }\n}\n\nexport type InvalidAbiDecodingTypeErrorType = InvalidAbiDecodingTypeError & {\n  name: 'InvalidAbiDecodingTypeError'\n}\nexport class InvalidAbiDecodingTypeError extends BaseError {\n  override name = 'InvalidAbiDecodingType'\n  constructor(type: string, { docsPath }: { docsPath: string }) {\n    super(\n      [\n        `Type \"${type}\" is not a valid decoding type.`,\n        'Please provide a valid ABI type.',\n      ].join('\\n'),\n      { docsPath },\n    )\n  }\n}\n\nexport type InvalidArrayErrorType = InvalidArrayError & {\n  name: 'InvalidArrayError'\n}\nexport class InvalidArrayError extends BaseError {\n  override name = 'InvalidArrayError'\n  constructor(value: unknown) {\n    super([`Value \"${value}\" is not a valid array.`].join('\\n'))\n  }\n}\n\nexport type InvalidDefinitionTypeErrorType = InvalidDefinitionTypeError & {\n  name: 'InvalidDefinitionTypeError'\n}\nexport class InvalidDefinitionTypeError extends BaseError {\n  override name = 'InvalidDefinitionTypeError'\n  constructor(type: string) {\n    super(\n      [\n        `\"${type}\" is not a valid definition type.`,\n        'Valid types: \"function\", \"event\", \"error\"',\n      ].join('\\n'),\n    )\n  }\n}\n\nexport type UnsupportedPackedAbiTypeErrorType = UnsupportedPackedAbiType & {\n  name: 'UnsupportedPackedAbiType'\n}\nexport class UnsupportedPackedAbiType extends BaseError {\n  override name = 'UnsupportedPackedAbiType'\n  constructor(type: unknown) {\n    super(`Type \"${type}\" is not supported for packed encoding.`)\n  }\n}\n","import { BaseError } from '../../errors/base.js'\nimport type { ErrorType } from '../../errors/utils.js'\n\nexport type NormalizeSignatureParameters = string\nexport type NormalizeSignatureReturnType = string\nexport type NormalizeSignatureErrorType = ErrorType\n\nexport function normalizeSignature(\n  signature: NormalizeSignatureParameters,\n): NormalizeSignatureReturnType {\n  let active = true\n  let current = ''\n  let level = 0\n  let result = ''\n  let valid = false\n\n  for (let i = 0; i < signature.length; i++) {\n    const char = signature[i]\n\n    // If the character is a separator, we want to reactivate.\n    if (['(', ')', ','].includes(char)) active = true\n\n    // If the character is a \"level\" token, we want to increment/decrement.\n    if (char === '(') level++\n    if (char === ')') level--\n\n    // If we aren't active, we don't want to mutate the result.\n    if (!active) continue\n\n    // If level === 0, we are at the definition level.\n    if (level === 0) {\n      if (char === ' ' && ['event', 'function', ''].includes(result))\n        result = ''\n      else {\n        result += char\n\n        // If we are at the end of the definition, we must be finished.\n        if (char === ')') {\n          valid = true\n          break\n        }\n      }\n\n      continue\n    }\n\n    // Ignore spaces\n    if (char === ' ') {\n      // If the previous character is a separator, and the current section isn't empty, we want to deactivate.\n      if (signature[i - 1] !== ',' && current !== ',' && current !== ',(') {\n        current = ''\n        active = false\n      }\n      continue\n    }\n\n    result += char\n    current += char\n  }\n\n  if (!valid) throw new BaseError('Unable to normalize signature.')\n\n  return result\n}\n","import { type AbiFunction, formatAbiItem } from 'abitype'\n\nimport type { ErrorType } from '../../errors/utils.js'\nimport {\n  type NormalizeSignatureErrorType,\n  normalizeSignature,\n} from './normalizeSignature.js'\n\nexport type GetFunctionSignatureErrorType =\n  | NormalizeSignatureErrorType\n  | ErrorType\n\nexport const getFunctionSignature = (fn_: string | AbiFunction) => {\n  const fn = (() => {\n    if (typeof fn_ === 'string') return fn_\n    return formatAbiItem(fn_)\n  })()\n  return normalizeSignature(fn)\n}\n","import type { AbiEvent, AbiFunction } from 'abitype'\n\nimport type { ErrorType } from '../../errors/utils.js'\nimport {\n  type GetFunctionSignatureErrorType,\n  getFunctionSignature,\n} from './getFunctionSignature.js'\n\nexport type GetEventSignatureErrorType =\n  | GetFunctionSignatureErrorType\n  | ErrorType\n\nexport const getEventSignature = (fn: string | AbiEvent) => {\n  return getFunctionSignature(fn as {} as AbiFunction)\n}\n","function number(n: number) {\n  if (!Number.isSafeInteger(n) || n < 0) throw new Error(`Wrong positive integer: ${n}`);\n}\n\nfunction bool(b: boolean) {\n  if (typeof b !== 'boolean') throw new Error(`Expected boolean, not ${b}`);\n}\n\nfunction bytes(b: Uint8Array | undefined, ...lengths: number[]) {\n  if (!(b instanceof Uint8Array)) throw new Error('Expected Uint8Array');\n  if (lengths.length > 0 && !lengths.includes(b.length))\n    throw new Error(`Expected Uint8Array of length ${lengths}, not of length=${b.length}`);\n}\n\ntype Hash = {\n  (data: Uint8Array): Uint8Array;\n  blockLen: number;\n  outputLen: number;\n  create: any;\n};\nfunction hash(hash: Hash) {\n  if (typeof hash !== 'function' || typeof hash.create !== 'function')\n    throw new Error('Hash should be wrapped by utils.wrapConstructor');\n  number(hash.outputLen);\n  number(hash.blockLen);\n}\n\nfunction exists(instance: any, checkFinished = true) {\n  if (instance.destroyed) throw new Error('Hash instance has been destroyed');\n  if (checkFinished && instance.finished) throw new Error('Hash#digest() has already been called');\n}\nfunction output(out: any, instance: any) {\n  bytes(out);\n  const min = instance.outputLen;\n  if (out.length < min) {\n    throw new Error(`digestInto() expects output buffer of length at least ${min}`);\n  }\n}\n\nexport { number, bool, bytes, hash, exists, output };\n\nconst assert = { number, bool, bytes, hash, exists, output };\nexport default assert;\n","const U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);\nconst _32n = /* @__PURE__ */ BigInt(32);\n\n// We are not using BigUint64Array, because they are extremely slow as per 2022\nfunction fromBig(n: bigint, le = false) {\n  if (le) return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) };\n  return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };\n}\n\nfunction split(lst: bigint[], le = false) {\n  let Ah = new Uint32Array(lst.length);\n  let Al = new Uint32Array(lst.length);\n  for (let i = 0; i < lst.length; i++) {\n    const { h, l } = fromBig(lst[i], le);\n    [Ah[i], Al[i]] = [h, l];\n  }\n  return [Ah, Al];\n}\n\nconst toBig = (h: number, l: number) => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0);\n// for Shift in [0, 32)\nconst shrSH = (h: number, _l: number, s: number) => h >>> s;\nconst shrSL = (h: number, l: number, s: number) => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in [1, 32)\nconst rotrSH = (h: number, l: number, s: number) => (h >>> s) | (l << (32 - s));\nconst rotrSL = (h: number, l: number, s: number) => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in (32, 64), NOTE: 32 is special case.\nconst rotrBH = (h: number, l: number, s: number) => (h << (64 - s)) | (l >>> (s - 32));\nconst rotrBL = (h: number, l: number, s: number) => (h >>> (s - 32)) | (l << (64 - s));\n// Right rotate for shift===32 (just swaps l&h)\nconst rotr32H = (_h: number, l: number) => l;\nconst rotr32L = (h: number, _l: number) => h;\n// Left rotate for Shift in [1, 32)\nconst rotlSH = (h: number, l: number, s: number) => (h << s) | (l >>> (32 - s));\nconst rotlSL = (h: number, l: number, s: number) => (l << s) | (h >>> (32 - s));\n// Left rotate for Shift in (32, 64), NOTE: 32 is special case.\nconst rotlBH = (h: number, l: number, s: number) => (l << (s - 32)) | (h >>> (64 - s));\nconst rotlBL = (h: number, l: number, s: number) => (h << (s - 32)) | (l >>> (64 - s));\n\n// JS uses 32-bit signed integers for bitwise operations which means we cannot\n// simple take carry out of low bit sum by shift, we need to use division.\nfunction add(Ah: number, Al: number, Bh: number, Bl: number) {\n  const l = (Al >>> 0) + (Bl >>> 0);\n  return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 };\n}\n// Addition with more than 2 elements\nconst add3L = (Al: number, Bl: number, Cl: number) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);\nconst add3H = (low: number, Ah: number, Bh: number, Ch: number) =>\n  (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;\nconst add4L = (Al: number, Bl: number, Cl: number, Dl: number) =>\n  (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);\nconst add4H = (low: number, Ah: number, Bh: number, Ch: number, Dh: number) =>\n  (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;\nconst add5L = (Al: number, Bl: number, Cl: number, Dl: number, El: number) =>\n  (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);\nconst add5H = (low: number, Ah: number, Bh: number, Ch: number, Dh: number, Eh: number) =>\n  (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;\n\n// prettier-ignore\nexport {\n  fromBig, split, toBig,\n  shrSH, shrSL,\n  rotrSH, rotrSL, rotrBH, rotrBL,\n  rotr32H, rotr32L,\n  rotlSH, rotlSL, rotlBH, rotlBL,\n  add, add3L, add3H, add4L, add4H, add5H, add5L,\n};\n// prettier-ignore\nconst u64 = {\n  fromBig, split, toBig,\n  shrSH, shrSL,\n  rotrSH, rotrSL, rotrBH, rotrBL,\n  rotr32H, rotr32L,\n  rotlSH, rotlSL, rotlBH, rotlBL,\n  add, add3L, add3H, add4L, add4H, add5H, add5L,\n};\nexport default u64;\n","// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.\n// See utils.ts for details.\n// The file will throw on node.js 14 and earlier.\n// @ts-ignore\nimport * as nc from 'node:crypto';\nexport const crypto =\n  nc && typeof nc === 'object' && 'webcrypto' in nc ? (nc.webcrypto as any) : undefined;\n","/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n\n// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.\n// node.js versions earlier than v19 don't declare it in global scope.\n// For node.js, package.json#exports field mapping rewrites import\n// from `crypto` to `cryptoNode`, which imports native module.\n// Makes the utils un-importable in browsers without a bundler.\n// Once node.js 18 is deprecated, we can just drop the import.\nimport { crypto } from '@noble/hashes/crypto';\n\n// prettier-ignore\nexport type TypedArray = Int8Array | Uint8ClampedArray | Uint8Array |\n  Uint16Array | Int16Array | Uint32Array | Int32Array;\n\nconst u8a = (a: any): a is Uint8Array => a instanceof Uint8Array;\n// Cast array to different type\nexport const u8 = (arr: TypedArray) => new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\nexport const u32 = (arr: TypedArray) =>\n  new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n\n// Cast array to view\nexport const createView = (arr: TypedArray) =>\n  new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n\n// The rotate right (circular right shift) operation for uint32\nexport const rotr = (word: number, shift: number) => (word << (32 - shift)) | (word >>> shift);\n\n// big-endian hardware is rare. Just in case someone still decides to run hashes:\n// early-throw an error because we don't support BE yet.\nexport const isLE = new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44;\nif (!isLE) throw new Error('Non little-endian hardware is not supported');\n\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) =>\n  i.toString(16).padStart(2, '0')\n);\n/**\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes: Uint8Array): string {\n  if (!u8a(bytes)) throw new Error('Uint8Array expected');\n  // pre-caching improves the speed 6x\n  let hex = '';\n  for (let i = 0; i < bytes.length; i++) {\n    hex += hexes[bytes[i]];\n  }\n  return hex;\n}\n\n/**\n * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n */\nexport function hexToBytes(hex: string): Uint8Array {\n  if (typeof hex !== 'string') throw new Error('hex string expected, got ' + typeof hex);\n  const len = hex.length;\n  if (len % 2) throw new Error('padded hex string expected, got unpadded hex of length ' + len);\n  const array = new Uint8Array(len / 2);\n  for (let i = 0; i < array.length; i++) {\n    const j = i * 2;\n    const hexByte = hex.slice(j, j + 2);\n    const byte = Number.parseInt(hexByte, 16);\n    if (Number.isNaN(byte) || byte < 0) throw new Error('Invalid byte sequence');\n    array[i] = byte;\n  }\n  return array;\n}\n\n// There is no setImmediate in browser and setTimeout is slow.\n// call of async fn will return Promise, which will be fullfiled only on\n// next scheduler queue processing step and this is exactly what we need.\nexport const nextTick = async () => {};\n\n// Returns control to thread each 'tick' ms to avoid blocking\nexport async function asyncLoop(iters: number, tick: number, cb: (i: number) => void) {\n  let ts = Date.now();\n  for (let i = 0; i < iters; i++) {\n    cb(i);\n    // Date.now() is not monotonic, so in case if clock goes backwards we return return control too\n    const diff = Date.now() - ts;\n    if (diff >= 0 && diff < tick) continue;\n    await nextTick();\n    ts += diff;\n  }\n}\n\n// Global symbols in both browsers and Node.js since v11\n// See https://github.com/microsoft/TypeScript/issues/31535\ndeclare const TextEncoder: any;\n\n/**\n * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])\n */\nexport function utf8ToBytes(str: string): Uint8Array {\n  if (typeof str !== 'string') throw new Error(`utf8ToBytes expected string, got ${typeof str}`);\n  return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n\nexport type Input = Uint8Array | string;\n/**\n * Normalizes (non-hex) string or Uint8Array to Uint8Array.\n * Warning: when Uint8Array is passed, it would NOT get copied.\n * Keep in mind for future mutable operations.\n */\nexport function toBytes(data: Input): Uint8Array {\n  if (typeof data === 'string') data = utf8ToBytes(data);\n  if (!u8a(data)) throw new Error(`expected Uint8Array, got ${typeof data}`);\n  return data;\n}\n\n/**\n * Copies several Uint8Arrays into one.\n */\nexport function concatBytes(...arrays: Uint8Array[]): Uint8Array {\n  const r = new Uint8Array(arrays.reduce((sum, a) => sum + a.length, 0));\n  let pad = 0; // walk through each item, ensure they have proper type\n  arrays.forEach((a) => {\n    if (!u8a(a)) throw new Error('Uint8Array expected');\n    r.set(a, pad);\n    pad += a.length;\n  });\n  return r;\n}\n\n// For runtime check if class implements interface\nexport abstract class Hash<T extends Hash<T>> {\n  abstract blockLen: number; // Bytes per block\n  abstract outputLen: number; // Bytes in output\n  abstract update(buf: Input): this;\n  // Writes digest into buf\n  abstract digestInto(buf: Uint8Array): void;\n  abstract digest(): Uint8Array;\n  /**\n   * Resets internal state. Makes Hash instance unusable.\n   * Reset is impossible for keyed hashes if key is consumed into state. If digest is not consumed\n   * by user, they will need to manually call `destroy()` when zeroing is necessary.\n   */\n  abstract destroy(): void;\n  /**\n   * Clones hash instance. Unsafe: doesn't check whether `to` is valid. Can be used as `clone()`\n   * when no options are passed.\n   * Reasons to use `_cloneInto` instead of clone: 1) performance 2) reuse instance => all internal\n   * buffers are overwritten => causes buffer overwrite which is used for digest in some cases.\n   * There are no guarantees for clean-up because it's impossible in JS.\n   */\n  abstract _cloneInto(to?: T): T;\n  // Safe version that clones internal state\n  clone(): T {\n    return this._cloneInto();\n  }\n}\n\n/**\n * XOF: streaming API to read digest in chunks.\n * Same as 'squeeze' in keccak/k12 and 'seek' in blake3, but more generic name.\n * When hash used in XOF mode it is up to user to call '.destroy' afterwards, since we cannot\n * destroy state, next call can require more bytes.\n */\nexport type HashXOF<T extends Hash<T>> = Hash<T> & {\n  xof(bytes: number): Uint8Array; // Read 'bytes' bytes from digest stream\n  xofInto(buf: Uint8Array): Uint8Array; // read buf.length bytes from digest stream into buf\n};\n\nconst toStr = {}.toString;\ntype EmptyObj = {};\nexport function checkOpts<T1 extends EmptyObj, T2 extends EmptyObj>(\n  defaults: T1,\n  opts?: T2\n): T1 & T2 {\n  if (opts !== undefined && toStr.call(opts) !== '[object Object]')\n    throw new Error('Options should be object or undefined');\n  const merged = Object.assign(defaults, opts);\n  return merged as T1 & T2;\n}\n\nexport type CHash = ReturnType<typeof wrapConstructor>;\n\nexport function wrapConstructor<T extends Hash<T>>(hashCons: () => Hash<T>) {\n  const hashC = (msg: Input): Uint8Array => hashCons().update(toBytes(msg)).digest();\n  const tmp = hashCons();\n  hashC.outputLen = tmp.outputLen;\n  hashC.blockLen = tmp.blockLen;\n  hashC.create = () => hashCons();\n  return hashC;\n}\n\nexport function wrapConstructorWithOpts<H extends Hash<H>, T extends Object>(\n  hashCons: (opts?: T) => Hash<H>\n) {\n  const hashC = (msg: Input, opts?: T): Uint8Array => hashCons(opts).update(toBytes(msg)).digest();\n  const tmp = hashCons({} as T);\n  hashC.outputLen = tmp.outputLen;\n  hashC.blockLen = tmp.blockLen;\n  hashC.create = (opts: T) => hashCons(opts);\n  return hashC;\n}\n\nexport function wrapXOFConstructorWithOpts<H extends HashXOF<H>, T extends Object>(\n  hashCons: (opts?: T) => HashXOF<H>\n) {\n  const hashC = (msg: Input, opts?: T): Uint8Array => hashCons(opts).update(toBytes(msg)).digest();\n  const tmp = hashCons({} as T);\n  hashC.outputLen = tmp.outputLen;\n  hashC.blockLen = tmp.blockLen;\n  hashC.create = (opts: T) => hashCons(opts);\n  return hashC;\n}\n\n/**\n * Secure PRNG. Uses `crypto.getRandomValues`, which defers to OS.\n */\nexport function randomBytes(bytesLength = 32): Uint8Array {\n  if (crypto && typeof crypto.getRandomValues === 'function') {\n    return crypto.getRandomValues(new Uint8Array(bytesLength));\n  }\n  throw new Error('crypto.getRandomValues must be defined');\n}\n","import { bytes, exists, number, output } from './_assert.js';\nimport { rotlBH, rotlBL, rotlSH, rotlSL, split } from './_u64.js';\nimport {\n  Hash,\n  u32,\n  Input,\n  toBytes,\n  wrapConstructor,\n  wrapXOFConstructorWithOpts,\n  HashXOF,\n} from './utils.js';\n\n// SHA3 (keccak) is based on a new design: basically, the internal state is bigger than output size.\n// It's called a sponge function.\n\n// Various per round constants calculations\nconst [SHA3_PI, SHA3_ROTL, _SHA3_IOTA]: [number[], number[], bigint[]] = [[], [], []];\nconst _0n = /* @__PURE__ */ BigInt(0);\nconst _1n = /* @__PURE__ */ BigInt(1);\nconst _2n = /* @__PURE__ */ BigInt(2);\nconst _7n = /* @__PURE__ */ BigInt(7);\nconst _256n = /* @__PURE__ */ BigInt(256);\nconst _0x71n = /* @__PURE__ */ BigInt(0x71);\nfor (let round = 0, R = _1n, x = 1, y = 0; round < 24; round++) {\n  // Pi\n  [x, y] = [y, (2 * x + 3 * y) % 5];\n  SHA3_PI.push(2 * (5 * y + x));\n  // Rotational\n  SHA3_ROTL.push((((round + 1) * (round + 2)) / 2) % 64);\n  // Iota\n  let t = _0n;\n  for (let j = 0; j < 7; j++) {\n    R = ((R << _1n) ^ ((R >> _7n) * _0x71n)) % _256n;\n    if (R & _2n) t ^= _1n << ((_1n << /* @__PURE__ */ BigInt(j)) - _1n);\n  }\n  _SHA3_IOTA.push(t);\n}\nconst [SHA3_IOTA_H, SHA3_IOTA_L] = /* @__PURE__ */ split(_SHA3_IOTA, true);\n\n// Left rotation (without 0, 32, 64)\nconst rotlH = (h: number, l: number, s: number) => (s > 32 ? rotlBH(h, l, s) : rotlSH(h, l, s));\nconst rotlL = (h: number, l: number, s: number) => (s > 32 ? rotlBL(h, l, s) : rotlSL(h, l, s));\n\n// Same as keccakf1600, but allows to skip some rounds\nexport function keccakP(s: Uint32Array, rounds: number = 24) {\n  const B = new Uint32Array(5 * 2);\n  // NOTE: all indices are x2 since we store state as u32 instead of u64 (bigints to slow in js)\n  for (let round = 24 - rounds; round < 24; round++) {\n    // Theta θ\n    for (let x = 0; x < 10; x++) B[x] = s[x] ^ s[x + 10] ^ s[x + 20] ^ s[x + 30] ^ s[x + 40];\n    for (let x = 0; x < 10; x += 2) {\n      const idx1 = (x + 8) % 10;\n      const idx0 = (x + 2) % 10;\n      const B0 = B[idx0];\n      const B1 = B[idx0 + 1];\n      const Th = rotlH(B0, B1, 1) ^ B[idx1];\n      const Tl = rotlL(B0, B1, 1) ^ B[idx1 + 1];\n      for (let y = 0; y < 50; y += 10) {\n        s[x + y] ^= Th;\n        s[x + y + 1] ^= Tl;\n      }\n    }\n    // Rho (ρ) and Pi (π)\n    let curH = s[2];\n    let curL = s[3];\n    for (let t = 0; t < 24; t++) {\n      const shift = SHA3_ROTL[t];\n      const Th = rotlH(curH, curL, shift);\n      const Tl = rotlL(curH, curL, shift);\n      const PI = SHA3_PI[t];\n      curH = s[PI];\n      curL = s[PI + 1];\n      s[PI] = Th;\n      s[PI + 1] = Tl;\n    }\n    // Chi (χ)\n    for (let y = 0; y < 50; y += 10) {\n      for (let x = 0; x < 10; x++) B[x] = s[y + x];\n      for (let x = 0; x < 10; x++) s[y + x] ^= ~B[(x + 2) % 10] & B[(x + 4) % 10];\n    }\n    // Iota (ι)\n    s[0] ^= SHA3_IOTA_H[round];\n    s[1] ^= SHA3_IOTA_L[round];\n  }\n  B.fill(0);\n}\n\nexport class Keccak extends Hash<Keccak> implements HashXOF<Keccak> {\n  protected state: Uint8Array;\n  protected pos = 0;\n  protected posOut = 0;\n  protected finished = false;\n  protected state32: Uint32Array;\n  protected destroyed = false;\n  // NOTE: we accept arguments in bytes instead of bits here.\n  constructor(\n    public blockLen: number,\n    public suffix: number,\n    public outputLen: number,\n    protected enableXOF = false,\n    protected rounds: number = 24\n  ) {\n    super();\n    // Can be passed from user as dkLen\n    number(outputLen);\n    // 1600 = 5x5 matrix of 64bit.  1600 bits === 200 bytes\n    if (0 >= this.blockLen || this.blockLen >= 200)\n      throw new Error('Sha3 supports only keccak-f1600 function');\n    this.state = new Uint8Array(200);\n    this.state32 = u32(this.state);\n  }\n  protected keccak() {\n    keccakP(this.state32, this.rounds);\n    this.posOut = 0;\n    this.pos = 0;\n  }\n  update(data: Input) {\n    exists(this);\n    const { blockLen, state } = this;\n    data = toBytes(data);\n    const len = data.length;\n    for (let pos = 0; pos < len; ) {\n      const take = Math.min(blockLen - this.pos, len - pos);\n      for (let i = 0; i < take; i++) state[this.pos++] ^= data[pos++];\n      if (this.pos === blockLen) this.keccak();\n    }\n    return this;\n  }\n  protected finish() {\n    if (this.finished) return;\n    this.finished = true;\n    const { state, suffix, pos, blockLen } = this;\n    // Do the padding\n    state[pos] ^= suffix;\n    if ((suffix & 0x80) !== 0 && pos === blockLen - 1) this.keccak();\n    state[blockLen - 1] ^= 0x80;\n    this.keccak();\n  }\n  protected writeInto(out: Uint8Array): Uint8Array {\n    exists(this, false);\n    bytes(out);\n    this.finish();\n    const bufferOut = this.state;\n    const { blockLen } = this;\n    for (let pos = 0, len = out.length; pos < len; ) {\n      if (this.posOut >= blockLen) this.keccak();\n      const take = Math.min(blockLen - this.posOut, len - pos);\n      out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos);\n      this.posOut += take;\n      pos += take;\n    }\n    return out;\n  }\n  xofInto(out: Uint8Array): Uint8Array {\n    // Sha3/Keccak usage with XOF is probably mistake, only SHAKE instances can do XOF\n    if (!this.enableXOF) throw new Error('XOF is not possible for this instance');\n    return this.writeInto(out);\n  }\n  xof(bytes: number): Uint8Array {\n    number(bytes);\n    return this.xofInto(new Uint8Array(bytes));\n  }\n  digestInto(out: Uint8Array) {\n    output(out, this);\n    if (this.finished) throw new Error('digest() was already called');\n    this.writeInto(out);\n    this.destroy();\n    return out;\n  }\n  digest() {\n    return this.digestInto(new Uint8Array(this.outputLen));\n  }\n  destroy() {\n    this.destroyed = true;\n    this.state.fill(0);\n  }\n  _cloneInto(to?: Keccak): Keccak {\n    const { blockLen, suffix, outputLen, rounds, enableXOF } = this;\n    to ||= new Keccak(blockLen, suffix, outputLen, enableXOF, rounds);\n    to.state32.set(this.state32);\n    to.pos = this.pos;\n    to.posOut = this.posOut;\n    to.finished = this.finished;\n    to.rounds = rounds;\n    // Suffix can change in cSHAKE\n    to.suffix = suffix;\n    to.outputLen = outputLen;\n    to.enableXOF = enableXOF;\n    to.destroyed = this.destroyed;\n    return to;\n  }\n}\n\nconst gen = (suffix: number, blockLen: number, outputLen: number) =>\n  wrapConstructor(() => new Keccak(blockLen, suffix, outputLen));\n\nexport const sha3_224 = /* @__PURE__ */ gen(0x06, 144, 224 / 8);\n/**\n * SHA3-256 hash function\n * @param message - that would be hashed\n */\nexport const sha3_256 = /* @__PURE__ */ gen(0x06, 136, 256 / 8);\nexport const sha3_384 = /* @__PURE__ */ gen(0x06, 104, 384 / 8);\nexport const sha3_512 = /* @__PURE__ */ gen(0x06, 72, 512 / 8);\nexport const keccak_224 = /* @__PURE__ */ gen(0x01, 144, 224 / 8);\n/**\n * keccak-256 hash function. Different from SHA3-256.\n * @param message - that would be hashed\n */\nexport const keccak_256 = /* @__PURE__ */ gen(0x01, 136, 256 / 8);\nexport const keccak_384 = /* @__PURE__ */ gen(0x01, 104, 384 / 8);\nexport const keccak_512 = /* @__PURE__ */ gen(0x01, 72, 512 / 8);\n\nexport type ShakeOpts = { dkLen?: number };\n\nconst genShake = (suffix: number, blockLen: number, outputLen: number) =>\n  wrapXOFConstructorWithOpts<HashXOF<Keccak>, ShakeOpts>(\n    (opts: ShakeOpts = {}) =>\n      new Keccak(blockLen, suffix, opts.dkLen === undefined ? outputLen : opts.dkLen, true)\n  );\n\nexport const shake128 = /* @__PURE__ */ genShake(0x1f, 168, 128 / 8);\nexport const shake256 = /* @__PURE__ */ genShake(0x1f, 136, 256 / 8);\n","import { keccak_256 } from '@noble/hashes/sha3'\n\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray, Hex } from '../../types/misc.js'\nimport { type IsHexErrorType, isHex } from '../data/isHex.js'\nimport { type ToBytesErrorType, toBytes } from '../encoding/toBytes.js'\nimport { type ToHexErrorType, toHex } from '../encoding/toHex.js'\n\ntype To = 'hex' | 'bytes'\n\nexport type Keccak256Hash<TTo extends To> =\n  | (TTo extends 'bytes' ? ByteArray : never)\n  | (TTo extends 'hex' ? Hex : never)\n\nexport type Keccak256ErrorType =\n  | IsHexErrorType\n  | ToBytesErrorType\n  | ToHexErrorType\n  | ErrorType\n\nexport function keccak256<TTo extends To = 'hex'>(\n  value: Hex | ByteArray,\n  to_?: TTo,\n): Keccak256Hash<TTo> {\n  const to = to_ || 'hex'\n  const bytes = keccak_256(\n    isHex(value, { strict: false }) ? toBytes(value) : value,\n  )\n  if (to === 'bytes') return bytes as Keccak256Hash<TTo>\n  return toHex(bytes) as Keccak256Hash<TTo>\n}\n","import type { AbiEvent } from 'abitype'\n\nimport type { ErrorType } from '../../errors/utils.js'\nimport { type ToBytesErrorType, toBytes } from '../encoding/toBytes.js'\nimport { getEventSignature } from './getEventSignature.js'\nimport { type Keccak256ErrorType, keccak256 } from './keccak256.js'\n\nconst hash = (value: string) => keccak256(toBytes(value))\n\nexport type GetEventSelectorErrorType =\n  | Keccak256ErrorType\n  | ToBytesErrorType\n  | ErrorType\n\nexport const getEventSelector = (fn: string | AbiEvent) =>\n  hash(getEventSignature(fn))\n","import {\n  SliceOffsetOutOfBoundsError,\n  type SliceOffsetOutOfBoundsErrorType,\n} from '../../errors/data.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray, Hex } from '../../types/misc.js'\n\nimport { type IsHexErrorType, isHex } from './isHex.js'\nimport { type SizeErrorType, size } from './size.js'\n\nexport type SliceReturnType<TValue extends ByteArray | Hex> = TValue extends Hex\n  ? Hex\n  : ByteArray\n\nexport type SliceErrorType =\n  | IsHexErrorType\n  | SliceBytesErrorType\n  | SliceHexErrorType\n  | ErrorType\n\n/**\n * @description Returns a section of the hex or byte array given a start/end bytes offset.\n *\n * @param value The hex or byte array to slice.\n * @param start The start offset (in bytes).\n * @param end The end offset (in bytes).\n */\nexport function slice<TValue extends ByteArray | Hex>(\n  value: TValue,\n  start?: number,\n  end?: number,\n  { strict }: { strict?: boolean } = {},\n): SliceReturnType<TValue> {\n  if (isHex(value, { strict: false }))\n    return sliceHex(value as Hex, start, end, {\n      strict,\n    }) as SliceReturnType<TValue>\n  return sliceBytes(value as ByteArray, start, end, {\n    strict,\n  }) as SliceReturnType<TValue>\n}\n\nexport type AssertStartOffsetErrorType =\n  | SliceOffsetOutOfBoundsErrorType\n  | SizeErrorType\n  | ErrorType\n\nfunction assertStartOffset(value: Hex | ByteArray, start?: number) {\n  if (typeof start === 'number' && start > 0 && start > size(value) - 1)\n    throw new SliceOffsetOutOfBoundsError({\n      offset: start,\n      position: 'start',\n      size: size(value),\n    })\n}\n\nexport type AssertEndOffsetErrorType =\n  | SliceOffsetOutOfBoundsErrorType\n  | SizeErrorType\n  | ErrorType\n\nfunction assertEndOffset(value: Hex | ByteArray, start?: number, end?: number) {\n  if (\n    typeof start === 'number' &&\n    typeof end === 'number' &&\n    size(value) !== end - start\n  ) {\n    throw new SliceOffsetOutOfBoundsError({\n      offset: end,\n      position: 'end',\n      size: size(value),\n    })\n  }\n}\n\nexport type SliceBytesErrorType =\n  | AssertStartOffsetErrorType\n  | AssertEndOffsetErrorType\n  | ErrorType\n\n/**\n * @description Returns a section of the byte array given a start/end bytes offset.\n *\n * @param value The byte array to slice.\n * @param start The start offset (in bytes).\n * @param end The end offset (in bytes).\n */\nexport function sliceBytes(\n  value_: ByteArray,\n  start?: number,\n  end?: number,\n  { strict }: { strict?: boolean } = {},\n): ByteArray {\n  assertStartOffset(value_, start)\n  const value = value_.slice(start, end)\n  if (strict) assertEndOffset(value, start, end)\n  return value\n}\n\nexport type SliceHexErrorType =\n  | AssertStartOffsetErrorType\n  | AssertEndOffsetErrorType\n  | ErrorType\n\n/**\n * @description Returns a section of the hex value given a start/end bytes offset.\n *\n * @param value The hex value to slice.\n * @param start The start offset (in bytes).\n * @param end The end offset (in bytes).\n */\nexport function sliceHex(\n  value_: Hex,\n  start?: number,\n  end?: number,\n  { strict }: { strict?: boolean } = {},\n): Hex {\n  assertStartOffset(value_, start)\n  const value = `0x${value_\n    .replace('0x', '')\n    .slice((start ?? 0) * 2, (end ?? value_.length) * 2)}` as const\n  if (strict) assertEndOffset(value, start, end)\n  return value\n}\n","import type {\n  AbiParameter,\n  AbiParameterToPrimitiveType,\n  AbiParametersToPrimitiveTypes,\n} from 'abitype'\n\nimport {\n  AbiEncodingArrayLengthMismatchError,\n  type AbiEncodingArrayLengthMismatchErrorType,\n  AbiEncodingBytesSizeMismatchError,\n  type AbiEncodingBytesSizeMismatchErrorType,\n  AbiEncodingLengthMismatchError,\n  type AbiEncodingLengthMismatchErrorType,\n  InvalidAbiEncodingTypeError,\n  type InvalidAbiEncodingTypeErrorType,\n  InvalidArrayError,\n  type InvalidArrayErrorType,\n} from '../../errors/abi.js'\nimport {\n  InvalidAddressError,\n  type InvalidAddressErrorType,\n} from '../../errors/address.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Hex } from '../../types/misc.js'\nimport { type IsAddressErrorType, isAddress } from '../address/isAddress.js'\nimport { type ConcatErrorType, concat } from '../data/concat.js'\nimport { type PadHexErrorType, padHex } from '../data/pad.js'\nimport { type SizeErrorType, size } from '../data/size.js'\nimport { type SliceErrorType, slice } from '../data/slice.js'\nimport {\n  type BoolToHexErrorType,\n  type NumberToHexErrorType,\n  type StringToHexErrorType,\n  boolToHex,\n  numberToHex,\n  stringToHex,\n} from '../encoding/toHex.js'\n\nexport type EncodeAbiParametersReturnType = Hex\n\nexport type EncodeAbiParametersErrorType =\n  | AbiEncodingLengthMismatchErrorType\n  | PrepareParamsErrorType\n  | EncodeParamsErrorType\n  | ErrorType\n\n/**\n * @description Encodes a list of primitive values into an ABI-encoded hex value.\n */\nexport function encodeAbiParameters<\n  const TParams extends readonly AbiParameter[] | readonly unknown[],\n>(\n  params: TParams,\n  values: TParams extends readonly AbiParameter[]\n    ? AbiParametersToPrimitiveTypes<TParams>\n    : never,\n): EncodeAbiParametersReturnType {\n  if (params.length !== values.length)\n    throw new AbiEncodingLengthMismatchError({\n      expectedLength: params.length as number,\n      givenLength: values.length,\n    })\n  // Prepare the parameters to determine dynamic types to encode.\n  const preparedParams = prepareParams({\n    params: params as readonly AbiParameter[],\n    values,\n  })\n  const data = encodeParams(preparedParams)\n  if (data.length === 0) return '0x'\n  return data\n}\n\n/////////////////////////////////////////////////////////////////\n\ntype PreparedParam = { dynamic: boolean; encoded: Hex }\n\ntype TupleAbiParameter = AbiParameter & { components: readonly AbiParameter[] }\ntype Tuple = AbiParameterToPrimitiveType<TupleAbiParameter>\n\nexport type PrepareParamsErrorType = ErrorType\n\nfunction prepareParams<const TParams extends readonly AbiParameter[]>({\n  params,\n  values,\n}: {\n  params: TParams\n  values: AbiParametersToPrimitiveTypes<TParams>\n}) {\n  const preparedParams: PreparedParam[] = []\n  for (let i = 0; i < params.length; i++) {\n    preparedParams.push(prepareParam({ param: params[i], value: values[i] }))\n  }\n  return preparedParams\n}\n\nexport type PrepareParamErrorType =\n  | GetArrayComponentsErrorType\n  | InvalidAbiEncodingTypeErrorType\n  | ErrorType\n\nfunction prepareParam<const TParam extends AbiParameter>({\n  param,\n  value,\n}: {\n  param: TParam\n  value: AbiParameterToPrimitiveType<TParam>\n}): PreparedParam {\n  const arrayComponents = getArrayComponents(param.type)\n  if (arrayComponents) {\n    const [length, type] = arrayComponents\n    return encodeArray(value, { length, param: { ...param, type } })\n  }\n  if (param.type === 'tuple') {\n    return encodeTuple(value as unknown as Tuple, {\n      param: param as TupleAbiParameter,\n    })\n  }\n  if (param.type === 'address') {\n    return encodeAddress(value as unknown as Hex)\n  }\n  if (param.type === 'bool') {\n    return encodeBool(value as unknown as boolean)\n  }\n  if (param.type.startsWith('uint') || param.type.startsWith('int')) {\n    const signed = param.type.startsWith('int')\n    return encodeNumber(value as unknown as number, { signed })\n  }\n  if (param.type.startsWith('bytes')) {\n    return encodeBytes(value as unknown as Hex, { param })\n  }\n  if (param.type === 'string') {\n    return encodeString(value as unknown as string)\n  }\n  throw new InvalidAbiEncodingTypeError(param.type, {\n    docsPath: '/docs/contract/encodeAbiParameters',\n  })\n}\n\n/////////////////////////////////////////////////////////////////\n\nexport type EncodeParamsErrorType =\n  | NumberToHexErrorType\n  | SizeErrorType\n  | ErrorType\n\nfunction encodeParams(preparedParams: PreparedParam[]): Hex {\n  // 1. Compute the size of the static part of the parameters.\n  let staticSize = 0\n  for (let i = 0; i < preparedParams.length; i++) {\n    const { dynamic, encoded } = preparedParams[i]\n    if (dynamic) staticSize += 32\n    else staticSize += size(encoded)\n  }\n\n  // 2. Split the parameters into static and dynamic parts.\n  const staticParams: Hex[] = []\n  const dynamicParams: Hex[] = []\n  let dynamicSize = 0\n  for (let i = 0; i < preparedParams.length; i++) {\n    const { dynamic, encoded } = preparedParams[i]\n    if (dynamic) {\n      staticParams.push(numberToHex(staticSize + dynamicSize, { size: 32 }))\n      dynamicParams.push(encoded)\n      dynamicSize += size(encoded)\n    } else {\n      staticParams.push(encoded)\n    }\n  }\n\n  // 3. Concatenate static and dynamic parts.\n  return concat([...staticParams, ...dynamicParams])\n}\n\n/////////////////////////////////////////////////////////////////\n\nexport type EncodeAddressErrorType =\n  | InvalidAddressErrorType\n  | IsAddressErrorType\n  | ErrorType\n\nfunction encodeAddress(value: Hex): PreparedParam {\n  if (!isAddress(value)) throw new InvalidAddressError({ address: value })\n  return { dynamic: false, encoded: padHex(value.toLowerCase() as Hex) }\n}\n\nexport type EncodeArrayErrorType =\n  | AbiEncodingArrayLengthMismatchErrorType\n  | ConcatErrorType\n  | EncodeParamsErrorType\n  | InvalidArrayErrorType\n  | NumberToHexErrorType\n  | PrepareParamErrorType\n  | ErrorType\n\nfunction encodeArray<const TParam extends AbiParameter>(\n  value: AbiParameterToPrimitiveType<TParam>,\n  {\n    length,\n    param,\n  }: {\n    length: number | null\n    param: TParam\n  },\n): PreparedParam {\n  const dynamic = length === null\n\n  if (!Array.isArray(value)) throw new InvalidArrayError(value)\n  if (!dynamic && value.length !== length)\n    throw new AbiEncodingArrayLengthMismatchError({\n      expectedLength: length!,\n      givenLength: value.length,\n      type: `${param.type}[${length}]`,\n    })\n\n  let dynamicChild = false\n  const preparedParams: PreparedParam[] = []\n  for (let i = 0; i < value.length; i++) {\n    const preparedParam = prepareParam({ param, value: value[i] })\n    if (preparedParam.dynamic) dynamicChild = true\n    preparedParams.push(preparedParam)\n  }\n\n  if (dynamic || dynamicChild) {\n    const data = encodeParams(preparedParams)\n    if (dynamic) {\n      const length = numberToHex(preparedParams.length, { size: 32 })\n      return {\n        dynamic: true,\n        encoded: preparedParams.length > 0 ? concat([length, data]) : length,\n      }\n    }\n    if (dynamicChild) return { dynamic: true, encoded: data }\n  }\n  return {\n    dynamic: false,\n    encoded: concat(preparedParams.map(({ encoded }) => encoded)),\n  }\n}\n\nexport type EncodeBytesErrorType =\n  | AbiEncodingBytesSizeMismatchErrorType\n  | ConcatErrorType\n  | PadHexErrorType\n  | NumberToHexErrorType\n  | SizeErrorType\n  | ErrorType\n\nfunction encodeBytes<const TParam extends AbiParameter>(\n  value: Hex,\n  { param }: { param: TParam },\n): PreparedParam {\n  const [, paramSize] = param.type.split('bytes')\n  const bytesSize = size(value)\n  if (!paramSize) {\n    let value_ = value\n    // If the size is not divisible by 32 bytes, pad the end\n    // with empty bytes to the ceiling 32 bytes.\n    if (bytesSize % 32 !== 0)\n      value_ = padHex(value_, {\n        dir: 'right',\n        size: Math.ceil((value.length - 2) / 2 / 32) * 32,\n      })\n    return {\n      dynamic: true,\n      encoded: concat([padHex(numberToHex(bytesSize, { size: 32 })), value_]),\n    }\n  }\n  if (bytesSize !== parseInt(paramSize))\n    throw new AbiEncodingBytesSizeMismatchError({\n      expectedSize: parseInt(paramSize),\n      value,\n    })\n  return { dynamic: false, encoded: padHex(value, { dir: 'right' }) }\n}\n\nexport type EncodeBoolErrorType =\n  | PadHexErrorType\n  | BoolToHexErrorType\n  | ErrorType\n\nfunction encodeBool(value: boolean): PreparedParam {\n  return { dynamic: false, encoded: padHex(boolToHex(value)) }\n}\n\nexport type EncodeNumberErrorType = NumberToHexErrorType | ErrorType\n\nfunction encodeNumber(\n  value: number,\n  { signed }: { signed: boolean },\n): PreparedParam {\n  return {\n    dynamic: false,\n    encoded: numberToHex(value, {\n      size: 32,\n      signed,\n    }),\n  }\n}\n\nexport type EncodeStringErrorType =\n  | ConcatErrorType\n  | NumberToHexErrorType\n  | PadHexErrorType\n  | SizeErrorType\n  | SliceErrorType\n  | StringToHexErrorType\n  | ErrorType\n\nfunction encodeString(value: string): PreparedParam {\n  const hexValue = stringToHex(value)\n  const partsLength = Math.ceil(size(hexValue) / 32)\n  const parts: Hex[] = []\n  for (let i = 0; i < partsLength; i++) {\n    parts.push(\n      padHex(slice(hexValue, i * 32, (i + 1) * 32), {\n        dir: 'right',\n      }),\n    )\n  }\n  return {\n    dynamic: true,\n    encoded: concat([\n      padHex(numberToHex(size(hexValue), { size: 32 })),\n      ...parts,\n    ]),\n  }\n}\n\nexport type EncodeTupleErrorType =\n  | ConcatErrorType\n  | EncodeParamsErrorType\n  | PrepareParamErrorType\n  | ErrorType\n\nfunction encodeTuple<\n  const TParam extends AbiParameter & { components: readonly AbiParameter[] },\n>(\n  value: AbiParameterToPrimitiveType<TParam>,\n  { param }: { param: TParam },\n): PreparedParam {\n  let dynamic = false\n  const preparedParams: PreparedParam[] = []\n  for (let i = 0; i < param.components.length; i++) {\n    const param_ = param.components[i]\n    const index = Array.isArray(value) ? i : param_.name\n    const preparedParam = prepareParam({\n      param: param_,\n      value: (value as any)[index!] as readonly unknown[],\n    })\n    preparedParams.push(preparedParam)\n    if (preparedParam.dynamic) dynamic = true\n  }\n  return {\n    dynamic,\n    encoded: dynamic\n      ? encodeParams(preparedParams)\n      : concat(preparedParams.map(({ encoded }) => encoded)),\n  }\n}\n\nexport type GetArrayComponentsErrorType = ErrorType\n\nexport function getArrayComponents(\n  type: string,\n): [length: number | null, innerType: string] | undefined {\n  const matches = type.match(/^(.*)\\[(\\d+)?\\]$/)\n  return matches\n    ? // Return `null` if the array is dynamic.\n      [matches[2] ? Number(matches[2]) : null, matches[1]]\n    : undefined\n}\n","import type { AbiFunction } from 'abitype'\n\nimport type { ErrorType } from '../../errors/utils.js'\nimport { type SliceErrorType, slice } from '../data/slice.js'\nimport { type ToBytesErrorType, toBytes } from '../encoding/toBytes.js'\nimport {\n  type GetFunctionSignatureErrorType,\n  getFunctionSignature,\n} from './getFunctionSignature.js'\nimport { type Keccak256ErrorType, keccak256 } from './keccak256.js'\n\nconst hash = (value: string) => keccak256(toBytes(value))\n\nexport type GetFunctionSelectorErrorType =\n  | GetFunctionSignatureErrorType\n  | Keccak256ErrorType\n  | SliceErrorType\n  | ToBytesErrorType\n  | ErrorType\n\nexport const getFunctionSelector = (fn: string | AbiFunction) =>\n  slice(hash(getFunctionSignature(fn)), 0, 4)\n","import { type Abi, type AbiParameter, type Address } from 'abitype'\n\nimport { AbiItemAmbiguityError } from '../../errors/abi.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type {\n  AbiItem,\n  GetFunctionArgs,\n  InferItemName,\n} from '../../types/contract.js'\nimport type { Hex } from '../../types/misc.js'\nimport { type IsHexErrorType, isHex } from '../../utils/data/isHex.js'\nimport { getEventSelector } from '../../utils/hash/getEventSelector.js'\nimport {\n  type GetFunctionSelectorErrorType,\n  getFunctionSelector,\n} from '../../utils/hash/getFunctionSelector.js'\nimport { type IsAddressErrorType, isAddress } from '../address/isAddress.js'\n\nexport type GetAbiItemParameters<\n  TAbi extends Abi | readonly unknown[] = Abi,\n  TItemName extends string = string,\n> = {\n  abi: TAbi\n  name: InferItemName<TAbi, TItemName> | Hex\n} & Partial<GetFunctionArgs<TAbi, TItemName>>\n\nexport type GetAbiItemReturnType<\n  TAbi extends Abi | readonly unknown[] = Abi,\n  TItemName extends string = string,\n> = Extract<\n  TAbi[number],\n  {\n    name: TItemName\n  }\n>\n\nexport type GetAbiItemErrorType =\n  | IsArgOfTypeErrorType\n  | IsHexErrorType\n  | GetFunctionSelectorErrorType\n  | ErrorType\n\nexport function getAbiItem<\n  const TAbi extends Abi | readonly unknown[],\n  TItemName extends string,\n>({\n  abi,\n  args = [],\n  name,\n}: GetAbiItemParameters<TAbi, TItemName>): GetAbiItemReturnType<\n  TAbi,\n  TItemName\n> {\n  const isSelector = isHex(name, { strict: false })\n\n  const abiItems = (abi as Abi).filter((abiItem) => {\n    if (isSelector) {\n      if (abiItem.type === 'function')\n        return getFunctionSelector(abiItem) === name\n      if (abiItem.type === 'event') return getEventSelector(abiItem) === name\n      return false\n    }\n    return 'name' in abiItem && abiItem.name === name\n  })\n\n  if (abiItems.length === 0) return undefined as any\n  if (abiItems.length === 1) return abiItems[0] as any\n\n  let matchedAbiItem: AbiItem | undefined = undefined\n  for (const abiItem of abiItems) {\n    if (!('inputs' in abiItem)) continue\n    if (!args || args.length === 0) {\n      if (!abiItem.inputs || abiItem.inputs.length === 0) return abiItem as any\n      continue\n    }\n    if (!abiItem.inputs) continue\n    if (abiItem.inputs.length === 0) continue\n    if (abiItem.inputs.length !== args.length) continue\n    const matched = (args as readonly unknown[]).every((arg, index) => {\n      const abiParameter = 'inputs' in abiItem && abiItem.inputs![index]\n      if (!abiParameter) return false\n      return isArgOfType(arg, abiParameter as AbiParameter)\n    })\n    if (matched) {\n      // Check for ambiguity against already matched parameters (e.g. `address` vs `bytes20`).\n      if (\n        matchedAbiItem &&\n        'inputs' in matchedAbiItem &&\n        matchedAbiItem.inputs\n      ) {\n        const ambiguousTypes = getAmbiguousTypes(\n          abiItem.inputs,\n          matchedAbiItem.inputs,\n          args as readonly unknown[],\n        )\n        if (ambiguousTypes)\n          throw new AbiItemAmbiguityError(\n            {\n              abiItem,\n              type: ambiguousTypes[0],\n            },\n            {\n              abiItem: matchedAbiItem,\n              type: ambiguousTypes[1],\n            },\n          )\n      }\n\n      matchedAbiItem = abiItem\n    }\n  }\n\n  if (matchedAbiItem)\n    return matchedAbiItem as GetAbiItemReturnType<TAbi, TItemName>\n  return abiItems[0] as GetAbiItemReturnType<TAbi, TItemName>\n}\n\nexport type IsArgOfTypeErrorType = IsAddressErrorType | ErrorType\n\nexport function isArgOfType(arg: unknown, abiParameter: AbiParameter): boolean {\n  const argType = typeof arg\n  const abiParameterType = abiParameter.type\n  switch (abiParameterType) {\n    case 'address':\n      return isAddress(arg as Address)\n    case 'bool':\n      return argType === 'boolean'\n    case 'function':\n      return argType === 'string'\n    case 'string':\n      return argType === 'string'\n    default: {\n      if (abiParameterType === 'tuple' && 'components' in abiParameter)\n        return Object.values(abiParameter.components).every(\n          (component, index) => {\n            return isArgOfType(\n              Object.values(arg as unknown[] | Record<string, unknown>)[index],\n              component as AbiParameter,\n            )\n          },\n        )\n\n      // `(u)int<M>`: (un)signed integer type of `M` bits, `0 < M <= 256`, `M % 8 == 0`\n      // https://regexr.com/6v8hp\n      if (\n        /^u?int(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/.test(\n          abiParameterType,\n        )\n      )\n        return argType === 'number' || argType === 'bigint'\n\n      // `bytes<M>`: binary type of `M` bytes, `0 < M <= 32`\n      // https://regexr.com/6va55\n      if (/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/.test(abiParameterType))\n        return argType === 'string' || arg instanceof Uint8Array\n\n      // fixed-length (`<type>[M]`) and dynamic (`<type>[]`) arrays\n      // https://regexr.com/6va6i\n      if (/[a-z]+[1-9]{0,3}(\\[[0-9]{0,}\\])+$/.test(abiParameterType)) {\n        return (\n          Array.isArray(arg) &&\n          arg.every((x: unknown) =>\n            isArgOfType(x, {\n              ...abiParameter,\n              // Pop off `[]` or `[M]` from end of type\n              type: abiParameterType.replace(/(\\[[0-9]{0,}\\])$/, ''),\n            } as AbiParameter),\n          )\n        )\n      }\n\n      return false\n    }\n  }\n}\n\nexport function getAmbiguousTypes(\n  sourceParameters: readonly AbiParameter[],\n  targetParameters: readonly AbiParameter[],\n  args: readonly unknown[],\n): AbiParameter['type'][] | undefined {\n  for (const parameterIndex in sourceParameters) {\n    const sourceParameter = sourceParameters[parameterIndex]\n    const targetParameter = targetParameters[parameterIndex]\n\n    if (\n      sourceParameter.type === 'tuple' &&\n      targetParameter.type === 'tuple' &&\n      'components' in sourceParameter &&\n      'components' in targetParameter\n    )\n      return getAmbiguousTypes(\n        sourceParameter.components,\n        targetParameter.components,\n        (args as any)[parameterIndex],\n      )\n\n    const types = [sourceParameter.type, targetParameter.type]\n\n    const ambiguous = (() => {\n      if (types.includes('address') && types.includes('bytes20')) return true\n      if (types.includes('address') && types.includes('string'))\n        return isAddress(args[parameterIndex] as Address)\n      if (types.includes('address') && types.includes('bytes'))\n        return isAddress(args[parameterIndex] as Address)\n      return false\n    })()\n\n    if (ambiguous) return types\n  }\n\n  return\n}\n","import type { Address } from 'abitype'\n\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Account } from '../types.js'\n\nexport type ParseAccountErrorType = ErrorType\n\nexport function parseAccount(account: Address | Account): Account {\n  if (typeof account === 'string') return { address: account, type: 'json-rpc' }\n  return account\n}\n","import type { Abi } from 'abitype'\n\nimport {\n  AbiFunctionNotFoundError,\n  type AbiFunctionNotFoundErrorType,\n} from '../../errors/abi.js'\nimport type {\n  AbiItem,\n  GetFunctionArgs,\n  InferFunctionName,\n} from '../../types/contract.js'\nimport { type ConcatHexErrorType, concatHex } from '../data/concat.js'\nimport {\n  type GetFunctionSelectorErrorType,\n  getFunctionSelector,\n} from '../hash/getFunctionSelector.js'\n\nimport type { ErrorType } from '../../errors/utils.js'\nimport {\n  type EncodeAbiParametersErrorType,\n  encodeAbiParameters,\n} from './encodeAbiParameters.js'\nimport { type FormatAbiItemErrorType, formatAbiItem } from './formatAbiItem.js'\nimport {\n  type GetAbiItemErrorType,\n  type GetAbiItemParameters,\n  getAbiItem,\n} from './getAbiItem.js'\n\nexport type EncodeFunctionDataParameters<\n  TAbi extends Abi | readonly unknown[] = Abi,\n  TFunctionName extends string | undefined = string,\n  _FunctionName = InferFunctionName<TAbi, TFunctionName>,\n> = {\n  functionName?: _FunctionName\n} & (TFunctionName extends string\n  ? { abi: TAbi } & GetFunctionArgs<TAbi, TFunctionName>\n  : _FunctionName extends string\n    ? { abi: [TAbi[number]] } & GetFunctionArgs<TAbi, _FunctionName>\n    : never)\n\nexport type EncodeFunctionDataErrorType =\n  | AbiFunctionNotFoundErrorType\n  | ConcatHexErrorType\n  | EncodeAbiParametersErrorType\n  | FormatAbiItemErrorType\n  | GetAbiItemErrorType\n  | GetFunctionSelectorErrorType\n  | ErrorType\n\nexport function encodeFunctionData<\n  const TAbi extends Abi | readonly unknown[],\n  TFunctionName extends string | undefined = undefined,\n>({\n  abi,\n  args,\n  functionName,\n}: EncodeFunctionDataParameters<TAbi, TFunctionName>) {\n  let abiItem = abi[0] as AbiItem\n  if (functionName) {\n    abiItem = getAbiItem({\n      abi,\n      args,\n      name: functionName,\n    } as GetAbiItemParameters)\n    if (!abiItem)\n      throw new AbiFunctionNotFoundError(functionName, {\n        docsPath: '/docs/contract/encodeFunctionData',\n      })\n  }\n\n  if (abiItem.type !== 'function')\n    throw new AbiFunctionNotFoundError(undefined, {\n      docsPath: '/docs/contract/encodeFunctionData',\n    })\n\n  const definition = formatAbiItem(abiItem)\n  const signature = getFunctionSelector(definition)\n  const data =\n    'inputs' in abiItem && abiItem.inputs\n      ? encodeAbiParameters(abiItem.inputs, (args ?? []) as readonly unknown[])\n      : undefined\n  return concatHex([signature, data ?? '0x'])\n}\n","import type { AbiError } from 'abitype'\n\n// https://docs.soliditylang.org/en/v0.8.16/control-structures.html#panic-via-assert-and-error-via-require\nexport const panicReasons = {\n  1: 'An `assert` condition failed.',\n  17: 'Arithmic operation resulted in underflow or overflow.',\n  18: 'Division or modulo by zero (e.g. `5 / 0` or `23 % 0`).',\n  33: 'Attempted to convert to an invalid type.',\n  34: 'Attempted to access a storage byte array that is incorrectly encoded.',\n  49: 'Performed `.pop()` on an empty array',\n  50: 'Array index is out of bounds.',\n  65: 'Allocated too much memory or created an array which is too large.',\n  81: 'Attempted to call a zero-initialized variable of internal function type.',\n} as const\n\nexport const solidityError: AbiError = {\n  inputs: [\n    {\n      name: 'message',\n      type: 'string',\n    },\n  ],\n  name: 'Error',\n  type: 'error',\n}\nexport const solidityPanic: AbiError = {\n  inputs: [\n    {\n      name: 'reason',\n      type: 'uint256',\n    },\n  ],\n  name: 'Panic',\n  type: 'error',\n}\n","import type { Address } from 'abitype'\n\nimport { InvalidAddressError } from '../../errors/address.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport {\n  type StringToBytesErrorType,\n  stringToBytes,\n} from '../encoding/toBytes.js'\nimport { type Keccak256ErrorType, keccak256 } from '../hash/keccak256.js'\nimport { type IsAddressErrorType, isAddress } from './isAddress.js'\n\nexport type ChecksumAddressErrorType =\n  | Keccak256ErrorType\n  | StringToBytesErrorType\n  | ErrorType\n\nexport function checksumAddress(address_: Address, chainId?: number): Address {\n  const hexAddress = chainId\n    ? `${chainId}${address_.toLowerCase()}`\n    : address_.substring(2).toLowerCase()\n  const hash = keccak256(stringToBytes(hexAddress), 'bytes')\n\n  const address = (\n    chainId ? hexAddress.substring(`${chainId}0x`.length) : hexAddress\n  ).split('')\n  for (let i = 0; i < 40; i += 2) {\n    if (hash[i >> 1] >> 4 >= 8 && address[i]) {\n      address[i] = address[i].toUpperCase()\n    }\n    if ((hash[i >> 1] & 0x0f) >= 8 && address[i + 1]) {\n      address[i + 1] = address[i + 1].toUpperCase()\n    }\n  }\n\n  return `0x${address.join('')}`\n}\n\nexport type GetAddressErrorType =\n  | ChecksumAddressErrorType\n  | IsAddressErrorType\n  | ErrorType\n\nexport function getAddress(address: string, chainId?: number): Address {\n  if (!isAddress(address)) throw new InvalidAddressError({ address })\n  return checksumAddress(address, chainId)\n}\n","import type {\n  AbiParameter,\n  AbiParameterToPrimitiveType,\n  AbiParametersToPrimitiveTypes,\n} from 'abitype'\n\nimport {\n  AbiDecodingDataSizeTooSmallError,\n  type AbiDecodingDataSizeTooSmallErrorType,\n  AbiDecodingZeroDataError,\n  type AbiDecodingZeroDataErrorType,\n  InvalidAbiDecodingTypeError,\n  type InvalidAbiDecodingTypeErrorType,\n} from '../../errors/abi.js'\nimport type { Hex } from '../../types/misc.js'\nimport {\n  type ChecksumAddressErrorType,\n  checksumAddress,\n} from '../address/getAddress.js'\nimport { type SizeErrorType, size } from '../data/size.js'\nimport { type SliceErrorType, slice } from '../data/slice.js'\nimport { type TrimErrorType, trim } from '../data/trim.js'\nimport {\n  type HexToBigIntErrorType,\n  type HexToBoolErrorType,\n  type HexToNumberErrorType,\n  type HexToStringErrorType,\n  hexToBigInt,\n  hexToBool,\n  hexToNumber,\n  hexToString,\n} from '../encoding/fromHex.js'\n\nimport type { ErrorType } from '../../errors/utils.js'\nimport {\n  type GetArrayComponentsErrorType,\n  getArrayComponents,\n} from './encodeAbiParameters.js'\n\nexport type DecodeAbiParametersReturnType<\n  TParams extends\n    | readonly AbiParameter[]\n    | readonly unknown[] = readonly AbiParameter[],\n> = AbiParametersToPrimitiveTypes<\n  TParams extends readonly AbiParameter[] ? TParams : AbiParameter[]\n>\n\nexport type DecodeAbiParametersErrorType =\n  | AbiDecodingDataSizeTooSmallErrorType\n  | AbiDecodingZeroDataErrorType\n  | DecodeParamsErrorType\n  | SizeErrorType\n  | ErrorType\n\nexport function decodeAbiParameters<\n  const TParams extends readonly AbiParameter[] | readonly unknown[],\n>(params: TParams, data: Hex): DecodeAbiParametersReturnType<TParams> {\n  if (data === '0x' && (params as unknown[]).length > 0)\n    throw new AbiDecodingZeroDataError()\n  if (size(data) && size(data) < 32)\n    throw new AbiDecodingDataSizeTooSmallError({\n      data,\n      params: params as readonly AbiParameter[],\n      size: size(data),\n    })\n  return decodeParams({\n    data,\n    params: params as readonly AbiParameter[],\n  }) as unknown as DecodeAbiParametersReturnType<TParams>\n}\n\n////////////////////////////////////////////////////////////////////\n\ntype TupleAbiParameter = AbiParameter & { components: readonly AbiParameter[] }\n\ntype DecodeParamsErrorType = DecodeParamErrorType | SizeErrorType | ErrorType\n\nfunction decodeParams<const TParams extends readonly AbiParameter[]>({\n  data,\n  params,\n}: { data: Hex; params: TParams }) {\n  const decodedValues: unknown[] = []\n  let position = 0\n\n  for (let i = 0; i < params.length; i++) {\n    if (position >= size(data))\n      throw new AbiDecodingDataSizeTooSmallError({\n        data,\n        params,\n        size: size(data),\n      })\n\n    const param = params[i]\n    const { consumed, value } = decodeParam({ data, param, position })\n    decodedValues.push(value)\n    // Step across the data by the amount of data consumed by this parameter.\n    position += consumed\n  }\n\n  return decodedValues as unknown as AbiParametersToPrimitiveTypes<TParams>\n}\n\ntype DecodeParamErrorType =\n  | DecodeArrayErrorType\n  | DecodeTupleErrorType\n  | DecodeStringErrorType\n  | DecodeBytesErrorType\n  | DecodeNumberErrorType\n  | DecodeAddressErrorType\n  | DecodeBoolErrorType\n  | InvalidAbiDecodingTypeErrorType\n  | ErrorType\n\nfunction decodeParam({\n  data,\n  param,\n  position,\n}: { data: Hex; param: AbiParameter; position: number }): {\n  consumed: number\n  value: any\n} {\n  const arrayComponents = getArrayComponents(param.type)\n  if (arrayComponents) {\n    const [length, type] = arrayComponents\n    return decodeArray(data, {\n      length,\n      param: { ...param, type: type } as AbiParameter,\n      position,\n    })\n  }\n  if (param.type === 'tuple') {\n    return decodeTuple(data, { param: param as TupleAbiParameter, position })\n  }\n  if (param.type === 'string') {\n    return decodeString(data, { position })\n  }\n  if (param.type.startsWith('bytes')) {\n    return decodeBytes(data, { param, position })\n  }\n\n  const value = slice(data, position, position + 32, { strict: true }) as Hex\n  if (param.type.startsWith('uint') || param.type.startsWith('int')) {\n    return decodeNumber(value, { param })\n  }\n  if (param.type === 'address') {\n    return decodeAddress(value)\n  }\n  if (param.type === 'bool') {\n    return decodeBool(value)\n  }\n  throw new InvalidAbiDecodingTypeError(param.type, {\n    docsPath: '/docs/contract/decodeAbiParameters',\n  })\n}\n\n////////////////////////////////////////////////////////////////////\n\ntype DecodeAddressErrorType =\n  | ChecksumAddressErrorType\n  | SliceErrorType\n  | ErrorType\n\nfunction decodeAddress(value: Hex) {\n  return { consumed: 32, value: checksumAddress(slice(value, -20)) }\n}\n\ntype DecodeArrayErrorType = HexToNumberErrorType | SliceErrorType | ErrorType\n\nfunction decodeArray<const TParam extends AbiParameter>(\n  data: Hex,\n  {\n    param,\n    length,\n    position,\n  }: {\n    param: TParam\n    length: number | null\n    position: number\n  },\n) {\n  // If the length of the array is not known in advance (dynamic array),\n  // we will need to decode the offset of the array data.\n  if (!length) {\n    // Get the offset of the array data.\n    const offset = hexToNumber(\n      slice(data, position, position + 32, { strict: true }),\n    )\n    // Get the length of the array from the offset.\n    const length = hexToNumber(\n      slice(data, offset, offset + 32, { strict: true }),\n    )\n\n    let consumed = 0\n    const value: AbiParameterToPrimitiveType<TParam>[] = []\n    for (let i = 0; i < length; ++i) {\n      const decodedChild = decodeParam({\n        data: slice(data, offset + 32),\n        param,\n        position: consumed,\n      })\n      consumed += decodedChild.consumed\n      value.push(decodedChild.value)\n    }\n    return { value, consumed: 32 }\n  }\n\n  // If the length of the array is known in advance,\n  // and the length of an element deeply nested in the array is not known,\n  // we need to decode the offset of the array data.\n  if (hasDynamicChild(param)) {\n    // Get the child type of the array.\n    const arrayComponents = getArrayComponents(param.type)\n    // If the child type is not known, the array is dynamic.\n    const dynamicChild = !arrayComponents?.[0]\n\n    let consumed = 0\n    const value: AbiParameterToPrimitiveType<TParam>[] = []\n    for (let i = 0; i < length; ++i) {\n      const offset = hexToNumber(\n        slice(data, position, position + 32, { strict: true }),\n      )\n      const decodedChild = decodeParam({\n        data: slice(data, offset),\n        param,\n        position: dynamicChild ? consumed : i * 32,\n      })\n      consumed += decodedChild.consumed\n      value.push(decodedChild.value)\n    }\n    return { value, consumed: 32 }\n  }\n\n  // If the length of the array is known in advance,\n  // and the length of each element in the array is known,\n  // the array data is encoded contiguously after the array.\n  let consumed = 0\n  const value: AbiParameterToPrimitiveType<TParam>[] = []\n  for (let i = 0; i < length; ++i) {\n    const decodedChild = decodeParam({\n      data,\n      param,\n      position: position + consumed,\n    })\n    consumed += decodedChild.consumed\n    value.push(decodedChild.value)\n  }\n  return { value, consumed }\n}\n\ntype DecodeBoolErrorType = HexToBoolErrorType | ErrorType\n\nfunction decodeBool(value: Hex) {\n  return { consumed: 32, value: hexToBool(value) }\n}\n\ntype DecodeBytesErrorType = HexToNumberErrorType | SliceErrorType | ErrorType\n\nfunction decodeBytes<const TParam extends AbiParameter>(\n  data: Hex,\n  { param, position }: { param: TParam; position: number },\n) {\n  const [_, size] = param.type.split('bytes')\n  if (!size) {\n    // If we don't have a size, we're dealing with a dynamic-size array\n    // so we need to read the offset of the data part first.\n    const offset = hexToNumber(\n      slice(data, position, position + 32, { strict: true }),\n    )\n    const length = hexToNumber(\n      slice(data, offset, offset + 32, { strict: true }),\n    )\n    // If there is no length, we have zero data.\n    if (length === 0) return { consumed: 32, value: '0x' }\n    const value = slice(data, offset + 32, offset + 32 + length, {\n      strict: true,\n    })\n    return { consumed: 32, value }\n  }\n\n  const value = slice(data, position, position + parseInt(size), {\n    strict: true,\n  })\n  return { consumed: 32, value }\n}\n\ntype DecodeNumberErrorType =\n  | HexToBigIntErrorType\n  | HexToNumberErrorType\n  | ErrorType\n\nfunction decodeNumber<const TParam extends AbiParameter>(\n  value: Hex,\n  { param }: { param: TParam },\n) {\n  const signed = param.type.startsWith('int')\n  const size = parseInt(param.type.split('int')[1] || '256')\n  return {\n    consumed: 32,\n    value:\n      size > 48\n        ? hexToBigInt(value, { signed })\n        : hexToNumber(value, { signed }),\n  }\n}\n\ntype DecodeStringErrorType =\n  | HexToNumberErrorType\n  | HexToStringErrorType\n  | SliceErrorType\n  | TrimErrorType\n  | ErrorType\n\nfunction decodeString(data: Hex, { position }: { position: number }) {\n  const offset = hexToNumber(\n    slice(data, position, position + 32, { strict: true }),\n  )\n  const length = hexToNumber(slice(data, offset, offset + 32, { strict: true }))\n  // If there is no length, we have zero data (empty string).\n  if (length === 0) return { consumed: 32, value: '' }\n  const value = hexToString(\n    trim(slice(data, offset + 32, offset + 32 + length, { strict: true })),\n  )\n  return { consumed: 32, value }\n}\n\ntype DecodeTupleErrorType =\n  | HasDynamicChildErrorType\n  | HexToNumberErrorType\n  | SliceErrorType\n  | ErrorType\n\nfunction decodeTuple<\n  const TParam extends AbiParameter & { components: readonly AbiParameter[] },\n>(data: Hex, { param, position }: { param: TParam; position: number }) {\n  // Tuples can have unnamed components (i.e. they are arrays), so we must\n  // determine whether the tuple is named or unnamed. In the case of a named\n  // tuple, the value will be an object where each property is the name of the\n  // component. In the case of an unnamed tuple, the value will be an array.\n  const hasUnnamedChild =\n    param.components.length === 0 || param.components.some(({ name }) => !name)\n\n  // Initialize the value to an object or an array, depending on whether the\n  // tuple is named or unnamed.\n  const value: any = hasUnnamedChild ? [] : {}\n  let consumed = 0\n\n  // If the tuple has a dynamic child, we must first decode the offset to the\n  // tuple data.\n  if (hasDynamicChild(param)) {\n    const offset = hexToNumber(\n      slice(data, position, position + 32, { strict: true }),\n    )\n    // Decode each component of the tuple, starting at the offset.\n    for (let i = 0; i < param.components.length; ++i) {\n      const component = param.components[i]\n      const decodedChild = decodeParam({\n        data: slice(data, offset),\n        param: component,\n        position: consumed,\n      })\n      consumed += decodedChild.consumed\n      value[hasUnnamedChild ? i : component?.name!] = decodedChild.value\n    }\n    return { consumed: 32, value }\n  }\n\n  // If the tuple has static children, we can just decode each component\n  // in sequence.\n  for (let i = 0; i < param.components.length; ++i) {\n    const component = param.components[i]\n    const decodedChild = decodeParam({\n      data,\n      param: component,\n      position: position + consumed,\n    })\n    consumed += decodedChild.consumed\n    value[hasUnnamedChild ? i : component?.name!] = decodedChild.value\n  }\n  return { consumed, value }\n}\n\ntype HasDynamicChildErrorType = GetArrayComponentsErrorType | ErrorType\n\nfunction hasDynamicChild(param: AbiParameter) {\n  const { type } = param\n  if (type === 'string') return true\n  if (type === 'bytes') return true\n  if (type.endsWith('[]')) return true\n\n  if (type === 'tuple') return (param as any).components?.some(hasDynamicChild)\n\n  const arrayComponents = getArrayComponents(param.type)\n  if (\n    arrayComponents &&\n    hasDynamicChild({ ...param, type: arrayComponents[1] } as AbiParameter)\n  )\n    return true\n\n  return false\n}\n","import type { Abi, ExtractAbiError, ExtractAbiErrorNames } from 'abitype'\n\nimport { solidityError, solidityPanic } from '../../constants/solidity.js'\nimport {\n  AbiDecodingZeroDataError,\n  type AbiDecodingZeroDataErrorType,\n  AbiErrorSignatureNotFoundError,\n  type AbiErrorSignatureNotFoundErrorType,\n} from '../../errors/abi.js'\nimport type { AbiItem, GetErrorArgs } from '../../types/contract.js'\nimport type { Hex } from '../../types/misc.js'\nimport { slice } from '../data/slice.js'\nimport {\n  type GetFunctionSelectorErrorType,\n  getFunctionSelector,\n} from '../hash/getFunctionSelector.js'\n\nimport type { ErrorType } from '../../errors/utils.js'\nimport {\n  type DecodeAbiParametersErrorType,\n  decodeAbiParameters,\n} from './decodeAbiParameters.js'\nimport { type FormatAbiItemErrorType, formatAbiItem } from './formatAbiItem.js'\n\nexport type DecodeErrorResultParameters<\n  TAbi extends Abi | readonly unknown[] = Abi,\n> = { abi?: TAbi; data: Hex }\n\nexport type DecodeErrorResultReturnType<\n  TAbi extends Abi | readonly unknown[] = Abi,\n  _ErrorNames extends string = TAbi extends Abi\n    ? Abi extends TAbi\n      ? string\n      : ExtractAbiErrorNames<TAbi>\n    : string,\n> = {\n  [TName in _ErrorNames]: {\n    abiItem: TAbi extends Abi ? ExtractAbiError<TAbi, TName> : AbiItem\n    args: GetErrorArgs<TAbi, TName>['args']\n    errorName: TName\n  }\n}[_ErrorNames]\n\nexport type DecodeErrorResultErrorType =\n  | AbiDecodingZeroDataErrorType\n  | AbiErrorSignatureNotFoundErrorType\n  | DecodeAbiParametersErrorType\n  | FormatAbiItemErrorType\n  | GetFunctionSelectorErrorType\n  | ErrorType\n\nexport function decodeErrorResult<const TAbi extends Abi | readonly unknown[]>({\n  abi,\n  data,\n}: DecodeErrorResultParameters<TAbi>): DecodeErrorResultReturnType<TAbi> {\n  const signature = slice(data, 0, 4)\n  if (signature === '0x') throw new AbiDecodingZeroDataError()\n\n  const abi_ = [...((abi as Abi) || []), solidityError, solidityPanic]\n  const abiItem = abi_.find(\n    (x) =>\n      x.type === 'error' && signature === getFunctionSelector(formatAbiItem(x)),\n  )\n  if (!abiItem)\n    throw new AbiErrorSignatureNotFoundError(signature, {\n      docsPath: '/docs/contract/decodeErrorResult',\n    })\n  return {\n    abiItem,\n    args: ('inputs' in abiItem && abiItem.inputs && abiItem.inputs.length > 0\n      ? decodeAbiParameters(abiItem.inputs, slice(data, 4))\n      : undefined) as readonly unknown[] | undefined,\n    errorName: (abiItem as { name: string }).name,\n  } as DecodeErrorResultReturnType<TAbi>\n}\n","import type { ErrorType } from '../errors/utils.js'\n\nexport type StringifyErrorType = ErrorType\n\nexport const stringify: typeof JSON.stringify = (value, replacer, space) =>\n  JSON.stringify(\n    value,\n    (key, value_) => {\n      const value = typeof value_ === 'bigint' ? value_.toString() : value_\n      return typeof replacer === 'function' ? replacer(key, value) : value\n    },\n    space,\n  )\n","import type { AbiParameter } from 'abitype'\n\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { AbiItem } from '../../types/contract.js'\nimport { stringify } from '../stringify.js'\n\nexport type FormatAbiItemWithArgsErrorType = ErrorType\n\nexport function formatAbiItemWithArgs({\n  abiItem,\n  args,\n  includeFunctionName = true,\n  includeName = false,\n}: {\n  abiItem: AbiItem\n  args: readonly unknown[]\n  includeFunctionName?: boolean\n  includeName?: boolean\n}) {\n  if (!('name' in abiItem)) return\n  if (!('inputs' in abiItem)) return\n  if (!abiItem.inputs) return\n  return `${includeFunctionName ? abiItem.name : ''}(${abiItem.inputs\n    .map(\n      (input: AbiParameter, i: number) =>\n        `${includeName && input.name ? `${input.name}: ` : ''}${\n          typeof args[i] === 'object' ? stringify(args[i]) : args[i]\n        }`,\n    )\n    .join(', ')})`\n}\n","import { etherUnits } from '../../constants/unit.js'\n\nimport { type FormatUnitsErrorType, formatUnits } from './formatUnits.js'\n\nexport type FormatEtherErrorType = FormatUnitsErrorType\n\n/**\n * Converts numerical wei to a string representation of ether.\n *\n * - Docs: https://viem.sh/docs/utilities/formatEther.html\n *\n * @example\n * import { formatEther } from 'viem'\n *\n * formatEther(1000000000000000000n)\n * // '1'\n */\nexport function formatEther(wei: bigint, unit: 'wei' | 'gwei' = 'wei') {\n  return formatUnits(wei, etherUnits[unit])\n}\n","import type { Account } from '../accounts/types.js'\nimport type { SendTransactionParameters } from '../actions/wallet/sendTransaction.js'\nimport type { BlockTag } from '../types/block.js'\nimport type { Chain } from '../types/chain.js'\nimport type { Hash, Hex } from '../types/misc.js'\nimport type { TransactionType } from '../types/transaction.js'\nimport { formatEther } from '../utils/unit/formatEther.js'\nimport { formatGwei } from '../utils/unit/formatGwei.js'\n\nimport { BaseError } from './base.js'\n\nexport function prettyPrint(\n  args: Record<string, bigint | number | string | undefined | false | unknown>,\n) {\n  const entries = Object.entries(args)\n    .map(([key, value]) => {\n      if (value === undefined || value === false) return null\n      return [key, value]\n    })\n    .filter(Boolean) as [string, string][]\n  const maxLength = entries.reduce((acc, [key]) => Math.max(acc, key.length), 0)\n  return entries\n    .map(([key, value]) => `  ${`${key}:`.padEnd(maxLength + 1)}  ${value}`)\n    .join('\\n')\n}\n\nexport type FeeConflictErrorType = FeeConflictError & {\n  name: 'FeeConflictError'\n}\nexport class FeeConflictError extends BaseError {\n  override name = 'FeeConflictError'\n  constructor() {\n    super(\n      [\n        'Cannot specify both a `gasPrice` and a `maxFeePerGas`/`maxPriorityFeePerGas`.',\n        'Use `maxFeePerGas`/`maxPriorityFeePerGas` for EIP-1559 compatible networks, and `gasPrice` for others.',\n      ].join('\\n'),\n    )\n  }\n}\n\nexport type InvalidLegacyVErrorType = InvalidLegacyVError & {\n  name: 'InvalidLegacyVError'\n}\nexport class InvalidLegacyVError extends BaseError {\n  override name = 'InvalidLegacyVError'\n\n  constructor({ v }: { v: bigint }) {\n    super(`Invalid \\`v\\` value \"${v}\". Expected 27 or 28.`)\n  }\n}\n\nexport type InvalidSerializableTransactionErrorType =\n  InvalidSerializableTransactionError & {\n    name: 'InvalidSerializableTransactionError'\n  }\nexport class InvalidSerializableTransactionError extends BaseError {\n  override name = 'InvalidSerializableTransactionError'\n\n  constructor({ transaction }: { transaction: Record<string, unknown> }) {\n    super('Cannot infer a transaction type from provided transaction.', {\n      metaMessages: [\n        'Provided Transaction:',\n        '{',\n        prettyPrint(transaction),\n        '}',\n        '',\n        'To infer the type, either provide:',\n        '- a `type` to the Transaction, or',\n        '- an EIP-1559 Transaction with `maxFeePerGas`, or',\n        '- an EIP-2930 Transaction with `gasPrice` & `accessList`, or',\n        '- a Legacy Transaction with `gasPrice`',\n      ],\n    })\n  }\n}\n\nexport type InvalidSerializedTransactionTypeErrorType =\n  InvalidSerializedTransactionTypeError & {\n    name: 'InvalidSerializedTransactionTypeError'\n  }\nexport class InvalidSerializedTransactionTypeError extends BaseError {\n  override name = 'InvalidSerializedTransactionType'\n\n  serializedType: Hex\n\n  constructor({ serializedType }: { serializedType: Hex }) {\n    super(`Serialized transaction type \"${serializedType}\" is invalid.`)\n\n    this.serializedType = serializedType\n  }\n}\n\nexport type InvalidSerializedTransactionErrorType =\n  InvalidSerializedTransactionError & {\n    name: 'InvalidSerializedTransactionError'\n  }\nexport class InvalidSerializedTransactionError extends BaseError {\n  override name = 'InvalidSerializedTransactionError'\n\n  serializedTransaction: Hex\n  type: TransactionType\n\n  constructor({\n    attributes,\n    serializedTransaction,\n    type,\n  }: {\n    attributes: Record<string, unknown>\n    serializedTransaction: Hex\n    type: TransactionType\n  }) {\n    const missing = Object.entries(attributes)\n      .map(([key, value]) => (typeof value === 'undefined' ? key : undefined))\n      .filter(Boolean)\n    super(`Invalid serialized transaction of type \"${type}\" was provided.`, {\n      metaMessages: [\n        `Serialized Transaction: \"${serializedTransaction}\"`,\n        missing.length > 0 ? `Missing Attributes: ${missing.join(', ')}` : '',\n      ].filter(Boolean),\n    })\n\n    this.serializedTransaction = serializedTransaction\n    this.type = type\n  }\n}\n\nexport type InvalidStorageKeySizeErrorType = InvalidStorageKeySizeError & {\n  name: 'InvalidStorageKeySizeError'\n}\nexport class InvalidStorageKeySizeError extends BaseError {\n  override name = 'InvalidStorageKeySizeError'\n\n  constructor({ storageKey }: { storageKey: Hex }) {\n    super(\n      `Size for storage key \"${storageKey}\" is invalid. Expected 32 bytes. Got ${Math.floor(\n        (storageKey.length - 2) / 2,\n      )} bytes.`,\n    )\n  }\n}\n\nexport type TransactionExecutionErrorType = TransactionExecutionError & {\n  name: 'TransactionExecutionError'\n}\nexport class TransactionExecutionError extends BaseError {\n  override cause: BaseError\n\n  override name = 'TransactionExecutionError'\n\n  constructor(\n    cause: BaseError,\n    {\n      account,\n      docsPath,\n      chain,\n      data,\n      gas,\n      gasPrice,\n      maxFeePerGas,\n      maxPriorityFeePerGas,\n      nonce,\n      to,\n      value,\n    }: Omit<SendTransactionParameters, 'account' | 'chain'> & {\n      account: Account\n      chain?: Chain\n      docsPath?: string\n    },\n  ) {\n    const prettyArgs = prettyPrint({\n      chain: chain && `${chain?.name} (id: ${chain?.id})`,\n      from: account?.address,\n      to,\n      value:\n        typeof value !== 'undefined' &&\n        `${formatEther(value)} ${chain?.nativeCurrency?.symbol || 'ETH'}`,\n      data,\n      gas,\n      gasPrice:\n        typeof gasPrice !== 'undefined' && `${formatGwei(gasPrice)} gwei`,\n      maxFeePerGas:\n        typeof maxFeePerGas !== 'undefined' &&\n        `${formatGwei(maxFeePerGas)} gwei`,\n      maxPriorityFeePerGas:\n        typeof maxPriorityFeePerGas !== 'undefined' &&\n        `${formatGwei(maxPriorityFeePerGas)} gwei`,\n      nonce,\n    })\n\n    super(cause.shortMessage, {\n      cause,\n      docsPath,\n      metaMessages: [\n        ...(cause.metaMessages ? [...cause.metaMessages, ' '] : []),\n        'Request Arguments:',\n        prettyArgs,\n      ].filter(Boolean) as string[],\n    })\n    this.cause = cause\n  }\n}\n\nexport type TransactionNotFoundErrorType = TransactionNotFoundError & {\n  name: 'TransactionNotFoundError'\n}\nexport class TransactionNotFoundError extends BaseError {\n  override name = 'TransactionNotFoundError'\n  constructor({\n    blockHash,\n    blockNumber,\n    blockTag,\n    hash,\n    index,\n  }: {\n    blockHash?: Hash\n    blockNumber?: bigint\n    blockTag?: BlockTag\n    hash?: Hash\n    index?: number\n  }) {\n    let identifier = 'Transaction'\n    if (blockTag && index !== undefined)\n      identifier = `Transaction at block time \"${blockTag}\" at index \"${index}\"`\n    if (blockHash && index !== undefined)\n      identifier = `Transaction at block hash \"${blockHash}\" at index \"${index}\"`\n    if (blockNumber && index !== undefined)\n      identifier = `Transaction at block number \"${blockNumber}\" at index \"${index}\"`\n    if (hash) identifier = `Transaction with hash \"${hash}\"`\n    super(`${identifier} could not be found.`)\n  }\n}\n\nexport type TransactionReceiptNotFoundErrorType =\n  TransactionReceiptNotFoundError & {\n    name: 'TransactionReceiptNotFoundError'\n  }\nexport class TransactionReceiptNotFoundError extends BaseError {\n  override name = 'TransactionReceiptNotFoundError'\n  constructor({ hash }: { hash: Hash }) {\n    super(\n      `Transaction receipt with hash \"${hash}\" could not be found. The Transaction may not be processed on a block yet.`,\n    )\n  }\n}\n\nexport type WaitForTransactionReceiptTimeoutErrorType =\n  WaitForTransactionReceiptTimeoutError & {\n    name: 'WaitForTransactionReceiptTimeoutError'\n  }\nexport class WaitForTransactionReceiptTimeoutError extends BaseError {\n  override name = 'WaitForTransactionReceiptTimeoutError'\n  constructor({ hash }: { hash: Hash }) {\n    super(\n      `Timed out while waiting for transaction with hash \"${hash}\" to be confirmed.`,\n    )\n  }\n}\n","import type { Abi, Address } from 'abitype'\n\nimport { parseAccount } from '../accounts/utils/parseAccount.js'\nimport type { CallParameters } from '../actions/public/call.js'\nimport { panicReasons } from '../constants/solidity.js'\nimport type { Chain } from '../types/chain.js'\nimport type { Hex } from '../types/misc.js'\nimport {\n  type DecodeErrorResultReturnType,\n  decodeErrorResult,\n} from '../utils/abi/decodeErrorResult.js'\nimport { formatAbiItem } from '../utils/abi/formatAbiItem.js'\nimport { formatAbiItemWithArgs } from '../utils/abi/formatAbiItemWithArgs.js'\nimport { getAbiItem } from '../utils/abi/getAbiItem.js'\nimport { formatEther } from '../utils/unit/formatEther.js'\nimport { formatGwei } from '../utils/unit/formatGwei.js'\n\nimport { AbiErrorSignatureNotFoundError } from './abi.js'\nimport { BaseError } from './base.js'\nimport { prettyPrint } from './transaction.js'\nimport { getContractAddress } from './utils.js'\n\nexport type CallExecutionErrorType = CallExecutionError & {\n  name: 'CallExecutionError'\n}\nexport class CallExecutionError extends BaseError {\n  override cause: BaseError\n\n  override name = 'CallExecutionError'\n\n  constructor(\n    cause: BaseError,\n    {\n      account: account_,\n      docsPath,\n      chain,\n      data,\n      gas,\n      gasPrice,\n      maxFeePerGas,\n      maxPriorityFeePerGas,\n      nonce,\n      to,\n      value,\n    }: CallParameters & { chain?: Chain; docsPath?: string },\n  ) {\n    const account = account_ ? parseAccount(account_) : undefined\n    const prettyArgs = prettyPrint({\n      from: account?.address,\n      to,\n      value:\n        typeof value !== 'undefined' &&\n        `${formatEther(value)} ${chain?.nativeCurrency?.symbol || 'ETH'}`,\n      data,\n      gas,\n      gasPrice:\n        typeof gasPrice !== 'undefined' && `${formatGwei(gasPrice)} gwei`,\n      maxFeePerGas:\n        typeof maxFeePerGas !== 'undefined' &&\n        `${formatGwei(maxFeePerGas)} gwei`,\n      maxPriorityFeePerGas:\n        typeof maxPriorityFeePerGas !== 'undefined' &&\n        `${formatGwei(maxPriorityFeePerGas)} gwei`,\n      nonce,\n    })\n\n    super(cause.shortMessage, {\n      cause,\n      docsPath,\n      metaMessages: [\n        ...(cause.metaMessages ? [...cause.metaMessages, ' '] : []),\n        'Raw Call Arguments:',\n        prettyArgs,\n      ].filter(Boolean) as string[],\n    })\n    this.cause = cause\n  }\n}\n\nexport type ContractFunctionExecutionErrorType =\n  ContractFunctionExecutionError & {\n    name: 'ContractFunctionExecutionError'\n  }\nexport class ContractFunctionExecutionError extends BaseError {\n  abi: Abi\n  args?: unknown[]\n  override cause: BaseError\n  contractAddress?: Address\n  formattedArgs?: string\n  functionName: string\n  sender?: Address\n\n  override name = 'ContractFunctionExecutionError'\n\n  constructor(\n    cause: BaseError,\n    {\n      abi,\n      args,\n      contractAddress,\n      docsPath,\n      functionName,\n      sender,\n    }: {\n      abi: Abi\n      args?: any\n      contractAddress?: Address\n      docsPath?: string\n      functionName: string\n      sender?: Address\n    },\n  ) {\n    const abiItem = getAbiItem({ abi, args, name: functionName })\n    const formattedArgs = abiItem\n      ? formatAbiItemWithArgs({\n          abiItem,\n          args,\n          includeFunctionName: false,\n          includeName: false,\n        })\n      : undefined\n    const functionWithParams = abiItem\n      ? formatAbiItem(abiItem, { includeName: true })\n      : undefined\n\n    const prettyArgs = prettyPrint({\n      address: contractAddress && getContractAddress(contractAddress),\n      function: functionWithParams,\n      args:\n        formattedArgs &&\n        formattedArgs !== '()' &&\n        `${[...Array(functionName?.length ?? 0).keys()]\n          .map(() => ' ')\n          .join('')}${formattedArgs}`,\n      sender,\n    })\n\n    super(\n      cause.shortMessage ||\n        `An unknown error occurred while executing the contract function \"${functionName}\".`,\n      {\n        cause,\n        docsPath,\n        metaMessages: [\n          ...(cause.metaMessages ? [...cause.metaMessages, ' '] : []),\n          'Contract Call:',\n          prettyArgs,\n        ].filter(Boolean) as string[],\n      },\n    )\n    this.abi = abi\n    this.args = args\n    this.cause = cause\n    this.contractAddress = contractAddress\n    this.functionName = functionName\n    this.sender = sender\n  }\n}\n\nexport type ContractFunctionRevertedErrorType =\n  ContractFunctionRevertedError & {\n    name: 'ContractFunctionRevertedError'\n  }\nexport class ContractFunctionRevertedError extends BaseError {\n  override name = 'ContractFunctionRevertedError'\n\n  data?: DecodeErrorResultReturnType\n  reason?: string\n  signature?: Hex\n\n  constructor({\n    abi,\n    data,\n    functionName,\n    message,\n  }: { abi: Abi; data?: Hex; functionName: string; message?: string }) {\n    let cause: Error | undefined\n    let decodedData: DecodeErrorResultReturnType | undefined = undefined\n    let metaMessages\n    let reason\n    if (data && data !== '0x') {\n      try {\n        decodedData = decodeErrorResult({ abi, data })\n        const { abiItem, errorName, args: errorArgs } = decodedData\n        if (errorName === 'Error') {\n          reason = (errorArgs as [string])[0]\n        } else if (errorName === 'Panic') {\n          const [firstArg] = errorArgs as [number]\n          reason = panicReasons[firstArg as keyof typeof panicReasons]\n        } else {\n          const errorWithParams = abiItem\n            ? formatAbiItem(abiItem, { includeName: true })\n            : undefined\n          const formattedArgs =\n            abiItem && errorArgs\n              ? formatAbiItemWithArgs({\n                  abiItem,\n                  args: errorArgs,\n                  includeFunctionName: false,\n                  includeName: false,\n                })\n              : undefined\n\n          metaMessages = [\n            errorWithParams ? `Error: ${errorWithParams}` : '',\n            formattedArgs && formattedArgs !== '()'\n              ? `       ${[...Array(errorName?.length ?? 0).keys()]\n                  .map(() => ' ')\n                  .join('')}${formattedArgs}`\n              : '',\n          ]\n        }\n      } catch (err) {\n        cause = err as Error\n      }\n    } else if (message) reason = message\n\n    let signature: Hex | undefined\n    if (cause instanceof AbiErrorSignatureNotFoundError) {\n      signature = cause.signature\n      metaMessages = [\n        `Unable to decode signature \"${signature}\" as it was not found on the provided ABI.`,\n        'Make sure you are using the correct ABI and that the error exists on it.',\n        `You can look up the decoded signature here: https://openchain.xyz/signatures?query=${signature}.`,\n      ]\n    }\n\n    super(\n      (reason && reason !== 'execution reverted') || signature\n        ? [\n            `The contract function \"${functionName}\" reverted with the following ${\n              signature ? 'signature' : 'reason'\n            }:`,\n            reason || signature,\n          ].join('\\n')\n        : `The contract function \"${functionName}\" reverted.`,\n      {\n        cause,\n        metaMessages,\n      },\n    )\n\n    this.data = decodedData\n    this.reason = reason\n    this.signature = signature\n  }\n}\n\nexport type ContractFunctionZeroDataErrorType =\n  ContractFunctionZeroDataError & {\n    name: 'ContractFunctionZeroDataError'\n  }\nexport class ContractFunctionZeroDataError extends BaseError {\n  override name = 'ContractFunctionZeroDataError'\n  constructor({ functionName }: { functionName: string }) {\n    super(`The contract function \"${functionName}\" returned no data (\"0x\").`, {\n      metaMessages: [\n        'This could be due to any of the following:',\n        `  - The contract does not have the function \"${functionName}\",`,\n        '  - The parameters passed to the contract function may be invalid, or',\n        '  - The address is not a contract.',\n      ],\n    })\n  }\n}\n\nexport type RawContractErrorType = RawContractError & {\n  name: 'RawContractError'\n}\nexport class RawContractError extends BaseError {\n  code = 3\n  override name = 'RawContractError'\n\n  data?: Hex | { data?: Hex }\n\n  constructor({\n    data,\n    message,\n  }: { data?: Hex | { data?: Hex }; message?: string }) {\n    super(message || '')\n    this.data = data\n  }\n}\n","import { stringify } from '../utils/stringify.js'\n\nimport { BaseError } from './base.js'\nimport { getUrl } from './utils.js'\n\nexport type HttpRequestErrorType = HttpRequestError & {\n  name: 'HttpRequestError'\n}\nexport class HttpRequestError extends BaseError {\n  override name = 'HttpRequestError'\n\n  body?: { [x: string]: unknown } | { [y: string]: unknown }[]\n  headers?: Headers\n  status?: number\n  url: string\n\n  constructor({\n    body,\n    details,\n    headers,\n    status,\n    url,\n  }: {\n    body?: { [x: string]: unknown } | { [y: string]: unknown }[]\n    details?: string\n    headers?: Headers\n    status?: number\n    url: string\n  }) {\n    super('HTTP request failed.', {\n      details,\n      metaMessages: [\n        status && `Status: ${status}`,\n        `URL: ${getUrl(url)}`,\n        body && `Request body: ${stringify(body)}`,\n      ].filter(Boolean) as string[],\n    })\n    this.body = body\n    this.headers = headers\n    this.status = status\n    this.url = url\n  }\n}\n\nexport type WebSocketRequestErrorType = WebSocketRequestError & {\n  name: 'WebSocketRequestError'\n}\nexport class WebSocketRequestError extends BaseError {\n  override name = 'WebSocketRequestError'\n\n  constructor({\n    body,\n    details,\n    url,\n  }: {\n    body: { [key: string]: unknown }\n    details: string\n    url: string\n  }) {\n    super('WebSocket request failed.', {\n      details,\n      metaMessages: [`URL: ${getUrl(url)}`, `Request body: ${stringify(body)}`],\n    })\n  }\n}\n\nexport type RpcRequestErrorType = RpcRequestError & {\n  name: 'RpcRequestError'\n}\nexport class RpcRequestError extends BaseError {\n  override name = 'RpcRequestError'\n\n  code: number\n\n  constructor({\n    body,\n    error,\n    url,\n  }: {\n    body: { [x: string]: unknown } | { [y: string]: unknown }[]\n    error: { code: number; message: string }\n    url: string\n  }) {\n    super('RPC Request failed.', {\n      cause: error as any,\n      details: error.message,\n      metaMessages: [`URL: ${getUrl(url)}`, `Request body: ${stringify(body)}`],\n    })\n    this.code = error.code\n  }\n}\n\nexport type TimeoutErrorType = TimeoutError & {\n  name: 'TimeoutError'\n}\nexport class TimeoutError extends BaseError {\n  override name = 'TimeoutError'\n\n  constructor({\n    body,\n    url,\n  }: {\n    body: { [x: string]: unknown } | { [y: string]: unknown }[]\n    url: string\n  }) {\n    super('The request took too long to respond.', {\n      details: 'The request timed out.',\n      metaMessages: [`URL: ${getUrl(url)}`, `Request body: ${stringify(body)}`],\n    })\n  }\n}\n","import type { Prettify } from '../types/utils.js'\nimport { BaseError } from './base.js'\nimport { RpcRequestError } from './request.js'\n\nconst unknownErrorCode = -1\n\nexport type RpcErrorCode =\n  | -1\n  | -32700 // Parse error\n  | -32600 // Invalid request\n  | -32601 // Method not found\n  | -32602 // Invalid params\n  | -32603 // Internal error\n  | -32000 // Invalid input\n  | -32001 // Resource not found\n  | -32002 // Resource unavailable\n  | -32003 // Transaction rejected\n  | -32004 // Method not supported\n  | -32005 // Limit exceeded\n  | -32006 // JSON-RPC version not supported\n  | -32042 // Method not found\n\ntype RpcErrorOptions<TCode extends number = RpcErrorCode> = {\n  code?: TCode | (number & {})\n  docsPath?: string\n  metaMessages?: string[]\n  shortMessage: string\n}\n\n/**\n * Error subclass implementing JSON RPC 2.0 errors and Ethereum RPC errors per EIP-1474.\n *\n * - EIP https://eips.ethereum.org/EIPS/eip-1474\n */\nexport type RpcErrorType = RpcError & { name: 'RpcError' }\nexport class RpcError<TCode extends number = RpcErrorCode> extends BaseError {\n  override name = 'RpcError'\n\n  code: TCode | (number & {})\n\n  constructor(\n    cause: Error,\n    { code, docsPath, metaMessages, shortMessage }: RpcErrorOptions<TCode>,\n  ) {\n    super(shortMessage, {\n      cause,\n      docsPath,\n      metaMessages:\n        metaMessages || (cause as { metaMessages?: string[] })?.metaMessages,\n    })\n    this.name = cause.name\n    this.code = (\n      cause instanceof RpcRequestError ? cause.code : code ?? unknownErrorCode\n    ) as TCode\n  }\n}\n\nexport type ProviderRpcErrorCode =\n  | 4001 // User Rejected Request\n  | 4100 // Unauthorized\n  | 4200 // Unsupported Method\n  | 4900 // Disconnected\n  | 4901 // Chain Disconnected\n  | 4902 // Chain Not Recognized\n\n/**\n * Error subclass implementing Ethereum Provider errors per EIP-1193.\n *\n * - EIP https://eips.ethereum.org/EIPS/eip-1193\n */\nexport type ProviderRpcErrorType = ProviderRpcError & {\n  name: 'ProviderRpcError'\n}\nexport class ProviderRpcError<\n  T = undefined,\n> extends RpcError<ProviderRpcErrorCode> {\n  override name = 'ProviderRpcError'\n\n  data?: T\n\n  constructor(\n    cause: Error,\n    options: Prettify<\n      RpcErrorOptions<ProviderRpcErrorCode> & {\n        data?: T\n      }\n    >,\n  ) {\n    super(cause, options)\n\n    this.data = options.data\n  }\n}\n\n/**\n * Subclass for a \"Parse error\" EIP-1474 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-1474#error-codes\n */\nexport type ParseRpcErrorType = ParseRpcError & {\n  code: -32700\n  name: 'ParseRpcError'\n}\nexport class ParseRpcError extends RpcError {\n  override name = 'ParseRpcError'\n  static code = -32700 as const\n\n  constructor(cause: Error) {\n    super(cause, {\n      code: ParseRpcError.code,\n      shortMessage:\n        'Invalid JSON was received by the server. An error occurred on the server while parsing the JSON text.',\n    })\n  }\n}\n\n/**\n * Subclass for a \"Invalid request\" EIP-1474 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-1474#error-codes\n */\nexport type InvalidRequestRpcErrorType = InvalidRequestRpcError & {\n  code: -32600\n  name: 'InvalidRequestRpcError'\n}\nexport class InvalidRequestRpcError extends RpcError {\n  override name = 'InvalidRequestRpcError'\n  static code = -32600 as const\n\n  constructor(cause: Error) {\n    super(cause, {\n      code: InvalidRequestRpcError.code,\n      shortMessage: 'JSON is not a valid request object.',\n    })\n  }\n}\n\n/**\n * Subclass for a \"Method not found\" EIP-1474 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-1474#error-codes\n */\nexport type MethodNotFoundRpcErrorType = MethodNotFoundRpcError & {\n  code: -32601\n  name: 'MethodNotFoundRpcError'\n}\nexport class MethodNotFoundRpcError extends RpcError {\n  override name = 'MethodNotFoundRpcError'\n  static code = -32601 as const\n\n  constructor(cause: Error) {\n    super(cause, {\n      code: MethodNotFoundRpcError.code,\n      shortMessage: 'The method does not exist / is not available.',\n    })\n  }\n}\n\n/**\n * Subclass for an \"Invalid params\" EIP-1474 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-1474#error-codes\n */\nexport type InvalidParamsRpcErrorType = InvalidParamsRpcError & {\n  code: -32602\n  name: 'InvalidParamsRpcError'\n}\nexport class InvalidParamsRpcError extends RpcError {\n  override name = 'InvalidParamsRpcError'\n  static code = -32602 as const\n\n  constructor(cause: Error) {\n    super(cause, {\n      code: InvalidParamsRpcError.code,\n      shortMessage: [\n        'Invalid parameters were provided to the RPC method.',\n        'Double check you have provided the correct parameters.',\n      ].join('\\n'),\n    })\n  }\n}\n\n/**\n * Subclass for an \"Internal error\" EIP-1474 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-1474#error-codes\n */\nexport type InternalRpcErrorType = InternalRpcError & {\n  code: -32603\n  name: 'InternalRpcError'\n}\nexport class InternalRpcError extends RpcError {\n  override name = 'InternalRpcError'\n  static code = -32603 as const\n\n  constructor(cause: Error) {\n    super(cause, {\n      code: InternalRpcError.code,\n      shortMessage: 'An internal error was received.',\n    })\n  }\n}\n\n/**\n * Subclass for an \"Invalid input\" EIP-1474 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-1474#error-codes\n */\nexport type InvalidInputRpcErrorType = InvalidInputRpcError & {\n  code: -32000\n  name: 'InvalidInputRpcError'\n}\nexport class InvalidInputRpcError extends RpcError {\n  override name = 'InvalidInputRpcError'\n  static code = -32000 as const\n\n  constructor(cause: Error) {\n    super(cause, {\n      code: InvalidInputRpcError.code,\n      shortMessage: [\n        'Missing or invalid parameters.',\n        'Double check you have provided the correct parameters.',\n      ].join('\\n'),\n    })\n  }\n}\n\n/**\n * Subclass for a \"Resource not found\" EIP-1474 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-1474#error-codes\n */\nexport type ResourceNotFoundRpcErrorType = ResourceNotFoundRpcError & {\n  code: -32001\n  name: 'ResourceNotFoundRpcError'\n}\nexport class ResourceNotFoundRpcError extends RpcError {\n  override name = 'ResourceNotFoundRpcError'\n  static code = -32001 as const\n\n  constructor(cause: Error) {\n    super(cause, {\n      code: ResourceNotFoundRpcError.code,\n      shortMessage: 'Requested resource not found.',\n    })\n  }\n}\n\n/**\n * Subclass for a \"Resource unavailable\" EIP-1474 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-1474#error-codes\n */\nexport type ResourceUnavailableRpcErrorType = ResourceUnavailableRpcError & {\n  code: -32002\n  name: 'ResourceUnavailableRpcError'\n}\nexport class ResourceUnavailableRpcError extends RpcError {\n  override name = 'ResourceUnavailableRpcError'\n  static code = -32002 as const\n\n  constructor(cause: Error) {\n    super(cause, {\n      code: ResourceUnavailableRpcError.code,\n      shortMessage: 'Requested resource not available.',\n    })\n  }\n}\n\n/**\n * Subclass for a \"Transaction rejected\" EIP-1474 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-1474#error-codes\n */\nexport type TransactionRejectedRpcErrorType = TransactionRejectedRpcError & {\n  code: -32003\n  name: 'TransactionRejectedRpcError'\n}\nexport class TransactionRejectedRpcError extends RpcError {\n  override name = 'TransactionRejectedRpcError'\n  static code = -32003 as const\n\n  constructor(cause: Error) {\n    super(cause, {\n      code: TransactionRejectedRpcError.code,\n      shortMessage: 'Transaction creation failed.',\n    })\n  }\n}\n\n/**\n * Subclass for a \"Method not supported\" EIP-1474 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-1474#error-codes\n */\nexport type MethodNotSupportedRpcErrorType = MethodNotSupportedRpcError & {\n  code: -32004\n  name: 'MethodNotSupportedRpcError'\n}\nexport class MethodNotSupportedRpcError extends RpcError {\n  override name = 'MethodNotSupportedRpcError'\n  static code = -32004 as const\n\n  constructor(cause: Error) {\n    super(cause, {\n      code: MethodNotSupportedRpcError.code,\n      shortMessage: 'Method is not implemented.',\n    })\n  }\n}\n\n/**\n * Subclass for a \"Limit exceeded\" EIP-1474 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-1474#error-codes\n */\nexport type LimitExceededRpcErrorType = LimitExceededRpcError & {\n  code: -32005\n  name: 'LimitExceededRpcError'\n}\nexport class LimitExceededRpcError extends RpcError {\n  override name = 'LimitExceededRpcError'\n  static code = -32005 as const\n\n  constructor(cause: Error) {\n    super(cause, {\n      code: LimitExceededRpcError.code,\n      shortMessage: 'Request exceeds defined limit.',\n    })\n  }\n}\n\n/**\n * Subclass for a \"JSON-RPC version not supported\" EIP-1474 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-1474#error-codes\n */\nexport type JsonRpcVersionUnsupportedErrorType =\n  JsonRpcVersionUnsupportedError & {\n    code: -32006\n    name: 'JsonRpcVersionUnsupportedError'\n  }\nexport class JsonRpcVersionUnsupportedError extends RpcError {\n  override name = 'JsonRpcVersionUnsupportedError'\n  static code = -32006 as const\n\n  constructor(cause: Error) {\n    super(cause, {\n      code: JsonRpcVersionUnsupportedError.code,\n      shortMessage: 'Version of JSON-RPC protocol is not supported.',\n    })\n  }\n}\n\n/**\n * Subclass for a \"User Rejected Request\" EIP-1193 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-1193#provider-errors\n */\nexport type UserRejectedRequestErrorType = UserRejectedRequestError & {\n  code: 4001\n  name: 'UserRejectedRequestError'\n}\nexport class UserRejectedRequestError extends ProviderRpcError {\n  override name = 'UserRejectedRequestError'\n  static code = 4001 as const\n\n  constructor(cause: Error) {\n    super(cause, {\n      code: UserRejectedRequestError.code,\n      shortMessage: 'User rejected the request.',\n    })\n  }\n}\n\n/**\n * Subclass for an \"Unauthorized\" EIP-1193 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-1193#provider-errors\n */\nexport type UnauthorizedProviderErrorType = UnauthorizedProviderError & {\n  code: 4100\n  name: 'UnauthorizedProviderError'\n}\nexport class UnauthorizedProviderError extends ProviderRpcError {\n  override name = 'UnauthorizedProviderError'\n  static code = 4100 as const\n\n  constructor(cause: Error) {\n    super(cause, {\n      code: UnauthorizedProviderError.code,\n      shortMessage:\n        'The requested method and/or account has not been authorized by the user.',\n    })\n  }\n}\n\n/**\n * Subclass for an \"Unsupported Method\" EIP-1193 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-1193#provider-errors\n */\nexport type UnsupportedProviderMethodErrorType =\n  UnsupportedProviderMethodError & {\n    code: 4200\n    name: 'UnsupportedProviderMethodError'\n  }\nexport class UnsupportedProviderMethodError extends ProviderRpcError {\n  override name = 'UnsupportedProviderMethodError'\n  static code = 4200 as const\n\n  constructor(cause: Error) {\n    super(cause, {\n      code: UnsupportedProviderMethodError.code,\n      shortMessage: 'The Provider does not support the requested method.',\n    })\n  }\n}\n\n/**\n * Subclass for an \"Disconnected\" EIP-1193 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-1193#provider-errors\n */\nexport type ProviderDisconnectedErrorType = ProviderDisconnectedError & {\n  code: 4900\n  name: 'ProviderDisconnectedError'\n}\nexport class ProviderDisconnectedError extends ProviderRpcError {\n  override name = 'ProviderDisconnectedError'\n  static code = 4900 as const\n\n  constructor(cause: Error) {\n    super(cause, {\n      code: ProviderDisconnectedError.code,\n      shortMessage: 'The Provider is disconnected from all chains.',\n    })\n  }\n}\n\n/**\n * Subclass for an \"Chain Disconnected\" EIP-1193 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-1193#provider-errors\n */\nexport type ChainDisconnectedErrorType = ChainDisconnectedError & {\n  code: 4901\n  name: 'ChainDisconnectedError'\n}\nexport class ChainDisconnectedError extends ProviderRpcError {\n  override name = 'ChainDisconnectedError'\n  static code = 4901 as const\n\n  constructor(cause: Error) {\n    super(cause, {\n      code: ChainDisconnectedError.code,\n      shortMessage: 'The Provider is not connected to the requested chain.',\n    })\n  }\n}\n\n/**\n * Subclass for an \"Switch Chain\" EIP-1193 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-1193#provider-errors\n */\nexport type SwitchChainErrorType = SwitchChainError & {\n  code: 4902\n  name: 'SwitchChainError'\n}\nexport class SwitchChainError extends ProviderRpcError {\n  override name = 'SwitchChainError'\n  static code = 4902 as const\n\n  constructor(cause: Error) {\n    super(cause, {\n      code: SwitchChainError.code,\n      shortMessage: 'An error occurred when attempting to switch chain.',\n    })\n  }\n}\n\n/**\n * Subclass for an unknown RPC error.\n */\nexport type UnknownRpcErrorType = UnknownRpcError & {\n  name: 'UnknownRpcError'\n}\nexport class UnknownRpcError extends RpcError {\n  override name = 'UnknownRpcError'\n\n  constructor(cause: Error) {\n    super(cause, {\n      shortMessage: 'An unknown RPC error occurred.',\n    })\n  }\n}\n","import type { SendTransactionParameters } from '../../actions/wallet/sendTransaction.js'\nimport { BaseError } from '../../errors/base.js'\nimport {\n  ExecutionRevertedError,\n  type ExecutionRevertedErrorType,\n  FeeCapTooHighError,\n  type FeeCapTooHighErrorType,\n  FeeCapTooLowError,\n  type FeeCapTooLowErrorType,\n  InsufficientFundsError,\n  type InsufficientFundsErrorType,\n  IntrinsicGasTooHighError,\n  type IntrinsicGasTooHighErrorType,\n  IntrinsicGasTooLowError,\n  type IntrinsicGasTooLowErrorType,\n  NonceMaxValueError,\n  type NonceMaxValueErrorType,\n  NonceTooHighError,\n  type NonceTooHighErrorType,\n  NonceTooLowError,\n  type NonceTooLowErrorType,\n  TipAboveFeeCapError,\n  type TipAboveFeeCapErrorType,\n  TransactionTypeNotSupportedError,\n  type TransactionTypeNotSupportedErrorType,\n  UnknownNodeError,\n  type UnknownNodeErrorType,\n} from '../../errors/node.js'\nimport { RpcRequestError } from '../../errors/request.js'\nimport {\n  InvalidInputRpcError,\n  TransactionRejectedRpcError,\n} from '../../errors/rpc.js'\n\nexport function containsNodeError(err: BaseError) {\n  return (\n    err instanceof TransactionRejectedRpcError ||\n    err instanceof InvalidInputRpcError ||\n    (err instanceof RpcRequestError && err.code === ExecutionRevertedError.code)\n  )\n}\n\nexport type GetNodeErrorParameters = Partial<SendTransactionParameters<any>>\n\nexport type GetNodeErrorReturnType =\n  | ExecutionRevertedErrorType\n  | FeeCapTooHighErrorType\n  | FeeCapTooLowErrorType\n  | NonceTooHighErrorType\n  | NonceTooLowErrorType\n  | NonceMaxValueErrorType\n  | InsufficientFundsErrorType\n  | IntrinsicGasTooHighErrorType\n  | IntrinsicGasTooLowErrorType\n  | TransactionTypeNotSupportedErrorType\n  | TipAboveFeeCapErrorType\n  | UnknownNodeErrorType\n\nexport function getNodeError(\n  err: BaseError,\n  args: GetNodeErrorParameters,\n): GetNodeErrorReturnType {\n  const message = (err.details || '').toLowerCase()\n\n  const executionRevertedError = err.walk(\n    (e) => (e as { code: number }).code === ExecutionRevertedError.code,\n  )\n  if (executionRevertedError instanceof BaseError) {\n    return new ExecutionRevertedError({\n      cause: err,\n      message: executionRevertedError.details,\n    }) as any\n  }\n  if (ExecutionRevertedError.nodeMessage.test(message))\n    return new ExecutionRevertedError({\n      cause: err,\n      message: err.details,\n    }) as any\n  if (FeeCapTooHighError.nodeMessage.test(message))\n    return new FeeCapTooHighError({\n      cause: err,\n      maxFeePerGas: args?.maxFeePerGas,\n    }) as any\n  if (FeeCapTooLowError.nodeMessage.test(message))\n    return new FeeCapTooLowError({\n      cause: err,\n      maxFeePerGas: args?.maxFeePerGas,\n    }) as any\n  if (NonceTooHighError.nodeMessage.test(message))\n    return new NonceTooHighError({ cause: err, nonce: args?.nonce }) as any\n  if (NonceTooLowError.nodeMessage.test(message))\n    return new NonceTooLowError({ cause: err, nonce: args?.nonce }) as any\n  if (NonceMaxValueError.nodeMessage.test(message))\n    return new NonceMaxValueError({ cause: err, nonce: args?.nonce }) as any\n  if (InsufficientFundsError.nodeMessage.test(message))\n    return new InsufficientFundsError({ cause: err }) as any\n  if (IntrinsicGasTooHighError.nodeMessage.test(message))\n    return new IntrinsicGasTooHighError({ cause: err, gas: args?.gas }) as any\n  if (IntrinsicGasTooLowError.nodeMessage.test(message))\n    return new IntrinsicGasTooLowError({ cause: err, gas: args?.gas }) as any\n  if (TransactionTypeNotSupportedError.nodeMessage.test(message))\n    return new TransactionTypeNotSupportedError({ cause: err }) as any\n  if (TipAboveFeeCapError.nodeMessage.test(message))\n    return new TipAboveFeeCapError({\n      cause: err,\n      maxFeePerGas: args?.maxFeePerGas,\n      maxPriorityFeePerGas: args?.maxPriorityFeePerGas,\n    }) as any\n  return new UnknownNodeError({\n    cause: err,\n  }) as any\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { ChainFormatter } from '../../types/chain.js'\n\nexport type ExtractErrorType = ErrorType\n\n/**\n * @description Picks out the keys from `value` that exist in the formatter..\n */\nexport function extract(\n  value_: Record<string, unknown>,\n  { format }: { format?: ChainFormatter['format'] },\n) {\n  if (!format) return {}\n\n  const value: Record<string, unknown> = {}\n  function extract_(formatted: Record<string, any>) {\n    const keys = Object.keys(formatted)\n    for (const key of keys) {\n      if (key in value_) value[key] = value_[key]\n      if (\n        formatted[key] &&\n        typeof formatted[key] === 'object' &&\n        !Array.isArray(formatted[key])\n      )\n        extract_(formatted[key])\n    }\n  }\n\n  const formatted = format(value_ || {})\n  extract_(formatted)\n\n  return value\n}\n","import {\n  type ParseAccountErrorType,\n  parseAccount,\n} from '../../accounts/utils/parseAccount.js'\nimport type { SendTransactionParameters } from '../../actions/wallet/sendTransaction.js'\nimport {\n  InvalidAddressError,\n  type InvalidAddressErrorType,\n} from '../../errors/address.js'\nimport {\n  FeeCapTooHighError,\n  type FeeCapTooHighErrorType,\n  TipAboveFeeCapError,\n  type TipAboveFeeCapErrorType,\n} from '../../errors/node.js'\nimport {\n  FeeConflictError,\n  type FeeConflictErrorType,\n} from '../../errors/transaction.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport { isAddress } from '../address/isAddress.js'\n\nexport type AssertRequestParameters = Partial<SendTransactionParameters<Chain>>\n\nexport type AssertRequestErrorType =\n  | InvalidAddressErrorType\n  | FeeConflictErrorType\n  | FeeCapTooHighErrorType\n  | ParseAccountErrorType\n  | TipAboveFeeCapErrorType\n  | ErrorType\n\nexport function assertRequest(args: AssertRequestParameters) {\n  const {\n    account: account_,\n    gasPrice,\n    maxFeePerGas,\n    maxPriorityFeePerGas,\n    to,\n  } = args\n  const account = account_ ? parseAccount(account_) : undefined\n  if (account && !isAddress(account.address))\n    throw new InvalidAddressError({ address: account.address })\n  if (to && !isAddress(to)) throw new InvalidAddressError({ address: to })\n  if (\n    typeof gasPrice !== 'undefined' &&\n    (typeof maxFeePerGas !== 'undefined' ||\n      typeof maxPriorityFeePerGas !== 'undefined')\n  )\n    throw new FeeConflictError()\n\n  if (maxFeePerGas && maxFeePerGas > 2n ** 256n - 1n)\n    throw new FeeCapTooHighError({ maxFeePerGas })\n  if (\n    maxPriorityFeePerGas &&\n    maxFeePerGas &&\n    maxPriorityFeePerGas > maxFeePerGas\n  )\n    throw new TipAboveFeeCapError({ maxFeePerGas, maxPriorityFeePerGas })\n}\n","import type { Abi, ExtractAbiFunctionNames } from 'abitype'\n\nimport {\n  AbiFunctionNotFoundError,\n  type AbiFunctionNotFoundErrorType,\n  AbiFunctionOutputsNotFoundError,\n  type AbiFunctionOutputsNotFoundErrorType,\n} from '../../errors/abi.js'\nimport type {\n  AbiItem,\n  ContractFunctionResult,\n  GetFunctionArgs,\n  InferFunctionName,\n} from '../../types/contract.js'\nimport type { Hex } from '../../types/misc.js'\n\nimport type { ErrorType } from '../../errors/utils.js'\nimport {\n  type DecodeAbiParametersErrorType,\n  decodeAbiParameters,\n} from './decodeAbiParameters.js'\nimport {\n  type GetAbiItemErrorType,\n  type GetAbiItemParameters,\n  getAbiItem,\n} from './getAbiItem.js'\n\nconst docsPath = '/docs/contract/decodeFunctionResult'\n\nexport type DecodeFunctionResultParameters<\n  TAbi extends Abi | readonly unknown[] = Abi,\n  TFunctionName extends string | undefined = string,\n  _FunctionName = InferFunctionName<TAbi, TFunctionName>,\n> = {\n  functionName?: _FunctionName\n  data: Hex\n} & (TFunctionName extends string\n  ? { abi: TAbi } & Partial<GetFunctionArgs<TAbi, TFunctionName>>\n  : _FunctionName extends string\n    ? { abi: [TAbi[number]] } & Partial<GetFunctionArgs<TAbi, _FunctionName>>\n    : never)\n\nexport type DecodeFunctionResultReturnType<\n  TAbi extends Abi | readonly unknown[] = Abi,\n  TFunctionName extends string | undefined = string,\n  _FunctionName extends string = TAbi extends Abi\n    ? Abi extends TAbi\n      ? string\n      : ExtractAbiFunctionNames<TAbi>[number]\n    : string,\n> = TFunctionName extends string\n  ? ContractFunctionResult<TAbi, TFunctionName>\n  : ContractFunctionResult<TAbi, _FunctionName>\n\nexport type DecodeFunctionResultErrorType =\n  | AbiFunctionNotFoundErrorType\n  | AbiFunctionOutputsNotFoundErrorType\n  | DecodeAbiParametersErrorType\n  | GetAbiItemErrorType\n  | ErrorType\n\nexport function decodeFunctionResult<\n  const TAbi extends Abi | readonly unknown[],\n  TFunctionName extends string | undefined = undefined,\n>({\n  abi,\n  args,\n  functionName,\n  data,\n}: DecodeFunctionResultParameters<\n  TAbi,\n  TFunctionName\n>): DecodeFunctionResultReturnType<TAbi, TFunctionName> {\n  let abiItem = abi[0] as AbiItem\n  if (functionName) {\n    abiItem = getAbiItem({\n      abi,\n      args,\n      name: functionName,\n    } as GetAbiItemParameters)\n    if (!abiItem) throw new AbiFunctionNotFoundError(functionName, { docsPath })\n  }\n\n  if (abiItem.type !== 'function')\n    throw new AbiFunctionNotFoundError(undefined, { docsPath })\n  if (!abiItem.outputs)\n    throw new AbiFunctionOutputsNotFoundError(abiItem.name, { docsPath })\n\n  const values = decodeAbiParameters(abiItem.outputs, data)\n  if (values && values.length > 1) return values as any\n  if (values && values.length === 1) return values[0] as any\n  return undefined as any\n}\n","/* [Multicall3](https://github.com/mds1/multicall) */\nexport const multicall3Abi = [\n  {\n    inputs: [\n      {\n        components: [\n          {\n            name: 'target',\n            type: 'address',\n          },\n          {\n            name: 'allowFailure',\n            type: 'bool',\n          },\n          {\n            name: 'callData',\n            type: 'bytes',\n          },\n        ],\n        name: 'calls',\n        type: 'tuple[]',\n      },\n    ],\n    name: 'aggregate3',\n    outputs: [\n      {\n        components: [\n          {\n            name: 'success',\n            type: 'bool',\n          },\n          {\n            name: 'returnData',\n            type: 'bytes',\n          },\n        ],\n        name: 'returnData',\n        type: 'tuple[]',\n      },\n    ],\n    stateMutability: 'view',\n    type: 'function',\n  },\n] as const\n\nconst universalResolverErrors = [\n  {\n    inputs: [],\n    name: 'ResolverNotFound',\n    type: 'error',\n  },\n  {\n    inputs: [],\n    name: 'ResolverWildcardNotSupported',\n    type: 'error',\n  },\n] as const\n\nexport const universalResolverResolveAbi = [\n  ...universalResolverErrors,\n  {\n    name: 'resolve',\n    type: 'function',\n    stateMutability: 'view',\n    inputs: [\n      { name: 'name', type: 'bytes' },\n      { name: 'data', type: 'bytes' },\n    ],\n    outputs: [\n      { name: '', type: 'bytes' },\n      { name: 'address', type: 'address' },\n    ],\n  },\n] as const\n\nexport const universalResolverReverseAbi = [\n  ...universalResolverErrors,\n  {\n    name: 'reverse',\n    type: 'function',\n    stateMutability: 'view',\n    inputs: [{ type: 'bytes', name: 'reverseName' }],\n    outputs: [\n      { type: 'string', name: 'resolvedName' },\n      { type: 'address', name: 'resolvedAddress' },\n      { type: 'address', name: 'reverseResolver' },\n      { type: 'address', name: 'resolver' },\n    ],\n  },\n] as const\n\nexport const textResolverAbi = [\n  {\n    name: 'text',\n    type: 'function',\n    stateMutability: 'view',\n    inputs: [\n      { name: 'name', type: 'bytes32' },\n      { name: 'key', type: 'string' },\n    ],\n    outputs: [{ name: '', type: 'string' }],\n  },\n] as const\n\nexport const addressResolverAbi = [\n  {\n    name: 'addr',\n    type: 'function',\n    stateMutability: 'view',\n    inputs: [{ name: 'name', type: 'bytes32' }],\n    outputs: [{ name: '', type: 'address' }],\n  },\n  {\n    name: 'addr',\n    type: 'function',\n    stateMutability: 'view',\n    inputs: [\n      { name: 'name', type: 'bytes32' },\n      { name: 'coinType', type: 'uint256' },\n    ],\n    outputs: [{ name: '', type: 'bytes' }],\n  },\n] as const\n\n// ERC-1271\n// isValidSignature(bytes32 hash, bytes signature) → bytes4 magicValue\nexport const smartAccountAbi = [\n  {\n    name: 'isValidSignature',\n    type: 'function',\n    stateMutability: 'view',\n    inputs: [\n      { name: 'hash', type: 'bytes32' },\n      { name: 'signature', type: 'bytes' },\n    ],\n    outputs: [{ name: '', type: 'bytes4' }],\n  },\n] as const\n\n// ERC-6492 - universal deployless signature validator contract\n// constructor(address _signer, bytes32 _hash, bytes _signature) → bytes4 returnValue\n// returnValue is either 0x1 (valid) or 0x0 (invalid)\nexport const universalSignatureValidatorAbi = [\n  {\n    inputs: [\n      {\n        internalType: 'address',\n        name: '_signer',\n        type: 'address',\n      },\n      {\n        internalType: 'bytes32',\n        name: '_hash',\n        type: 'bytes32',\n      },\n      {\n        internalType: 'bytes',\n        name: '_signature',\n        type: 'bytes',\n      },\n    ],\n    stateMutability: 'nonpayable',\n    type: 'constructor',\n  },\n] as const\n","export const aggregate3Signature = '0x82ad56cb'\n","import {\n  ChainDoesNotSupportContract,\n  type ChainDoesNotSupportContractErrorType,\n} from '../../errors/chain.js'\nimport type { Chain, ChainContract } from '../../types/chain.js'\n\nexport type GetChainContractAddressErrorType =\n  ChainDoesNotSupportContractErrorType\n\nexport function getChainContractAddress({\n  blockNumber,\n  chain,\n  contract: name,\n}: {\n  blockNumber?: bigint\n  chain: Chain\n  contract: string\n}) {\n  const contract = (chain?.contracts as Record<string, ChainContract>)?.[name]\n  if (!contract)\n    throw new ChainDoesNotSupportContract({\n      chain,\n      contract: { name },\n    })\n\n  if (\n    blockNumber &&\n    contract.blockCreated &&\n    contract.blockCreated > blockNumber\n  )\n    throw new ChainDoesNotSupportContract({\n      blockNumber,\n      chain,\n      contract: {\n        name,\n        blockCreated: contract.blockCreated,\n      },\n    })\n\n  return contract.address\n}\n","import type { CallParameters } from '../../actions/public/call.js'\nimport type { BaseError } from '../../errors/base.js'\nimport {\n  CallExecutionError,\n  type CallExecutionErrorType,\n} from '../../errors/contract.js'\nimport { UnknownNodeError } from '../../errors/node.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\n\nimport {\n  type GetNodeErrorParameters,\n  type GetNodeErrorReturnType,\n  getNodeError,\n} from './getNodeError.js'\n\nexport type GetCallErrorReturnType<cause = ErrorType> = Omit<\n  CallExecutionErrorType,\n  'cause'\n> & {\n  cause: cause | GetNodeErrorReturnType\n}\n\nexport function getCallError<err extends ErrorType<string>>(\n  err: err,\n  {\n    docsPath,\n    ...args\n  }: CallParameters & {\n    chain?: Chain\n    docsPath?: string\n  },\n): GetCallErrorReturnType<err> {\n  const cause = (() => {\n    const cause = getNodeError(\n      err as {} as BaseError,\n      args as GetNodeErrorParameters,\n    )\n    if (cause instanceof UnknownNodeError) return err as {} as BaseError\n    return cause\n  })()\n  return new CallExecutionError(cause, {\n    docsPath,\n    ...args,\n  }) as GetCallErrorReturnType<err>\n}\n","import type { ErrorType } from '../../errors/utils.js'\n\ntype Resolved<TReturnType extends readonly unknown[] = any> = [\n  result: TReturnType[number],\n  results: TReturnType,\n]\n\ntype PendingPromise<TReturnType extends readonly unknown[] = any> = {\n  resolve?: (data: Resolved<TReturnType>) => void\n  reject?: (reason?: unknown) => void\n}\n\ntype SchedulerItem = { args: unknown; pendingPromise: PendingPromise }\n\ntype BatchResultsCompareFn<TResult = unknown> = (\n  a: TResult,\n  b: TResult,\n) => number\n\nexport type CreateBatchSchedulerArguments<\n  TParameters = unknown,\n  TReturnType extends readonly unknown[] = readonly unknown[],\n> = {\n  fn: (args: TParameters[]) => Promise<TReturnType>\n  id: number | string\n  shouldSplitBatch?: (args: TParameters[]) => boolean\n  wait?: number\n  sort?: BatchResultsCompareFn<TReturnType[number]>\n}\n\nexport type CreateBatchSchedulerReturnType<\n  TParameters = unknown,\n  TReturnType extends readonly unknown[] = readonly unknown[],\n> = {\n  flush: () => void\n  schedule: TParameters extends undefined\n    ? (args?: TParameters) => Promise<Resolved<TReturnType>>\n    : (args: TParameters) => Promise<Resolved<TReturnType>>\n}\n\nexport type CreateBatchSchedulerErrorType = ErrorType\n\nconst schedulerCache = /*#__PURE__*/ new Map<number | string, SchedulerItem[]>()\n\nexport function createBatchScheduler<\n  TParameters,\n  TReturnType extends readonly unknown[],\n>({\n  fn,\n  id,\n  shouldSplitBatch,\n  wait = 0,\n  sort,\n}: CreateBatchSchedulerArguments<\n  TParameters,\n  TReturnType\n>): CreateBatchSchedulerReturnType<TParameters, TReturnType> {\n  const exec = async () => {\n    const scheduler = getScheduler()\n    flush()\n\n    const args = scheduler.map(({ args }) => args)\n\n    if (args.length === 0) return\n\n    fn(args as TParameters[])\n      .then((data) => {\n        if (sort && Array.isArray(data)) data.sort(sort)\n        for (let i = 0; i < scheduler.length; i++) {\n          const { pendingPromise } = scheduler[i]\n          pendingPromise.resolve?.([data[i], data])\n        }\n      })\n      .catch((err) => {\n        for (let i = 0; i < scheduler.length; i++) {\n          const { pendingPromise } = scheduler[i]\n          pendingPromise.reject?.(err)\n        }\n      })\n  }\n\n  const flush = () => schedulerCache.delete(id)\n\n  const getBatchedArgs = () =>\n    getScheduler().map(({ args }) => args) as TParameters[]\n\n  const getScheduler = () => schedulerCache.get(id) || []\n\n  const setScheduler = (item: SchedulerItem) =>\n    schedulerCache.set(id, [...getScheduler(), item])\n\n  return {\n    flush,\n    async schedule(args: TParameters) {\n      const pendingPromise: PendingPromise<TReturnType> = {}\n      const promise = new Promise<Resolved<TReturnType>>((resolve, reject) => {\n        pendingPromise.resolve = resolve\n        pendingPromise.reject = reject\n      })\n\n      const split = shouldSplitBatch?.([...getBatchedArgs(), args])\n\n      if (split) exec()\n\n      const hasActiveScheduler = getScheduler().length > 0\n      if (hasActiveScheduler) {\n        setScheduler({ args, pendingPromise })\n        return promise\n      }\n\n      setScheduler({ args, pendingPromise })\n      setTimeout(exec, wait)\n      return promise\n    },\n  } as unknown as CreateBatchSchedulerReturnType<TParameters, TReturnType>\n}\n","import type { Address } from 'abitype'\n\nimport type { Hex } from '../types/misc.js'\nimport { stringify } from '../utils/stringify.js'\n\nimport { BaseError } from './base.js'\nimport { getUrl } from './utils.js'\n\nexport type OffchainLookupErrorType = OffchainLookupError & {\n  name: 'OffchainLookupError'\n}\nexport class OffchainLookupError extends BaseError {\n  override name = 'OffchainLookupError'\n  constructor({\n    callbackSelector,\n    cause,\n    data,\n    extraData,\n    sender,\n    urls,\n  }: {\n    callbackSelector: Hex\n    cause: BaseError\n    data: Hex\n    extraData: Hex\n    sender: Address\n    urls: readonly string[]\n  }) {\n    super(\n      cause.shortMessage ||\n        'An error occurred while fetching for an offchain result.',\n      {\n        cause,\n        metaMessages: [\n          ...(cause.metaMessages || []),\n          cause.metaMessages?.length ? '' : [],\n          'Offchain Gateway Call:',\n          urls && [\n            '  Gateway URL(s):',\n            ...urls.map((url) => `    ${getUrl(url)}`),\n          ],\n          `  Sender: ${sender}`,\n          `  Data: ${data}`,\n          `  Callback selector: ${callbackSelector}`,\n          `  Extra data: ${extraData}`,\n        ].flat(),\n      },\n    )\n  }\n}\n\nexport type OffchainLookupResponseMalformedErrorType =\n  OffchainLookupResponseMalformedError & {\n    name: 'OffchainLookupResponseMalformedError'\n  }\nexport class OffchainLookupResponseMalformedError extends BaseError {\n  override name = 'OffchainLookupResponseMalformedError'\n  constructor({ result, url }: { result: any; url: string }) {\n    super(\n      'Offchain gateway response is malformed. Response data must be a hex value.',\n      {\n        metaMessages: [\n          `Gateway URL: ${getUrl(url)}`,\n          `Response: ${stringify(result)}`,\n        ],\n      },\n    )\n  }\n}\n\nexport type OffchainLookupSenderMismatchErrorType =\n  OffchainLookupSenderMismatchError & {\n    name: 'OffchainLookupSenderMismatchError'\n  }\nexport class OffchainLookupSenderMismatchError extends BaseError {\n  override name = 'OffchainLookupSenderMismatchError'\n  constructor({ sender, to }: { sender: Address; to: Address }) {\n    super(\n      'Reverted sender address does not match target contract address (`to`).',\n      {\n        metaMessages: [\n          `Contract address: ${to}`,\n          `OffchainLookup sender address: ${sender}`,\n        ],\n      },\n    )\n  }\n}\n","import type { Address } from 'abitype'\n\nimport {\n  InvalidAddressError,\n  type InvalidAddressErrorType,\n} from '../../errors/address.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport { isAddress } from './isAddress.js'\n\nexport type IsAddressEqualReturnType = boolean\nexport type IsAddressEqualErrorType = InvalidAddressErrorType | ErrorType\n\nexport function isAddressEqual(a: Address, b: Address) {\n  if (!isAddress(a)) throw new InvalidAddressError({ address: a })\n  if (!isAddress(b)) throw new InvalidAddressError({ address: b })\n  return a.toLowerCase() === b.toLowerCase()\n}\n","import type { Abi, Address } from 'abitype'\n\nimport { type CallParameters, call } from '../actions/public/call.js'\nimport type { Transport } from '../clients/transports/createTransport.js'\nimport { type BaseError } from '../errors/base.js'\nimport {\n  OffchainLookupError,\n  OffchainLookupResponseMalformedError,\n  OffchainLookupSenderMismatchError,\n} from '../errors/ccip.js'\nimport { HttpRequestError } from '../errors/request.js'\nimport type { Chain } from '../types/chain.js'\nimport type { GetErrorArgs } from '../types/contract.js'\nimport type { Hex } from '../types/misc.js'\n\nimport type { Client } from '../clients/createClient.js'\nimport type { ErrorType } from '../errors/utils.js'\nimport { decodeErrorResult } from './abi/decodeErrorResult.js'\nimport { encodeAbiParameters } from './abi/encodeAbiParameters.js'\nimport { isAddressEqual } from './address/isAddressEqual.js'\nimport { concat } from './data/concat.js'\nimport { isHex } from './data/isHex.js'\nimport { stringify } from './stringify.js'\n\nexport const offchainLookupSignature = '0x556f1830'\nexport const offchainLookupAbiItem = {\n  name: 'OffchainLookup',\n  type: 'error',\n  inputs: [\n    {\n      name: 'sender',\n      type: 'address',\n    },\n    {\n      name: 'urls',\n      type: 'string[]',\n    },\n    {\n      name: 'callData',\n      type: 'bytes',\n    },\n    {\n      name: 'callbackFunction',\n      type: 'bytes4',\n    },\n    {\n      name: 'extraData',\n      type: 'bytes',\n    },\n  ],\n} as const satisfies Abi[number]\n\nexport type OffchainLookupErrorType = ErrorType\n\nexport async function offchainLookup<TChain extends Chain | undefined>(\n  client: Client<Transport, TChain>,\n  {\n    blockNumber,\n    blockTag,\n    data,\n    to,\n  }: Pick<CallParameters, 'blockNumber' | 'blockTag'> & {\n    data: Hex\n    to: Address\n  },\n): Promise<Hex> {\n  const { args } = decodeErrorResult({\n    data,\n    abi: [offchainLookupAbiItem],\n  }) as unknown as GetErrorArgs<\n    [typeof offchainLookupAbiItem],\n    'OffchainLookup'\n  >\n  const [sender, urls, callData, callbackSelector, extraData] = args\n\n  try {\n    if (!isAddressEqual(to, sender))\n      throw new OffchainLookupSenderMismatchError({ sender, to })\n\n    const result = await ccipFetch({ data: callData, sender, urls })\n\n    const { data: data_ } = await call(client, {\n      blockNumber,\n      blockTag,\n      data: concat([\n        callbackSelector,\n        encodeAbiParameters(\n          [{ type: 'bytes' }, { type: 'bytes' }],\n          [result, extraData],\n        ),\n      ]),\n      to,\n    } as CallParameters)\n\n    return data_!\n  } catch (err) {\n    throw new OffchainLookupError({\n      callbackSelector,\n      cause: err as BaseError,\n      data,\n      extraData,\n      sender,\n      urls,\n    })\n  }\n}\n\nexport type CcipFetchErrorType = ErrorType\n\nexport async function ccipFetch({\n  data,\n  sender,\n  urls,\n}: { data: Hex; sender: Address; urls: readonly string[] }) {\n  let error = new Error('An unknown error occurred.')\n\n  for (let i = 0; i < urls.length; i++) {\n    const url = urls[i]\n    const method = url.includes('{data}') ? 'GET' : 'POST'\n    const body = method === 'POST' ? { data, sender } : undefined\n\n    try {\n      const response = await fetch(\n        url.replace('{sender}', sender).replace('{data}', data),\n        {\n          body: JSON.stringify(body),\n          method,\n        },\n      )\n\n      let result\n      if (\n        response.headers.get('Content-Type')?.startsWith('application/json')\n      ) {\n        result = (await response.json()).data\n      } else {\n        result = (await response.text()) as any\n      }\n\n      if (!response.ok) {\n        error = new HttpRequestError({\n          body,\n          details: result?.error\n            ? stringify(result.error)\n            : response.statusText,\n          headers: response.headers,\n          status: response.status,\n          url,\n        })\n        continue\n      }\n\n      if (!isHex(result)) {\n        error = new OffchainLookupResponseMalformedError({\n          result,\n          url,\n        })\n        continue\n      }\n\n      return result\n    } catch (err) {\n      error = new HttpRequestError({\n        body,\n        details: (err as Error).message,\n        url,\n      })\n    }\n  }\n\n  throw error\n}\n","import type { Address } from 'abitype'\n\nimport type { Account } from '../../accounts/types.js'\nimport {\n  type ParseAccountErrorType,\n  parseAccount,\n} from '../../accounts/utils/parseAccount.js'\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport { multicall3Abi } from '../../constants/abis.js'\nimport { aggregate3Signature } from '../../constants/contract.js'\nimport { BaseError } from '../../errors/base.js'\nimport {\n  ChainDoesNotSupportContract,\n  ClientChainNotConfiguredError,\n} from '../../errors/chain.js'\nimport {\n  RawContractError,\n  type RawContractErrorType,\n} from '../../errors/contract.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { BlockTag } from '../../types/block.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Hex } from '../../types/misc.js'\nimport type { RpcTransactionRequest } from '../../types/rpc.js'\nimport type { TransactionRequest } from '../../types/transaction.js'\nimport type { UnionOmit } from '../../types/utils.js'\nimport {\n  type DecodeFunctionResultErrorType,\n  decodeFunctionResult,\n} from '../../utils/abi/decodeFunctionResult.js'\nimport {\n  type EncodeFunctionDataErrorType,\n  encodeFunctionData,\n} from '../../utils/abi/encodeFunctionData.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport {\n  type GetChainContractAddressErrorType,\n  getChainContractAddress,\n} from '../../utils/chain/getChainContractAddress.js'\nimport {\n  type NumberToHexErrorType,\n  numberToHex,\n} from '../../utils/encoding/toHex.js'\nimport {\n  type GetCallErrorReturnType,\n  getCallError,\n} from '../../utils/errors/getCallError.js'\nimport { extract } from '../../utils/formatters/extract.js'\nimport {\n  type FormatTransactionRequestErrorType,\n  type FormattedTransactionRequest,\n  formatTransactionRequest,\n} from '../../utils/formatters/transactionRequest.js'\nimport {\n  type CreateBatchSchedulerErrorType,\n  createBatchScheduler,\n} from '../../utils/promise/createBatchScheduler.js'\nimport { assertRequest } from '../../utils/transaction/assertRequest.js'\nimport type {\n  AssertRequestErrorType,\n  AssertRequestParameters,\n} from '../../utils/transaction/assertRequest.js'\n\nexport type FormattedCall<\n  TChain extends Chain | undefined = Chain | undefined,\n> = FormattedTransactionRequest<TChain>\n\nexport type CallParameters<\n  TChain extends Chain | undefined = Chain | undefined,\n> = UnionOmit<FormattedCall<TChain>, 'from'> & {\n  account?: Account | Address\n  batch?: boolean\n} & (\n    | {\n        /** The balance of the account at a block number. */\n        blockNumber?: bigint\n        blockTag?: never\n      }\n    | {\n        blockNumber?: never\n        /**\n         * The balance of the account at a block tag.\n         * @default 'latest'\n         */\n        blockTag?: BlockTag\n      }\n  )\n\nexport type CallReturnType = { data: Hex | undefined }\n\nexport type CallErrorType = GetCallErrorReturnType<\n  | ParseAccountErrorType\n  | AssertRequestErrorType\n  | NumberToHexErrorType\n  | FormatTransactionRequestErrorType\n  | ScheduleMulticallErrorType\n  | RequestErrorType\n>\n\n/**\n * Executes a new message call immediately without submitting a transaction to the network.\n *\n * - Docs: https://viem.sh/docs/actions/public/call.html\n * - JSON-RPC Methods: [`eth_call`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_call)\n *\n * @param client - Client to use\n * @param parameters - {@link CallParameters}\n * @returns The call data. {@link CallReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { call } from 'viem/public'\n *\n * const client = createPublicClient({\n *   chain: mainnet,\n *   transport: http(),\n * })\n * const data = await call(client, {\n *   account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266',\n *   data: '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2',\n *   to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',\n * })\n */\nexport async function call<TChain extends Chain | undefined>(\n  client: Client<Transport, TChain>,\n  args: CallParameters<TChain>,\n): Promise<CallReturnType> {\n  const {\n    account: account_ = client.account,\n    batch = Boolean(client.batch?.multicall),\n    blockNumber,\n    blockTag = 'latest',\n    accessList,\n    data,\n    gas,\n    gasPrice,\n    maxFeePerGas,\n    maxPriorityFeePerGas,\n    nonce,\n    to,\n    value,\n    ...rest\n  } = args\n  const account = account_ ? parseAccount(account_) : undefined\n\n  try {\n    assertRequest(args as AssertRequestParameters)\n\n    const blockNumberHex = blockNumber ? numberToHex(blockNumber) : undefined\n    const block = blockNumberHex || blockTag\n\n    const chainFormat = client.chain?.formatters?.transactionRequest?.format\n    const format = chainFormat || formatTransactionRequest\n\n    const request = format({\n      // Pick out extra data that might exist on the chain's transaction request type.\n      ...extract(rest, { format: chainFormat }),\n      from: account?.address,\n      accessList,\n      data,\n      gas,\n      gasPrice,\n      maxFeePerGas,\n      maxPriorityFeePerGas,\n      nonce,\n      to,\n      value,\n    } as TransactionRequest) as TransactionRequest\n\n    if (batch && shouldPerformMulticall({ request })) {\n      try {\n        return await scheduleMulticall(client, {\n          ...request,\n          blockNumber,\n          blockTag,\n        } as unknown as ScheduleMulticallParameters<TChain>)\n      } catch (err) {\n        if (\n          !(err instanceof ClientChainNotConfiguredError) &&\n          !(err instanceof ChainDoesNotSupportContract)\n        )\n          throw err\n      }\n    }\n\n    const response = await client.request({\n      method: 'eth_call',\n      params: block\n        ? [request as Partial<RpcTransactionRequest>, block]\n        : [request as Partial<RpcTransactionRequest>],\n    })\n    if (response === '0x') return { data: undefined }\n    return { data: response }\n  } catch (err) {\n    const data = getRevertErrorData(err)\n    const { offchainLookup, offchainLookupSignature } = await import(\n      '../../utils/ccip.js'\n    )\n    if (data?.slice(0, 10) === offchainLookupSignature && to) {\n      return { data: await offchainLookup(client, { data, to }) }\n    }\n    throw getCallError(err as ErrorType, {\n      ...args,\n      account,\n      chain: client.chain,\n    })\n  }\n}\n\n// We only want to perform a scheduled multicall if:\n// - The request has calldata,\n// - The request has a target address,\n// - The target address is not already the aggregate3 signature,\n// - The request has no other properties (`nonce`, `gas`, etc cannot be sent with a multicall).\nfunction shouldPerformMulticall({ request }: { request: TransactionRequest }) {\n  const { data, to, ...request_ } = request\n  if (!data) return false\n  if (data.startsWith(aggregate3Signature)) return false\n  if (!to) return false\n  if (\n    Object.values(request_).filter((x) => typeof x !== 'undefined').length > 0\n  )\n    return false\n  return true\n}\n\ntype ScheduleMulticallParameters<TChain extends Chain | undefined> = Pick<\n  CallParameters<TChain>,\n  'blockNumber' | 'blockTag'\n> & {\n  data: Hex\n  multicallAddress?: Address\n  to: Address\n}\n\nexport type ScheduleMulticallErrorType =\n  | GetChainContractAddressErrorType\n  | NumberToHexErrorType\n  | CreateBatchSchedulerErrorType\n  | EncodeFunctionDataErrorType\n  | DecodeFunctionResultErrorType\n  | RawContractErrorType\n  | ErrorType\n\nasync function scheduleMulticall<TChain extends Chain | undefined>(\n  client: Client<Transport>,\n  args: ScheduleMulticallParameters<TChain>,\n) {\n  const { batchSize = 1024, wait = 0 } =\n    typeof client.batch?.multicall === 'object' ? client.batch.multicall : {}\n  const {\n    blockNumber,\n    blockTag = 'latest',\n    data,\n    multicallAddress: multicallAddress_,\n    to,\n  } = args\n\n  let multicallAddress = multicallAddress_\n  if (!multicallAddress) {\n    if (!client.chain) throw new ClientChainNotConfiguredError()\n\n    multicallAddress = getChainContractAddress({\n      blockNumber,\n      chain: client.chain,\n      contract: 'multicall3',\n    })\n  }\n\n  const blockNumberHex = blockNumber ? numberToHex(blockNumber) : undefined\n  const block = blockNumberHex || blockTag\n\n  const { schedule } = createBatchScheduler({\n    id: `${client.uid}.${block}`,\n    wait,\n    shouldSplitBatch(args) {\n      const size = args.reduce((size, { data }) => size + (data.length - 2), 0)\n      return size > batchSize * 2\n    },\n    fn: async (\n      requests: {\n        data: Hex\n        to: Address\n      }[],\n    ) => {\n      const calls = requests.map((request) => ({\n        allowFailure: true,\n        callData: request.data,\n        target: request.to,\n      }))\n\n      const calldata = encodeFunctionData({\n        abi: multicall3Abi,\n        args: [calls],\n        functionName: 'aggregate3',\n      })\n\n      const data = await client.request({\n        method: 'eth_call',\n        params: [\n          {\n            data: calldata,\n            to: multicallAddress,\n          },\n          block,\n        ],\n      })\n\n      return decodeFunctionResult({\n        abi: multicall3Abi,\n        args: [calls],\n        functionName: 'aggregate3',\n        data: data || '0x',\n      })\n    },\n  })\n\n  const [{ returnData, success }] = await schedule({ data, to })\n\n  if (!success) throw new RawContractError({ data: returnData })\n  if (returnData === '0x') return { data: undefined }\n  return { data: returnData }\n}\n\nexport type GetRevertErrorDataErrorType = ErrorType\n\nexport function getRevertErrorData(err: unknown) {\n  if (!(err instanceof BaseError)) return undefined\n  const error = err.walk() as RawContractError\n  return typeof error.data === 'object' ? error.data.data : error.data\n}\n","import { exists, output } from './_assert.js';\nimport { Hash, createView, Input, toBytes } from './utils.js';\n\n// Polyfill for Safari 14\nfunction setBigUint64(view: DataView, byteOffset: number, value: bigint, isLE: boolean): void {\n  if (typeof view.setBigUint64 === 'function') return view.setBigUint64(byteOffset, value, isLE);\n  const _32n = BigInt(32);\n  const _u32_max = BigInt(0xffffffff);\n  const wh = Number((value >> _32n) & _u32_max);\n  const wl = Number(value & _u32_max);\n  const h = isLE ? 4 : 0;\n  const l = isLE ? 0 : 4;\n  view.setUint32(byteOffset + h, wh, isLE);\n  view.setUint32(byteOffset + l, wl, isLE);\n}\n\n// Base SHA2 class (RFC 6234)\nexport abstract class SHA2<T extends SHA2<T>> extends Hash<T> {\n  protected abstract process(buf: DataView, offset: number): void;\n  protected abstract get(): number[];\n  protected abstract set(...args: number[]): void;\n  abstract destroy(): void;\n  protected abstract roundClean(): void;\n  // For partial updates less than block size\n  protected buffer: Uint8Array;\n  protected view: DataView;\n  protected finished = false;\n  protected length = 0;\n  protected pos = 0;\n  protected destroyed = false;\n\n  constructor(\n    readonly blockLen: number,\n    public outputLen: number,\n    readonly padOffset: number,\n    readonly isLE: boolean\n  ) {\n    super();\n    this.buffer = new Uint8Array(blockLen);\n    this.view = createView(this.buffer);\n  }\n  update(data: Input): this {\n    exists(this);\n    const { view, buffer, blockLen } = this;\n    data = toBytes(data);\n    const len = data.length;\n    for (let pos = 0; pos < len; ) {\n      const take = Math.min(blockLen - this.pos, len - pos);\n      // Fast path: we have at least one block in input, cast it to view and process\n      if (take === blockLen) {\n        const dataView = createView(data);\n        for (; blockLen <= len - pos; pos += blockLen) this.process(dataView, pos);\n        continue;\n      }\n      buffer.set(data.subarray(pos, pos + take), this.pos);\n      this.pos += take;\n      pos += take;\n      if (this.pos === blockLen) {\n        this.process(view, 0);\n        this.pos = 0;\n      }\n    }\n    this.length += data.length;\n    this.roundClean();\n    return this;\n  }\n  digestInto(out: Uint8Array) {\n    exists(this);\n    output(out, this);\n    this.finished = true;\n    // Padding\n    // We can avoid allocation of buffer for padding completely if it\n    // was previously not allocated here. But it won't change performance.\n    const { buffer, view, blockLen, isLE } = this;\n    let { pos } = this;\n    // append the bit '1' to the message\n    buffer[pos++] = 0b10000000;\n    this.buffer.subarray(pos).fill(0);\n    // we have less than padOffset left in buffer, so we cannot put length in current block, need process it and pad again\n    if (this.padOffset > blockLen - pos) {\n      this.process(view, 0);\n      pos = 0;\n    }\n    // Pad until full block byte with zeros\n    for (let i = pos; i < blockLen; i++) buffer[i] = 0;\n    // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that\n    // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen.\n    // So we just write lowest 64 bits of that value.\n    setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);\n    this.process(view, 0);\n    const oview = createView(out);\n    const len = this.outputLen;\n    // NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT\n    if (len % 4) throw new Error('_sha2: outputLen should be aligned to 32bit');\n    const outLen = len / 4;\n    const state = this.get();\n    if (outLen > state.length) throw new Error('_sha2: outputLen bigger than state');\n    for (let i = 0; i < outLen; i++) oview.setUint32(4 * i, state[i], isLE);\n  }\n  digest() {\n    const { buffer, outputLen } = this;\n    this.digestInto(buffer);\n    const res = buffer.slice(0, outputLen);\n    this.destroy();\n    return res;\n  }\n  _cloneInto(to?: T): T {\n    to ||= new (this.constructor as any)() as T;\n    to.set(...this.get());\n    const { blockLen, buffer, length, finished, destroyed, pos } = this;\n    to.length = length;\n    to.pos = pos;\n    to.finished = finished;\n    to.destroyed = destroyed;\n    if (length % blockLen) to.buffer.set(buffer);\n    return to;\n  }\n}\n","import { SHA2 } from './_sha2.js';\nimport { rotr, wrapConstructor } from './utils.js';\n\n// SHA2-256 need to try 2^128 hashes to execute birthday attack.\n// BTC network is doing 2^67 hashes/sec as per early 2023.\n\n// Choice: a ? b : c\nconst Chi = (a: number, b: number, c: number) => (a & b) ^ (~a & c);\n// Majority function, true if any two inpust is true\nconst Maj = (a: number, b: number, c: number) => (a & b) ^ (a & c) ^ (b & c);\n\n// Round constants:\n// first 32 bits of the fractional parts of the cube roots of the first 64 primes 2..311)\n// prettier-ignore\nconst SHA256_K = /* @__PURE__ */new Uint32Array([\n  0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n  0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n  0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n  0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n  0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n  0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n  0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n  0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2\n]);\n\n// Initial state (first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19):\n// prettier-ignore\nconst IV = /* @__PURE__ */new Uint32Array([\n  0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19\n]);\n\n// Temporary buffer, not used to store anything between runs\n// Named this way because it matches specification.\nconst SHA256_W = /* @__PURE__ */ new Uint32Array(64);\nclass SHA256 extends SHA2<SHA256> {\n  // We cannot use array here since array allows indexing by variable\n  // which means optimizer/compiler cannot use registers.\n  A = IV[0] | 0;\n  B = IV[1] | 0;\n  C = IV[2] | 0;\n  D = IV[3] | 0;\n  E = IV[4] | 0;\n  F = IV[5] | 0;\n  G = IV[6] | 0;\n  H = IV[7] | 0;\n\n  constructor() {\n    super(64, 32, 8, false);\n  }\n  protected get(): [number, number, number, number, number, number, number, number] {\n    const { A, B, C, D, E, F, G, H } = this;\n    return [A, B, C, D, E, F, G, H];\n  }\n  // prettier-ignore\n  protected set(\n    A: number, B: number, C: number, D: number, E: number, F: number, G: number, H: number\n  ) {\n    this.A = A | 0;\n    this.B = B | 0;\n    this.C = C | 0;\n    this.D = D | 0;\n    this.E = E | 0;\n    this.F = F | 0;\n    this.G = G | 0;\n    this.H = H | 0;\n  }\n  protected process(view: DataView, offset: number): void {\n    // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array\n    for (let i = 0; i < 16; i++, offset += 4) SHA256_W[i] = view.getUint32(offset, false);\n    for (let i = 16; i < 64; i++) {\n      const W15 = SHA256_W[i - 15];\n      const W2 = SHA256_W[i - 2];\n      const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3);\n      const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10);\n      SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;\n    }\n    // Compression function main loop, 64 rounds\n    let { A, B, C, D, E, F, G, H } = this;\n    for (let i = 0; i < 64; i++) {\n      const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);\n      const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n      const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);\n      const T2 = (sigma0 + Maj(A, B, C)) | 0;\n      H = G;\n      G = F;\n      F = E;\n      E = (D + T1) | 0;\n      D = C;\n      C = B;\n      B = A;\n      A = (T1 + T2) | 0;\n    }\n    // Add the compressed chunk to the current hash value\n    A = (A + this.A) | 0;\n    B = (B + this.B) | 0;\n    C = (C + this.C) | 0;\n    D = (D + this.D) | 0;\n    E = (E + this.E) | 0;\n    F = (F + this.F) | 0;\n    G = (G + this.G) | 0;\n    H = (H + this.H) | 0;\n    this.set(A, B, C, D, E, F, G, H);\n  }\n  protected roundClean() {\n    SHA256_W.fill(0);\n  }\n  destroy() {\n    this.set(0, 0, 0, 0, 0, 0, 0, 0);\n    this.buffer.fill(0);\n  }\n}\n// Constants from https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf\nclass SHA224 extends SHA256 {\n  A = 0xc1059ed8 | 0;\n  B = 0x367cd507 | 0;\n  C = 0x3070dd17 | 0;\n  D = 0xf70e5939 | 0;\n  E = 0xffc00b31 | 0;\n  F = 0x68581511 | 0;\n  G = 0x64f98fa7 | 0;\n  H = 0xbefa4fa4 | 0;\n  constructor() {\n    super();\n    this.outputLen = 28;\n  }\n}\n\n/**\n * SHA2-256 hash function\n * @param message - data that would be hashed\n */\nexport const sha256 = /* @__PURE__ */ wrapConstructor(() => new SHA256());\nexport const sha224 = /* @__PURE__ */ wrapConstructor(() => new SHA224());\n","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// 100 lines of code in the file are duplicated from noble-hashes (utils).\n// This is OK: `abstract` directory does not use noble-hashes.\n// User may opt-in into using different hashing library. This way, noble-hashes\n// won't be included into their bundle.\nconst _0n = BigInt(0);\nconst _1n = BigInt(1);\nconst _2n = BigInt(2);\nconst u8a = (a: any): a is Uint8Array => a instanceof Uint8Array;\nexport type Hex = Uint8Array | string; // hex strings are accepted for simplicity\nexport type PrivKey = Hex | bigint; // bigints are accepted to ease learning curve\nexport type CHash = {\n  (message: Uint8Array | string): Uint8Array;\n  blockLen: number;\n  outputLen: number;\n  create(opts?: { dkLen?: number }): any; // For shake\n};\nexport type FHash = (message: Uint8Array | string) => Uint8Array;\n\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) =>\n  i.toString(16).padStart(2, '0')\n);\n/**\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes: Uint8Array): string {\n  if (!u8a(bytes)) throw new Error('Uint8Array expected');\n  // pre-caching improves the speed 6x\n  let hex = '';\n  for (let i = 0; i < bytes.length; i++) {\n    hex += hexes[bytes[i]];\n  }\n  return hex;\n}\n\nexport function numberToHexUnpadded(num: number | bigint): string {\n  const hex = num.toString(16);\n  return hex.length & 1 ? `0${hex}` : hex;\n}\n\nexport function hexToNumber(hex: string): bigint {\n  if (typeof hex !== 'string') throw new Error('hex string expected, got ' + typeof hex);\n  // Big Endian\n  return BigInt(hex === '' ? '0' : `0x${hex}`);\n}\n\n/**\n * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n */\nexport function hexToBytes(hex: string): Uint8Array {\n  if (typeof hex !== 'string') throw new Error('hex string expected, got ' + typeof hex);\n  const len = hex.length;\n  if (len % 2) throw new Error('padded hex string expected, got unpadded hex of length ' + len);\n  const array = new Uint8Array(len / 2);\n  for (let i = 0; i < array.length; i++) {\n    const j = i * 2;\n    const hexByte = hex.slice(j, j + 2);\n    const byte = Number.parseInt(hexByte, 16);\n    if (Number.isNaN(byte) || byte < 0) throw new Error('Invalid byte sequence');\n    array[i] = byte;\n  }\n  return array;\n}\n\n// BE: Big Endian, LE: Little Endian\nexport function bytesToNumberBE(bytes: Uint8Array): bigint {\n  return hexToNumber(bytesToHex(bytes));\n}\nexport function bytesToNumberLE(bytes: Uint8Array): bigint {\n  if (!u8a(bytes)) throw new Error('Uint8Array expected');\n  return hexToNumber(bytesToHex(Uint8Array.from(bytes).reverse()));\n}\n\nexport function numberToBytesBE(n: number | bigint, len: number): Uint8Array {\n  return hexToBytes(n.toString(16).padStart(len * 2, '0'));\n}\nexport function numberToBytesLE(n: number | bigint, len: number): Uint8Array {\n  return numberToBytesBE(n, len).reverse();\n}\n// Unpadded, rarely used\nexport function numberToVarBytesBE(n: number | bigint): Uint8Array {\n  return hexToBytes(numberToHexUnpadded(n));\n}\n\n/**\n * Takes hex string or Uint8Array, converts to Uint8Array.\n * Validates output length.\n * Will throw error for other types.\n * @param title descriptive title for an error e.g. 'private key'\n * @param hex hex string or Uint8Array\n * @param expectedLength optional, will compare to result array's length\n * @returns\n */\nexport function ensureBytes(title: string, hex: Hex, expectedLength?: number): Uint8Array {\n  let res: Uint8Array;\n  if (typeof hex === 'string') {\n    try {\n      res = hexToBytes(hex);\n    } catch (e) {\n      throw new Error(`${title} must be valid hex string, got \"${hex}\". Cause: ${e}`);\n    }\n  } else if (u8a(hex)) {\n    // Uint8Array.from() instead of hash.slice() because node.js Buffer\n    // is instance of Uint8Array, and its slice() creates **mutable** copy\n    res = Uint8Array.from(hex);\n  } else {\n    throw new Error(`${title} must be hex string or Uint8Array`);\n  }\n  const len = res.length;\n  if (typeof expectedLength === 'number' && len !== expectedLength)\n    throw new Error(`${title} expected ${expectedLength} bytes, got ${len}`);\n  return res;\n}\n\n/**\n * Copies several Uint8Arrays into one.\n */\nexport function concatBytes(...arrays: Uint8Array[]): Uint8Array {\n  const r = new Uint8Array(arrays.reduce((sum, a) => sum + a.length, 0));\n  let pad = 0; // walk through each item, ensure they have proper type\n  arrays.forEach((a) => {\n    if (!u8a(a)) throw new Error('Uint8Array expected');\n    r.set(a, pad);\n    pad += a.length;\n  });\n  return r;\n}\n\nexport function equalBytes(b1: Uint8Array, b2: Uint8Array) {\n  // We don't care about timing attacks here\n  if (b1.length !== b2.length) return false;\n  for (let i = 0; i < b1.length; i++) if (b1[i] !== b2[i]) return false;\n  return true;\n}\n\n// Global symbols in both browsers and Node.js since v11\n// See https://github.com/microsoft/TypeScript/issues/31535\ndeclare const TextEncoder: any;\n\n/**\n * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])\n */\nexport function utf8ToBytes(str: string): Uint8Array {\n  if (typeof str !== 'string') throw new Error(`utf8ToBytes expected string, got ${typeof str}`);\n  return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n\n// Bit operations\n\n/**\n * Calculates amount of bits in a bigint.\n * Same as `n.toString(2).length`\n */\nexport function bitLen(n: bigint) {\n  let len;\n  for (len = 0; n > _0n; n >>= _1n, len += 1);\n  return len;\n}\n\n/**\n * Gets single bit at position.\n * NOTE: first bit position is 0 (same as arrays)\n * Same as `!!+Array.from(n.toString(2)).reverse()[pos]`\n */\nexport function bitGet(n: bigint, pos: number) {\n  return (n >> BigInt(pos)) & _1n;\n}\n\n/**\n * Sets single bit at position.\n */\nexport const bitSet = (n: bigint, pos: number, value: boolean) => {\n  return n | ((value ? _1n : _0n) << BigInt(pos));\n};\n\n/**\n * Calculate mask for N bits. Not using ** operator with bigints because of old engines.\n * Same as BigInt(`0b${Array(i).fill('1').join('')}`)\n */\nexport const bitMask = (n: number) => (_2n << BigInt(n - 1)) - _1n;\n\n// DRBG\n\nconst u8n = (data?: any) => new Uint8Array(data); // creates Uint8Array\nconst u8fr = (arr: any) => Uint8Array.from(arr); // another shortcut\ntype Pred<T> = (v: Uint8Array) => T | undefined;\n/**\n * Minimal HMAC-DRBG from NIST 800-90 for RFC6979 sigs.\n * @returns function that will call DRBG until 2nd arg returns something meaningful\n * @example\n *   const drbg = createHmacDRBG<Key>(32, 32, hmac);\n *   drbg(seed, bytesToKey); // bytesToKey must return Key or undefined\n */\nexport function createHmacDrbg<T>(\n  hashLen: number,\n  qByteLen: number,\n  hmacFn: (key: Uint8Array, ...messages: Uint8Array[]) => Uint8Array\n): (seed: Uint8Array, predicate: Pred<T>) => T {\n  if (typeof hashLen !== 'number' || hashLen < 2) throw new Error('hashLen must be a number');\n  if (typeof qByteLen !== 'number' || qByteLen < 2) throw new Error('qByteLen must be a number');\n  if (typeof hmacFn !== 'function') throw new Error('hmacFn must be a function');\n  // Step B, Step C: set hashLen to 8*ceil(hlen/8)\n  let v = u8n(hashLen); // Minimal non-full-spec HMAC-DRBG from NIST 800-90 for RFC6979 sigs.\n  let k = u8n(hashLen); // Steps B and C of RFC6979 3.2: set hashLen, in our case always same\n  let i = 0; // Iterations counter, will throw when over 1000\n  const reset = () => {\n    v.fill(1);\n    k.fill(0);\n    i = 0;\n  };\n  const h = (...b: Uint8Array[]) => hmacFn(k, v, ...b); // hmac(k)(v, ...values)\n  const reseed = (seed = u8n()) => {\n    // HMAC-DRBG reseed() function. Steps D-G\n    k = h(u8fr([0x00]), seed); // k = hmac(k || v || 0x00 || seed)\n    v = h(); // v = hmac(k || v)\n    if (seed.length === 0) return;\n    k = h(u8fr([0x01]), seed); // k = hmac(k || v || 0x01 || seed)\n    v = h(); // v = hmac(k || v)\n  };\n  const gen = () => {\n    // HMAC-DRBG generate() function\n    if (i++ >= 1000) throw new Error('drbg: tried 1000 values');\n    let len = 0;\n    const out: Uint8Array[] = [];\n    while (len < qByteLen) {\n      v = h();\n      const sl = v.slice();\n      out.push(sl);\n      len += v.length;\n    }\n    return concatBytes(...out);\n  };\n  const genUntil = (seed: Uint8Array, pred: Pred<T>): T => {\n    reset();\n    reseed(seed); // Steps D-G\n    let res: T | undefined = undefined; // Step H: grind until k is in [1..n-1]\n    while (!(res = pred(gen()))) reseed();\n    reset();\n    return res;\n  };\n  return genUntil;\n}\n\n// Validating curves and fields\n\nconst validatorFns = {\n  bigint: (val: any) => typeof val === 'bigint',\n  function: (val: any) => typeof val === 'function',\n  boolean: (val: any) => typeof val === 'boolean',\n  string: (val: any) => typeof val === 'string',\n  stringOrUint8Array: (val: any) => typeof val === 'string' || val instanceof Uint8Array,\n  isSafeInteger: (val: any) => Number.isSafeInteger(val),\n  array: (val: any) => Array.isArray(val),\n  field: (val: any, object: any) => (object as any).Fp.isValid(val),\n  hash: (val: any) => typeof val === 'function' && Number.isSafeInteger(val.outputLen),\n} as const;\ntype Validator = keyof typeof validatorFns;\ntype ValMap<T extends Record<string, any>> = { [K in keyof T]?: Validator };\n// type Record<K extends string | number | symbol, T> = { [P in K]: T; }\n\nexport function validateObject<T extends Record<string, any>>(\n  object: T,\n  validators: ValMap<T>,\n  optValidators: ValMap<T> = {}\n) {\n  const checkField = (fieldName: keyof T, type: Validator, isOptional: boolean) => {\n    const checkVal = validatorFns[type];\n    if (typeof checkVal !== 'function')\n      throw new Error(`Invalid validator \"${type}\", expected function`);\n\n    const val = object[fieldName as keyof typeof object];\n    if (isOptional && val === undefined) return;\n    if (!checkVal(val, object)) {\n      throw new Error(\n        `Invalid param ${String(fieldName)}=${val} (${typeof val}), expected ${type}`\n      );\n    }\n  };\n  for (const [fieldName, type] of Object.entries(validators)) checkField(fieldName, type!, false);\n  for (const [fieldName, type] of Object.entries(optValidators)) checkField(fieldName, type!, true);\n  return object;\n}\n// validate type tests\n// const o: { a: number; b: number; c: number } = { a: 1, b: 5, c: 6 };\n// const z0 = validateObject(o, { a: 'isSafeInteger' }, { c: 'bigint' }); // Ok!\n// // Should fail type-check\n// const z1 = validateObject(o, { a: 'tmp' }, { c: 'zz' });\n// const z2 = validateObject(o, { a: 'isSafeInteger' }, { c: 'zz' });\n// const z3 = validateObject(o, { test: 'boolean', z: 'bug' });\n// const z4 = validateObject(o, { a: 'boolean', z: 'bug' });\n","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// Utilities for modular arithmetics and finite fields\nimport {\n  bitMask,\n  numberToBytesBE,\n  numberToBytesLE,\n  bytesToNumberBE,\n  bytesToNumberLE,\n  ensureBytes,\n  validateObject,\n} from './utils.js';\n// prettier-ignore\nconst _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3);\n// prettier-ignore\nconst _4n = BigInt(4), _5n = BigInt(5), _8n = BigInt(8);\n// prettier-ignore\nconst _9n = BigInt(9), _16n = BigInt(16);\n\n// Calculates a modulo b\nexport function mod(a: bigint, b: bigint): bigint {\n  const result = a % b;\n  return result >= _0n ? result : b + result;\n}\n/**\n * Efficiently raise num to power and do modular division.\n * Unsafe in some contexts: uses ladder, so can expose bigint bits.\n * @example\n * pow(2n, 6n, 11n) // 64n % 11n == 9n\n */\n// TODO: use field version && remove\nexport function pow(num: bigint, power: bigint, modulo: bigint): bigint {\n  if (modulo <= _0n || power < _0n) throw new Error('Expected power/modulo > 0');\n  if (modulo === _1n) return _0n;\n  let res = _1n;\n  while (power > _0n) {\n    if (power & _1n) res = (res * num) % modulo;\n    num = (num * num) % modulo;\n    power >>= _1n;\n  }\n  return res;\n}\n\n// Does x ^ (2 ^ power) mod p. pow2(30, 4) == 30 ^ (2 ^ 4)\nexport function pow2(x: bigint, power: bigint, modulo: bigint): bigint {\n  let res = x;\n  while (power-- > _0n) {\n    res *= res;\n    res %= modulo;\n  }\n  return res;\n}\n\n// Inverses number over modulo\nexport function invert(number: bigint, modulo: bigint): bigint {\n  if (number === _0n || modulo <= _0n) {\n    throw new Error(`invert: expected positive integers, got n=${number} mod=${modulo}`);\n  }\n  // Euclidean GCD https://brilliant.org/wiki/extended-euclidean-algorithm/\n  // Fermat's little theorem \"CT-like\" version inv(n) = n^(m-2) mod m is 30x slower.\n  let a = mod(number, modulo);\n  let b = modulo;\n  // prettier-ignore\n  let x = _0n, y = _1n, u = _1n, v = _0n;\n  while (a !== _0n) {\n    // JIT applies optimization if those two lines follow each other\n    const q = b / a;\n    const r = b % a;\n    const m = x - u * q;\n    const n = y - v * q;\n    // prettier-ignore\n    b = a, a = r, x = u, y = v, u = m, v = n;\n  }\n  const gcd = b;\n  if (gcd !== _1n) throw new Error('invert: does not exist');\n  return mod(x, modulo);\n}\n\n/**\n * Tonelli-Shanks square root search algorithm.\n * 1. https://eprint.iacr.org/2012/685.pdf (page 12)\n * 2. Square Roots from 1; 24, 51, 10 to Dan Shanks\n * Will start an infinite loop if field order P is not prime.\n * @param P field order\n * @returns function that takes field Fp (created from P) and number n\n */\nexport function tonelliShanks(P: bigint) {\n  // Legendre constant: used to calculate Legendre symbol (a | p),\n  // which denotes the value of a^((p-1)/2) (mod p).\n  // (a | p) ≡ 1    if a is a square (mod p)\n  // (a | p) ≡ -1   if a is not a square (mod p)\n  // (a | p) ≡ 0    if a ≡ 0 (mod p)\n  const legendreC = (P - _1n) / _2n;\n\n  let Q: bigint, S: number, Z: bigint;\n  // Step 1: By factoring out powers of 2 from p - 1,\n  // find q and s such that p - 1 = q*(2^s) with q odd\n  for (Q = P - _1n, S = 0; Q % _2n === _0n; Q /= _2n, S++);\n\n  // Step 2: Select a non-square z such that (z | p) ≡ -1 and set c ≡ zq\n  for (Z = _2n; Z < P && pow(Z, legendreC, P) !== P - _1n; Z++);\n\n  // Fast-path\n  if (S === 1) {\n    const p1div4 = (P + _1n) / _4n;\n    return function tonelliFast<T>(Fp: IField<T>, n: T) {\n      const root = Fp.pow(n, p1div4);\n      if (!Fp.eql(Fp.sqr(root), n)) throw new Error('Cannot find square root');\n      return root;\n    };\n  }\n\n  // Slow-path\n  const Q1div2 = (Q + _1n) / _2n;\n  return function tonelliSlow<T>(Fp: IField<T>, n: T): T {\n    // Step 0: Check that n is indeed a square: (n | p) should not be ≡ -1\n    if (Fp.pow(n, legendreC) === Fp.neg(Fp.ONE)) throw new Error('Cannot find square root');\n    let r = S;\n    // TODO: will fail at Fp2/etc\n    let g = Fp.pow(Fp.mul(Fp.ONE, Z), Q); // will update both x and b\n    let x = Fp.pow(n, Q1div2); // first guess at the square root\n    let b = Fp.pow(n, Q); // first guess at the fudge factor\n\n    while (!Fp.eql(b, Fp.ONE)) {\n      if (Fp.eql(b, Fp.ZERO)) return Fp.ZERO; // https://en.wikipedia.org/wiki/Tonelli%E2%80%93Shanks_algorithm (4. If t = 0, return r = 0)\n      // Find m such b^(2^m)==1\n      let m = 1;\n      for (let t2 = Fp.sqr(b); m < r; m++) {\n        if (Fp.eql(t2, Fp.ONE)) break;\n        t2 = Fp.sqr(t2); // t2 *= t2\n      }\n      // NOTE: r-m-1 can be bigger than 32, need to convert to bigint before shift, otherwise there will be overflow\n      const ge = Fp.pow(g, _1n << BigInt(r - m - 1)); // ge = 2^(r-m-1)\n      g = Fp.sqr(ge); // g = ge * ge\n      x = Fp.mul(x, ge); // x *= ge\n      b = Fp.mul(b, g); // b *= g\n      r = m;\n    }\n    return x;\n  };\n}\n\nexport function FpSqrt(P: bigint) {\n  // NOTE: different algorithms can give different roots, it is up to user to decide which one they want.\n  // For example there is FpSqrtOdd/FpSqrtEven to choice root based on oddness (used for hash-to-curve).\n\n  // P ≡ 3 (mod 4)\n  // √n = n^((P+1)/4)\n  if (P % _4n === _3n) {\n    // Not all roots possible!\n    // const ORDER =\n    //   0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaabn;\n    // const NUM = 72057594037927816n;\n    const p1div4 = (P + _1n) / _4n;\n    return function sqrt3mod4<T>(Fp: IField<T>, n: T) {\n      const root = Fp.pow(n, p1div4);\n      // Throw if root**2 != n\n      if (!Fp.eql(Fp.sqr(root), n)) throw new Error('Cannot find square root');\n      return root;\n    };\n  }\n\n  // Atkin algorithm for q ≡ 5 (mod 8), https://eprint.iacr.org/2012/685.pdf (page 10)\n  if (P % _8n === _5n) {\n    const c1 = (P - _5n) / _8n;\n    return function sqrt5mod8<T>(Fp: IField<T>, n: T) {\n      const n2 = Fp.mul(n, _2n);\n      const v = Fp.pow(n2, c1);\n      const nv = Fp.mul(n, v);\n      const i = Fp.mul(Fp.mul(nv, _2n), v);\n      const root = Fp.mul(nv, Fp.sub(i, Fp.ONE));\n      if (!Fp.eql(Fp.sqr(root), n)) throw new Error('Cannot find square root');\n      return root;\n    };\n  }\n\n  // P ≡ 9 (mod 16)\n  if (P % _16n === _9n) {\n    // NOTE: tonelli is too slow for bls-Fp2 calculations even on start\n    // Means we cannot use sqrt for constants at all!\n    //\n    // const c1 = Fp.sqrt(Fp.negate(Fp.ONE)); //  1. c1 = sqrt(-1) in F, i.e., (c1^2) == -1 in F\n    // const c2 = Fp.sqrt(c1);                //  2. c2 = sqrt(c1) in F, i.e., (c2^2) == c1 in F\n    // const c3 = Fp.sqrt(Fp.negate(c1));     //  3. c3 = sqrt(-c1) in F, i.e., (c3^2) == -c1 in F\n    // const c4 = (P + _7n) / _16n;           //  4. c4 = (q + 7) / 16        # Integer arithmetic\n    // sqrt = (x) => {\n    //   let tv1 = Fp.pow(x, c4);             //  1. tv1 = x^c4\n    //   let tv2 = Fp.mul(c1, tv1);           //  2. tv2 = c1 * tv1\n    //   const tv3 = Fp.mul(c2, tv1);         //  3. tv3 = c2 * tv1\n    //   let tv4 = Fp.mul(c3, tv1);           //  4. tv4 = c3 * tv1\n    //   const e1 = Fp.equals(Fp.square(tv2), x); //  5.  e1 = (tv2^2) == x\n    //   const e2 = Fp.equals(Fp.square(tv3), x); //  6.  e2 = (tv3^2) == x\n    //   tv1 = Fp.cmov(tv1, tv2, e1); //  7. tv1 = CMOV(tv1, tv2, e1)  # Select tv2 if (tv2^2) == x\n    //   tv2 = Fp.cmov(tv4, tv3, e2); //  8. tv2 = CMOV(tv4, tv3, e2)  # Select tv3 if (tv3^2) == x\n    //   const e3 = Fp.equals(Fp.square(tv2), x); //  9.  e3 = (tv2^2) == x\n    //   return Fp.cmov(tv1, tv2, e3); //  10.  z = CMOV(tv1, tv2, e3)  # Select the sqrt from tv1 and tv2\n    // }\n  }\n\n  // Other cases: Tonelli-Shanks algorithm\n  return tonelliShanks(P);\n}\n\n// Little-endian check for first LE bit (last BE bit);\nexport const isNegativeLE = (num: bigint, modulo: bigint) => (mod(num, modulo) & _1n) === _1n;\n\n// Field is not always over prime: for example, Fp2 has ORDER(q)=p^m\nexport interface IField<T> {\n  ORDER: bigint;\n  BYTES: number;\n  BITS: number;\n  MASK: bigint;\n  ZERO: T;\n  ONE: T;\n  // 1-arg\n  create: (num: T) => T;\n  isValid: (num: T) => boolean;\n  is0: (num: T) => boolean;\n  neg(num: T): T;\n  inv(num: T): T;\n  sqrt(num: T): T;\n  sqr(num: T): T;\n  // 2-args\n  eql(lhs: T, rhs: T): boolean;\n  add(lhs: T, rhs: T): T;\n  sub(lhs: T, rhs: T): T;\n  mul(lhs: T, rhs: T | bigint): T;\n  pow(lhs: T, power: bigint): T;\n  div(lhs: T, rhs: T | bigint): T;\n  // N for NonNormalized (for now)\n  addN(lhs: T, rhs: T): T;\n  subN(lhs: T, rhs: T): T;\n  mulN(lhs: T, rhs: T | bigint): T;\n  sqrN(num: T): T;\n\n  // Optional\n  // Should be same as sgn0 function in\n  // [RFC9380](https://www.rfc-editor.org/rfc/rfc9380#section-4.1).\n  // NOTE: sgn0 is 'negative in LE', which is same as odd. And negative in LE is kinda strange definition anyway.\n  isOdd?(num: T): boolean; // Odd instead of even since we have it for Fp2\n  // legendre?(num: T): T;\n  pow(lhs: T, power: bigint): T;\n  invertBatch: (lst: T[]) => T[];\n  toBytes(num: T): Uint8Array;\n  fromBytes(bytes: Uint8Array): T;\n  // If c is False, CMOV returns a, otherwise it returns b.\n  cmov(a: T, b: T, c: boolean): T;\n}\n// prettier-ignore\nconst FIELD_FIELDS = [\n  'create', 'isValid', 'is0', 'neg', 'inv', 'sqrt', 'sqr',\n  'eql', 'add', 'sub', 'mul', 'pow', 'div',\n  'addN', 'subN', 'mulN', 'sqrN'\n] as const;\nexport function validateField<T>(field: IField<T>) {\n  const initial = {\n    ORDER: 'bigint',\n    MASK: 'bigint',\n    BYTES: 'isSafeInteger',\n    BITS: 'isSafeInteger',\n  } as Record<string, string>;\n  const opts = FIELD_FIELDS.reduce((map, val: string) => {\n    map[val] = 'function';\n    return map;\n  }, initial);\n  return validateObject(field, opts);\n}\n\n// Generic field functions\n\n/**\n * Same as `pow` but for Fp: non-constant-time.\n * Unsafe in some contexts: uses ladder, so can expose bigint bits.\n */\nexport function FpPow<T>(f: IField<T>, num: T, power: bigint): T {\n  // Should have same speed as pow for bigints\n  // TODO: benchmark!\n  if (power < _0n) throw new Error('Expected power > 0');\n  if (power === _0n) return f.ONE;\n  if (power === _1n) return num;\n  let p = f.ONE;\n  let d = num;\n  while (power > _0n) {\n    if (power & _1n) p = f.mul(p, d);\n    d = f.sqr(d);\n    power >>= _1n;\n  }\n  return p;\n}\n\n/**\n * Efficiently invert an array of Field elements.\n * `inv(0)` will return `undefined` here: make sure to throw an error.\n */\nexport function FpInvertBatch<T>(f: IField<T>, nums: T[]): T[] {\n  const tmp = new Array(nums.length);\n  // Walk from first to last, multiply them by each other MOD p\n  const lastMultiplied = nums.reduce((acc, num, i) => {\n    if (f.is0(num)) return acc;\n    tmp[i] = acc;\n    return f.mul(acc, num);\n  }, f.ONE);\n  // Invert last element\n  const inverted = f.inv(lastMultiplied);\n  // Walk from last to first, multiply them by inverted each other MOD p\n  nums.reduceRight((acc, num, i) => {\n    if (f.is0(num)) return acc;\n    tmp[i] = f.mul(acc, tmp[i]);\n    return f.mul(acc, num);\n  }, inverted);\n  return tmp;\n}\n\nexport function FpDiv<T>(f: IField<T>, lhs: T, rhs: T | bigint): T {\n  return f.mul(lhs, typeof rhs === 'bigint' ? invert(rhs, f.ORDER) : f.inv(rhs));\n}\n\n// This function returns True whenever the value x is a square in the field F.\nexport function FpIsSquare<T>(f: IField<T>) {\n  const legendreConst = (f.ORDER - _1n) / _2n; // Integer arithmetic\n  return (x: T): boolean => {\n    const p = f.pow(x, legendreConst);\n    return f.eql(p, f.ZERO) || f.eql(p, f.ONE);\n  };\n}\n\n// CURVE.n lengths\nexport function nLength(n: bigint, nBitLength?: number) {\n  // Bit size, byte size of CURVE.n\n  const _nBitLength = nBitLength !== undefined ? nBitLength : n.toString(2).length;\n  const nByteLength = Math.ceil(_nBitLength / 8);\n  return { nBitLength: _nBitLength, nByteLength };\n}\n\ntype FpField = IField<bigint> & Required<Pick<IField<bigint>, 'isOdd'>>;\n/**\n * Initializes a finite field over prime. **Non-primes are not supported.**\n * Do not init in loop: slow. Very fragile: always run a benchmark on a change.\n * Major performance optimizations:\n * * a) denormalized operations like mulN instead of mul\n * * b) same object shape: never add or remove keys\n * * c) Object.freeze\n * @param ORDER prime positive bigint\n * @param bitLen how many bits the field consumes\n * @param isLE (def: false) if encoding / decoding should be in little-endian\n * @param redef optional faster redefinitions of sqrt and other methods\n */\nexport function Field(\n  ORDER: bigint,\n  bitLen?: number,\n  isLE = false,\n  redef: Partial<IField<bigint>> = {}\n): Readonly<FpField> {\n  if (ORDER <= _0n) throw new Error(`Expected Field ORDER > 0, got ${ORDER}`);\n  const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, bitLen);\n  if (BYTES > 2048) throw new Error('Field lengths over 2048 bytes are not supported');\n  const sqrtP = FpSqrt(ORDER);\n  const f: Readonly<FpField> = Object.freeze({\n    ORDER,\n    BITS,\n    BYTES,\n    MASK: bitMask(BITS),\n    ZERO: _0n,\n    ONE: _1n,\n    create: (num) => mod(num, ORDER),\n    isValid: (num) => {\n      if (typeof num !== 'bigint')\n        throw new Error(`Invalid field element: expected bigint, got ${typeof num}`);\n      return _0n <= num && num < ORDER; // 0 is valid element, but it's not invertible\n    },\n    is0: (num) => num === _0n,\n    isOdd: (num) => (num & _1n) === _1n,\n    neg: (num) => mod(-num, ORDER),\n    eql: (lhs, rhs) => lhs === rhs,\n\n    sqr: (num) => mod(num * num, ORDER),\n    add: (lhs, rhs) => mod(lhs + rhs, ORDER),\n    sub: (lhs, rhs) => mod(lhs - rhs, ORDER),\n    mul: (lhs, rhs) => mod(lhs * rhs, ORDER),\n    pow: (num, power) => FpPow(f, num, power),\n    div: (lhs, rhs) => mod(lhs * invert(rhs, ORDER), ORDER),\n\n    // Same as above, but doesn't normalize\n    sqrN: (num) => num * num,\n    addN: (lhs, rhs) => lhs + rhs,\n    subN: (lhs, rhs) => lhs - rhs,\n    mulN: (lhs, rhs) => lhs * rhs,\n\n    inv: (num) => invert(num, ORDER),\n    sqrt: redef.sqrt || ((n) => sqrtP(f, n)),\n    invertBatch: (lst) => FpInvertBatch(f, lst),\n    // TODO: do we really need constant cmov?\n    // We don't have const-time bigints anyway, so probably will be not very useful\n    cmov: (a, b, c) => (c ? b : a),\n    toBytes: (num) => (isLE ? numberToBytesLE(num, BYTES) : numberToBytesBE(num, BYTES)),\n    fromBytes: (bytes) => {\n      if (bytes.length !== BYTES)\n        throw new Error(`Fp.fromBytes: expected ${BYTES}, got ${bytes.length}`);\n      return isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);\n    },\n  } as FpField);\n  return Object.freeze(f);\n}\n\nexport function FpSqrtOdd<T>(Fp: IField<T>, elm: T) {\n  if (!Fp.isOdd) throw new Error(`Field doesn't have isOdd`);\n  const root = Fp.sqrt(elm);\n  return Fp.isOdd(root) ? root : Fp.neg(root);\n}\n\nexport function FpSqrtEven<T>(Fp: IField<T>, elm: T) {\n  if (!Fp.isOdd) throw new Error(`Field doesn't have isOdd`);\n  const root = Fp.sqrt(elm);\n  return Fp.isOdd(root) ? Fp.neg(root) : root;\n}\n\n/**\n * \"Constant-time\" private key generation utility.\n * Same as mapKeyToField, but accepts less bytes (40 instead of 48 for 32-byte field).\n * Which makes it slightly more biased, less secure.\n * @deprecated use mapKeyToField instead\n */\nexport function hashToPrivateScalar(\n  hash: string | Uint8Array,\n  groupOrder: bigint,\n  isLE = false\n): bigint {\n  hash = ensureBytes('privateHash', hash);\n  const hashLen = hash.length;\n  const minLen = nLength(groupOrder).nByteLength + 8;\n  if (minLen < 24 || hashLen < minLen || hashLen > 1024)\n    throw new Error(`hashToPrivateScalar: expected ${minLen}-1024 bytes of input, got ${hashLen}`);\n  const num = isLE ? bytesToNumberLE(hash) : bytesToNumberBE(hash);\n  return mod(num, groupOrder - _1n) + _1n;\n}\n\n/**\n * Returns total number of bytes consumed by the field element.\n * For example, 32 bytes for usual 256-bit weierstrass curve.\n * @param fieldOrder number of field elements, usually CURVE.n\n * @returns byte length of field\n */\nexport function getFieldBytesLength(fieldOrder: bigint): number {\n  if (typeof fieldOrder !== 'bigint') throw new Error('field order must be bigint');\n  const bitLength = fieldOrder.toString(2).length;\n  return Math.ceil(bitLength / 8);\n}\n\n/**\n * Returns minimal amount of bytes that can be safely reduced\n * by field order.\n * Should be 2^-128 for 128-bit curve such as P256.\n * @param fieldOrder number of field elements, usually CURVE.n\n * @returns byte length of target hash\n */\nexport function getMinHashLength(fieldOrder: bigint): number {\n  const length = getFieldBytesLength(fieldOrder);\n  return length + Math.ceil(length / 2);\n}\n\n/**\n * \"Constant-time\" private key generation utility.\n * Can take (n + n/2) or more bytes of uniform input e.g. from CSPRNG or KDF\n * and convert them into private scalar, with the modulo bias being negligible.\n * Needs at least 48 bytes of input for 32-byte private key.\n * https://research.kudelskisecurity.com/2020/07/28/the-definitive-guide-to-modulo-bias-and-how-to-avoid-it/\n * FIPS 186-5, A.2 https://csrc.nist.gov/publications/detail/fips/186/5/final\n * RFC 9380, https://www.rfc-editor.org/rfc/rfc9380#section-5\n * @param hash hash output from SHA3 or a similar function\n * @param groupOrder size of subgroup - (e.g. secp256k1.CURVE.n)\n * @param isLE interpret hash bytes as LE num\n * @returns valid private scalar\n */\nexport function mapHashToField(key: Uint8Array, fieldOrder: bigint, isLE = false): Uint8Array {\n  const len = key.length;\n  const fieldLen = getFieldBytesLength(fieldOrder);\n  const minLen = getMinHashLength(fieldOrder);\n  // No small numbers: need to understand bias story. No huge numbers: easier to detect JS timings.\n  if (len < 16 || len < minLen || len > 1024)\n    throw new Error(`expected ${minLen}-1024 bytes of input, got ${len}`);\n  const num = isLE ? bytesToNumberBE(key) : bytesToNumberLE(key);\n  // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0\n  const reduced = mod(num, fieldOrder - _1n) + _1n;\n  return isLE ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen);\n}\n","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// Abelian group utilities\nimport { IField, validateField, nLength } from './modular.js';\nimport { validateObject } from './utils.js';\nconst _0n = BigInt(0);\nconst _1n = BigInt(1);\n\nexport type AffinePoint<T> = {\n  x: T;\n  y: T;\n} & { z?: never; t?: never };\n\nexport interface Group<T extends Group<T>> {\n  double(): T;\n  negate(): T;\n  add(other: T): T;\n  subtract(other: T): T;\n  equals(other: T): boolean;\n  multiply(scalar: bigint): T;\n}\n\nexport type GroupConstructor<T> = {\n  BASE: T;\n  ZERO: T;\n};\nexport type Mapper<T> = (i: T[]) => T[];\n\n// Elliptic curve multiplication of Point by scalar. Fragile.\n// Scalars should always be less than curve order: this should be checked inside of a curve itself.\n// Creates precomputation tables for fast multiplication:\n// - private scalar is split by fixed size windows of W bits\n// - every window point is collected from window's table & added to accumulator\n// - since windows are different, same point inside tables won't be accessed more than once per calc\n// - each multiplication is 'Math.ceil(CURVE_ORDER / 𝑊) + 1' point additions (fixed for any scalar)\n// - +1 window is neccessary for wNAF\n// - wNAF reduces table size: 2x less memory + 2x faster generation, but 10% slower multiplication\n// TODO: Research returning 2d JS array of windows, instead of a single window. This would allow\n// windows to be in different memory locations\nexport function wNAF<T extends Group<T>>(c: GroupConstructor<T>, bits: number) {\n  const constTimeNegate = (condition: boolean, item: T): T => {\n    const neg = item.negate();\n    return condition ? neg : item;\n  };\n  const opts = (W: number) => {\n    const windows = Math.ceil(bits / W) + 1; // +1, because\n    const windowSize = 2 ** (W - 1); // -1 because we skip zero\n    return { windows, windowSize };\n  };\n  return {\n    constTimeNegate,\n    // non-const time multiplication ladder\n    unsafeLadder(elm: T, n: bigint) {\n      let p = c.ZERO;\n      let d: T = elm;\n      while (n > _0n) {\n        if (n & _1n) p = p.add(d);\n        d = d.double();\n        n >>= _1n;\n      }\n      return p;\n    },\n\n    /**\n     * Creates a wNAF precomputation window. Used for caching.\n     * Default window size is set by `utils.precompute()` and is equal to 8.\n     * Number of precomputed points depends on the curve size:\n     * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where:\n     * - 𝑊 is the window size\n     * - 𝑛 is the bitlength of the curve order.\n     * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.\n     * @returns precomputed point tables flattened to a single array\n     */\n    precomputeWindow(elm: T, W: number): Group<T>[] {\n      const { windows, windowSize } = opts(W);\n      const points: T[] = [];\n      let p: T = elm;\n      let base = p;\n      for (let window = 0; window < windows; window++) {\n        base = p;\n        points.push(base);\n        // =1, because we skip zero\n        for (let i = 1; i < windowSize; i++) {\n          base = base.add(p);\n          points.push(base);\n        }\n        p = base.double();\n      }\n      return points;\n    },\n\n    /**\n     * Implements ec multiplication using precomputed tables and w-ary non-adjacent form.\n     * @param W window size\n     * @param precomputes precomputed tables\n     * @param n scalar (we don't check here, but should be less than curve order)\n     * @returns real and fake (for const-time) points\n     */\n    wNAF(W: number, precomputes: T[], n: bigint): { p: T; f: T } {\n      // TODO: maybe check that scalar is less than group order? wNAF behavious is undefined otherwise\n      // But need to carefully remove other checks before wNAF. ORDER == bits here\n      const { windows, windowSize } = opts(W);\n\n      let p = c.ZERO;\n      let f = c.BASE;\n\n      const mask = BigInt(2 ** W - 1); // Create mask with W ones: 0b1111 for W=4 etc.\n      const maxNumber = 2 ** W;\n      const shiftBy = BigInt(W);\n\n      for (let window = 0; window < windows; window++) {\n        const offset = window * windowSize;\n        // Extract W bits.\n        let wbits = Number(n & mask);\n\n        // Shift number by W bits.\n        n >>= shiftBy;\n\n        // If the bits are bigger than max size, we'll split those.\n        // +224 => 256 - 32\n        if (wbits > windowSize) {\n          wbits -= maxNumber;\n          n += _1n;\n        }\n\n        // This code was first written with assumption that 'f' and 'p' will never be infinity point:\n        // since each addition is multiplied by 2 ** W, it cannot cancel each other. However,\n        // there is negate now: it is possible that negated element from low value\n        // would be the same as high element, which will create carry into next window.\n        // It's not obvious how this can fail, but still worth investigating later.\n\n        // Check if we're onto Zero point.\n        // Add random point inside current window to f.\n        const offset1 = offset;\n        const offset2 = offset + Math.abs(wbits) - 1; // -1 because we skip zero\n        const cond1 = window % 2 !== 0;\n        const cond2 = wbits < 0;\n        if (wbits === 0) {\n          // The most important part for const-time getPublicKey\n          f = f.add(constTimeNegate(cond1, precomputes[offset1]));\n        } else {\n          p = p.add(constTimeNegate(cond2, precomputes[offset2]));\n        }\n      }\n      // JIT-compiler should not eliminate f here, since it will later be used in normalizeZ()\n      // Even if the variable is still unused, there are some checks which will\n      // throw an exception, so compiler needs to prove they won't happen, which is hard.\n      // At this point there is a way to F be infinity-point even if p is not,\n      // which makes it less const-time: around 1 bigint multiply.\n      return { p, f };\n    },\n\n    wNAFCached(P: T, precomputesMap: Map<T, T[]>, n: bigint, transform: Mapper<T>): { p: T; f: T } {\n      // @ts-ignore\n      const W: number = P._WINDOW_SIZE || 1;\n      // Calculate precomputes on a first run, reuse them after\n      let comp = precomputesMap.get(P);\n      if (!comp) {\n        comp = this.precomputeWindow(P, W) as T[];\n        if (W !== 1) {\n          precomputesMap.set(P, transform(comp));\n        }\n      }\n      return this.wNAF(W, comp, n);\n    },\n  };\n}\n\n// Generic BasicCurve interface: works even for polynomial fields (BLS): P, n, h would be ok.\n// Though generator can be different (Fp2 / Fp6 for BLS).\nexport type BasicCurve<T> = {\n  Fp: IField<T>; // Field over which we'll do calculations (Fp)\n  n: bigint; // Curve order, total count of valid points in the field\n  nBitLength?: number; // bit length of curve order\n  nByteLength?: number; // byte length of curve order\n  h: bigint; // cofactor. we can assign default=1, but users will just ignore it w/o validation\n  hEff?: bigint; // Number to multiply to clear cofactor\n  Gx: T; // base point X coordinate\n  Gy: T; // base point Y coordinate\n  allowInfinityPoint?: boolean; // bls12-381 requires it. ZERO point is valid, but invalid pubkey\n};\n\nexport function validateBasic<FP, T>(curve: BasicCurve<FP> & T) {\n  validateField(curve.Fp);\n  validateObject(\n    curve,\n    {\n      n: 'bigint',\n      h: 'bigint',\n      Gx: 'field',\n      Gy: 'field',\n    },\n    {\n      nBitLength: 'isSafeInteger',\n      nByteLength: 'isSafeInteger',\n    }\n  );\n  // Set defaults\n  return Object.freeze({\n    ...nLength(curve.n, curve.nBitLength),\n    ...curve,\n    ...{ p: curve.Fp.ORDER },\n  } as const);\n}\n","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// Short Weierstrass curve. The formula is: y² = x³ + ax + b\nimport * as mod from './modular.js';\nimport * as ut from './utils.js';\nimport { CHash, Hex, PrivKey, ensureBytes } from './utils.js';\nimport { Group, GroupConstructor, wNAF, BasicCurve, validateBasic, AffinePoint } from './curve.js';\n\nexport type { AffinePoint };\ntype HmacFnSync = (key: Uint8Array, ...messages: Uint8Array[]) => Uint8Array;\ntype EndomorphismOpts = {\n  beta: bigint;\n  splitScalar: (k: bigint) => { k1neg: boolean; k1: bigint; k2neg: boolean; k2: bigint };\n};\nexport type BasicWCurve<T> = BasicCurve<T> & {\n  // Params: a, b\n  a: T;\n  b: T;\n\n  // Optional params\n  allowedPrivateKeyLengths?: readonly number[]; // for P521\n  wrapPrivateKey?: boolean; // bls12-381 requires mod(n) instead of rejecting keys >= n\n  endo?: EndomorphismOpts; // Endomorphism options for Koblitz curves\n  // When a cofactor != 1, there can be an effective methods to:\n  // 1. Determine whether a point is torsion-free\n  isTorsionFree?: (c: ProjConstructor<T>, point: ProjPointType<T>) => boolean;\n  // 2. Clear torsion component\n  clearCofactor?: (c: ProjConstructor<T>, point: ProjPointType<T>) => ProjPointType<T>;\n};\n\ntype Entropy = Hex | true;\nexport type SignOpts = { lowS?: boolean; extraEntropy?: Entropy; prehash?: boolean };\nexport type VerOpts = { lowS?: boolean; prehash?: boolean };\n\n/**\n * ### Design rationale for types\n *\n * * Interaction between classes from different curves should fail:\n *   `k256.Point.BASE.add(p256.Point.BASE)`\n * * For this purpose we want to use `instanceof` operator, which is fast and works during runtime\n * * Different calls of `curve()` would return different classes -\n *   `curve(params) !== curve(params)`: if somebody decided to monkey-patch their curve,\n *   it won't affect others\n *\n * TypeScript can't infer types for classes created inside a function. Classes is one instance of nominative types in TypeScript and interfaces only check for shape, so it's hard to create unique type for every function call.\n *\n * We can use generic types via some param, like curve opts, but that would:\n *     1. Enable interaction between `curve(params)` and `curve(params)` (curves of same params)\n *     which is hard to debug.\n *     2. Params can be generic and we can't enforce them to be constant value:\n *     if somebody creates curve from non-constant params,\n *     it would be allowed to interact with other curves with non-constant params\n *\n * TODO: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-7.html#unique-symbol\n */\n\n// Instance for 3d XYZ points\nexport interface ProjPointType<T> extends Group<ProjPointType<T>> {\n  readonly px: T;\n  readonly py: T;\n  readonly pz: T;\n  get x(): T;\n  get y(): T;\n  multiply(scalar: bigint): ProjPointType<T>;\n  toAffine(iz?: T): AffinePoint<T>;\n  isTorsionFree(): boolean;\n  clearCofactor(): ProjPointType<T>;\n  assertValidity(): void;\n  hasEvenY(): boolean;\n  toRawBytes(isCompressed?: boolean): Uint8Array;\n  toHex(isCompressed?: boolean): string;\n\n  multiplyUnsafe(scalar: bigint): ProjPointType<T>;\n  multiplyAndAddUnsafe(Q: ProjPointType<T>, a: bigint, b: bigint): ProjPointType<T> | undefined;\n  _setWindowSize(windowSize: number): void;\n}\n// Static methods for 3d XYZ points\nexport interface ProjConstructor<T> extends GroupConstructor<ProjPointType<T>> {\n  new (x: T, y: T, z: T): ProjPointType<T>;\n  fromAffine(p: AffinePoint<T>): ProjPointType<T>;\n  fromHex(hex: Hex): ProjPointType<T>;\n  fromPrivateKey(privateKey: PrivKey): ProjPointType<T>;\n  normalizeZ(points: ProjPointType<T>[]): ProjPointType<T>[];\n}\n\nexport type CurvePointsType<T> = BasicWCurve<T> & {\n  // Bytes\n  fromBytes?: (bytes: Uint8Array) => AffinePoint<T>;\n  toBytes?: (c: ProjConstructor<T>, point: ProjPointType<T>, isCompressed: boolean) => Uint8Array;\n};\n\nfunction validatePointOpts<T>(curve: CurvePointsType<T>) {\n  const opts = validateBasic(curve);\n  ut.validateObject(\n    opts,\n    {\n      a: 'field',\n      b: 'field',\n    },\n    {\n      allowedPrivateKeyLengths: 'array',\n      wrapPrivateKey: 'boolean',\n      isTorsionFree: 'function',\n      clearCofactor: 'function',\n      allowInfinityPoint: 'boolean',\n      fromBytes: 'function',\n      toBytes: 'function',\n    }\n  );\n  const { endo, Fp, a } = opts;\n  if (endo) {\n    if (!Fp.eql(a, Fp.ZERO)) {\n      throw new Error('Endomorphism can only be defined for Koblitz curves that have a=0');\n    }\n    if (\n      typeof endo !== 'object' ||\n      typeof endo.beta !== 'bigint' ||\n      typeof endo.splitScalar !== 'function'\n    ) {\n      throw new Error('Expected endomorphism with beta: bigint and splitScalar: function');\n    }\n  }\n  return Object.freeze({ ...opts } as const);\n}\n\nexport type CurvePointsRes<T> = {\n  ProjectivePoint: ProjConstructor<T>;\n  normPrivateKeyToScalar: (key: PrivKey) => bigint;\n  weierstrassEquation: (x: T) => T;\n  isWithinCurveOrder: (num: bigint) => boolean;\n};\n\n// ASN.1 DER encoding utilities\nconst { bytesToNumberBE: b2n, hexToBytes: h2b } = ut;\nexport const DER = {\n  // asn.1 DER encoding utils\n  Err: class DERErr extends Error {\n    constructor(m = '') {\n      super(m);\n    }\n  },\n  _parseInt(data: Uint8Array): { d: bigint; l: Uint8Array } {\n    const { Err: E } = DER;\n    if (data.length < 2 || data[0] !== 0x02) throw new E('Invalid signature integer tag');\n    const len = data[1];\n    const res = data.subarray(2, len + 2);\n    if (!len || res.length !== len) throw new E('Invalid signature integer: wrong length');\n    // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag,\n    // since we always use positive integers here. It must always be empty:\n    // - add zero byte if exists\n    // - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding)\n    if (res[0] & 0b10000000) throw new E('Invalid signature integer: negative');\n    if (res[0] === 0x00 && !(res[1] & 0b10000000))\n      throw new E('Invalid signature integer: unnecessary leading zero');\n    return { d: b2n(res), l: data.subarray(len + 2) }; // d is data, l is left\n  },\n  toSig(hex: string | Uint8Array): { r: bigint; s: bigint } {\n    // parse DER signature\n    const { Err: E } = DER;\n    const data = typeof hex === 'string' ? h2b(hex) : hex;\n    if (!(data instanceof Uint8Array)) throw new Error('ui8a expected');\n    let l = data.length;\n    if (l < 2 || data[0] != 0x30) throw new E('Invalid signature tag');\n    if (data[1] !== l - 2) throw new E('Invalid signature: incorrect length');\n    const { d: r, l: sBytes } = DER._parseInt(data.subarray(2));\n    const { d: s, l: rBytesLeft } = DER._parseInt(sBytes);\n    if (rBytesLeft.length) throw new E('Invalid signature: left bytes after parsing');\n    return { r, s };\n  },\n  hexFromSig(sig: { r: bigint; s: bigint }): string {\n    // Add leading zero if first byte has negative bit enabled. More details in '_parseInt'\n    const slice = (s: string): string => (Number.parseInt(s[0], 16) & 0b1000 ? '00' + s : s);\n    const h = (num: number | bigint) => {\n      const hex = num.toString(16);\n      return hex.length & 1 ? `0${hex}` : hex;\n    };\n    const s = slice(h(sig.s));\n    const r = slice(h(sig.r));\n    const shl = s.length / 2;\n    const rhl = r.length / 2;\n    const sl = h(shl);\n    const rl = h(rhl);\n    return `30${h(rhl + shl + 4)}02${rl}${r}02${sl}${s}`;\n  },\n};\n\n// Be friendly to bad ECMAScript parsers by not using bigint literals\n// prettier-ignore\nconst _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3), _4n = BigInt(4);\n\nexport function weierstrassPoints<T>(opts: CurvePointsType<T>) {\n  const CURVE = validatePointOpts(opts);\n  const { Fp } = CURVE; // All curves has same field / group length as for now, but they can differ\n\n  const toBytes =\n    CURVE.toBytes ||\n    ((_c: ProjConstructor<T>, point: ProjPointType<T>, _isCompressed: boolean) => {\n      const a = point.toAffine();\n      return ut.concatBytes(Uint8Array.from([0x04]), Fp.toBytes(a.x), Fp.toBytes(a.y));\n    });\n  const fromBytes =\n    CURVE.fromBytes ||\n    ((bytes: Uint8Array) => {\n      // const head = bytes[0];\n      const tail = bytes.subarray(1);\n      // if (head !== 0x04) throw new Error('Only non-compressed encoding is supported');\n      const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES));\n      const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES));\n      return { x, y };\n    });\n\n  /**\n   * y² = x³ + ax + b: Short weierstrass curve formula\n   * @returns y²\n   */\n  function weierstrassEquation(x: T): T {\n    const { a, b } = CURVE;\n    const x2 = Fp.sqr(x); // x * x\n    const x3 = Fp.mul(x2, x); // x2 * x\n    return Fp.add(Fp.add(x3, Fp.mul(x, a)), b); // x3 + a * x + b\n  }\n  // Validate whether the passed curve params are valid.\n  // We check if curve equation works for generator point.\n  // `assertValidity()` won't work: `isTorsionFree()` is not available at this point in bls12-381.\n  // ProjectivePoint class has not been initialized yet.\n  if (!Fp.eql(Fp.sqr(CURVE.Gy), weierstrassEquation(CURVE.Gx)))\n    throw new Error('bad generator point: equation left != right');\n\n  // Valid group elements reside in range 1..n-1\n  function isWithinCurveOrder(num: bigint): boolean {\n    return typeof num === 'bigint' && _0n < num && num < CURVE.n;\n  }\n  function assertGE(num: bigint) {\n    if (!isWithinCurveOrder(num)) throw new Error('Expected valid bigint: 0 < bigint < curve.n');\n  }\n  // Validates if priv key is valid and converts it to bigint.\n  // Supports options allowedPrivateKeyLengths and wrapPrivateKey.\n  function normPrivateKeyToScalar(key: PrivKey): bigint {\n    const { allowedPrivateKeyLengths: lengths, nByteLength, wrapPrivateKey, n } = CURVE;\n    if (lengths && typeof key !== 'bigint') {\n      if (key instanceof Uint8Array) key = ut.bytesToHex(key);\n      // Normalize to hex string, pad. E.g. P521 would norm 130-132 char hex to 132-char bytes\n      if (typeof key !== 'string' || !lengths.includes(key.length)) throw new Error('Invalid key');\n      key = key.padStart(nByteLength * 2, '0');\n    }\n    let num: bigint;\n    try {\n      num =\n        typeof key === 'bigint'\n          ? key\n          : ut.bytesToNumberBE(ensureBytes('private key', key, nByteLength));\n    } catch (error) {\n      throw new Error(`private key must be ${nByteLength} bytes, hex or bigint, not ${typeof key}`);\n    }\n    if (wrapPrivateKey) num = mod.mod(num, n); // disabled by default, enabled for BLS\n    assertGE(num); // num in range [1..N-1]\n    return num;\n  }\n\n  const pointPrecomputes = new Map<Point, Point[]>();\n  function assertPrjPoint(other: unknown) {\n    if (!(other instanceof Point)) throw new Error('ProjectivePoint expected');\n  }\n  /**\n   * Projective Point works in 3d / projective (homogeneous) coordinates: (x, y, z) ∋ (x=x/z, y=y/z)\n   * Default Point works in 2d / affine coordinates: (x, y)\n   * We're doing calculations in projective, because its operations don't require costly inversion.\n   */\n  class Point implements ProjPointType<T> {\n    static readonly BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);\n    static readonly ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO);\n\n    constructor(readonly px: T, readonly py: T, readonly pz: T) {\n      if (px == null || !Fp.isValid(px)) throw new Error('x required');\n      if (py == null || !Fp.isValid(py)) throw new Error('y required');\n      if (pz == null || !Fp.isValid(pz)) throw new Error('z required');\n    }\n\n    // Does not validate if the point is on-curve.\n    // Use fromHex instead, or call assertValidity() later.\n    static fromAffine(p: AffinePoint<T>): Point {\n      const { x, y } = p || {};\n      if (!p || !Fp.isValid(x) || !Fp.isValid(y)) throw new Error('invalid affine point');\n      if (p instanceof Point) throw new Error('projective point not allowed');\n      const is0 = (i: T) => Fp.eql(i, Fp.ZERO);\n      // fromAffine(x:0, y:0) would produce (x:0, y:0, z:1), but we need (x:0, y:1, z:0)\n      if (is0(x) && is0(y)) return Point.ZERO;\n      return new Point(x, y, Fp.ONE);\n    }\n\n    get x(): T {\n      return this.toAffine().x;\n    }\n    get y(): T {\n      return this.toAffine().y;\n    }\n\n    /**\n     * Takes a bunch of Projective Points but executes only one\n     * inversion on all of them. Inversion is very slow operation,\n     * so this improves performance massively.\n     * Optimization: converts a list of projective points to a list of identical points with Z=1.\n     */\n    static normalizeZ(points: Point[]): Point[] {\n      const toInv = Fp.invertBatch(points.map((p) => p.pz));\n      return points.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine);\n    }\n\n    /**\n     * Converts hash string or Uint8Array to Point.\n     * @param hex short/long ECDSA hex\n     */\n    static fromHex(hex: Hex): Point {\n      const P = Point.fromAffine(fromBytes(ensureBytes('pointHex', hex)));\n      P.assertValidity();\n      return P;\n    }\n\n    // Multiplies generator point by privateKey.\n    static fromPrivateKey(privateKey: PrivKey) {\n      return Point.BASE.multiply(normPrivateKeyToScalar(privateKey));\n    }\n\n    // We calculate precomputes for elliptic curve point multiplication\n    // using windowed method. This specifies window size and\n    // stores precomputed values. Usually only base point would be precomputed.\n    _WINDOW_SIZE?: number;\n\n    // \"Private method\", don't use it directly\n    _setWindowSize(windowSize: number) {\n      this._WINDOW_SIZE = windowSize;\n      pointPrecomputes.delete(this);\n    }\n\n    // A point on curve is valid if it conforms to equation.\n    assertValidity(): void {\n      if (this.is0()) {\n        // (0, 1, 0) aka ZERO is invalid in most contexts.\n        // In BLS, ZERO can be serialized, so we allow it.\n        // (0, 0, 0) is wrong representation of ZERO and is always invalid.\n        if (CURVE.allowInfinityPoint && !Fp.is0(this.py)) return;\n        throw new Error('bad point: ZERO');\n      }\n      // Some 3rd-party test vectors require different wording between here & `fromCompressedHex`\n      const { x, y } = this.toAffine();\n      // Check if x, y are valid field elements\n      if (!Fp.isValid(x) || !Fp.isValid(y)) throw new Error('bad point: x or y not FE');\n      const left = Fp.sqr(y); // y²\n      const right = weierstrassEquation(x); // x³ + ax + b\n      if (!Fp.eql(left, right)) throw new Error('bad point: equation left != right');\n      if (!this.isTorsionFree()) throw new Error('bad point: not in prime-order subgroup');\n    }\n    hasEvenY(): boolean {\n      const { y } = this.toAffine();\n      if (Fp.isOdd) return !Fp.isOdd(y);\n      throw new Error(\"Field doesn't support isOdd\");\n    }\n\n    /**\n     * Compare one point to another.\n     */\n    equals(other: Point): boolean {\n      assertPrjPoint(other);\n      const { px: X1, py: Y1, pz: Z1 } = this;\n      const { px: X2, py: Y2, pz: Z2 } = other;\n      const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1));\n      const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1));\n      return U1 && U2;\n    }\n\n    /**\n     * Flips point to one corresponding to (x, -y) in Affine coordinates.\n     */\n    negate(): Point {\n      return new Point(this.px, Fp.neg(this.py), this.pz);\n    }\n\n    // Renes-Costello-Batina exception-free doubling formula.\n    // There is 30% faster Jacobian formula, but it is not complete.\n    // https://eprint.iacr.org/2015/1060, algorithm 3\n    // Cost: 8M + 3S + 3*a + 2*b3 + 15add.\n    double() {\n      const { a, b } = CURVE;\n      const b3 = Fp.mul(b, _3n);\n      const { px: X1, py: Y1, pz: Z1 } = this;\n      let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore\n      let t0 = Fp.mul(X1, X1); // step 1\n      let t1 = Fp.mul(Y1, Y1);\n      let t2 = Fp.mul(Z1, Z1);\n      let t3 = Fp.mul(X1, Y1);\n      t3 = Fp.add(t3, t3); // step 5\n      Z3 = Fp.mul(X1, Z1);\n      Z3 = Fp.add(Z3, Z3);\n      X3 = Fp.mul(a, Z3);\n      Y3 = Fp.mul(b3, t2);\n      Y3 = Fp.add(X3, Y3); // step 10\n      X3 = Fp.sub(t1, Y3);\n      Y3 = Fp.add(t1, Y3);\n      Y3 = Fp.mul(X3, Y3);\n      X3 = Fp.mul(t3, X3);\n      Z3 = Fp.mul(b3, Z3); // step 15\n      t2 = Fp.mul(a, t2);\n      t3 = Fp.sub(t0, t2);\n      t3 = Fp.mul(a, t3);\n      t3 = Fp.add(t3, Z3);\n      Z3 = Fp.add(t0, t0); // step 20\n      t0 = Fp.add(Z3, t0);\n      t0 = Fp.add(t0, t2);\n      t0 = Fp.mul(t0, t3);\n      Y3 = Fp.add(Y3, t0);\n      t2 = Fp.mul(Y1, Z1); // step 25\n      t2 = Fp.add(t2, t2);\n      t0 = Fp.mul(t2, t3);\n      X3 = Fp.sub(X3, t0);\n      Z3 = Fp.mul(t2, t1);\n      Z3 = Fp.add(Z3, Z3); // step 30\n      Z3 = Fp.add(Z3, Z3);\n      return new Point(X3, Y3, Z3);\n    }\n\n    // Renes-Costello-Batina exception-free addition formula.\n    // There is 30% faster Jacobian formula, but it is not complete.\n    // https://eprint.iacr.org/2015/1060, algorithm 1\n    // Cost: 12M + 0S + 3*a + 3*b3 + 23add.\n    add(other: Point): Point {\n      assertPrjPoint(other);\n      const { px: X1, py: Y1, pz: Z1 } = this;\n      const { px: X2, py: Y2, pz: Z2 } = other;\n      let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore\n      const a = CURVE.a;\n      const b3 = Fp.mul(CURVE.b, _3n);\n      let t0 = Fp.mul(X1, X2); // step 1\n      let t1 = Fp.mul(Y1, Y2);\n      let t2 = Fp.mul(Z1, Z2);\n      let t3 = Fp.add(X1, Y1);\n      let t4 = Fp.add(X2, Y2); // step 5\n      t3 = Fp.mul(t3, t4);\n      t4 = Fp.add(t0, t1);\n      t3 = Fp.sub(t3, t4);\n      t4 = Fp.add(X1, Z1);\n      let t5 = Fp.add(X2, Z2); // step 10\n      t4 = Fp.mul(t4, t5);\n      t5 = Fp.add(t0, t2);\n      t4 = Fp.sub(t4, t5);\n      t5 = Fp.add(Y1, Z1);\n      X3 = Fp.add(Y2, Z2); // step 15\n      t5 = Fp.mul(t5, X3);\n      X3 = Fp.add(t1, t2);\n      t5 = Fp.sub(t5, X3);\n      Z3 = Fp.mul(a, t4);\n      X3 = Fp.mul(b3, t2); // step 20\n      Z3 = Fp.add(X3, Z3);\n      X3 = Fp.sub(t1, Z3);\n      Z3 = Fp.add(t1, Z3);\n      Y3 = Fp.mul(X3, Z3);\n      t1 = Fp.add(t0, t0); // step 25\n      t1 = Fp.add(t1, t0);\n      t2 = Fp.mul(a, t2);\n      t4 = Fp.mul(b3, t4);\n      t1 = Fp.add(t1, t2);\n      t2 = Fp.sub(t0, t2); // step 30\n      t2 = Fp.mul(a, t2);\n      t4 = Fp.add(t4, t2);\n      t0 = Fp.mul(t1, t4);\n      Y3 = Fp.add(Y3, t0);\n      t0 = Fp.mul(t5, t4); // step 35\n      X3 = Fp.mul(t3, X3);\n      X3 = Fp.sub(X3, t0);\n      t0 = Fp.mul(t3, t1);\n      Z3 = Fp.mul(t5, Z3);\n      Z3 = Fp.add(Z3, t0); // step 40\n      return new Point(X3, Y3, Z3);\n    }\n\n    subtract(other: Point) {\n      return this.add(other.negate());\n    }\n\n    private is0() {\n      return this.equals(Point.ZERO);\n    }\n    private wNAF(n: bigint): { p: Point; f: Point } {\n      return wnaf.wNAFCached(this, pointPrecomputes, n, (comp: Point[]) => {\n        const toInv = Fp.invertBatch(comp.map((p) => p.pz));\n        return comp.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine);\n      });\n    }\n\n    /**\n     * Non-constant-time multiplication. Uses double-and-add algorithm.\n     * It's faster, but should only be used when you don't care about\n     * an exposed private key e.g. sig verification, which works over *public* keys.\n     */\n    multiplyUnsafe(n: bigint): Point {\n      const I = Point.ZERO;\n      if (n === _0n) return I;\n      assertGE(n); // Will throw on 0\n      if (n === _1n) return this;\n      const { endo } = CURVE;\n      if (!endo) return wnaf.unsafeLadder(this, n);\n\n      // Apply endomorphism\n      let { k1neg, k1, k2neg, k2 } = endo.splitScalar(n);\n      let k1p = I;\n      let k2p = I;\n      let d: Point = this;\n      while (k1 > _0n || k2 > _0n) {\n        if (k1 & _1n) k1p = k1p.add(d);\n        if (k2 & _1n) k2p = k2p.add(d);\n        d = d.double();\n        k1 >>= _1n;\n        k2 >>= _1n;\n      }\n      if (k1neg) k1p = k1p.negate();\n      if (k2neg) k2p = k2p.negate();\n      k2p = new Point(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz);\n      return k1p.add(k2p);\n    }\n\n    /**\n     * Constant time multiplication.\n     * Uses wNAF method. Windowed method may be 10% faster,\n     * but takes 2x longer to generate and consumes 2x memory.\n     * Uses precomputes when available.\n     * Uses endomorphism for Koblitz curves.\n     * @param scalar by which the point would be multiplied\n     * @returns New point\n     */\n    multiply(scalar: bigint): Point {\n      assertGE(scalar);\n      let n = scalar;\n      let point: Point, fake: Point; // Fake point is used to const-time mult\n      const { endo } = CURVE;\n      if (endo) {\n        const { k1neg, k1, k2neg, k2 } = endo.splitScalar(n);\n        let { p: k1p, f: f1p } = this.wNAF(k1);\n        let { p: k2p, f: f2p } = this.wNAF(k2);\n        k1p = wnaf.constTimeNegate(k1neg, k1p);\n        k2p = wnaf.constTimeNegate(k2neg, k2p);\n        k2p = new Point(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz);\n        point = k1p.add(k2p);\n        fake = f1p.add(f2p);\n      } else {\n        const { p, f } = this.wNAF(n);\n        point = p;\n        fake = f;\n      }\n      // Normalize `z` for both points, but return only real one\n      return Point.normalizeZ([point, fake])[0];\n    }\n\n    /**\n     * Efficiently calculate `aP + bQ`. Unsafe, can expose private key, if used incorrectly.\n     * Not using Strauss-Shamir trick: precomputation tables are faster.\n     * The trick could be useful if both P and Q are not G (not in our case).\n     * @returns non-zero affine point\n     */\n    multiplyAndAddUnsafe(Q: Point, a: bigint, b: bigint): Point | undefined {\n      const G = Point.BASE; // No Strauss-Shamir trick: we have 10% faster G precomputes\n      const mul = (\n        P: Point,\n        a: bigint // Select faster multiply() method\n      ) => (a === _0n || a === _1n || !P.equals(G) ? P.multiplyUnsafe(a) : P.multiply(a));\n      const sum = mul(this, a).add(mul(Q, b));\n      return sum.is0() ? undefined : sum;\n    }\n\n    // Converts Projective point to affine (x, y) coordinates.\n    // Can accept precomputed Z^-1 - for example, from invertBatch.\n    // (x, y, z) ∋ (x=x/z, y=y/z)\n    toAffine(iz?: T): AffinePoint<T> {\n      const { px: x, py: y, pz: z } = this;\n      const is0 = this.is0();\n      // If invZ was 0, we return zero point. However we still want to execute\n      // all operations, so we replace invZ with a random number, 1.\n      if (iz == null) iz = is0 ? Fp.ONE : Fp.inv(z);\n      const ax = Fp.mul(x, iz);\n      const ay = Fp.mul(y, iz);\n      const zz = Fp.mul(z, iz);\n      if (is0) return { x: Fp.ZERO, y: Fp.ZERO };\n      if (!Fp.eql(zz, Fp.ONE)) throw new Error('invZ was invalid');\n      return { x: ax, y: ay };\n    }\n    isTorsionFree(): boolean {\n      const { h: cofactor, isTorsionFree } = CURVE;\n      if (cofactor === _1n) return true; // No subgroups, always torsion-free\n      if (isTorsionFree) return isTorsionFree(Point, this);\n      throw new Error('isTorsionFree() has not been declared for the elliptic curve');\n    }\n    clearCofactor(): Point {\n      const { h: cofactor, clearCofactor } = CURVE;\n      if (cofactor === _1n) return this; // Fast-path\n      if (clearCofactor) return clearCofactor(Point, this) as Point;\n      return this.multiplyUnsafe(CURVE.h);\n    }\n\n    toRawBytes(isCompressed = true): Uint8Array {\n      this.assertValidity();\n      return toBytes(Point, this, isCompressed);\n    }\n\n    toHex(isCompressed = true): string {\n      return ut.bytesToHex(this.toRawBytes(isCompressed));\n    }\n  }\n  const _bits = CURVE.nBitLength;\n  const wnaf = wNAF(Point, CURVE.endo ? Math.ceil(_bits / 2) : _bits);\n  // Validate if generator point is on curve\n  return {\n    CURVE,\n    ProjectivePoint: Point as ProjConstructor<T>,\n    normPrivateKeyToScalar,\n    weierstrassEquation,\n    isWithinCurveOrder,\n  };\n}\n\n// Instance\nexport interface SignatureType {\n  readonly r: bigint;\n  readonly s: bigint;\n  readonly recovery?: number;\n  assertValidity(): void;\n  addRecoveryBit(recovery: number): RecoveredSignatureType;\n  hasHighS(): boolean;\n  normalizeS(): SignatureType;\n  recoverPublicKey(msgHash: Hex): ProjPointType<bigint>;\n  toCompactRawBytes(): Uint8Array;\n  toCompactHex(): string;\n  // DER-encoded\n  toDERRawBytes(isCompressed?: boolean): Uint8Array;\n  toDERHex(isCompressed?: boolean): string;\n}\nexport type RecoveredSignatureType = SignatureType & {\n  readonly recovery: number;\n};\n// Static methods\nexport type SignatureConstructor = {\n  new (r: bigint, s: bigint): SignatureType;\n  fromCompact(hex: Hex): SignatureType;\n  fromDER(hex: Hex): SignatureType;\n};\ntype SignatureLike = { r: bigint; s: bigint };\n\nexport type PubKey = Hex | ProjPointType<bigint>;\n\nexport type CurveType = BasicWCurve<bigint> & {\n  hash: CHash; // CHash not FHash because we need outputLen for DRBG\n  hmac: HmacFnSync;\n  randomBytes: (bytesLength?: number) => Uint8Array;\n  lowS?: boolean;\n  bits2int?: (bytes: Uint8Array) => bigint;\n  bits2int_modN?: (bytes: Uint8Array) => bigint;\n};\n\nfunction validateOpts(curve: CurveType) {\n  const opts = validateBasic(curve);\n  ut.validateObject(\n    opts,\n    {\n      hash: 'hash',\n      hmac: 'function',\n      randomBytes: 'function',\n    },\n    {\n      bits2int: 'function',\n      bits2int_modN: 'function',\n      lowS: 'boolean',\n    }\n  );\n  return Object.freeze({ lowS: true, ...opts } as const);\n}\n\nexport type CurveFn = {\n  CURVE: ReturnType<typeof validateOpts>;\n  getPublicKey: (privateKey: PrivKey, isCompressed?: boolean) => Uint8Array;\n  getSharedSecret: (privateA: PrivKey, publicB: Hex, isCompressed?: boolean) => Uint8Array;\n  sign: (msgHash: Hex, privKey: PrivKey, opts?: SignOpts) => RecoveredSignatureType;\n  verify: (signature: Hex | SignatureLike, msgHash: Hex, publicKey: Hex, opts?: VerOpts) => boolean;\n  ProjectivePoint: ProjConstructor<bigint>;\n  Signature: SignatureConstructor;\n  utils: {\n    normPrivateKeyToScalar: (key: PrivKey) => bigint;\n    isValidPrivateKey(privateKey: PrivKey): boolean;\n    randomPrivateKey: () => Uint8Array;\n    precompute: (windowSize?: number, point?: ProjPointType<bigint>) => ProjPointType<bigint>;\n  };\n};\n\nexport function weierstrass(curveDef: CurveType): CurveFn {\n  const CURVE = validateOpts(curveDef) as ReturnType<typeof validateOpts>;\n  const { Fp, n: CURVE_ORDER } = CURVE;\n  const compressedLen = Fp.BYTES + 1; // e.g. 33 for 32\n  const uncompressedLen = 2 * Fp.BYTES + 1; // e.g. 65 for 32\n\n  function isValidFieldElement(num: bigint): boolean {\n    return _0n < num && num < Fp.ORDER; // 0 is banned since it's not invertible FE\n  }\n  function modN(a: bigint) {\n    return mod.mod(a, CURVE_ORDER);\n  }\n  function invN(a: bigint) {\n    return mod.invert(a, CURVE_ORDER);\n  }\n\n  const {\n    ProjectivePoint: Point,\n    normPrivateKeyToScalar,\n    weierstrassEquation,\n    isWithinCurveOrder,\n  } = weierstrassPoints({\n    ...CURVE,\n    toBytes(_c, point, isCompressed: boolean): Uint8Array {\n      const a = point.toAffine();\n      const x = Fp.toBytes(a.x);\n      const cat = ut.concatBytes;\n      if (isCompressed) {\n        return cat(Uint8Array.from([point.hasEvenY() ? 0x02 : 0x03]), x);\n      } else {\n        return cat(Uint8Array.from([0x04]), x, Fp.toBytes(a.y));\n      }\n    },\n    fromBytes(bytes: Uint8Array) {\n      const len = bytes.length;\n      const head = bytes[0];\n      const tail = bytes.subarray(1);\n      // this.assertValidity() is done inside of fromHex\n      if (len === compressedLen && (head === 0x02 || head === 0x03)) {\n        const x = ut.bytesToNumberBE(tail);\n        if (!isValidFieldElement(x)) throw new Error('Point is not on curve');\n        const y2 = weierstrassEquation(x); // y² = x³ + ax + b\n        let y = Fp.sqrt(y2); // y = y² ^ (p+1)/4\n        const isYOdd = (y & _1n) === _1n;\n        // ECDSA\n        const isHeadOdd = (head & 1) === 1;\n        if (isHeadOdd !== isYOdd) y = Fp.neg(y);\n        return { x, y };\n      } else if (len === uncompressedLen && head === 0x04) {\n        const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES));\n        const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES));\n        return { x, y };\n      } else {\n        throw new Error(\n          `Point of length ${len} was invalid. Expected ${compressedLen} compressed bytes or ${uncompressedLen} uncompressed bytes`\n        );\n      }\n    },\n  });\n  const numToNByteStr = (num: bigint): string =>\n    ut.bytesToHex(ut.numberToBytesBE(num, CURVE.nByteLength));\n\n  function isBiggerThanHalfOrder(number: bigint) {\n    const HALF = CURVE_ORDER >> _1n;\n    return number > HALF;\n  }\n\n  function normalizeS(s: bigint) {\n    return isBiggerThanHalfOrder(s) ? modN(-s) : s;\n  }\n  // slice bytes num\n  const slcNum = (b: Uint8Array, from: number, to: number) => ut.bytesToNumberBE(b.slice(from, to));\n\n  /**\n   * ECDSA signature with its (r, s) properties. Supports DER & compact representations.\n   */\n  class Signature implements SignatureType {\n    constructor(readonly r: bigint, readonly s: bigint, readonly recovery?: number) {\n      this.assertValidity();\n    }\n\n    // pair (bytes of r, bytes of s)\n    static fromCompact(hex: Hex) {\n      const l = CURVE.nByteLength;\n      hex = ensureBytes('compactSignature', hex, l * 2);\n      return new Signature(slcNum(hex, 0, l), slcNum(hex, l, 2 * l));\n    }\n\n    // DER encoded ECDSA signature\n    // https://bitcoin.stackexchange.com/questions/57644/what-are-the-parts-of-a-bitcoin-transaction-input-script\n    static fromDER(hex: Hex) {\n      const { r, s } = DER.toSig(ensureBytes('DER', hex));\n      return new Signature(r, s);\n    }\n\n    assertValidity(): void {\n      // can use assertGE here\n      if (!isWithinCurveOrder(this.r)) throw new Error('r must be 0 < r < CURVE.n');\n      if (!isWithinCurveOrder(this.s)) throw new Error('s must be 0 < s < CURVE.n');\n    }\n\n    addRecoveryBit(recovery: number): RecoveredSignature {\n      return new Signature(this.r, this.s, recovery) as RecoveredSignature;\n    }\n\n    recoverPublicKey(msgHash: Hex): typeof Point.BASE {\n      const { r, s, recovery: rec } = this;\n      const h = bits2int_modN(ensureBytes('msgHash', msgHash)); // Truncate hash\n      if (rec == null || ![0, 1, 2, 3].includes(rec)) throw new Error('recovery id invalid');\n      const radj = rec === 2 || rec === 3 ? r + CURVE.n : r;\n      if (radj >= Fp.ORDER) throw new Error('recovery id 2 or 3 invalid');\n      const prefix = (rec & 1) === 0 ? '02' : '03';\n      const R = Point.fromHex(prefix + numToNByteStr(radj));\n      const ir = invN(radj); // r^-1\n      const u1 = modN(-h * ir); // -hr^-1\n      const u2 = modN(s * ir); // sr^-1\n      const Q = Point.BASE.multiplyAndAddUnsafe(R, u1, u2); // (sr^-1)R-(hr^-1)G = -(hr^-1)G + (sr^-1)\n      if (!Q) throw new Error('point at infinify'); // unsafe is fine: no priv data leaked\n      Q.assertValidity();\n      return Q;\n    }\n\n    // Signatures should be low-s, to prevent malleability.\n    hasHighS(): boolean {\n      return isBiggerThanHalfOrder(this.s);\n    }\n\n    normalizeS() {\n      return this.hasHighS() ? new Signature(this.r, modN(-this.s), this.recovery) : this;\n    }\n\n    // DER-encoded\n    toDERRawBytes() {\n      return ut.hexToBytes(this.toDERHex());\n    }\n    toDERHex() {\n      return DER.hexFromSig({ r: this.r, s: this.s });\n    }\n\n    // padded bytes of r, then padded bytes of s\n    toCompactRawBytes() {\n      return ut.hexToBytes(this.toCompactHex());\n    }\n    toCompactHex() {\n      return numToNByteStr(this.r) + numToNByteStr(this.s);\n    }\n  }\n  type RecoveredSignature = Signature & { recovery: number };\n\n  const utils = {\n    isValidPrivateKey(privateKey: PrivKey) {\n      try {\n        normPrivateKeyToScalar(privateKey);\n        return true;\n      } catch (error) {\n        return false;\n      }\n    },\n    normPrivateKeyToScalar: normPrivateKeyToScalar,\n\n    /**\n     * Produces cryptographically secure private key from random of size\n     * (groupLen + ceil(groupLen / 2)) with modulo bias being negligible.\n     */\n    randomPrivateKey: (): Uint8Array => {\n      const length = mod.getMinHashLength(CURVE.n);\n      return mod.mapHashToField(CURVE.randomBytes(length), CURVE.n);\n    },\n\n    /**\n     * Creates precompute table for an arbitrary EC point. Makes point \"cached\".\n     * Allows to massively speed-up `point.multiply(scalar)`.\n     * @returns cached point\n     * @example\n     * const fast = utils.precompute(8, ProjectivePoint.fromHex(someonesPubKey));\n     * fast.multiply(privKey); // much faster ECDH now\n     */\n    precompute(windowSize = 8, point = Point.BASE): typeof Point.BASE {\n      point._setWindowSize(windowSize);\n      point.multiply(BigInt(3)); // 3 is arbitrary, just need any number here\n      return point;\n    },\n  };\n\n  /**\n   * Computes public key for a private key. Checks for validity of the private key.\n   * @param privateKey private key\n   * @param isCompressed whether to return compact (default), or full key\n   * @returns Public key, full when isCompressed=false; short when isCompressed=true\n   */\n  function getPublicKey(privateKey: PrivKey, isCompressed = true): Uint8Array {\n    return Point.fromPrivateKey(privateKey).toRawBytes(isCompressed);\n  }\n\n  /**\n   * Quick and dirty check for item being public key. Does not validate hex, or being on-curve.\n   */\n  function isProbPub(item: PrivKey | PubKey): boolean {\n    const arr = item instanceof Uint8Array;\n    const str = typeof item === 'string';\n    const len = (arr || str) && (item as Hex).length;\n    if (arr) return len === compressedLen || len === uncompressedLen;\n    if (str) return len === 2 * compressedLen || len === 2 * uncompressedLen;\n    if (item instanceof Point) return true;\n    return false;\n  }\n\n  /**\n   * ECDH (Elliptic Curve Diffie Hellman).\n   * Computes shared public key from private key and public key.\n   * Checks: 1) private key validity 2) shared key is on-curve.\n   * Does NOT hash the result.\n   * @param privateA private key\n   * @param publicB different public key\n   * @param isCompressed whether to return compact (default), or full key\n   * @returns shared public key\n   */\n  function getSharedSecret(privateA: PrivKey, publicB: Hex, isCompressed = true): Uint8Array {\n    if (isProbPub(privateA)) throw new Error('first arg must be private key');\n    if (!isProbPub(publicB)) throw new Error('second arg must be public key');\n    const b = Point.fromHex(publicB); // check for being on-curve\n    return b.multiply(normPrivateKeyToScalar(privateA)).toRawBytes(isCompressed);\n  }\n\n  // RFC6979: ensure ECDSA msg is X bytes and < N. RFC suggests optional truncating via bits2octets.\n  // FIPS 186-4 4.6 suggests the leftmost min(nBitLen, outLen) bits, which matches bits2int.\n  // bits2int can produce res>N, we can do mod(res, N) since the bitLen is the same.\n  // int2octets can't be used; pads small msgs with 0: unacceptatble for trunc as per RFC vectors\n  const bits2int =\n    CURVE.bits2int ||\n    function (bytes: Uint8Array): bigint {\n      // For curves with nBitLength % 8 !== 0: bits2octets(bits2octets(m)) !== bits2octets(m)\n      // for some cases, since bytes.length * 8 is not actual bitLength.\n      const num = ut.bytesToNumberBE(bytes); // check for == u8 done here\n      const delta = bytes.length * 8 - CURVE.nBitLength; // truncate to nBitLength leftmost bits\n      return delta > 0 ? num >> BigInt(delta) : num;\n    };\n  const bits2int_modN =\n    CURVE.bits2int_modN ||\n    function (bytes: Uint8Array): bigint {\n      return modN(bits2int(bytes)); // can't use bytesToNumberBE here\n    };\n  // NOTE: pads output with zero as per spec\n  const ORDER_MASK = ut.bitMask(CURVE.nBitLength);\n  /**\n   * Converts to bytes. Checks if num in `[0..ORDER_MASK-1]` e.g.: `[0..2^256-1]`.\n   */\n  function int2octets(num: bigint): Uint8Array {\n    if (typeof num !== 'bigint') throw new Error('bigint expected');\n    if (!(_0n <= num && num < ORDER_MASK))\n      throw new Error(`bigint expected < 2^${CURVE.nBitLength}`);\n    // works with order, can have different size than numToField!\n    return ut.numberToBytesBE(num, CURVE.nByteLength);\n  }\n\n  // Steps A, D of RFC6979 3.2\n  // Creates RFC6979 seed; converts msg/privKey to numbers.\n  // Used only in sign, not in verify.\n  // NOTE: we cannot assume here that msgHash has same amount of bytes as curve order, this will be wrong at least for P521.\n  // Also it can be bigger for P224 + SHA256\n  function prepSig(msgHash: Hex, privateKey: PrivKey, opts = defaultSigOpts) {\n    if (['recovered', 'canonical'].some((k) => k in opts))\n      throw new Error('sign() legacy options not supported');\n    const { hash, randomBytes } = CURVE;\n    let { lowS, prehash, extraEntropy: ent } = opts; // generates low-s sigs by default\n    if (lowS == null) lowS = true; // RFC6979 3.2: we skip step A, because we already provide hash\n    msgHash = ensureBytes('msgHash', msgHash);\n    if (prehash) msgHash = ensureBytes('prehashed msgHash', hash(msgHash));\n\n    // We can't later call bits2octets, since nested bits2int is broken for curves\n    // with nBitLength % 8 !== 0. Because of that, we unwrap it here as int2octets call.\n    // const bits2octets = (bits) => int2octets(bits2int_modN(bits))\n    const h1int = bits2int_modN(msgHash);\n    const d = normPrivateKeyToScalar(privateKey); // validate private key, convert to bigint\n    const seedArgs = [int2octets(d), int2octets(h1int)];\n    // extraEntropy. RFC6979 3.6: additional k' (optional).\n    if (ent != null) {\n      // K = HMAC_K(V || 0x00 || int2octets(x) || bits2octets(h1) || k')\n      const e = ent === true ? randomBytes(Fp.BYTES) : ent; // generate random bytes OR pass as-is\n      seedArgs.push(ensureBytes('extraEntropy', e)); // check for being bytes\n    }\n    const seed = ut.concatBytes(...seedArgs); // Step D of RFC6979 3.2\n    const m = h1int; // NOTE: no need to call bits2int second time here, it is inside truncateHash!\n    // Converts signature params into point w r/s, checks result for validity.\n    function k2sig(kBytes: Uint8Array): RecoveredSignature | undefined {\n      // RFC 6979 Section 3.2, step 3: k = bits2int(T)\n      const k = bits2int(kBytes); // Cannot use fields methods, since it is group element\n      if (!isWithinCurveOrder(k)) return; // Important: all mod() calls here must be done over N\n      const ik = invN(k); // k^-1 mod n\n      const q = Point.BASE.multiply(k).toAffine(); // q = Gk\n      const r = modN(q.x); // r = q.x mod n\n      if (r === _0n) return;\n      // Can use scalar blinding b^-1(bm + bdr) where b ∈ [1,q−1] according to\n      // https://tches.iacr.org/index.php/TCHES/article/view/7337/6509. We've decided against it:\n      // a) dependency on CSPRNG b) 15% slowdown c) doesn't really help since bigints are not CT\n      const s = modN(ik * modN(m + r * d)); // Not using blinding here\n      if (s === _0n) return;\n      let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n); // recovery bit (2 or 3, when q.x > n)\n      let normS = s;\n      if (lowS && isBiggerThanHalfOrder(s)) {\n        normS = normalizeS(s); // if lowS was passed, ensure s is always\n        recovery ^= 1; // // in the bottom half of N\n      }\n      return new Signature(r, normS, recovery) as RecoveredSignature; // use normS, not s\n    }\n    return { seed, k2sig };\n  }\n  const defaultSigOpts: SignOpts = { lowS: CURVE.lowS, prehash: false };\n  const defaultVerOpts: VerOpts = { lowS: CURVE.lowS, prehash: false };\n\n  /**\n   * Signs message hash with a private key.\n   * ```\n   * sign(m, d, k) where\n   *   (x, y) = G × k\n   *   r = x mod n\n   *   s = (m + dr)/k mod n\n   * ```\n   * @param msgHash NOT message. msg needs to be hashed to `msgHash`, or use `prehash`.\n   * @param privKey private key\n   * @param opts lowS for non-malleable sigs. extraEntropy for mixing randomness into k. prehash will hash first arg.\n   * @returns signature with recovery param\n   */\n  function sign(msgHash: Hex, privKey: PrivKey, opts = defaultSigOpts): RecoveredSignature {\n    const { seed, k2sig } = prepSig(msgHash, privKey, opts); // Steps A, D of RFC6979 3.2.\n    const C = CURVE;\n    const drbg = ut.createHmacDrbg<RecoveredSignature>(C.hash.outputLen, C.nByteLength, C.hmac);\n    return drbg(seed, k2sig); // Steps B, C, D, E, F, G\n  }\n\n  // Enable precomputes. Slows down first publicKey computation by 20ms.\n  Point.BASE._setWindowSize(8);\n  // utils.precompute(8, ProjectivePoint.BASE)\n\n  /**\n   * Verifies a signature against message hash and public key.\n   * Rejects lowS signatures by default: to override,\n   * specify option `{lowS: false}`. Implements section 4.1.4 from https://www.secg.org/sec1-v2.pdf:\n   *\n   * ```\n   * verify(r, s, h, P) where\n   *   U1 = hs^-1 mod n\n   *   U2 = rs^-1 mod n\n   *   R = U1⋅G - U2⋅P\n   *   mod(R.x, n) == r\n   * ```\n   */\n  function verify(\n    signature: Hex | SignatureLike,\n    msgHash: Hex,\n    publicKey: Hex,\n    opts = defaultVerOpts\n  ): boolean {\n    const sg = signature;\n    msgHash = ensureBytes('msgHash', msgHash);\n    publicKey = ensureBytes('publicKey', publicKey);\n    if ('strict' in opts) throw new Error('options.strict was renamed to lowS');\n    const { lowS, prehash } = opts;\n\n    let _sig: Signature | undefined = undefined;\n    let P: ProjPointType<bigint>;\n    try {\n      if (typeof sg === 'string' || sg instanceof Uint8Array) {\n        // Signature can be represented in 2 ways: compact (2*nByteLength) & DER (variable-length).\n        // Since DER can also be 2*nByteLength bytes, we check for it first.\n        try {\n          _sig = Signature.fromDER(sg);\n        } catch (derError) {\n          if (!(derError instanceof DER.Err)) throw derError;\n          _sig = Signature.fromCompact(sg);\n        }\n      } else if (typeof sg === 'object' && typeof sg.r === 'bigint' && typeof sg.s === 'bigint') {\n        const { r, s } = sg;\n        _sig = new Signature(r, s);\n      } else {\n        throw new Error('PARSE');\n      }\n      P = Point.fromHex(publicKey);\n    } catch (error) {\n      if ((error as Error).message === 'PARSE')\n        throw new Error(`signature must be Signature instance, Uint8Array or hex string`);\n      return false;\n    }\n    if (lowS && _sig.hasHighS()) return false;\n    if (prehash) msgHash = CURVE.hash(msgHash);\n    const { r, s } = _sig;\n    const h = bits2int_modN(msgHash); // Cannot use fields methods, since it is group element\n    const is = invN(s); // s^-1\n    const u1 = modN(h * is); // u1 = hs^-1 mod n\n    const u2 = modN(r * is); // u2 = rs^-1 mod n\n    const R = Point.BASE.multiplyAndAddUnsafe(P, u1, u2)?.toAffine(); // R = u1⋅G + u2⋅P\n    if (!R) return false;\n    const v = modN(R.x);\n    return v === r;\n  }\n  return {\n    CURVE,\n    getPublicKey,\n    getSharedSecret,\n    sign,\n    verify,\n    ProjectivePoint: Point,\n    Signature,\n    utils,\n  };\n}\n\n/**\n * Implementation of the Shallue and van de Woestijne method for any weierstrass curve.\n * TODO: check if there is a way to merge this with uvRatio in Edwards; move to modular.\n * b = True and y = sqrt(u / v) if (u / v) is square in F, and\n * b = False and y = sqrt(Z * (u / v)) otherwise.\n * @param Fp\n * @param Z\n * @returns\n */\nexport function SWUFpSqrtRatio<T>(Fp: mod.IField<T>, Z: T) {\n  // Generic implementation\n  const q = Fp.ORDER;\n  let l = _0n;\n  for (let o = q - _1n; o % _2n === _0n; o /= _2n) l += _1n;\n  const c1 = l; // 1. c1, the largest integer such that 2^c1 divides q - 1.\n  // We need 2n ** c1 and 2n ** (c1-1). We can't use **; but we can use <<.\n  // 2n ** c1 == 2n << (c1-1)\n  const _2n_pow_c1_1 = _2n << (c1 - _1n - _1n);\n  const _2n_pow_c1 = _2n_pow_c1_1 * _2n;\n  const c2 = (q - _1n) / _2n_pow_c1; // 2. c2 = (q - 1) / (2^c1)  # Integer arithmetic\n  const c3 = (c2 - _1n) / _2n; // 3. c3 = (c2 - 1) / 2            # Integer arithmetic\n  const c4 = _2n_pow_c1 - _1n; // 4. c4 = 2^c1 - 1                # Integer arithmetic\n  const c5 = _2n_pow_c1_1; // 5. c5 = 2^(c1 - 1)                  # Integer arithmetic\n  const c6 = Fp.pow(Z, c2); // 6. c6 = Z^c2\n  const c7 = Fp.pow(Z, (c2 + _1n) / _2n); // 7. c7 = Z^((c2 + 1) / 2)\n  let sqrtRatio = (u: T, v: T): { isValid: boolean; value: T } => {\n    let tv1 = c6; // 1. tv1 = c6\n    let tv2 = Fp.pow(v, c4); // 2. tv2 = v^c4\n    let tv3 = Fp.sqr(tv2); // 3. tv3 = tv2^2\n    tv3 = Fp.mul(tv3, v); // 4. tv3 = tv3 * v\n    let tv5 = Fp.mul(u, tv3); // 5. tv5 = u * tv3\n    tv5 = Fp.pow(tv5, c3); // 6. tv5 = tv5^c3\n    tv5 = Fp.mul(tv5, tv2); // 7. tv5 = tv5 * tv2\n    tv2 = Fp.mul(tv5, v); // 8. tv2 = tv5 * v\n    tv3 = Fp.mul(tv5, u); // 9. tv3 = tv5 * u\n    let tv4 = Fp.mul(tv3, tv2); // 10. tv4 = tv3 * tv2\n    tv5 = Fp.pow(tv4, c5); // 11. tv5 = tv4^c5\n    let isQR = Fp.eql(tv5, Fp.ONE); // 12. isQR = tv5 == 1\n    tv2 = Fp.mul(tv3, c7); // 13. tv2 = tv3 * c7\n    tv5 = Fp.mul(tv4, tv1); // 14. tv5 = tv4 * tv1\n    tv3 = Fp.cmov(tv2, tv3, isQR); // 15. tv3 = CMOV(tv2, tv3, isQR)\n    tv4 = Fp.cmov(tv5, tv4, isQR); // 16. tv4 = CMOV(tv5, tv4, isQR)\n    // 17. for i in (c1, c1 - 1, ..., 2):\n    for (let i = c1; i > _1n; i--) {\n      let tv5 = i - _2n; // 18.    tv5 = i - 2\n      tv5 = _2n << (tv5 - _1n); // 19.    tv5 = 2^tv5\n      let tvv5 = Fp.pow(tv4, tv5); // 20.    tv5 = tv4^tv5\n      const e1 = Fp.eql(tvv5, Fp.ONE); // 21.    e1 = tv5 == 1\n      tv2 = Fp.mul(tv3, tv1); // 22.    tv2 = tv3 * tv1\n      tv1 = Fp.mul(tv1, tv1); // 23.    tv1 = tv1 * tv1\n      tvv5 = Fp.mul(tv4, tv1); // 24.    tv5 = tv4 * tv1\n      tv3 = Fp.cmov(tv2, tv3, e1); // 25.    tv3 = CMOV(tv2, tv3, e1)\n      tv4 = Fp.cmov(tvv5, tv4, e1); // 26.    tv4 = CMOV(tv5, tv4, e1)\n    }\n    return { isValid: isQR, value: tv3 };\n  };\n  if (Fp.ORDER % _4n === _3n) {\n    // sqrt_ratio_3mod4(u, v)\n    const c1 = (Fp.ORDER - _3n) / _4n; // 1. c1 = (q - 3) / 4     # Integer arithmetic\n    const c2 = Fp.sqrt(Fp.neg(Z)); // 2. c2 = sqrt(-Z)\n    sqrtRatio = (u: T, v: T) => {\n      let tv1 = Fp.sqr(v); // 1. tv1 = v^2\n      const tv2 = Fp.mul(u, v); // 2. tv2 = u * v\n      tv1 = Fp.mul(tv1, tv2); // 3. tv1 = tv1 * tv2\n      let y1 = Fp.pow(tv1, c1); // 4. y1 = tv1^c1\n      y1 = Fp.mul(y1, tv2); // 5. y1 = y1 * tv2\n      const y2 = Fp.mul(y1, c2); // 6. y2 = y1 * c2\n      const tv3 = Fp.mul(Fp.sqr(y1), v); // 7. tv3 = y1^2; 8. tv3 = tv3 * v\n      const isQR = Fp.eql(tv3, u); // 9. isQR = tv3 == u\n      let y = Fp.cmov(y2, y1, isQR); // 10. y = CMOV(y2, y1, isQR)\n      return { isValid: isQR, value: y }; // 11. return (isQR, y) isQR ? y : y*c2\n    };\n  }\n  // No curves uses that\n  // if (Fp.ORDER % _8n === _5n) // sqrt_ratio_5mod8\n  return sqrtRatio;\n}\n/**\n * Simplified Shallue-van de Woestijne-Ulas Method\n * https://www.rfc-editor.org/rfc/rfc9380#section-6.6.2\n */\nexport function mapToCurveSimpleSWU<T>(\n  Fp: mod.IField<T>,\n  opts: {\n    A: T;\n    B: T;\n    Z: T;\n  }\n) {\n  mod.validateField(Fp);\n  if (!Fp.isValid(opts.A) || !Fp.isValid(opts.B) || !Fp.isValid(opts.Z))\n    throw new Error('mapToCurveSimpleSWU: invalid opts');\n  const sqrtRatio = SWUFpSqrtRatio(Fp, opts.Z);\n  if (!Fp.isOdd) throw new Error('Fp.isOdd is not implemented!');\n  // Input: u, an element of F.\n  // Output: (x, y), a point on E.\n  return (u: T): { x: T; y: T } => {\n    // prettier-ignore\n    let tv1, tv2, tv3, tv4, tv5, tv6, x, y;\n    tv1 = Fp.sqr(u); // 1.  tv1 = u^2\n    tv1 = Fp.mul(tv1, opts.Z); // 2.  tv1 = Z * tv1\n    tv2 = Fp.sqr(tv1); // 3.  tv2 = tv1^2\n    tv2 = Fp.add(tv2, tv1); // 4.  tv2 = tv2 + tv1\n    tv3 = Fp.add(tv2, Fp.ONE); // 5.  tv3 = tv2 + 1\n    tv3 = Fp.mul(tv3, opts.B); // 6.  tv3 = B * tv3\n    tv4 = Fp.cmov(opts.Z, Fp.neg(tv2), !Fp.eql(tv2, Fp.ZERO)); // 7.  tv4 = CMOV(Z, -tv2, tv2 != 0)\n    tv4 = Fp.mul(tv4, opts.A); // 8.  tv4 = A * tv4\n    tv2 = Fp.sqr(tv3); // 9.  tv2 = tv3^2\n    tv6 = Fp.sqr(tv4); // 10. tv6 = tv4^2\n    tv5 = Fp.mul(tv6, opts.A); // 11. tv5 = A * tv6\n    tv2 = Fp.add(tv2, tv5); // 12. tv2 = tv2 + tv5\n    tv2 = Fp.mul(tv2, tv3); // 13. tv2 = tv2 * tv3\n    tv6 = Fp.mul(tv6, tv4); // 14. tv6 = tv6 * tv4\n    tv5 = Fp.mul(tv6, opts.B); // 15. tv5 = B * tv6\n    tv2 = Fp.add(tv2, tv5); // 16. tv2 = tv2 + tv5\n    x = Fp.mul(tv1, tv3); // 17.   x = tv1 * tv3\n    const { isValid, value } = sqrtRatio(tv2, tv6); // 18. (is_gx1_square, y1) = sqrt_ratio(tv2, tv6)\n    y = Fp.mul(tv1, u); // 19.   y = tv1 * u  -> Z * u^3 * y1\n    y = Fp.mul(y, value); // 20.   y = y * y1\n    x = Fp.cmov(x, tv3, isValid); // 21.   x = CMOV(x, tv3, is_gx1_square)\n    y = Fp.cmov(y, value, isValid); // 22.   y = CMOV(y, y1, is_gx1_square)\n    const e1 = Fp.isOdd!(u) === Fp.isOdd!(y); // 23.  e1 = sgn0(u) == sgn0(y)\n    y = Fp.cmov(Fp.neg(y), y, e1); // 24.   y = CMOV(-y, y, e1)\n    x = Fp.div(x, tv4); // 25.   x = x / tv4\n    return { x, y };\n  };\n}\n","import { hash as assertHash, bytes as assertBytes, exists as assertExists } from './_assert.js';\nimport { Hash, CHash, Input, toBytes } from './utils.js';\n// HMAC (RFC 2104)\nexport class HMAC<T extends Hash<T>> extends Hash<HMAC<T>> {\n  oHash: T;\n  iHash: T;\n  blockLen: number;\n  outputLen: number;\n  private finished = false;\n  private destroyed = false;\n\n  constructor(hash: CHash, _key: Input) {\n    super();\n    assertHash(hash);\n    const key = toBytes(_key);\n    this.iHash = hash.create() as T;\n    if (typeof this.iHash.update !== 'function')\n      throw new Error('Expected instance of class which extends utils.Hash');\n    this.blockLen = this.iHash.blockLen;\n    this.outputLen = this.iHash.outputLen;\n    const blockLen = this.blockLen;\n    const pad = new Uint8Array(blockLen);\n    // blockLen can be bigger than outputLen\n    pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);\n    for (let i = 0; i < pad.length; i++) pad[i] ^= 0x36;\n    this.iHash.update(pad);\n    // By doing update (processing of first block) of outer hash here we can re-use it between multiple calls via clone\n    this.oHash = hash.create() as T;\n    // Undo internal XOR && apply outer XOR\n    for (let i = 0; i < pad.length; i++) pad[i] ^= 0x36 ^ 0x5c;\n    this.oHash.update(pad);\n    pad.fill(0);\n  }\n  update(buf: Input) {\n    assertExists(this);\n    this.iHash.update(buf);\n    return this;\n  }\n  digestInto(out: Uint8Array) {\n    assertExists(this);\n    assertBytes(out, this.outputLen);\n    this.finished = true;\n    this.iHash.digestInto(out);\n    this.oHash.update(out);\n    this.oHash.digestInto(out);\n    this.destroy();\n  }\n  digest() {\n    const out = new Uint8Array(this.oHash.outputLen);\n    this.digestInto(out);\n    return out;\n  }\n  _cloneInto(to?: HMAC<T>): HMAC<T> {\n    // Create new instance without calling constructor since key already in state and we don't know it.\n    to ||= Object.create(Object.getPrototypeOf(this), {});\n    const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;\n    to = to as this;\n    to.finished = finished;\n    to.destroyed = destroyed;\n    to.blockLen = blockLen;\n    to.outputLen = outputLen;\n    to.oHash = oHash._cloneInto(to.oHash);\n    to.iHash = iHash._cloneInto(to.iHash);\n    return to;\n  }\n  destroy() {\n    this.destroyed = true;\n    this.oHash.destroy();\n    this.iHash.destroy();\n  }\n}\n\n/**\n * HMAC: RFC2104 message authentication code.\n * @param hash - function that would be used e.g. sha256\n * @param key - message key\n * @param message - message data\n */\nexport const hmac = (hash: CHash, key: Input, message: Input): Uint8Array =>\n  new HMAC<any>(hash, key).update(message).digest();\nhmac.create = (hash: CHash, key: Input) => new HMAC<any>(hash, key);\n","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { hmac } from '@noble/hashes/hmac';\nimport { concatBytes, randomBytes } from '@noble/hashes/utils';\nimport { weierstrass, CurveType } from './abstract/weierstrass.js';\nimport { CHash } from './abstract/utils.js';\n\n// connects noble-curves to noble-hashes\nexport function getHash(hash: CHash) {\n  return {\n    hash,\n    hmac: (key: Uint8Array, ...msgs: Uint8Array[]) => hmac(hash, key, concatBytes(...msgs)),\n    randomBytes,\n  };\n}\n// Same API as @noble/hashes, with ability to create curve with custom hash\ntype CurveDef = Readonly<Omit<CurveType, 'hash' | 'hmac' | 'randomBytes'>>;\nexport function createCurve(curveDef: CurveDef, defHash: CHash) {\n  const create = (hash: CHash) => weierstrass({ ...curveDef, ...getHash(hash) });\n  return Object.freeze({ ...create(defHash), create });\n}\n","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { sha256 } from '@noble/hashes/sha256';\nimport { randomBytes } from '@noble/hashes/utils';\nimport { Field, mod, pow2 } from './abstract/modular.js';\nimport { ProjPointType as PointType, mapToCurveSimpleSWU } from './abstract/weierstrass.js';\nimport type { Hex, PrivKey } from './abstract/utils.js';\nimport { bytesToNumberBE, concatBytes, ensureBytes, numberToBytesBE } from './abstract/utils.js';\nimport { createHasher, isogenyMap } from './abstract/hash-to-curve.js';\nimport { createCurve } from './_shortw_utils.js';\n\nconst secp256k1P = BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f');\nconst secp256k1N = BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141');\nconst _1n = BigInt(1);\nconst _2n = BigInt(2);\nconst divNearest = (a: bigint, b: bigint) => (a + b / _2n) / b;\n\n/**\n * √n = n^((p+1)/4) for fields p = 3 mod 4. We unwrap the loop and multiply bit-by-bit.\n * (P+1n/4n).toString(2) would produce bits [223x 1, 0, 22x 1, 4x 0, 11, 00]\n */\nfunction sqrtMod(y: bigint): bigint {\n  const P = secp256k1P;\n  // prettier-ignore\n  const _3n = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22);\n  // prettier-ignore\n  const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88);\n  const b2 = (y * y * y) % P; // x^3, 11\n  const b3 = (b2 * b2 * y) % P; // x^7\n  const b6 = (pow2(b3, _3n, P) * b3) % P;\n  const b9 = (pow2(b6, _3n, P) * b3) % P;\n  const b11 = (pow2(b9, _2n, P) * b2) % P;\n  const b22 = (pow2(b11, _11n, P) * b11) % P;\n  const b44 = (pow2(b22, _22n, P) * b22) % P;\n  const b88 = (pow2(b44, _44n, P) * b44) % P;\n  const b176 = (pow2(b88, _88n, P) * b88) % P;\n  const b220 = (pow2(b176, _44n, P) * b44) % P;\n  const b223 = (pow2(b220, _3n, P) * b3) % P;\n  const t1 = (pow2(b223, _23n, P) * b22) % P;\n  const t2 = (pow2(t1, _6n, P) * b2) % P;\n  const root = pow2(t2, _2n, P);\n  if (!Fp.eql(Fp.sqr(root), y)) throw new Error('Cannot find square root');\n  return root;\n}\n\nconst Fp = Field(secp256k1P, undefined, undefined, { sqrt: sqrtMod });\n\nexport const secp256k1 = createCurve(\n  {\n    a: BigInt(0), // equation params: a, b\n    b: BigInt(7), // Seem to be rigid: bitcointalk.org/index.php?topic=289795.msg3183975#msg3183975\n    Fp, // Field's prime: 2n**256n - 2n**32n - 2n**9n - 2n**8n - 2n**7n - 2n**6n - 2n**4n - 1n\n    n: secp256k1N, // Curve order, total count of valid points in the field\n    // Base point (x, y) aka generator point\n    Gx: BigInt('55066263022277343669578718895168534326250603453777594175500187360389116729240'),\n    Gy: BigInt('32670510020758816978083085130507043184471273380659243275938904335757337482424'),\n    h: BigInt(1), // Cofactor\n    lowS: true, // Allow only low-S signatures by default in sign() and verify()\n    /**\n     * secp256k1 belongs to Koblitz curves: it has efficiently computable endomorphism.\n     * Endomorphism uses 2x less RAM, speeds up precomputation by 2x and ECDH / key recovery by 20%.\n     * For precomputed wNAF it trades off 1/2 init time & 1/3 ram for 20% perf hit.\n     * Explanation: https://gist.github.com/paulmillr/eb670806793e84df628a7c434a873066\n     */\n    endo: {\n      beta: BigInt('0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee'),\n      splitScalar: (k: bigint) => {\n        const n = secp256k1N;\n        const a1 = BigInt('0x3086d221a7d46bcde86c90e49284eb15');\n        const b1 = -_1n * BigInt('0xe4437ed6010e88286f547fa90abfe4c3');\n        const a2 = BigInt('0x114ca50f7a8e2f3f657c1108d9d44cfd8');\n        const b2 = a1;\n        const POW_2_128 = BigInt('0x100000000000000000000000000000000'); // (2n**128n).toString(16)\n\n        const c1 = divNearest(b2 * k, n);\n        const c2 = divNearest(-b1 * k, n);\n        let k1 = mod(k - c1 * a1 - c2 * a2, n);\n        let k2 = mod(-c1 * b1 - c2 * b2, n);\n        const k1neg = k1 > POW_2_128;\n        const k2neg = k2 > POW_2_128;\n        if (k1neg) k1 = n - k1;\n        if (k2neg) k2 = n - k2;\n        if (k1 > POW_2_128 || k2 > POW_2_128) {\n          throw new Error('splitScalar: Endomorphism failed, k=' + k);\n        }\n        return { k1neg, k1, k2neg, k2 };\n      },\n    },\n  },\n  sha256\n);\n\n// Schnorr signatures are superior to ECDSA from above. Below is Schnorr-specific BIP0340 code.\n// https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki\nconst _0n = BigInt(0);\nconst fe = (x: bigint) => typeof x === 'bigint' && _0n < x && x < secp256k1P;\nconst ge = (x: bigint) => typeof x === 'bigint' && _0n < x && x < secp256k1N;\n/** An object mapping tags to their tagged hash prefix of [SHA256(tag) | SHA256(tag)] */\nconst TAGGED_HASH_PREFIXES: { [tag: string]: Uint8Array } = {};\nfunction taggedHash(tag: string, ...messages: Uint8Array[]): Uint8Array {\n  let tagP = TAGGED_HASH_PREFIXES[tag];\n  if (tagP === undefined) {\n    const tagH = sha256(Uint8Array.from(tag, (c) => c.charCodeAt(0)));\n    tagP = concatBytes(tagH, tagH);\n    TAGGED_HASH_PREFIXES[tag] = tagP;\n  }\n  return sha256(concatBytes(tagP, ...messages));\n}\n\n// ECDSA compact points are 33-byte. Schnorr is 32: we strip first byte 0x02 or 0x03\nconst pointToBytes = (point: PointType<bigint>) => point.toRawBytes(true).slice(1);\nconst numTo32b = (n: bigint) => numberToBytesBE(n, 32);\nconst modP = (x: bigint) => mod(x, secp256k1P);\nconst modN = (x: bigint) => mod(x, secp256k1N);\nconst Point = secp256k1.ProjectivePoint;\nconst GmulAdd = (Q: PointType<bigint>, a: bigint, b: bigint) =>\n  Point.BASE.multiplyAndAddUnsafe(Q, a, b);\n\n// Calculate point, scalar and bytes\nfunction schnorrGetExtPubKey(priv: PrivKey) {\n  let d_ = secp256k1.utils.normPrivateKeyToScalar(priv); // same method executed in fromPrivateKey\n  let p = Point.fromPrivateKey(d_); // P = d'⋅G; 0 < d' < n check is done inside\n  const scalar = p.hasEvenY() ? d_ : modN(-d_);\n  return { scalar: scalar, bytes: pointToBytes(p) };\n}\n/**\n * lift_x from BIP340. Convert 32-byte x coordinate to elliptic curve point.\n * @returns valid point checked for being on-curve\n */\nfunction lift_x(x: bigint): PointType<bigint> {\n  if (!fe(x)) throw new Error('bad x: need 0 < x < p'); // Fail if x ≥ p.\n  const xx = modP(x * x);\n  const c = modP(xx * x + BigInt(7)); // Let c = x³ + 7 mod p.\n  let y = sqrtMod(c); // Let y = c^(p+1)/4 mod p.\n  if (y % _2n !== _0n) y = modP(-y); // Return the unique point P such that x(P) = x and\n  const p = new Point(x, y, _1n); // y(P) = y if y mod 2 = 0 or y(P) = p-y otherwise.\n  p.assertValidity();\n  return p;\n}\n/**\n * Create tagged hash, convert it to bigint, reduce modulo-n.\n */\nfunction challenge(...args: Uint8Array[]): bigint {\n  return modN(bytesToNumberBE(taggedHash('BIP0340/challenge', ...args)));\n}\n\n/**\n * Schnorr public key is just `x` coordinate of Point as per BIP340.\n */\nfunction schnorrGetPublicKey(privateKey: Hex): Uint8Array {\n  return schnorrGetExtPubKey(privateKey).bytes; // d'=int(sk). Fail if d'=0 or d'≥n. Ret bytes(d'⋅G)\n}\n\n/**\n * Creates Schnorr signature as per BIP340. Verifies itself before returning anything.\n * auxRand is optional and is not the sole source of k generation: bad CSPRNG won't be dangerous.\n */\nfunction schnorrSign(\n  message: Hex,\n  privateKey: PrivKey,\n  auxRand: Hex = randomBytes(32)\n): Uint8Array {\n  const m = ensureBytes('message', message);\n  const { bytes: px, scalar: d } = schnorrGetExtPubKey(privateKey); // checks for isWithinCurveOrder\n  const a = ensureBytes('auxRand', auxRand, 32); // Auxiliary random data a: a 32-byte array\n  const t = numTo32b(d ^ bytesToNumberBE(taggedHash('BIP0340/aux', a))); // Let t be the byte-wise xor of bytes(d) and hash/aux(a)\n  const rand = taggedHash('BIP0340/nonce', t, px, m); // Let rand = hash/nonce(t || bytes(P) || m)\n  const k_ = modN(bytesToNumberBE(rand)); // Let k' = int(rand) mod n\n  if (k_ === _0n) throw new Error('sign failed: k is zero'); // Fail if k' = 0.\n  const { bytes: rx, scalar: k } = schnorrGetExtPubKey(k_); // Let R = k'⋅G.\n  const e = challenge(rx, px, m); // Let e = int(hash/challenge(bytes(R) || bytes(P) || m)) mod n.\n  const sig = new Uint8Array(64); // Let sig = bytes(R) || bytes((k + ed) mod n).\n  sig.set(rx, 0);\n  sig.set(numTo32b(modN(k + e * d)), 32);\n  // If Verify(bytes(P), m, sig) (see below) returns failure, abort\n  if (!schnorrVerify(sig, m, px)) throw new Error('sign: Invalid signature produced');\n  return sig;\n}\n\n/**\n * Verifies Schnorr signature.\n * Will swallow errors & return false except for initial type validation of arguments.\n */\nfunction schnorrVerify(signature: Hex, message: Hex, publicKey: Hex): boolean {\n  const sig = ensureBytes('signature', signature, 64);\n  const m = ensureBytes('message', message);\n  const pub = ensureBytes('publicKey', publicKey, 32);\n  try {\n    const P = lift_x(bytesToNumberBE(pub)); // P = lift_x(int(pk)); fail if that fails\n    const r = bytesToNumberBE(sig.subarray(0, 32)); // Let r = int(sig[0:32]); fail if r ≥ p.\n    if (!fe(r)) return false;\n    const s = bytesToNumberBE(sig.subarray(32, 64)); // Let s = int(sig[32:64]); fail if s ≥ n.\n    if (!ge(s)) return false;\n    const e = challenge(numTo32b(r), pointToBytes(P), m); // int(challenge(bytes(r)||bytes(P)||m))%n\n    const R = GmulAdd(P, s, modN(-e)); // R = s⋅G - e⋅P\n    if (!R || !R.hasEvenY() || R.toAffine().x !== r) return false; // -eP == (n-e)P\n    return true; // Fail if is_infinite(R) / not has_even_y(R) / x(R) ≠ r.\n  } catch (error) {\n    return false;\n  }\n}\n\nexport const schnorr = /* @__PURE__ */ (() => ({\n  getPublicKey: schnorrGetPublicKey,\n  sign: schnorrSign,\n  verify: schnorrVerify,\n  utils: {\n    randomPrivateKey: secp256k1.utils.randomPrivateKey,\n    lift_x,\n    pointToBytes,\n    numberToBytesBE,\n    bytesToNumberBE,\n    taggedHash,\n    mod,\n  },\n}))();\n\nconst isoMap = /* @__PURE__ */ (() =>\n  isogenyMap(\n    Fp,\n    [\n      // xNum\n      [\n        '0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa8c7',\n        '0x7d3d4c80bc321d5b9f315cea7fd44c5d595d2fc0bf63b92dfff1044f17c6581',\n        '0x534c328d23f234e6e2a413deca25caece4506144037c40314ecbd0b53d9dd262',\n        '0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa88c',\n      ],\n      // xDen\n      [\n        '0xd35771193d94918a9ca34ccbb7b640dd86cd409542f8487d9fe6b745781eb49b',\n        '0xedadc6f64383dc1df7c4b2d51b54225406d36b641f5e41bbc52a56612a8c6d14',\n        '0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1\n      ],\n      // yNum\n      [\n        '0x4bda12f684bda12f684bda12f684bda12f684bda12f684bda12f684b8e38e23c',\n        '0xc75e0c32d5cb7c0fa9d0a54b12a0a6d5647ab046d686da6fdffc90fc201d71a3',\n        '0x29a6194691f91a73715209ef6512e576722830a201be2018a765e85a9ecee931',\n        '0x2f684bda12f684bda12f684bda12f684bda12f684bda12f684bda12f38e38d84',\n      ],\n      // yDen\n      [\n        '0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffff93b',\n        '0x7a06534bb8bdb49fd5e9e6632722c2989467c1bfc8e8d978dfb425d2685c2573',\n        '0x6484aa716545ca2cf3a70c3fa8fe337e0a3d21162f0d6299a7bf8192bfd2a76f',\n        '0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1\n      ],\n    ].map((i) => i.map((j) => BigInt(j))) as [bigint[], bigint[], bigint[], bigint[]]\n  ))();\nconst mapSWU = /* @__PURE__ */ (() =>\n  mapToCurveSimpleSWU(Fp, {\n    A: BigInt('0x3f8731abdd661adca08a5558f0f5d272e953d363cb6f0e5d405447c01a444533'),\n    B: BigInt('1771'),\n    Z: Fp.create(BigInt('-11')),\n  }))();\nconst htf = /* @__PURE__ */ (() =>\n  createHasher(\n    secp256k1.ProjectivePoint,\n    (scalars: bigint[]) => {\n      const { x, y } = mapSWU(Fp.create(scalars[0]));\n      return isoMap(x, y);\n    },\n    {\n      DST: 'secp256k1_XMD:SHA-256_SSWU_RO_',\n      encodeDST: 'secp256k1_XMD:SHA-256_SSWU_NU_',\n      p: Fp.ORDER,\n      m: 1,\n      k: 128,\n      expand: 'xmd',\n      hash: sha256,\n    }\n  ))();\nexport const hashToCurve = /* @__PURE__ */ (() => htf.hashToCurve)();\nexport const encodeToCurve = /* @__PURE__ */ (() => htf.encodeToCurve)();\n","import type { Chain, ChainConfig, ChainFormatters } from '../../types/chain.js'\nimport type { Assign } from '../../types/utils.js'\n\nexport function defineChain<\n  const chain extends Chain,\n  formatters extends ChainFormatters | undefined = undefined,\n>(\n  chain: chain,\n  config: ChainConfig<formatters> = {},\n): Assign<chain, ChainConfig<formatters>> {\n  const {\n    fees = chain.fees,\n    formatters = chain.formatters,\n    serializers = chain.serializers,\n  } = config\n  return {\n    ...chain,\n    fees,\n    formatters,\n    serializers,\n  } as unknown as Assign<chain, ChainConfig<formatters>>\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { BlockTag } from '../../types/block.js'\nimport type { Chain } from '../../types/chain.js'\nimport type {\n  ExtractChainFormatterExclude,\n  ExtractChainFormatterReturnType,\n} from '../../types/chain.js'\nimport type { RpcTransaction } from '../../types/rpc.js'\nimport type { Transaction } from '../../types/transaction.js'\nimport type { UnionOmit } from '../../types/utils.js'\nimport { hexToNumber } from '../encoding/fromHex.js'\nimport { type DefineFormatterErrorType, defineFormatter } from './formatter.js'\n\ntype TransactionPendingDependencies =\n  | 'blockHash'\n  | 'blockNumber'\n  | 'transactionIndex'\n\nexport type FormattedTransaction<\n  TChain extends { formatters?: Chain['formatters'] } | undefined =\n    | { formatters?: Chain['formatters'] }\n    | undefined,\n  TBlockTag extends BlockTag = BlockTag,\n  _FormatterReturnType = ExtractChainFormatterReturnType<\n    TChain,\n    'transaction',\n    Transaction\n  >,\n  _ExcludedPendingDependencies extends string = TransactionPendingDependencies &\n    ExtractChainFormatterExclude<TChain, 'transaction'>,\n> = UnionOmit<_FormatterReturnType, TransactionPendingDependencies> & {\n  [_key in _ExcludedPendingDependencies]: never\n} & Pick<\n    Transaction<bigint, number, TBlockTag extends 'pending' ? true : false>,\n    TransactionPendingDependencies\n  >\n\nexport const transactionType = {\n  '0x0': 'legacy',\n  '0x1': 'eip2930',\n  '0x2': 'eip1559',\n} as const\n\nexport type FormatTransactionErrorType = ErrorType\n\nexport function formatTransaction(transaction: Partial<RpcTransaction>) {\n  const transaction_ = {\n    ...transaction,\n    blockHash: transaction.blockHash ? transaction.blockHash : null,\n    blockNumber: transaction.blockNumber\n      ? BigInt(transaction.blockNumber)\n      : null,\n    chainId: transaction.chainId ? hexToNumber(transaction.chainId) : undefined,\n    gas: transaction.gas ? BigInt(transaction.gas) : undefined,\n    gasPrice: transaction.gasPrice ? BigInt(transaction.gasPrice) : undefined,\n    maxFeePerGas: transaction.maxFeePerGas\n      ? BigInt(transaction.maxFeePerGas)\n      : undefined,\n    maxPriorityFeePerGas: transaction.maxPriorityFeePerGas\n      ? BigInt(transaction.maxPriorityFeePerGas)\n      : undefined,\n    nonce: transaction.nonce ? hexToNumber(transaction.nonce) : undefined,\n    to: transaction.to ? transaction.to : null,\n    transactionIndex: transaction.transactionIndex\n      ? Number(transaction.transactionIndex)\n      : null,\n    type: transaction.type ? transactionType[transaction.type] : undefined,\n    typeHex: transaction.type ? transaction.type : undefined,\n    value: transaction.value ? BigInt(transaction.value) : undefined,\n    v: transaction.v ? BigInt(transaction.v) : undefined,\n  } as Transaction\n\n  transaction_.yParity = (() => {\n    // If `yParity` is provided, we will use it.\n    if (transaction.yParity) return Number(transaction.yParity)\n\n    // If no `yParity` provided, try derive from `v`.\n    if (typeof transaction_.v === 'bigint') {\n      if (transaction_.v === 0n || transaction_.v === 27n) return 0\n      if (transaction_.v === 1n || transaction_.v === 28n) return 1\n      if (transaction_.v >= 35n) return transaction_.v % 2n === 0n ? 1 : 0\n    }\n\n    return undefined\n  })()\n\n  if (transaction_.type === 'legacy') {\n    delete transaction_.accessList\n    delete transaction_.maxFeePerGas\n    delete transaction_.maxPriorityFeePerGas\n    delete transaction_.yParity\n  }\n  if (transaction_.type === 'eip2930') {\n    delete transaction_.maxFeePerGas\n    delete transaction_.maxPriorityFeePerGas\n  }\n  return transaction_\n}\n\nexport type DefineTransactionErrorType = DefineFormatterErrorType | ErrorType\n\nexport const defineTransaction = /*#__PURE__*/ defineFormatter(\n  'transaction',\n  formatTransaction,\n)\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { Block, BlockTag } from '../../types/block.js'\nimport type { Chain } from '../../types/chain.js'\nimport type {\n  ExtractChainFormatterExclude,\n  ExtractChainFormatterReturnType,\n} from '../../types/chain.js'\nimport type { Hash } from '../../types/misc.js'\nimport type { RpcBlock } from '../../types/rpc.js'\nimport type { Prettify } from '../../types/utils.js'\n\nimport { type DefineFormatterErrorType, defineFormatter } from './formatter.js'\nimport { type FormattedTransaction, formatTransaction } from './transaction.js'\n\ntype BlockPendingDependencies = 'hash' | 'logsBloom' | 'nonce' | 'number'\n\nexport type FormattedBlock<\n  TChain extends { formatters?: Chain['formatters'] } | undefined =\n    | { formatters?: Chain['formatters'] }\n    | undefined,\n  TIncludeTransactions extends boolean = boolean,\n  TBlockTag extends BlockTag = BlockTag,\n  _FormatterReturnType = ExtractChainFormatterReturnType<\n    TChain,\n    'block',\n    Block<bigint, TIncludeTransactions>\n  >,\n  _ExcludedPendingDependencies extends string = BlockPendingDependencies &\n    ExtractChainFormatterExclude<TChain, 'block'>,\n  _Formatted = Omit<_FormatterReturnType, BlockPendingDependencies> & {\n    [_key in _ExcludedPendingDependencies]: never\n  } & Pick<\n      Block<bigint, TIncludeTransactions, TBlockTag>,\n      BlockPendingDependencies\n    >,\n  _Transactions = TIncludeTransactions extends true\n    ? Prettify<FormattedTransaction<TChain, TBlockTag>>[]\n    : Hash[],\n> = Omit<_Formatted, 'transactions'> & {\n  transactions: _Transactions\n}\n\nexport type FormatBlockErrorType = ErrorType\n\nexport function formatBlock(block: Partial<RpcBlock>) {\n  const transactions = block.transactions?.map((transaction) => {\n    if (typeof transaction === 'string') return transaction\n    return formatTransaction(transaction)\n  })\n  return {\n    ...block,\n    baseFeePerGas: block.baseFeePerGas ? BigInt(block.baseFeePerGas) : null,\n    difficulty: block.difficulty ? BigInt(block.difficulty) : undefined,\n    gasLimit: block.gasLimit ? BigInt(block.gasLimit) : undefined,\n    gasUsed: block.gasUsed ? BigInt(block.gasUsed) : undefined,\n    hash: block.hash ? block.hash : null,\n    logsBloom: block.logsBloom ? block.logsBloom : null,\n    nonce: block.nonce ? block.nonce : null,\n    number: block.number ? BigInt(block.number) : null,\n    size: block.size ? BigInt(block.size) : undefined,\n    timestamp: block.timestamp ? BigInt(block.timestamp) : undefined,\n    transactions,\n    totalDifficulty: block.totalDifficulty\n      ? BigInt(block.totalDifficulty)\n      : null,\n  } as Block\n}\n\nexport type DefineBlockErrorType = DefineFormatterErrorType | ErrorType\n\nexport const defineBlock = /*#__PURE__*/ defineFormatter('block', formatBlock)\n","import type { ErrorType } from '../../errors/utils.js'\nimport type {\n  Chain,\n  ExtractChainFormatterReturnType,\n} from '../../types/chain.js'\nimport type { RpcTransactionReceipt } from '../../types/rpc.js'\nimport type { TransactionReceipt } from '../../types/transaction.js'\nimport { hexToNumber } from '../encoding/fromHex.js'\n\nimport { type DefineFormatterErrorType, defineFormatter } from './formatter.js'\nimport { formatLog } from './log.js'\nimport { transactionType } from './transaction.js'\n\nexport type FormattedTransactionReceipt<\n  TChain extends Chain | undefined = Chain | undefined,\n> = ExtractChainFormatterReturnType<\n  TChain,\n  'transactionReceipt',\n  TransactionReceipt\n>\n\nconst statuses = {\n  '0x0': 'reverted',\n  '0x1': 'success',\n} as const\n\nexport type FormatTransactionReceiptErrorType = ErrorType\n\nexport function formatTransactionReceipt(\n  transactionReceipt: Partial<RpcTransactionReceipt>,\n) {\n  return {\n    ...transactionReceipt,\n    blockNumber: transactionReceipt.blockNumber\n      ? BigInt(transactionReceipt.blockNumber)\n      : null,\n    contractAddress: transactionReceipt.contractAddress\n      ? transactionReceipt.contractAddress\n      : null,\n    cumulativeGasUsed: transactionReceipt.cumulativeGasUsed\n      ? BigInt(transactionReceipt.cumulativeGasUsed)\n      : null,\n    effectiveGasPrice: transactionReceipt.effectiveGasPrice\n      ? BigInt(transactionReceipt.effectiveGasPrice)\n      : null,\n    gasUsed: transactionReceipt.gasUsed\n      ? BigInt(transactionReceipt.gasUsed)\n      : null,\n    logs: transactionReceipt.logs\n      ? transactionReceipt.logs.map((log) => formatLog(log))\n      : null,\n    to: transactionReceipt.to ? transactionReceipt.to : null,\n    transactionIndex: transactionReceipt.transactionIndex\n      ? hexToNumber(transactionReceipt.transactionIndex)\n      : null,\n    status: transactionReceipt.status\n      ? statuses[transactionReceipt.status]\n      : null,\n    type: transactionReceipt.type\n      ? transactionType[\n          transactionReceipt.type as keyof typeof transactionType\n        ] || transactionReceipt.type\n      : null,\n  } as TransactionReceipt\n}\n\nexport type DefineTransactionReceiptErrorType =\n  | DefineFormatterErrorType\n  | ErrorType\n\nexport const defineTransactionReceipt = /*#__PURE__*/ defineFormatter(\n  'transactionReceipt',\n  formatTransactionReceipt,\n)\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { Log } from '../../types/log.js'\nimport type { RpcLog } from '../../types/rpc.js'\n\nexport type FormatLogErrorType = ErrorType\n\nexport function formatLog(\n  log: Partial<RpcLog>,\n  { args, eventName }: { args?: unknown; eventName?: string } = {},\n) {\n  return {\n    ...log,\n    blockHash: log.blockHash ? log.blockHash : null,\n    blockNumber: log.blockNumber ? BigInt(log.blockNumber) : null,\n    logIndex: log.logIndex ? Number(log.logIndex) : null,\n    transactionHash: log.transactionHash ? log.transactionHash : null,\n    transactionIndex: log.transactionIndex\n      ? Number(log.transactionIndex)\n      : null,\n    ...(eventName ? { args, eventName } : {}),\n  } as Log\n}\n","export {\n  type Abi,\n  type Address,\n  type Narrow,\n  type ParseAbi,\n  type ParseAbiItem,\n  type ParseAbiParameter,\n  type ParseAbiParameters,\n  type ResolvedConfig,\n  type TypedData,\n  type TypedDataDomain,\n  type TypedDataParameter,\n  CircularReferenceError,\n  InvalidAbiParameterError,\n  InvalidAbiParametersError,\n  InvalidAbiItemError,\n  InvalidAbiTypeParameterError,\n  InvalidFunctionModifierError,\n  InvalidModifierError,\n  InvalidParameterError,\n  InvalidParenthesisError,\n  InvalidSignatureError,\n  InvalidStructSignatureError,\n  SolidityProtectedKeywordError,\n  UnknownTypeError,\n  UnknownSignatureError,\n  parseAbi,\n  parseAbiItem,\n  parseAbiParameter,\n  parseAbiParameters,\n} from 'abitype'\n\nexport {\n  getContract,\n  type GetContractErrorType,\n  type GetContractParameters,\n  type GetContractReturnType,\n} from './actions/getContract.js'\nexport {\n  type AddChainErrorType,\n  type AddChainParameters,\n} from './actions/wallet/addChain.js'\nexport {\n  type CallErrorType,\n  type CallParameters,\n  type CallReturnType,\n} from './actions/public/call.js'\nexport type {\n  CreateBlockFilterErrorType,\n  CreateBlockFilterReturnType,\n} from './actions/public/createBlockFilter.js'\nexport type {\n  CreateContractEventFilterErrorType,\n  CreateContractEventFilterParameters,\n  CreateContractEventFilterReturnType,\n} from './actions/public/createContractEventFilter.js'\nexport type {\n  CreateEventFilterErrorType,\n  CreateEventFilterParameters,\n  CreateEventFilterReturnType,\n} from './actions/public/createEventFilter.js'\nexport type {\n  CreatePendingTransactionFilterErrorType,\n  CreatePendingTransactionFilterReturnType,\n} from './actions/public/createPendingTransactionFilter.js'\nexport type {\n  DeployContractErrorType,\n  DeployContractParameters,\n  DeployContractReturnType,\n} from './actions/wallet/deployContract.js'\nexport type {\n  DropTransactionErrorType,\n  DropTransactionParameters,\n} from './actions/test/dropTransaction.js'\nexport type {\n  GetAutomineErrorType,\n  GetAutomineReturnType,\n} from './actions/test/getAutomine.js'\nexport type {\n  EstimateContractGasErrorType,\n  EstimateContractGasParameters,\n  EstimateContractGasReturnType,\n} from './actions/public/estimateContractGas.js'\nexport type {\n  EstimateGasErrorType,\n  EstimateGasParameters,\n  EstimateGasReturnType,\n} from './actions/public/estimateGas.js'\nexport type {\n  EstimateFeesPerGasErrorType,\n  EstimateFeesPerGasParameters,\n  EstimateFeesPerGasReturnType,\n} from './actions/public/estimateFeesPerGas.js'\nexport type {\n  EstimateMaxPriorityFeePerGasErrorType,\n  EstimateMaxPriorityFeePerGasParameters,\n  EstimateMaxPriorityFeePerGasReturnType,\n} from './actions/public/estimateMaxPriorityFeePerGas.js'\nexport type {\n  GetAddressesErrorType,\n  GetAddressesReturnType,\n} from './actions/wallet/getAddresses.js'\nexport type {\n  GetBalanceErrorType,\n  GetBalanceParameters,\n  GetBalanceReturnType,\n} from './actions/public/getBalance.js'\nexport type {\n  GetBlockNumberErrorType,\n  GetBlockNumberParameters,\n  GetBlockNumberReturnType,\n} from './actions/public/getBlockNumber.js'\nexport type {\n  GetBlockErrorType,\n  GetBlockParameters,\n  GetBlockReturnType,\n} from './actions/public/getBlock.js'\nexport type {\n  GetBlockTransactionCountErrorType,\n  GetBlockTransactionCountParameters,\n  GetBlockTransactionCountReturnType,\n} from './actions/public/getBlockTransactionCount.js'\nexport type {\n  GetBytecodeErrorType,\n  GetBytecodeParameters,\n  GetBytecodeReturnType,\n} from './actions/public/getBytecode.js'\nexport type {\n  GetChainIdErrorType,\n  GetChainIdReturnType,\n} from './actions/public/getChainId.js'\nexport type {\n  GetEnsAddressErrorType,\n  GetEnsAddressParameters,\n  GetEnsAddressReturnType,\n} from './actions/ens/getEnsAddress.js'\nexport type {\n  GetEnsNameErrorType,\n  GetEnsNameParameters,\n  GetEnsNameReturnType,\n} from './actions/ens/getEnsName.js'\nexport type {\n  GetEnsResolverErrorType,\n  GetEnsResolverParameters,\n  GetEnsResolverReturnType,\n} from './actions/ens/getEnsResolver.js'\nexport type {\n  GetFeeHistoryErrorType,\n  GetFeeHistoryParameters,\n  GetFeeHistoryReturnType,\n} from './actions/public/getFeeHistory.js'\nexport type {\n  GetFilterChangesErrorType,\n  GetFilterChangesParameters,\n  GetFilterChangesReturnType,\n} from './actions/public/getFilterChanges.js'\nexport type {\n  GetFilterLogsErrorType,\n  GetFilterLogsParameters,\n  GetFilterLogsReturnType,\n} from './actions/public/getFilterLogs.js'\nexport type {\n  GetGasPriceErrorType,\n  GetGasPriceReturnType,\n} from './actions/public/getGasPrice.js'\nexport type {\n  GetLogsErrorType,\n  GetLogsParameters,\n  GetLogsReturnType,\n} from './actions/public/getLogs.js'\nexport type {\n  GetPermissionsErrorType,\n  GetPermissionsReturnType,\n} from './actions/wallet/getPermissions.js'\nexport type {\n  GetStorageAtErrorType,\n  GetStorageAtParameters,\n  GetStorageAtReturnType,\n} from './actions/public/getStorageAt.js'\nexport type {\n  GetTransactionConfirmationsErrorType,\n  GetTransactionConfirmationsParameters,\n  GetTransactionConfirmationsReturnType,\n} from './actions/public/getTransactionConfirmations.js'\nexport type {\n  GetTransactionCountErrorType,\n  GetTransactionCountParameters,\n  GetTransactionCountReturnType,\n} from './actions/public/getTransactionCount.js'\nexport type {\n  GetTransactionErrorType,\n  GetTransactionParameters,\n  GetTransactionReturnType,\n} from './actions/public/getTransaction.js'\nexport type {\n  GetTransactionReceiptErrorType,\n  GetTransactionReceiptParameters,\n  GetTransactionReceiptReturnType,\n} from './actions/public/getTransactionReceipt.js'\nexport type {\n  ImpersonateAccountErrorType,\n  ImpersonateAccountParameters,\n} from './actions/test/impersonateAccount.js'\nexport type {\n  IncreaseTimeErrorType,\n  IncreaseTimeParameters,\n} from './actions/test/increaseTime.js'\nexport type { MineErrorType, MineParameters } from './actions/test/mine.js'\nexport type {\n  MulticallErrorType,\n  MulticallParameters,\n  MulticallReturnType,\n} from './actions/public/multicall.js'\nexport type {\n  OnBlock,\n  OnBlockParameter,\n  WatchBlocksErrorType,\n  WatchBlocksParameters,\n  WatchBlocksReturnType,\n} from './actions/public/watchBlocks.js'\nexport type {\n  OnBlockNumberFn,\n  OnBlockNumberParameter,\n  WatchBlockNumberErrorType,\n  WatchBlockNumberParameters,\n  WatchBlockNumberReturnType,\n} from './actions/public/watchBlockNumber.js'\nexport type {\n  WatchEventOnLogsFn,\n  /** @deprecated - use `WatchEventOnLogsFn` instead. */\n  WatchEventOnLogsFn as OnLogFn,\n  WatchEventOnLogsParameter,\n  /** @deprecated - use `WatchEventOnLogsParameter` instead. */\n  WatchEventOnLogsParameter as OnLogParameter,\n  WatchEventErrorType,\n  WatchEventParameters,\n  WatchEventReturnType,\n} from './actions/public/watchEvent.js'\nexport type {\n  OnTransactionsFn,\n  OnTransactionsParameter,\n  WatchPendingTransactionsErrorType,\n  WatchPendingTransactionsParameters,\n  WatchPendingTransactionsReturnType,\n} from './actions/public/watchPendingTransactions.js'\nexport type {\n  ReadContractErrorType,\n  ReadContractParameters,\n  ReadContractReturnType,\n} from './actions/public/readContract.js'\nexport type {\n  ReplacementReason,\n  ReplacementReturnType,\n  WaitForTransactionReceiptErrorType,\n  WaitForTransactionReceiptParameters,\n  WaitForTransactionReceiptReturnType,\n} from './actions/public/waitForTransactionReceipt.js'\nexport type {\n  RequestAddressesErrorType,\n  RequestAddressesReturnType,\n} from './actions/wallet/requestAddresses.js'\nexport type {\n  RequestPermissionsErrorType,\n  RequestPermissionsReturnType,\n  RequestPermissionsParameters,\n} from './actions/wallet/requestPermissions.js'\nexport type {\n  GetTxpoolContentErrorType,\n  GetTxpoolContentReturnType,\n} from './actions/test/getTxpoolContent.js'\nexport type {\n  GetTxpoolStatusErrorType,\n  GetTxpoolStatusReturnType,\n} from './actions/test/getTxpoolStatus.js'\nexport type {\n  InspectTxpoolErrorType,\n  InspectTxpoolReturnType,\n} from './actions/test/inspectTxpool.js'\nexport type { ResetErrorType, ResetParameters } from './actions/test/reset.js'\nexport type {\n  RevertErrorType,\n  RevertParameters,\n} from './actions/test/revert.js'\nexport type {\n  SendTransactionErrorType,\n  SendTransactionParameters,\n  SendTransactionReturnType,\n} from './actions/wallet/sendTransaction.js'\nexport type {\n  PrepareTransactionRequestErrorType,\n  PrepareTransactionRequestParameters,\n  PrepareTransactionRequestReturnType,\n  /** @deprecated import `prepareTransactionRequest` from `viem/actions` instead. */\n  prepareTransactionRequest as prepareRequest,\n} from './actions/wallet/prepareTransactionRequest.js'\nexport type {\n  SendUnsignedTransactionErrorType,\n  SendUnsignedTransactionParameters,\n  SendUnsignedTransactionReturnType,\n} from './actions/test/sendUnsignedTransaction.js'\nexport type {\n  SetBalanceErrorType,\n  SetBalanceParameters,\n} from './actions/test/setBalance.js'\nexport type {\n  SetBlockGasLimitErrorType,\n  SetBlockGasLimitParameters,\n} from './actions/test/setBlockGasLimit.js'\nexport type {\n  SetBlockTimestampIntervalErrorType,\n  SetBlockTimestampIntervalParameters,\n} from './actions/test/setBlockTimestampInterval.js'\nexport type {\n  SetCodeErrorType,\n  SetCodeParameters,\n} from './actions/test/setCode.js'\nexport type {\n  SetCoinbaseErrorType,\n  SetCoinbaseParameters,\n} from './actions/test/setCoinbase.js'\nexport type {\n  SetIntervalMiningErrorType,\n  SetIntervalMiningParameters,\n} from './actions/test/setIntervalMining.js'\nexport type {\n  SetMinGasPriceErrorType,\n  SetMinGasPriceParameters,\n} from './actions/test/setMinGasPrice.js'\nexport type {\n  SetNextBlockBaseFeePerGasErrorType,\n  SetNextBlockBaseFeePerGasParameters,\n} from './actions/test/setNextBlockBaseFeePerGas.js'\nexport type {\n  SetNextBlockTimestampErrorType,\n  SetNextBlockTimestampParameters,\n} from './actions/test/setNextBlockTimestamp.js'\nexport type {\n  SetNonceErrorType,\n  SetNonceParameters,\n} from './actions/test/setNonce.js'\nexport type {\n  SetStorageAtErrorType,\n  SetStorageAtParameters,\n} from './actions/test/setStorageAt.js'\nexport type {\n  SignMessageErrorType,\n  SignMessageParameters,\n  SignMessageReturnType,\n} from './actions/wallet/signMessage.js'\nexport type {\n  SignTypedDataErrorType,\n  SignTypedDataParameters,\n  SignTypedDataReturnType,\n} from './actions/wallet/signTypedData.js'\nexport type {\n  SimulateContractErrorType,\n  SimulateContractParameters,\n  SimulateContractReturnType,\n} from './actions/public/simulateContract.js'\nexport type {\n  StopImpersonatingAccountErrorType,\n  StopImpersonatingAccountParameters,\n} from './actions/test/stopImpersonatingAccount.js'\nexport type {\n  SwitchChainErrorType,\n  SwitchChainParameters,\n} from './actions/wallet/switchChain.js'\nexport type {\n  UninstallFilterErrorType,\n  UninstallFilterParameters,\n  UninstallFilterReturnType,\n} from './actions/public/uninstallFilter.js'\nexport type {\n  WatchAssetErrorType,\n  WatchAssetParameters,\n  WatchAssetReturnType,\n} from './actions/wallet/watchAsset.js'\nexport type {\n  VerifyHashErrorType,\n  VerifyHashParameters,\n  VerifyHashReturnType,\n} from './actions/public/verifyHash.js'\nexport type {\n  WatchContractEventOnLogsParameter,\n  WatchContractEventErrorType,\n  WatchContractEventParameters,\n  WatchContractEventReturnType,\n} from './actions/public/watchContractEvent.js'\nexport type {\n  WriteContractErrorType,\n  WriteContractParameters,\n  WriteContractReturnType,\n} from './actions/wallet/writeContract.js'\nexport type {\n  Chain,\n  ChainContract,\n  ChainFees,\n  ChainFormatter,\n  /** @deprecated use `ChainFormatter` instead. */\n  ChainFormatter as Formatter,\n  ChainFormatters,\n  /** @deprecated use `ChainFormatters` instead. */\n  ChainFormatters as Formatters,\n  ChainSerializers,\n  /** @deprecated use `ChainSerializers` instead. */\n  ChainSerializers as Serializers,\n  ExtractChainFormatterExclude,\n  /** @deprecated use `ExtractChainFormatterExclude` instead. */\n  ExtractChainFormatterExclude as ExtractFormatterExclude,\n  ExtractChainFormatterParameters,\n  /** @deprecated use `ExtractChainFormatterParameters` instead. */\n  ExtractChainFormatterParameters as ExtractFormatterParameters,\n  ExtractChainFormatterReturnType,\n  /** @deprecated use `ExtractChainFormatterReturnType` instead. */\n  ExtractChainFormatterReturnType as ExtractFormatterReturnType,\n} from './types/chain.js'\nexport {\n  type Client,\n  type ClientConfig,\n  type CreateClientErrorType,\n  type MulticallBatchOptions,\n  createClient,\n} from './clients/createClient.js'\nexport {\n  type CustomTransport,\n  type CustomTransportConfig,\n  type CustomTransportErrorType,\n  custom,\n} from './clients/transports/custom.js'\nexport {\n  type FallbackTransport,\n  type FallbackTransportConfig,\n  type FallbackTransportErrorType,\n  fallback,\n} from './clients/transports/fallback.js'\nexport {\n  type HttpTransport,\n  type HttpTransportConfig,\n  type HttpTransportErrorType,\n  http,\n} from './clients/transports/http.js'\nexport {\n  type PublicClient,\n  type PublicClientConfig,\n  type CreatePublicClientErrorType,\n  createPublicClient,\n} from './clients/createPublicClient.js'\nexport {\n  type TestClient,\n  type TestClientConfig,\n  type CreateTestClientErrorType,\n  createTestClient,\n} from './clients/createTestClient.js'\nexport {\n  type PublicActions,\n  publicActions,\n} from './clients/decorators/public.js'\nexport {\n  type TestActions,\n  testActions,\n} from './clients/decorators/test.js'\nexport {\n  type WalletActions,\n  walletActions,\n} from './clients/decorators/wallet.js'\nexport {\n  type Transport,\n  type TransportConfig,\n  type CreateTransportErrorType,\n  createTransport,\n} from './clients/transports/createTransport.js'\nexport {\n  type WalletClient,\n  type WalletClientConfig,\n  type CreateWalletClientErrorType,\n  createWalletClient,\n} from './clients/createWalletClient.js'\nexport {\n  type WebSocketTransport,\n  type WebSocketTransportConfig,\n  type WebSocketTransportErrorType,\n  webSocket,\n} from './clients/transports/webSocket.js'\nexport { multicall3Abi } from './constants/abis.js'\nexport { zeroAddress } from './constants/address.js'\nexport { etherUnits, gweiUnits, weiUnits } from './constants/unit.js'\nexport {\n  maxInt8,\n  maxInt16,\n  maxInt24,\n  maxInt32,\n  maxInt40,\n  maxInt48,\n  maxInt56,\n  maxInt64,\n  maxInt72,\n  maxInt80,\n  maxInt88,\n  maxInt96,\n  maxInt104,\n  maxInt112,\n  maxInt120,\n  maxInt128,\n  maxInt136,\n  maxInt144,\n  maxInt152,\n  maxInt160,\n  maxInt168,\n  maxInt176,\n  maxInt184,\n  maxInt192,\n  maxInt200,\n  maxInt208,\n  maxInt216,\n  maxInt224,\n  maxInt232,\n  maxInt240,\n  maxInt248,\n  maxInt256,\n  maxUint8,\n  maxUint16,\n  maxUint24,\n  maxUint32,\n  maxUint40,\n  maxUint48,\n  maxUint56,\n  maxUint64,\n  maxUint72,\n  maxUint80,\n  maxUint88,\n  maxUint96,\n  maxUint104,\n  maxUint112,\n  maxUint120,\n  maxUint128,\n  maxUint136,\n  maxUint144,\n  maxUint152,\n  maxUint160,\n  maxUint168,\n  maxUint176,\n  maxUint184,\n  maxUint192,\n  maxUint200,\n  maxUint208,\n  maxUint216,\n  maxUint224,\n  maxUint232,\n  maxUint240,\n  maxUint248,\n  maxUint256,\n  minInt8,\n  minInt16,\n  minInt24,\n  minInt32,\n  minInt40,\n  minInt48,\n  minInt56,\n  minInt64,\n  minInt72,\n  minInt80,\n  minInt88,\n  minInt96,\n  minInt104,\n  minInt112,\n  minInt120,\n  minInt128,\n  minInt136,\n  minInt144,\n  minInt152,\n  minInt160,\n  minInt168,\n  minInt176,\n  minInt184,\n  minInt192,\n  minInt200,\n  minInt208,\n  minInt216,\n  minInt224,\n  minInt232,\n  minInt240,\n  minInt248,\n  minInt256,\n} from './constants/number.js'\nexport { zeroHash } from './constants/bytes.js'\nexport { presignMessagePrefix } from './constants/strings.js'\nexport {\n  AbiConstructorNotFoundError,\n  type AbiConstructorNotFoundErrorType,\n  AbiConstructorParamsNotFoundError,\n  type AbiConstructorParamsNotFoundErrorType,\n  AbiDecodingDataSizeInvalidError,\n  type AbiDecodingDataSizeInvalidErrorType,\n  AbiDecodingDataSizeTooSmallError,\n  type AbiDecodingDataSizeTooSmallErrorType,\n  AbiDecodingZeroDataError,\n  type AbiDecodingZeroDataErrorType,\n  AbiEncodingArrayLengthMismatchError,\n  type AbiEncodingArrayLengthMismatchErrorType,\n  AbiEncodingLengthMismatchError,\n  type AbiEncodingLengthMismatchErrorType,\n  AbiEncodingBytesSizeMismatchError,\n  type AbiEncodingBytesSizeMismatchErrorType,\n  AbiErrorInputsNotFoundError,\n  type AbiErrorInputsNotFoundErrorType,\n  AbiErrorNotFoundError,\n  type AbiErrorNotFoundErrorType,\n  AbiErrorSignatureNotFoundError,\n  type AbiErrorSignatureNotFoundErrorType,\n  AbiEventNotFoundError,\n  type AbiEventNotFoundErrorType,\n  AbiEventSignatureEmptyTopicsError,\n  type AbiEventSignatureEmptyTopicsErrorType,\n  AbiEventSignatureNotFoundError,\n  type AbiEventSignatureNotFoundErrorType,\n  AbiFunctionNotFoundError,\n  type AbiFunctionNotFoundErrorType,\n  AbiFunctionOutputsNotFoundError,\n  type AbiFunctionOutputsNotFoundErrorType,\n  AbiFunctionSignatureNotFoundError,\n  type AbiFunctionSignatureNotFoundErrorType,\n  BytesSizeMismatchError,\n  type BytesSizeMismatchErrorType,\n  DecodeLogDataMismatch,\n  type DecodeLogDataMismatchErrorType,\n  DecodeLogTopicsMismatch,\n  type DecodeLogTopicsMismatchErrorType,\n  InvalidAbiDecodingTypeError,\n  type InvalidAbiDecodingTypeErrorType,\n  InvalidAbiEncodingTypeError,\n  type InvalidAbiEncodingTypeErrorType,\n  InvalidArrayError,\n  type InvalidArrayErrorType,\n  InvalidDefinitionTypeError,\n  type InvalidDefinitionTypeErrorType,\n  UnsupportedPackedAbiType,\n  type UnsupportedPackedAbiTypeErrorType,\n} from './errors/abi.js'\nexport { BaseError, type BaseErrorType } from './errors/base.js'\nexport {\n  BlockNotFoundError,\n  type BlockNotFoundErrorType,\n} from './errors/block.js'\nexport {\n  CallExecutionError,\n  type CallExecutionErrorType,\n  ContractFunctionExecutionError,\n  type ContractFunctionExecutionErrorType,\n  ContractFunctionRevertedError,\n  type ContractFunctionRevertedErrorType,\n  ContractFunctionZeroDataError,\n  type ContractFunctionZeroDataErrorType,\n  RawContractError,\n  type RawContractErrorType,\n} from './errors/contract.js'\nexport {\n  BaseFeeScalarError,\n  type BaseFeeScalarErrorType,\n  Eip1559FeesNotSupportedError,\n  type Eip1559FeesNotSupportedErrorType,\n  MaxFeePerGasTooLowError,\n  type MaxFeePerGasTooLowErrorType,\n} from './errors/fee.js'\nexport {\n  ChainDisconnectedError,\n  type ChainDisconnectedErrorType,\n  InternalRpcError,\n  type InternalRpcErrorType,\n  InvalidInputRpcError,\n  type InvalidInputRpcErrorType,\n  InvalidParamsRpcError,\n  type InvalidParamsRpcErrorType,\n  InvalidRequestRpcError,\n  type InvalidRequestRpcErrorType,\n  JsonRpcVersionUnsupportedError,\n  type JsonRpcVersionUnsupportedErrorType,\n  LimitExceededRpcError,\n  type LimitExceededRpcErrorType,\n  MethodNotFoundRpcError,\n  type MethodNotFoundRpcErrorType,\n  MethodNotSupportedRpcError,\n  type MethodNotSupportedRpcErrorType,\n  ParseRpcError,\n  type ParseRpcErrorType,\n  ProviderDisconnectedError,\n  type ProviderDisconnectedErrorType,\n  ProviderRpcError,\n  type ProviderRpcErrorCode,\n  type ProviderRpcErrorType,\n  ResourceNotFoundRpcError,\n  type ResourceNotFoundRpcErrorType,\n  ResourceUnavailableRpcError,\n  type ResourceUnavailableRpcErrorType,\n  RpcError,\n  type RpcErrorType,\n  type RpcErrorCode,\n  SwitchChainError,\n  TransactionRejectedRpcError,\n  type TransactionRejectedRpcErrorType,\n  UnauthorizedProviderError,\n  type UnauthorizedProviderErrorType,\n  UnknownRpcError,\n  type UnknownRpcErrorType,\n  UnsupportedProviderMethodError,\n  type UnsupportedProviderMethodErrorType,\n  UserRejectedRequestError,\n  type UserRejectedRequestErrorType,\n} from './errors/rpc.js'\nexport {\n  ChainDoesNotSupportContract,\n  type ChainDoesNotSupportContractErrorType,\n  ChainMismatchError,\n  type ChainMismatchErrorType,\n  ChainNotFoundError,\n  type ChainNotFoundErrorType,\n  ClientChainNotConfiguredError,\n  type ClientChainNotConfiguredErrorType,\n  InvalidChainIdError,\n  type InvalidChainIdErrorType,\n} from './errors/chain.js'\nexport {\n  DataLengthTooLongError,\n  type DataLengthTooLongErrorType,\n  DataLengthTooShortError,\n  type DataLengthTooShortErrorType,\n  InvalidBytesBooleanError,\n  type InvalidBytesBooleanErrorType,\n  IntegerOutOfRangeError,\n  type IntegerOutOfRangeErrorType,\n  InvalidHexBooleanError,\n  type InvalidHexBooleanErrorType,\n  InvalidHexValueError,\n  type InvalidHexValueErrorType,\n  OffsetOutOfBoundsError,\n  type OffsetOutOfBoundsErrorType,\n  SizeOverflowError,\n  type SizeOverflowErrorType,\n} from './errors/encoding.js'\nexport {\n  type EnsAvatarInvalidMetadataError,\n  EnsAvatarUriResolutionError,\n  type EnsAvatarInvalidMetadataErrorType,\n  EnsAvatarInvalidNftUriError,\n  type EnsAvatarInvalidNftUriErrorType,\n  EnsAvatarUnsupportedNamespaceError,\n  type EnsAvatarUnsupportedNamespaceErrorType,\n  type EnsAvatarUriResolutionErrorType,\n} from './errors/ens.js'\nexport {\n  EstimateGasExecutionError,\n  type EstimateGasExecutionErrorType,\n} from './errors/estimateGas.js'\nexport {\n  ExecutionRevertedError,\n  type ExecutionRevertedErrorType,\n  FeeCapTooHighError,\n  type FeeCapTooHighErrorType,\n  FeeCapTooLowError,\n  type FeeCapTooLowErrorType,\n  InsufficientFundsError,\n  type InsufficientFundsErrorType,\n  IntrinsicGasTooHighError,\n  type IntrinsicGasTooHighErrorType,\n  IntrinsicGasTooLowError,\n  type IntrinsicGasTooLowErrorType,\n  NonceMaxValueError,\n  type NonceMaxValueErrorType,\n  NonceTooHighError,\n  type NonceTooHighErrorType,\n  NonceTooLowError,\n  type NonceTooLowErrorType,\n  TipAboveFeeCapError,\n  type TipAboveFeeCapErrorType,\n  TransactionTypeNotSupportedError,\n  type TransactionTypeNotSupportedErrorType,\n  UnknownNodeError,\n  type UnknownNodeErrorType,\n} from './errors/node.js'\nexport {\n  FilterTypeNotSupportedError,\n  type FilterTypeNotSupportedErrorType,\n} from './errors/log.js'\nexport {\n  HttpRequestError,\n  type HttpRequestErrorType,\n  RpcRequestError,\n  type RpcRequestErrorType,\n  TimeoutError,\n  type TimeoutErrorType,\n  WebSocketRequestError,\n  type WebSocketRequestErrorType,\n} from './errors/request.js'\nexport {\n  InvalidAddressError,\n  type InvalidAddressErrorType,\n} from './errors/address.js'\nexport {\n  FeeConflictError,\n  type FeeConflictErrorType,\n  InvalidLegacyVError,\n  type InvalidLegacyVErrorType,\n  InvalidSerializableTransactionError,\n  type InvalidSerializableTransactionErrorType,\n  InvalidSerializedTransactionError,\n  type InvalidSerializedTransactionErrorType,\n  InvalidSerializedTransactionTypeError,\n  type InvalidSerializedTransactionTypeErrorType,\n  InvalidStorageKeySizeError,\n  type InvalidStorageKeySizeErrorType,\n  TransactionExecutionError,\n  type TransactionExecutionErrorType,\n  TransactionNotFoundError,\n  type TransactionNotFoundErrorType,\n  TransactionReceiptNotFoundError,\n  type TransactionReceiptNotFoundErrorType,\n  WaitForTransactionReceiptTimeoutError,\n  type WaitForTransactionReceiptTimeoutErrorType,\n} from './errors/transaction.js'\nexport {\n  SizeExceedsPaddingSizeError,\n  type SizeExceedsPaddingSizeErrorType,\n  SliceOffsetOutOfBoundsError,\n  type SliceOffsetOutOfBoundsErrorType,\n} from './errors/data.js'\nexport {\n  UrlRequiredError,\n  type UrlRequiredErrorType,\n} from './errors/transport.js'\nexport type {\n  AbiItem,\n  ContractFunctionConfig,\n  ContractFunctionResult,\n  GetConstructorArgs,\n  GetErrorArgs,\n  GetEventArgs,\n  GetEventArgsFromTopics,\n  GetFunctionArgs,\n  GetValue,\n  InferErrorName,\n  InferEventName,\n  InferFunctionName,\n  InferItemName,\n} from './types/contract.js'\nexport type {\n  AccessList,\n  Transaction,\n  TransactionBase,\n  TransactionEIP1559,\n  TransactionEIP2930,\n  TransactionLegacy,\n  TransactionReceipt,\n  TransactionRequest,\n  TransactionRequestBase,\n  TransactionRequestEIP1559,\n  TransactionRequestEIP2930,\n  TransactionRequestLegacy,\n  TransactionSerializable,\n  TransactionSerializableBase,\n  TransactionSerializableEIP1559,\n  TransactionSerializableEIP2930,\n  TransactionSerializableLegacy,\n  TransactionSerialized,\n  TransactionSerializedEIP1559,\n  TransactionSerializedEIP2930,\n  TransactionSerializedLegacy,\n  TransactionType,\n} from './types/transaction.js'\nexport type {\n  Account,\n  AccountSource,\n  CustomSource,\n  HDAccount,\n  HDOptions,\n  JsonRpcAccount,\n  LocalAccount,\n  PrivateKeyAccount,\n} from './accounts/types.js'\nexport type { AssetGateway, AssetGatewayUrls } from './types/ens.js'\nexport type {\n  Block,\n  BlockIdentifier,\n  BlockNumber,\n  BlockTag,\n  Uncle,\n} from './types/block.js'\nexport type {\n  ByteArray,\n  Hash,\n  Hex,\n  LogTopic,\n  Signature,\n  CompactSignature,\n  SignableMessage,\n} from './types/misc.js'\nexport type { GetChain } from './types/chain.js'\nexport type {\n  AddEthereumChainParameter,\n  EIP1193EventMap,\n  EIP1193Events,\n  EIP1193Parameters,\n  EIP1193Provider,\n  EIP1193RequestFn,\n  EIP1474Methods,\n  ProviderRpcError as EIP1193ProviderRpcError,\n  ProviderConnectInfo,\n  ProviderMessage,\n  PublicRpcSchema,\n  NetworkSync,\n  RpcSchema,\n  RpcSchemaOverride,\n  TestRpcSchema,\n  WatchAssetParams,\n  WalletPermissionCaveat,\n  WalletPermission,\n  WalletRpcSchema,\n} from './types/eip1193.js'\nexport type {\n  FeeHistory,\n  FeeValues,\n  FeeValuesEIP1559,\n  FeeValuesLegacy,\n  FeeValuesType,\n} from './types/fee.js'\nexport type { Filter } from './types/filter.js'\nexport type {\n  GetTypedDataDomain,\n  GetTypedDataMessage,\n  GetTypedDataPrimaryType,\n  GetTypedDataTypes,\n  TypedDataDefinition,\n} from './types/typedData.js'\nexport type { GetTransportConfig } from './types/transport.js'\nexport type { HDKey } from '@scure/bip32'\nexport type { Log } from './types/log.js'\nexport type {\n  MulticallContract,\n  MulticallContracts,\n  MulticallResult,\n  MulticallResults,\n} from './types/multicall.js'\nexport type { ParseAccount } from './types/account.js'\nexport type {\n  RpcBlock,\n  RpcBlockIdentifier,\n  RpcBlockNumber,\n  RpcFeeHistory,\n  RpcFeeValues,\n  RpcLog,\n  RpcTransaction,\n  RpcTransactionReceipt,\n  RpcTransactionRequest,\n  RpcUncle,\n} from './types/rpc.js'\nexport type { Withdrawal } from './types/withdrawal.js'\nexport { labelhash, type LabelhashErrorType } from './utils/ens/labelhash.js'\nexport { namehash, type NamehashErrorType } from './utils/ens/namehash.js'\nexport {\n  type FormattedBlock,\n  defineBlock,\n  type DefineBlockErrorType,\n  formatBlock,\n  type FormatBlockErrorType,\n} from './utils/formatters/block.js'\nexport { formatLog, type FormatLogErrorType } from './utils/formatters/log.js'\nexport {\n  type DecodeAbiParametersErrorType,\n  type DecodeAbiParametersReturnType,\n  decodeAbiParameters,\n} from './utils/abi/decodeAbiParameters.js'\nexport {\n  type DecodeDeployDataErrorType,\n  type DecodeDeployDataParameters,\n  type DecodeDeployDataReturnType,\n  decodeDeployData,\n} from './utils/abi/decodeDeployData.js'\nexport {\n  type DecodeErrorResultErrorType,\n  type DecodeErrorResultParameters,\n  type DecodeErrorResultReturnType,\n  decodeErrorResult,\n} from './utils/abi/decodeErrorResult.js'\nexport {\n  type DecodeEventLogErrorType,\n  type DecodeEventLogParameters,\n  type DecodeEventLogReturnType,\n  decodeEventLog,\n} from './utils/abi/decodeEventLog.js'\nexport {\n  type DecodeFunctionDataErrorType,\n  type DecodeFunctionDataParameters,\n  decodeFunctionData,\n} from './utils/abi/decodeFunctionData.js'\nexport {\n  type DecodeFunctionResultErrorType,\n  type DecodeFunctionResultParameters,\n  type DecodeFunctionResultReturnType,\n  decodeFunctionResult,\n} from './utils/abi/decodeFunctionResult.js'\nexport {\n  type EncodeAbiParametersErrorType,\n  type EncodeAbiParametersReturnType,\n  encodeAbiParameters,\n} from './utils/abi/encodeAbiParameters.js'\nexport {\n  type EncodeDeployDataErrorType,\n  type EncodeDeployDataParameters,\n  encodeDeployData,\n} from './utils/abi/encodeDeployData.js'\nexport {\n  type EncodeErrorResultErrorType,\n  type EncodeErrorResultParameters,\n  encodeErrorResult,\n} from './utils/abi/encodeErrorResult.js'\nexport {\n  type EncodeEventTopicsErrorType,\n  type EncodeEventTopicsParameters,\n  encodeEventTopics,\n} from './utils/abi/encodeEventTopics.js'\nexport {\n  type EncodeFunctionDataErrorType,\n  type EncodeFunctionDataParameters,\n  encodeFunctionData,\n} from './utils/abi/encodeFunctionData.js'\nexport {\n  type EncodeFunctionResultErrorType,\n  type EncodeFunctionResultParameters,\n  encodeFunctionResult,\n} from './utils/abi/encodeFunctionResult.js'\nexport {\n  type FormattedTransaction,\n  defineTransaction,\n  type DefineTransactionErrorType,\n  formatTransaction,\n  type FormatTransactionErrorType,\n  transactionType,\n} from './utils/formatters/transaction.js'\nexport {\n  type FormattedTransactionReceipt,\n  defineTransactionReceipt,\n  type DefineTransactionReceiptErrorType,\n  formatTransactionReceipt,\n  type FormatTransactionReceiptErrorType,\n} from './utils/formatters/transactionReceipt.js'\nexport {\n  type FormattedTransactionRequest,\n  defineTransactionRequest,\n  type DefineTransactionRequestErrorType,\n  formatTransactionRequest,\n  type FormatTransactionRequestErrorType,\n  rpcTransactionType,\n} from './utils/formatters/transactionRequest.js'\nexport {\n  type GetAbiItemErrorType,\n  type GetAbiItemParameters,\n  getAbiItem,\n} from './utils/abi/getAbiItem.js'\nexport {\n  type GetContractAddressOptions,\n  type GetCreate2AddressOptions,\n  type GetCreate2AddressErrorType,\n  type GetCreateAddressOptions,\n  type GetCreateAddressErrorType,\n  getContractAddress,\n  getCreate2Address,\n  getCreateAddress,\n} from './utils/address/getContractAddress.js'\nexport {\n  type GetSerializedTransactionType,\n  type GetSerializedTransactionTypeErrorType,\n  getSerializedTransactionType,\n} from './utils/transaction/getSerializedTransactionType.js'\nexport {\n  type GetTransactionType,\n  type GetTransationTypeErrorType,\n  getTransactionType,\n} from './utils/transaction/getTransactionType.js'\nexport {\n  type HashDomainErrorType,\n  type HashTypedDataErrorType,\n  type HashTypedDataParameters,\n  type HashTypedDataReturnType,\n  hashDomain,\n  hashTypedData,\n} from './utils/signature/hashTypedData.js'\nexport {\n  type CompactSignatureToSignatureErrorType,\n  compactSignatureToSignature,\n} from './utils/signature/compactSignatureToSignature.js'\nexport {\n  type HexToCompactSignatureErrorType,\n  hexToCompactSignature,\n} from './utils/signature/hexToCompactSignature.js'\nexport {\n  type HexToSignatureErrorType,\n  hexToSignature,\n} from './utils/signature/hexToSignature.js'\nexport {\n  type RecoverAddressErrorType,\n  type RecoverAddressParameters,\n  type RecoverAddressReturnType,\n  recoverAddress,\n} from './utils/signature/recoverAddress.js'\nexport {\n  type RecoverMessageAddressErrorType,\n  type RecoverMessageAddressParameters,\n  type RecoverMessageAddressReturnType,\n  recoverMessageAddress,\n} from './utils/signature/recoverMessageAddress.js'\nexport {\n  type RecoverPublicKeyErrorType,\n  type RecoverPublicKeyParameters,\n  type RecoverPublicKeyReturnType,\n  recoverPublicKey,\n} from './utils/signature/recoverPublicKey.js'\nexport {\n  type RecoverTypedDataAddressErrorType,\n  type RecoverTypedDataAddressParameters,\n  type RecoverTypedDataAddressReturnType,\n  recoverTypedDataAddress,\n} from './utils/signature/recoverTypedDataAddress.js'\nexport {\n  type SignatureToCompactSignatureErrorType,\n  signatureToCompactSignature,\n} from './utils/signature/signatureToCompactSignature.js'\nexport {\n  type CompactSignatureToHexErrorType,\n  compactSignatureToHex,\n} from './utils/signature/compactSignatureToHex.js'\nexport {\n  type SignatureToHexErrorType,\n  signatureToHex,\n} from './utils/signature/signatureToHex.js'\nexport {\n  bytesToRlp,\n  type BytesToRlpErrorType,\n  hexToRlp,\n  type HexToRlpErrorType,\n  toRlp,\n  type ToRlpErrorType,\n  type ToRlpReturnType,\n} from './utils/encoding/toRlp.js'\nexport {\n  type VerifyMessageErrorType,\n  type VerifyMessageParameters,\n  type VerifyMessageReturnType,\n  verifyMessage,\n} from './utils/signature/verifyMessage.js'\nexport {\n  type VerifyTypedDataErrorType,\n  type VerifyTypedDataParameters,\n  type VerifyTypedDataReturnType,\n  verifyTypedData,\n} from './utils/signature/verifyTypedData.js'\nexport {\n  type AssertRequestErrorType,\n  assertRequest,\n} from './utils/transaction/assertRequest.js'\nexport {\n  type AssertTransactionEIP1559ErrorType,\n  assertTransactionEIP1559,\n  type AssertTransactionEIP2930ErrorType,\n  assertTransactionEIP2930,\n  type AssertTransactionLegacyErrorType,\n  assertTransactionLegacy,\n} from './utils/transaction/assertTransaction.js'\nexport {\n  type BoolToBytesErrorType,\n  type BoolToBytesOpts,\n  boolToBytes,\n  type HexToBytesErrorType,\n  type HexToBytesOpts,\n  hexToBytes,\n  type NumberToBytesErrorType,\n  numberToBytes,\n  type StringToBytesErrorType,\n  type StringToBytesOpts,\n  stringToBytes,\n  type ToBytesErrorType,\n  type ToBytesParameters,\n  toBytes,\n} from './utils/encoding/toBytes.js'\nexport {\n  type BoolToHexErrorType,\n  type BoolToHexOpts,\n  boolToHex,\n  type BytesToHexErrorType,\n  type BytesToHexOpts,\n  bytesToHex,\n  type NumberToHexErrorType,\n  type NumberToHexOpts,\n  numberToHex,\n  type StringToHexErrorType,\n  type StringToHexOpts,\n  stringToHex,\n  type ToHexErrorType,\n  type ToHexParameters,\n  toHex,\n} from './utils/encoding/toHex.js'\nexport {\n  type BytesToBigIntErrorType,\n  type BytesToBigIntOpts,\n  bytesToBigInt,\n  /** @deprecated - use `bytesToBigInt` */\n  bytesToBigInt as bytesToBigint,\n  type BytesToBoolErrorType,\n  type BytesToBoolOpts,\n  bytesToBool,\n  type BytesToNumberErrorType,\n  type BytesToNumberOpts,\n  bytesToNumber,\n  type BytesToStringErrorType,\n  type BytesToStringOpts,\n  bytesToString,\n  type FromBytesErrorType,\n  type FromBytesParameters,\n  fromBytes,\n} from './utils/encoding/fromBytes.js'\nexport {\n  type CcipFetchErrorType,\n  ccipFetch,\n  type OffchainLookupErrorType,\n  offchainLookup,\n  offchainLookupAbiItem,\n  offchainLookupSignature,\n} from './utils/ccip.js'\nexport {\n  type ConcatBytesErrorType,\n  type ConcatErrorType,\n  type ConcatHexErrorType,\n  type ConcatReturnType,\n  concat,\n  concatBytes,\n  concatHex,\n} from './utils/data/concat.js'\nexport {\n  type AssertCurrentChainErrorType,\n  type AssertCurrentChainParameters,\n  assertCurrentChain,\n} from './utils/chain/assertCurrentChain.js'\nexport { defineChain } from './utils/chain/defineChain.js'\nexport {\n  type ExtractChainErrorType,\n  type ExtractChainParameters,\n  type ExtractChainReturnType,\n  extractChain,\n} from './utils/chain/extractChain.js'\nexport {\n  type GetChainContractAddressErrorType,\n  getChainContractAddress,\n} from './utils/chain/getChainContractAddress.js'\nexport {\n  type EncodePackedErrorType,\n  encodePacked,\n} from './utils/abi/encodePacked.js'\nexport {\n  type FormatEtherErrorType,\n  formatEther,\n} from './utils/unit/formatEther.js'\nexport {\n  type FormatGweiErrorType,\n  formatGwei,\n} from './utils/unit/formatGwei.js'\nexport {\n  type FormatUnitsErrorType,\n  formatUnits,\n} from './utils/unit/formatUnits.js'\nexport {\n  type FromHexErrorType,\n  fromHex,\n  type HexToBigIntErrorType,\n  hexToBigInt,\n  type HexToBoolErrorType,\n  hexToBool,\n  type HexToNumberErrorType,\n  hexToNumber,\n  type HexToStringErrorType,\n  hexToString,\n} from './utils/encoding/fromHex.js'\nexport {\n  type FromRlpErrorType,\n  type FromRlpReturnType,\n  fromRlp,\n} from './utils/encoding/fromRlp.js'\nexport {\n  type ChecksumAddressErrorType,\n  type GetAddressErrorType,\n  checksumAddress,\n  getAddress,\n} from './utils/address/getAddress.js'\nexport {\n  type GetContractErrorReturnType,\n  getContractError,\n} from './utils/errors/getContractError.js'\nexport {\n  type GetEventSelectorErrorType,\n  getEventSelector,\n} from './utils/hash/getEventSelector.js'\nexport {\n  type GetEventSignatureErrorType,\n  getEventSignature,\n} from './utils/hash/getEventSignature.js'\nexport {\n  type GetFunctionSelectorErrorType,\n  getFunctionSelector,\n} from './utils/hash/getFunctionSelector.js'\nexport {\n  type GetFunctionSignatureErrorType,\n  getFunctionSignature,\n} from './utils/hash/getFunctionSignature.js'\nexport {\n  type HashMessageErrorType,\n  hashMessage,\n} from './utils/signature/hashMessage.js'\nexport {\n  type IsAddressErrorType,\n  isAddress,\n} from './utils/address/isAddress.js'\nexport {\n  type IsAddressEqualErrorType,\n  isAddressEqual,\n} from './utils/address/isAddressEqual.js'\nexport { type IsBytesErrorType, isBytes } from './utils/data/isBytes.js'\nexport { type IsHashErrorType, isHash } from './utils/hash/isHash.js'\nexport { type IsHexErrorType, isHex } from './utils/data/isHex.js'\nexport { type Keccak256ErrorType, keccak256 } from './utils/hash/keccak256.js'\nexport { type Sha256ErrorType, sha256 } from './utils/hash/sha256.js'\nexport { type Ripemd160ErrorType, ripemd160 } from './utils/hash/ripemd160.js'\nexport {\n  type PadBytesErrorType,\n  type PadErrorType,\n  type PadHexErrorType,\n  type PadReturnType,\n  pad,\n  padBytes,\n  padHex,\n} from './utils/data/pad.js'\nexport {\n  type ParseEtherErrorType,\n  parseEther,\n} from './utils/unit/parseEther.js'\nexport { type ParseGweiErrorType, parseGwei } from './utils/unit/parseGwei.js'\nexport {\n  type ParseTransactionErrorType,\n  type ParseTransactionReturnType,\n  parseTransaction,\n} from './utils/transaction/parseTransaction.js'\nexport {\n  type ParseUnitsErrorType,\n  parseUnits,\n} from './utils/unit/parseUnits.js'\nexport {\n  type SerializeAccessListErrorType,\n  serializeAccessList,\n} from './utils/transaction/serializeAccessList.js'\nexport {\n  serializeTransaction,\n  type SerializeTransactionErrorType,\n  type SerializedTransactionReturnType,\n  type SerializeTransactionFn,\n} from './utils/transaction/serializeTransaction.js'\nexport { type SizeErrorType, size } from './utils/data/size.js'\nexport {\n  type SliceBytesErrorType,\n  type SliceErrorType,\n  type SliceHexErrorType,\n  slice,\n  sliceBytes,\n  sliceHex,\n} from './utils/data/slice.js'\nexport { type StringifyErrorType, stringify } from './utils/stringify.js'\nexport {\n  type TrimErrorType,\n  type TrimReturnType,\n  trim,\n} from './utils/data/trim.js'\nexport {\n  type DomainSeparatorErrorType,\n  type GetTypesForEIP712DomainErrorType,\n  type ValidateTypedDataErrorType,\n  validateTypedData,\n  domainSeparator,\n  getTypesForEIP712Domain,\n} from './utils/typedData.js'\n","import type { Client } from '../clients/createClient.js'\n\n/**\n * Retrieves and returns an action from the client (if exists), and falls\n * back to the tree-shakable action.\n *\n * Useful for extracting overridden actions from a client (ie. if a consumer\n * wants to override the `sendTransaction` implementation).\n */\nexport function getAction<params extends {}, returnType extends {}>(\n  client: Client,\n  action: (_: any, params: params) => returnType,\n  // Some minifiers drop `Function.prototype.name`, meaning that `action.name`\n  // will not work. For that case, the consumer needs to pass the name explicitly.\n  name: string,\n) {\n  return (params: params): returnType =>\n    (\n      client as Client & {\n        [key: string]: (params: params) => returnType\n      }\n    )[action.name || name]?.(params) ?? action(client, params)\n}\n","import type { Abi, AbiParameter, AbiParameterToPrimitiveType } from 'abitype'\n\nimport {\n  AbiEventNotFoundError,\n  type AbiEventNotFoundErrorType,\n} from '../../errors/abi.js'\nimport {\n  FilterTypeNotSupportedError,\n  type FilterTypeNotSupportedErrorType,\n} from '../../errors/log.js'\nimport type {\n  AbiItem,\n  EventDefinition,\n  GetEventArgs,\n  InferEventName,\n} from '../../types/contract.js'\nimport type { Hex } from '../../types/misc.js'\nimport { type ToBytesErrorType, toBytes } from '../encoding/toBytes.js'\nimport {\n  type GetEventSelectorErrorType,\n  getEventSelector,\n} from '../hash/getEventSelector.js'\nimport { type Keccak256ErrorType, keccak256 } from '../hash/keccak256.js'\n\nimport type { ErrorType } from '../../errors/utils.js'\nimport {\n  type EncodeAbiParametersErrorType,\n  encodeAbiParameters,\n} from './encodeAbiParameters.js'\nimport { type FormatAbiItemErrorType, formatAbiItem } from './formatAbiItem.js'\nimport { type GetAbiItemParameters, getAbiItem } from './getAbiItem.js'\n\nexport type EncodeEventTopicsParameters<\n  TAbi extends Abi | readonly unknown[] = Abi,\n  TEventName extends string | undefined = string,\n  _EventName = InferEventName<TAbi, TEventName>,\n> = {\n  eventName?: _EventName\n} & (TEventName extends string\n  ? { abi: TAbi; args?: GetEventArgs<TAbi, TEventName> }\n  : _EventName extends string\n    ? { abi: [TAbi[number]]; args?: GetEventArgs<TAbi, _EventName> }\n    : never)\n\nexport type EncodeEventTopicsErrorType =\n  | AbiEventNotFoundErrorType\n  | EncodeArgErrorType\n  | FormatAbiItemErrorType\n  | GetEventSelectorErrorType\n  | ErrorType\n\nexport function encodeEventTopics<\n  const TAbi extends Abi | readonly unknown[],\n  TEventName extends string | undefined = undefined,\n>({ abi, eventName, args }: EncodeEventTopicsParameters<TAbi, TEventName>) {\n  let abiItem = abi[0] as AbiItem\n  if (eventName) {\n    abiItem = getAbiItem({\n      abi,\n      args,\n      name: eventName,\n    } as GetAbiItemParameters)\n    if (!abiItem)\n      throw new AbiEventNotFoundError(eventName, {\n        docsPath: '/docs/contract/encodeEventTopics',\n      })\n  }\n\n  if (abiItem.type !== 'event')\n    throw new AbiEventNotFoundError(undefined, {\n      docsPath: '/docs/contract/encodeEventTopics',\n    })\n\n  const definition = formatAbiItem(abiItem)\n  const signature = getEventSelector(definition as EventDefinition)\n\n  let topics: Hex[] = []\n  if (args && 'inputs' in abiItem) {\n    const indexedInputs = abiItem.inputs?.filter(\n      (param) => 'indexed' in param && param.indexed,\n    )\n    const args_ = Array.isArray(args)\n      ? args\n      : Object.values(args).length > 0\n        ? indexedInputs?.map((x: any) => (args as any)[x.name]) ?? []\n        : []\n\n    if (args_.length > 0) {\n      topics =\n        indexedInputs?.map((param, i) =>\n          Array.isArray(args_[i])\n            ? args_[i].map((_: any, j: number) =>\n                encodeArg({ param, value: args_[i][j] }),\n              )\n            : args_[i]\n              ? encodeArg({ param, value: args_[i] })\n              : null,\n        ) ?? []\n    }\n  }\n  return [signature, ...topics]\n}\n\nexport type EncodeArgErrorType =\n  | Keccak256ErrorType\n  | ToBytesErrorType\n  | EncodeAbiParametersErrorType\n  | FilterTypeNotSupportedErrorType\n  | ErrorType\n\nfunction encodeArg({\n  param,\n  value,\n}: { param: AbiParameter; value: AbiParameterToPrimitiveType<AbiParameter> }) {\n  if (param.type === 'string' || param.type === 'bytes')\n    return keccak256(toBytes(value as string))\n  if (param.type === 'tuple' || param.type.match(/^(.*)\\[(\\d+)?\\]$/))\n    throw new FilterTypeNotSupportedError(param.type)\n  return encodeAbiParameters([param], [value])\n}\n","import { BaseError } from './base.js'\n\nexport type FilterTypeNotSupportedErrorType = FilterTypeNotSupportedError & {\n  name: 'FilterTypeNotSupportedError'\n}\nexport class FilterTypeNotSupportedError extends BaseError {\n  override name = 'FilterTypeNotSupportedError'\n  constructor(type: string) {\n    super(`Filter type \"${type}\" is not supported.`)\n  }\n}\n","import type { Abi, Address } from 'abitype'\n\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { BlockNumber, BlockTag } from '../../types/block.js'\nimport type { Chain } from '../../types/chain.js'\nimport type {\n  InferEventName,\n  MaybeExtractEventArgsFromAbi,\n} from '../../types/contract.js'\nimport type { Filter } from '../../types/filter.js'\nimport type { Hex } from '../../types/misc.js'\nimport {\n  type EncodeEventTopicsErrorType,\n  type EncodeEventTopicsParameters,\n  encodeEventTopics,\n} from '../../utils/abi/encodeEventTopics.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport {\n  type NumberToHexErrorType,\n  numberToHex,\n} from '../../utils/encoding/toHex.js'\nimport { createFilterRequestScope } from '../../utils/filters/createFilterRequestScope.js'\n\nexport type CreateContractEventFilterParameters<\n  TAbi extends Abi | readonly unknown[] = Abi,\n  TEventName extends string | undefined = undefined,\n  TArgs extends\n    | MaybeExtractEventArgsFromAbi<TAbi, TEventName>\n    | undefined = undefined,\n  TStrict extends boolean | undefined = undefined,\n  TFromBlock extends BlockNumber | BlockTag | undefined = undefined,\n  TToBlock extends BlockNumber | BlockTag | undefined = undefined,\n> = {\n  address?: Address | Address[]\n  abi: TAbi\n  eventName?: InferEventName<TAbi, TEventName>\n  fromBlock?: TFromBlock | BlockNumber | BlockTag\n  /**\n   * Whether or not the logs must match the indexed/non-indexed arguments in the event ABI item.\n   * @default false\n   */\n  strict?: TStrict\n  toBlock?: TToBlock | BlockNumber | BlockTag\n} & (undefined extends TEventName\n  ? {\n      args?: never\n    }\n  : MaybeExtractEventArgsFromAbi<\n        TAbi,\n        TEventName\n      > extends infer TEventFilterArgs\n    ? {\n        args?:\n          | TEventFilterArgs\n          | (TArgs extends TEventFilterArgs ? TArgs : never)\n      }\n    : {\n        args?: never\n      })\n\nexport type CreateContractEventFilterReturnType<\n  TAbi extends Abi | readonly unknown[] = Abi,\n  TEventName extends string | undefined = undefined,\n  TArgs extends\n    | MaybeExtractEventArgsFromAbi<TAbi, TEventName>\n    | undefined = undefined,\n  TStrict extends boolean | undefined = undefined,\n  TFromBlock extends BlockNumber | BlockTag | undefined = undefined,\n  TToBlock extends BlockNumber | BlockTag | undefined = undefined,\n> = Filter<'event', TAbi, TEventName, TArgs, TStrict, TFromBlock, TToBlock>\n\nexport type CreateContractEventFilterErrorType =\n  | EncodeEventTopicsErrorType\n  | RequestErrorType\n  | NumberToHexErrorType\n  | ErrorType\n\n/**\n * Creates a Filter to retrieve event logs that can be used with [`getFilterChanges`](https://viem.sh/docs/actions/public/getFilterChanges.html) or [`getFilterLogs`](https://viem.sh/docs/actions/public/getFilterLogs.html).\n *\n * - Docs: https://viem.sh/docs/contract/createContractEventFilter.html\n *\n * @param client - Client to use\n * @param parameters - {@link CreateContractEventFilterParameters}\n * @returns [`Filter`](https://viem.sh/docs/glossary/types.html#filter). {@link CreateContractEventFilterReturnType}\n *\n * @example\n * import { createPublicClient, http, parseAbi } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { createContractEventFilter } from 'viem/contract'\n *\n * const client = createPublicClient({\n *   chain: mainnet,\n *   transport: http(),\n * })\n * const filter = await createContractEventFilter(client, {\n *   abi: parseAbi(['event Transfer(address indexed, address indexed, uint256)']),\n * })\n */\nexport async function createContractEventFilter<\n  TChain extends Chain | undefined,\n  const TAbi extends Abi | readonly unknown[],\n  TEventName extends string | undefined,\n  TArgs extends MaybeExtractEventArgsFromAbi<TAbi, TEventName> | undefined,\n  TStrict extends boolean | undefined = undefined,\n  TFromBlock extends BlockNumber | BlockTag | undefined = undefined,\n  TToBlock extends BlockNumber | BlockTag | undefined = undefined,\n>(\n  client: Client<Transport, TChain>,\n  {\n    address,\n    abi,\n    args,\n    eventName,\n    fromBlock,\n    strict,\n    toBlock,\n  }: CreateContractEventFilterParameters<\n    TAbi,\n    TEventName,\n    TArgs,\n    TStrict,\n    TFromBlock,\n    TToBlock\n  >,\n): Promise<\n  CreateContractEventFilterReturnType<\n    TAbi,\n    TEventName,\n    TArgs,\n    TStrict,\n    TFromBlock,\n    TToBlock\n  >\n> {\n  const getRequest = createFilterRequestScope(client, {\n    method: 'eth_newFilter',\n  })\n\n  const topics = eventName\n    ? encodeEventTopics({\n        abi,\n        args,\n        eventName,\n      } as unknown as EncodeEventTopicsParameters)\n    : undefined\n  const id: Hex = await client.request({\n    method: 'eth_newFilter',\n    params: [\n      {\n        address,\n        fromBlock:\n          typeof fromBlock === 'bigint' ? numberToHex(fromBlock) : fromBlock,\n        toBlock: typeof toBlock === 'bigint' ? numberToHex(toBlock) : toBlock,\n        topics,\n      },\n    ],\n  })\n\n  return {\n    abi,\n    args,\n    eventName,\n    id,\n    request: getRequest(id),\n    strict,\n    type: 'event',\n  } as unknown as CreateContractEventFilterReturnType<\n    TAbi,\n    TEventName,\n    TArgs,\n    TStrict,\n    TFromBlock,\n    TToBlock\n  >\n}\n","import type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { OnResponseFn } from '../../clients/transports/fallback.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { PublicRpcSchema } from '../../types/eip1193.js'\nimport type { EIP1193RequestFn } from '../../types/eip1193.js'\nimport type { Hex } from '../../types/misc.js'\nimport type { Filter } from '../../types/utils.js'\n\ntype CreateFilterRequestScopeParameters = {\n  method:\n    | 'eth_newFilter'\n    | 'eth_newPendingTransactionFilter'\n    | 'eth_newBlockFilter'\n}\n\ntype FilterRpcSchema = Filter<\n  PublicRpcSchema,\n  { Method: 'eth_getFilterLogs' | 'eth_getFilterChanges' }\n>\n\ntype CreateFilterRequestScopeReturnType = (\n  id: Hex,\n) => EIP1193RequestFn<FilterRpcSchema>\n\n/**\n * Scopes `request` to the filter ID. If the client is a fallback, it will\n * listen for responses and scope the child transport `request` function\n * to the successful filter ID.\n */\nexport function createFilterRequestScope<TChain extends Chain | undefined>(\n  client: Client<Transport, TChain>,\n  { method }: CreateFilterRequestScopeParameters,\n): CreateFilterRequestScopeReturnType {\n  const requestMap: Record<Hex, EIP1193RequestFn> = {}\n\n  if (client.transport.type === 'fallback')\n    client.transport.onResponse?.(\n      ({\n        method: method_,\n        response: id,\n        status,\n        transport,\n      }: Parameters<OnResponseFn>[0]) => {\n        if (status === 'success' && method === method_)\n          requestMap[id as Hex] = transport.request\n      },\n    )\n\n  return ((id) =>\n    requestMap[id] || client.request) as CreateFilterRequestScopeReturnType\n}\n","import type { Abi } from 'abitype'\n\nimport type { Account } from '../../accounts/types.js'\nimport {\n  type ParseAccountErrorType,\n  parseAccount,\n} from '../../accounts/utils/parseAccount.js'\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { BaseError } from '../../errors/base.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { ContractFunctionConfig, GetValue } from '../../types/contract.js'\nimport type { UnionOmit } from '../../types/utils.js'\nimport {\n  type EncodeFunctionDataErrorType,\n  type EncodeFunctionDataParameters,\n  encodeFunctionData,\n} from '../../utils/abi/encodeFunctionData.js'\nimport {\n  type GetContractErrorReturnType,\n  getContractError,\n} from '../../utils/errors/getContractError.js'\nimport { getAction } from '../../utils/getAction.js'\nimport {\n  type EstimateGasErrorType,\n  type EstimateGasParameters,\n  estimateGas,\n} from './estimateGas.js'\n\nexport type EstimateContractGasParameters<\n  TAbi extends Abi | readonly unknown[] = Abi,\n  TFunctionName extends string = string,\n  TChain extends Chain | undefined = Chain | undefined,\n  TAccount extends Account | undefined = undefined,\n> = ContractFunctionConfig<TAbi, TFunctionName, 'payable' | 'nonpayable'> &\n  UnionOmit<EstimateGasParameters<TChain, TAccount>, 'data' | 'to' | 'value'> &\n  GetValue<\n    TAbi,\n    TFunctionName,\n    EstimateGasParameters<TChain> extends EstimateGasParameters\n      ? EstimateGasParameters<TChain>['value']\n      : EstimateGasParameters['value']\n  >\n\nexport type EstimateContractGasReturnType = bigint\n\nexport type EstimateContractGasErrorType = GetContractErrorReturnType<\n  EncodeFunctionDataErrorType | EstimateGasErrorType | ParseAccountErrorType\n>\n\n/**\n * Estimates the gas required to successfully execute a contract write function call.\n *\n * - Docs: https://viem.sh/docs/contract/estimateContractGas.html\n *\n * Internally, uses a [Public Client](https://viem.sh/docs/clients/public.html) to call the [`estimateGas` action](https://viem.sh/docs/actions/public/estimateGas.html) with [ABI-encoded `data`](https://viem.sh/docs/contract/encodeFunctionData.html).\n *\n * @param client - Client to use\n * @param parameters - {@link EstimateContractGasParameters}\n * @returns The gas estimate (in wei). {@link EstimateContractGasReturnType}\n *\n * @example\n * import { createPublicClient, http, parseAbi } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { estimateContractGas } from 'viem/contract'\n *\n * const client = createPublicClient({\n *   chain: mainnet,\n *   transport: http(),\n * })\n * const gas = await estimateContractGas(client, {\n *   address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\n *   abi: parseAbi(['function mint() public']),\n *   functionName: 'mint',\n *   account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266',\n * })\n */\nexport async function estimateContractGas<\n  const TAbi extends Abi | readonly unknown[],\n  TFunctionName extends string,\n  TChain extends Chain | undefined,\n  TAccount extends Account | undefined = undefined,\n>(\n  client: Client<Transport, TChain, TAccount>,\n  {\n    abi,\n    address,\n    args,\n    functionName,\n    ...request\n  }: EstimateContractGasParameters<TAbi, TFunctionName, TChain, TAccount>,\n): Promise<EstimateContractGasReturnType> {\n  const data = encodeFunctionData({\n    abi,\n    args,\n    functionName,\n  } as unknown as EncodeFunctionDataParameters<TAbi, TFunctionName>)\n  try {\n    const gas = await getAction(\n      client,\n      estimateGas,\n      'estimateGas',\n    )({\n      data,\n      to: address,\n      ...request,\n    } as unknown as EstimateGasParameters<TChain>)\n    return gas\n  } catch (err) {\n    const account = request.account ? parseAccount(request.account) : undefined\n    throw getContractError(err as BaseError, {\n      abi: abi as Abi,\n      address,\n      args,\n      docsPath: '/docs/contract/estimateContractGas',\n      functionName,\n      sender: account?.address,\n    })\n  }\n}\n","import type { Abi, Address } from 'abitype'\n\nimport { AbiDecodingZeroDataError } from '../../errors/abi.js'\nimport { BaseError } from '../../errors/base.js'\nimport {\n  ContractFunctionExecutionError,\n  type ContractFunctionExecutionErrorType,\n  ContractFunctionRevertedError,\n  type ContractFunctionRevertedErrorType,\n  ContractFunctionZeroDataError,\n  type ContractFunctionZeroDataErrorType,\n  RawContractError,\n} from '../../errors/contract.js'\nimport { InternalRpcError } from '../../errors/rpc.js'\nimport type { ErrorType } from '../../errors/utils.js'\n\nconst EXECUTION_REVERTED_ERROR_CODE = 3\n\nexport type GetContractErrorReturnType<cause = ErrorType> = Omit<\n  ContractFunctionExecutionErrorType,\n  'cause'\n> & {\n  cause:\n    | cause\n    | ContractFunctionZeroDataErrorType\n    | ContractFunctionRevertedErrorType\n}\n\nexport function getContractError<err extends ErrorType<string>>(\n  err: err,\n  {\n    abi,\n    address,\n    args,\n    docsPath,\n    functionName,\n    sender,\n  }: {\n    abi: Abi\n    args: any\n    address?: Address\n    docsPath?: string\n    functionName: string\n    sender?: Address\n  },\n): GetContractErrorReturnType {\n  const { code, data, message, shortMessage } = (\n    err instanceof RawContractError\n      ? err\n      : err instanceof BaseError\n        ? err.walk((err) => 'data' in (err as Error)) || err.walk()\n        : {}\n  ) as RawContractError\n\n  const cause = (() => {\n    if (err instanceof AbiDecodingZeroDataError)\n      return new ContractFunctionZeroDataError({ functionName })\n    if (\n      [EXECUTION_REVERTED_ERROR_CODE, InternalRpcError.code].includes(code) &&\n      (data || message || shortMessage)\n    ) {\n      return new ContractFunctionRevertedError({\n        abi,\n        data: typeof data === 'object' ? data.data : data,\n        functionName,\n        message: shortMessage ?? message,\n      })\n    }\n    return err\n  })()\n\n  return new ContractFunctionExecutionError(cause as BaseError, {\n    abi,\n    args,\n    contractAddress: address,\n    docsPath,\n    functionName,\n    sender,\n  }) as GetContractErrorReturnType\n}\n","import type { Account } from '../../accounts/types.js'\nimport {\n  type ParseAccountErrorType,\n  parseAccount,\n} from '../../accounts/utils/parseAccount.js'\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport { AccountNotFoundError } from '../../errors/account.js'\nimport type { BaseError } from '../../errors/base.js'\nimport type { GetAccountParameter } from '../../types/account.js'\nimport type { BlockTag } from '../../types/block.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { TransactionRequest } from '../../types/transaction.js'\nimport type { UnionOmit } from '../../types/utils.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport {\n  type NumberToHexErrorType,\n  numberToHex,\n} from '../../utils/encoding/toHex.js'\nimport {\n  type GetEstimateGasErrorReturnType,\n  getEstimateGasError,\n} from '../../utils/errors/getEstimateGasError.js'\nimport { extract } from '../../utils/formatters/extract.js'\nimport {\n  type FormattedTransactionRequest,\n  formatTransactionRequest,\n} from '../../utils/formatters/transactionRequest.js'\nimport {\n  type AssertRequestErrorType,\n  type AssertRequestParameters,\n  assertRequest,\n} from '../../utils/transaction/assertRequest.js'\nimport {\n  type PrepareTransactionRequestParameters,\n  prepareTransactionRequest,\n} from '../wallet/prepareTransactionRequest.js'\n\nexport type FormattedEstimateGas<\n  TChain extends Chain | undefined = Chain | undefined,\n> = FormattedTransactionRequest<TChain>\n\nexport type EstimateGasParameters<\n  TChain extends Chain | undefined = Chain | undefined,\n  TAccount extends Account | undefined = undefined,\n> = UnionOmit<FormattedEstimateGas<TChain>, 'from'> &\n  GetAccountParameter<TAccount> &\n  (\n    | {\n        /** The balance of the account at a block number. */\n        blockNumber?: bigint\n        blockTag?: never\n      }\n    | {\n        blockNumber?: never\n        /**\n         * The balance of the account at a block tag.\n         * @default 'latest'\n         */\n        blockTag?: BlockTag\n      }\n  )\n\nexport type EstimateGasReturnType = bigint\n\nexport type EstimateGasErrorType = GetEstimateGasErrorReturnType<\n  | ParseAccountErrorType\n  | NumberToHexErrorType\n  | RequestErrorType\n  | AssertRequestErrorType\n>\n\n/**\n * Estimates the gas necessary to complete a transaction without submitting it to the network.\n *\n * - Docs: https://viem.sh/docs/actions/public/estimateGas.html\n * - JSON-RPC Methods: [`eth_estimateGas`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_estimategas)\n *\n * @param client - Client to use\n * @param parameters - {@link EstimateGasParameters}\n * @returns The gas estimate (in wei). {@link EstimateGasReturnType}\n *\n * @example\n * import { createPublicClient, http, parseEther } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { estimateGas } from 'viem/public'\n *\n * const client = createPublicClient({\n *   chain: mainnet,\n *   transport: http(),\n * })\n * const gasEstimate = await estimateGas(client, {\n *   account: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',\n *   to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',\n *   value: parseEther('1'),\n * })\n */\nexport async function estimateGas<\n  TChain extends Chain | undefined,\n  TAccount extends Account | undefined = undefined,\n>(\n  client: Client<Transport, TChain, TAccount>,\n  args: EstimateGasParameters<TChain, TAccount>,\n): Promise<EstimateGasReturnType> {\n  const account_ = args.account ?? client.account\n  if (!account_)\n    throw new AccountNotFoundError({\n      docsPath: '/docs/actions/public/estimateGas',\n    })\n  const account = parseAccount(account_)\n\n  try {\n    const {\n      accessList,\n      blockNumber,\n      blockTag,\n      data,\n      gas,\n      gasPrice,\n      maxFeePerGas,\n      maxPriorityFeePerGas,\n      nonce,\n      to,\n      value,\n      ...rest\n    } =\n      account.type === 'local'\n        ? ((await prepareTransactionRequest(\n            client,\n            args as PrepareTransactionRequestParameters,\n          )) as EstimateGasParameters)\n        : args\n\n    const blockNumberHex = blockNumber ? numberToHex(blockNumber) : undefined\n    const block = blockNumberHex || blockTag\n\n    assertRequest(args as AssertRequestParameters)\n\n    const chainFormat = client.chain?.formatters?.transactionRequest?.format\n    const format = chainFormat || formatTransactionRequest\n\n    const request = format({\n      // Pick out extra data that might exist on the chain's transaction request type.\n      ...extract(rest, { format: chainFormat }),\n      from: account.address,\n      accessList,\n      data,\n      gas,\n      gasPrice,\n      maxFeePerGas,\n      maxPriorityFeePerGas,\n      nonce,\n      to,\n      value,\n    } as TransactionRequest)\n\n    const balance = await client.request({\n      method: 'eth_estimateGas',\n      params: block ? [request, block] : [request],\n    })\n    return BigInt(balance)\n  } catch (err) {\n    throw getEstimateGasError(err as BaseError, {\n      ...args,\n      account,\n      chain: client.chain,\n    })\n  }\n}\n","import { BaseError } from './base.js'\n\nexport type AccountNotFoundErrorType = AccountNotFoundError & {\n  name: 'AccountNotFoundError'\n}\nexport class AccountNotFoundError extends BaseError {\n  override name = 'AccountNotFoundError'\n  constructor({ docsPath }: { docsPath?: string } = {}) {\n    super(\n      [\n        'Could not find an Account to execute with this Action.',\n        'Please provide an Account with the `account` argument on the Action, or by supplying an `account` to the WalletClient.',\n      ].join('\\n'),\n      {\n        docsPath,\n        docsSlug: 'account',\n      },\n    )\n  }\n}\n","import type { Account } from '../accounts/types.js'\nimport type { EstimateGasParameters } from '../actions/public/estimateGas.js'\nimport type { Chain } from '../types/chain.js'\nimport { formatEther } from '../utils/unit/formatEther.js'\nimport { formatGwei } from '../utils/unit/formatGwei.js'\n\nimport { BaseError } from './base.js'\nimport { prettyPrint } from './transaction.js'\n\nexport type EstimateGasExecutionErrorType = EstimateGasExecutionError & {\n  name: 'EstimateGasExecutionError'\n}\nexport class EstimateGasExecutionError extends BaseError {\n  override cause: BaseError\n\n  override name = 'EstimateGasExecutionError'\n\n  constructor(\n    cause: BaseError,\n    {\n      account,\n      docsPath,\n      chain,\n      data,\n      gas,\n      gasPrice,\n      maxFeePerGas,\n      maxPriorityFeePerGas,\n      nonce,\n      to,\n      value,\n    }: Omit<EstimateGasParameters<any, any>, 'account'> & {\n      account?: Account\n      chain?: Chain\n      docsPath?: string\n    },\n  ) {\n    const prettyArgs = prettyPrint({\n      from: account?.address,\n      to,\n      value:\n        typeof value !== 'undefined' &&\n        `${formatEther(value)} ${chain?.nativeCurrency?.symbol || 'ETH'}`,\n      data,\n      gas,\n      gasPrice:\n        typeof gasPrice !== 'undefined' && `${formatGwei(gasPrice)} gwei`,\n      maxFeePerGas:\n        typeof maxFeePerGas !== 'undefined' &&\n        `${formatGwei(maxFeePerGas)} gwei`,\n      maxPriorityFeePerGas:\n        typeof maxPriorityFeePerGas !== 'undefined' &&\n        `${formatGwei(maxPriorityFeePerGas)} gwei`,\n      nonce,\n    })\n\n    super(cause.shortMessage, {\n      cause,\n      docsPath,\n      metaMessages: [\n        ...(cause.metaMessages ? [...cause.metaMessages, ' '] : []),\n        'Estimate Gas Arguments:',\n        prettyArgs,\n      ].filter(Boolean) as string[],\n    })\n    this.cause = cause\n  }\n}\n","import type { Account } from '../../accounts/types.js'\nimport type { EstimateGasParameters } from '../../actions/public/estimateGas.js'\nimport type { BaseError } from '../../errors/base.js'\nimport {\n  EstimateGasExecutionError,\n  type EstimateGasExecutionErrorType,\n} from '../../errors/estimateGas.js'\nimport { UnknownNodeError } from '../../errors/node.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\n\nimport {\n  type GetNodeErrorParameters,\n  type GetNodeErrorReturnType,\n  getNodeError,\n} from './getNodeError.js'\n\nexport type GetEstimateGasErrorReturnType<cause = ErrorType> = Omit<\n  EstimateGasExecutionErrorType,\n  'cause'\n> & { cause: cause | GetNodeErrorReturnType }\n\nexport function getEstimateGasError<err extends ErrorType<string>>(\n  err: err,\n  {\n    docsPath,\n    ...args\n  }: Omit<EstimateGasParameters, 'account'> & {\n    account?: Account\n    chain?: Chain\n    docsPath?: string\n  },\n): GetEstimateGasErrorReturnType<err> {\n  const cause = (() => {\n    const cause = getNodeError(\n      err as {} as BaseError,\n      args as GetNodeErrorParameters,\n    )\n    if (cause instanceof UnknownNodeError) return err as {} as BaseError\n    return cause\n  })()\n  return new EstimateGasExecutionError(cause, {\n    docsPath,\n    ...args,\n  }) as GetEstimateGasErrorReturnType<err>\n}\n","import type { Account } from '../../accounts/types.js'\nimport {\n  type ParseAccountErrorType,\n  parseAccount,\n} from '../../accounts/utils/parseAccount.js'\nimport {\n  type EstimateFeesPerGasErrorType,\n  internal_estimateFeesPerGas,\n} from '../../actions/public/estimateFeesPerGas.js'\nimport {\n  type EstimateGasErrorType,\n  type EstimateGasParameters,\n  estimateGas,\n} from '../../actions/public/estimateGas.js'\nimport {\n  type GetBlockErrorType,\n  getBlock,\n} from '../../actions/public/getBlock.js'\nimport {\n  type GetTransactionCountErrorType,\n  getTransactionCount,\n} from '../../actions/public/getTransactionCount.js'\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport {\n  AccountNotFoundError,\n  type AccountNotFoundErrorType,\n} from '../../errors/account.js'\nimport {\n  Eip1559FeesNotSupportedError,\n  MaxFeePerGasTooLowError,\n} from '../../errors/fee.js'\nimport type { GetAccountParameter } from '../../types/account.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { GetChain } from '../../types/chain.js'\nimport type { TransactionSerializable } from '../../types/transaction.js'\nimport type { UnionOmit } from '../../types/utils.js'\nimport type { FormattedTransactionRequest } from '../../utils/formatters/transactionRequest.js'\nimport { getAction } from '../../utils/getAction.js'\nimport type {\n  AssertRequestErrorType,\n  AssertRequestParameters,\n} from '../../utils/transaction/assertRequest.js'\nimport { assertRequest } from '../../utils/transaction/assertRequest.js'\nimport { getTransactionType } from '../../utils/transaction/getTransactionType.js'\n\nexport type PrepareTransactionRequestParameters<\n  TChain extends Chain | undefined = Chain | undefined,\n  TAccount extends Account | undefined = Account | undefined,\n  TChainOverride extends Chain | undefined = Chain | undefined,\n> = UnionOmit<\n  FormattedTransactionRequest<\n    TChainOverride extends Chain ? TChainOverride : TChain\n  >,\n  'from'\n> &\n  GetAccountParameter<TAccount> &\n  GetChain<TChain, TChainOverride>\n\nexport type PrepareTransactionRequestReturnType<\n  TChain extends Chain | undefined = Chain | undefined,\n  TAccount extends Account | undefined = Account | undefined,\n  TChainOverride extends Chain | undefined = Chain | undefined,\n> = FormattedTransactionRequest<\n  TChainOverride extends Chain ? TChainOverride : TChain\n> &\n  GetAccountParameter<TAccount> &\n  GetChain<TChain, TChainOverride>\n\nexport type PrepareTransactionRequestErrorType =\n  | AccountNotFoundErrorType\n  | AssertRequestErrorType\n  | ParseAccountErrorType\n  | GetBlockErrorType\n  | GetTransactionCountErrorType\n  | EstimateGasErrorType\n  | EstimateFeesPerGasErrorType\n\n/**\n * Prepares a transaction request for signing.\n *\n * - Docs: https://viem.sh/docs/actions/wallet/prepareTransactionRequest.html\n *\n * @param args - {@link PrepareTransactionRequestParameters}\n * @returns The transaction request. {@link PrepareTransactionRequestReturnType}\n *\n * @example\n * import { createWalletClient, custom } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { prepareTransactionRequest } from 'viem/actions'\n *\n * const client = createWalletClient({\n *   chain: mainnet,\n *   transport: custom(window.ethereum),\n * })\n * const request = await prepareTransactionRequest(client, {\n *   account: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',\n *   to: '0x0000000000000000000000000000000000000000',\n *   value: 1n,\n * })\n *\n * @example\n * // Account Hoisting\n * import { createWalletClient, http } from 'viem'\n * import { privateKeyToAccount } from 'viem/accounts'\n * import { mainnet } from 'viem/chains'\n * import { prepareTransactionRequest } from 'viem/actions'\n *\n * const client = createWalletClient({\n *   account: privateKeyToAccount('0x…'),\n *   chain: mainnet,\n *   transport: custom(window.ethereum),\n * })\n * const request = await prepareTransactionRequest(client, {\n *   to: '0x0000000000000000000000000000000000000000',\n *   value: 1n,\n * })\n */\nexport async function prepareTransactionRequest<\n  TChain extends Chain | undefined,\n  TAccount extends Account | undefined,\n  TChainOverride extends Chain | undefined = undefined,\n>(\n  client: Client<Transport, TChain, TAccount>,\n  args: PrepareTransactionRequestParameters<TChain, TAccount, TChainOverride>,\n): Promise<\n  PrepareTransactionRequestReturnType<TChain, TAccount, TChainOverride>\n> {\n  const { account: account_ = client.account, chain, gas, nonce, type } = args\n  if (!account_) throw new AccountNotFoundError()\n  const account = parseAccount(account_)\n\n  const block = await getAction(\n    client,\n    getBlock,\n    'getBlock',\n  )({ blockTag: 'latest' })\n\n  const request = { ...args, from: account.address }\n\n  if (typeof nonce === 'undefined')\n    request.nonce = await getAction(\n      client,\n      getTransactionCount,\n      'getTransactionCount',\n    )({\n      address: account.address,\n      blockTag: 'pending',\n    })\n\n  if (typeof type === 'undefined') {\n    try {\n      request.type = getTransactionType(\n        request as TransactionSerializable,\n      ) as any\n    } catch {\n      // infer type from block\n      request.type =\n        typeof block.baseFeePerGas === 'bigint' ? 'eip1559' : 'legacy'\n    }\n  }\n\n  if (request.type === 'eip1559') {\n    // EIP-1559 fees\n    const { maxFeePerGas, maxPriorityFeePerGas } =\n      await internal_estimateFeesPerGas(client, {\n        block,\n        chain,\n        request: request as PrepareTransactionRequestParameters,\n      })\n\n    if (\n      typeof args.maxPriorityFeePerGas === 'undefined' &&\n      args.maxFeePerGas &&\n      args.maxFeePerGas < maxPriorityFeePerGas\n    )\n      throw new MaxFeePerGasTooLowError({\n        maxPriorityFeePerGas,\n      })\n\n    request.maxPriorityFeePerGas = maxPriorityFeePerGas\n    request.maxFeePerGas = maxFeePerGas\n  } else {\n    // Legacy fees\n    if (\n      typeof args.maxFeePerGas !== 'undefined' ||\n      typeof args.maxPriorityFeePerGas !== 'undefined'\n    )\n      throw new Eip1559FeesNotSupportedError()\n\n    const { gasPrice: gasPrice_ } = await internal_estimateFeesPerGas(client, {\n      block,\n      chain,\n      request: request as PrepareTransactionRequestParameters,\n      type: 'legacy',\n    })\n    request.gasPrice = gasPrice_\n  }\n\n  if (typeof gas === 'undefined')\n    request.gas = await getAction(\n      client,\n      estimateGas,\n      'estimateGas',\n    )({\n      ...request,\n      account: { address: account.address, type: 'json-rpc' },\n    } as EstimateGasParameters)\n\n  assertRequest(request as AssertRequestParameters)\n\n  return request as unknown as PrepareTransactionRequestReturnType<\n    TChain,\n    TAccount,\n    TChainOverride\n  >\n}\n","import { formatGwei } from '../utils/unit/formatGwei.js'\nimport { BaseError } from './base.js'\n\nexport type BaseFeeScalarErrorType = BaseFeeScalarError & {\n  name: 'BaseFeeScalarError'\n}\nexport class BaseFeeScalarError extends BaseError {\n  override name = 'BaseFeeScalarError'\n  constructor() {\n    super('`baseFeeMultiplier` must be greater than 1.')\n  }\n}\n\nexport type Eip1559FeesNotSupportedErrorType = Eip1559FeesNotSupportedError & {\n  name: 'Eip1559FeesNotSupportedError'\n}\nexport class Eip1559FeesNotSupportedError extends BaseError {\n  override name = 'Eip1559FeesNotSupportedError'\n  constructor() {\n    super('Chain does not support EIP-1559 fees.')\n  }\n}\n\nexport type MaxFeePerGasTooLowErrorType = MaxFeePerGasTooLowError & {\n  name: 'MaxFeePerGasTooLowError'\n}\nexport class MaxFeePerGasTooLowError extends BaseError {\n  override name = 'MaxFeePerGasTooLowError'\n  constructor({ maxPriorityFeePerGas }: { maxPriorityFeePerGas: bigint }) {\n    super(\n      `\\`maxFeePerGas\\` cannot be less than the \\`maxPriorityFeePerGas\\` (${formatGwei(\n        maxPriorityFeePerGas,\n      )} gwei).`,\n    )\n  }\n}\n","import type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport {\n  Eip1559FeesNotSupportedError,\n  type Eip1559FeesNotSupportedErrorType,\n} from '../../errors/fee.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Account } from '../../types/account.js'\nimport type { Block } from '../../types/block.js'\nimport type { Chain, ChainFeesFnParameters } from '../../types/chain.js'\nimport type { GetChain } from '../../types/chain.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport {\n  type HexToBigIntErrorType,\n  hexToBigInt,\n} from '../../utils/encoding/fromHex.js'\nimport { getAction } from '../../utils/getAction.js'\nimport type { PrepareTransactionRequestParameters } from '../wallet/prepareTransactionRequest.js'\nimport { type GetBlockErrorType, getBlock } from './getBlock.js'\nimport { type GetGasPriceErrorType, getGasPrice } from './getGasPrice.js'\n\nexport type EstimateMaxPriorityFeePerGasParameters<\n  chain extends Chain | undefined = Chain | undefined,\n  chainOverride extends Chain | undefined = Chain | undefined,\n> = GetChain<chain, chainOverride>\n\nexport type EstimateMaxPriorityFeePerGasReturnType = bigint\n\nexport type EstimateMaxPriorityFeePerGasErrorType =\n  | GetBlockErrorType\n  | HexToBigIntErrorType\n  | RequestErrorType\n  | GetBlockErrorType\n  | GetGasPriceErrorType\n  | Eip1559FeesNotSupportedErrorType\n  | ErrorType\n\n/**\n * Returns an estimate for the max priority fee per gas (in wei) for a\n * transaction to be likely included in the next block.\n * Defaults to [`chain.fees.defaultPriorityFee`](/docs/clients/chains.html#fees-defaultpriorityfee) if set.\n *\n * - Docs: https://viem.sh/docs/actions/public/estimateMaxPriorityFeePerGas.html\n *\n * @param client - Client to use\n * @returns An estimate (in wei) for the max priority fee per gas. {@link EstimateMaxPriorityFeePerGasReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { estimateMaxPriorityFeePerGas } from 'viem/actions'\n *\n * const client = createPublicClient({\n *   chain: mainnet,\n *   transport: http(),\n * })\n * const maxPriorityFeePerGas = await estimateMaxPriorityFeePerGas(client)\n * // 10000000n\n */\nexport async function estimateMaxPriorityFeePerGas<\n  chain extends Chain | undefined,\n  chainOverride extends Chain | undefined,\n>(\n  client: Client<Transport, chain>,\n  args?: EstimateMaxPriorityFeePerGasParameters<chain, chainOverride>,\n): Promise<EstimateMaxPriorityFeePerGasReturnType> {\n  return internal_estimateMaxPriorityFeePerGas(client, args as any)\n}\n\nexport async function internal_estimateMaxPriorityFeePerGas<\n  chain extends Chain | undefined,\n  chainOverride extends Chain | undefined,\n>(\n  client: Client<Transport, chain>,\n  args: EstimateMaxPriorityFeePerGasParameters<chain, chainOverride> & {\n    block?: Block\n    request?: PrepareTransactionRequestParameters<\n      chain,\n      Account | undefined,\n      chainOverride\n    >\n  },\n): Promise<EstimateMaxPriorityFeePerGasReturnType> {\n  const { block: block_, chain = client.chain, request } = args || {}\n  if (typeof chain?.fees?.defaultPriorityFee === 'function') {\n    const block = block_ || (await getAction(client, getBlock, 'getBlock')({}))\n    return chain.fees.defaultPriorityFee({\n      block,\n      client,\n      request,\n    } as ChainFeesFnParameters)\n  }\n\n  if (typeof chain?.fees?.defaultPriorityFee !== 'undefined')\n    return chain?.fees?.defaultPriorityFee\n\n  try {\n    const maxPriorityFeePerGasHex = await client.request({\n      method: 'eth_maxPriorityFeePerGas',\n    })\n    return hexToBigInt(maxPriorityFeePerGasHex)\n  } catch {\n    // If the RPC Provider does not support `eth_maxPriorityFeePerGas`\n    // fall back to calculating it manually via `gasPrice - baseFeePerGas`.\n    // See: https://github.com/ethereum/pm/issues/328#:~:text=eth_maxPriorityFeePerGas%20after%20London%20will%20effectively%20return%20eth_gasPrice%20%2D%20baseFee\n    const [block, gasPrice] = await Promise.all([\n      block_\n        ? Promise.resolve(block_)\n        : getAction(client, getBlock, 'getBlock')({}),\n      getAction(client, getGasPrice, 'getGasPrice')({}),\n    ])\n\n    if (typeof block.baseFeePerGas !== 'bigint')\n      throw new Eip1559FeesNotSupportedError()\n\n    const maxPriorityFeePerGas = gasPrice - block.baseFeePerGas\n\n    if (maxPriorityFeePerGas < 0n) return 0n\n    return maxPriorityFeePerGas\n  }\n}\n","import type { Hash } from '../types/misc.js'\n\nimport { BaseError } from './base.js'\n\nexport type BlockNotFoundErrorType = BlockNotFoundError & {\n  name: 'BlockNotFoundError'\n}\nexport class BlockNotFoundError extends BaseError {\n  override name = 'BlockNotFoundError'\n  constructor({\n    blockHash,\n    blockNumber,\n  }: {\n    blockHash?: Hash\n    blockNumber?: bigint\n  }) {\n    let identifier = 'Block'\n    if (blockHash) identifier = `Block at hash \"${blockHash}\"`\n    if (blockNumber) identifier = `Block at number \"${blockNumber}\"`\n    super(`${identifier} could not be found.`)\n  }\n}\n","import type { Account } from '../../accounts/types.js'\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport {\n  BlockNotFoundError,\n  type BlockNotFoundErrorType,\n} from '../../errors/block.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { BlockTag } from '../../types/block.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Hash } from '../../types/misc.js'\nimport type { RpcBlock } from '../../types/rpc.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport {\n  type NumberToHexErrorType,\n  numberToHex,\n} from '../../utils/encoding/toHex.js'\nimport {\n  type FormattedBlock,\n  formatBlock,\n} from '../../utils/formatters/block.js'\n\nexport type GetBlockParameters<\n  TIncludeTransactions extends boolean = false,\n  TBlockTag extends BlockTag = 'latest',\n> = {\n  /** Whether or not to include transaction data in the response. */\n  includeTransactions?: TIncludeTransactions\n} & (\n  | {\n      /** Hash of the block. */\n      blockHash?: Hash\n      blockNumber?: never\n      blockTag?: never\n    }\n  | {\n      blockHash?: never\n      /** The block number. */\n      blockNumber?: bigint\n      blockTag?: never\n    }\n  | {\n      blockHash?: never\n      blockNumber?: never\n      /**\n       * The block tag.\n       * @default 'latest'\n       */\n      blockTag?: TBlockTag | BlockTag\n    }\n)\n\nexport type GetBlockReturnType<\n  TChain extends Chain | undefined = Chain | undefined,\n  TIncludeTransactions extends boolean = false,\n  TBlockTag extends BlockTag = 'latest',\n> = FormattedBlock<TChain, TIncludeTransactions, TBlockTag>\n\nexport type GetBlockErrorType =\n  | BlockNotFoundErrorType\n  | NumberToHexErrorType\n  | RequestErrorType\n  | ErrorType\n\n/**\n * Returns information about a block at a block number, hash, or tag.\n *\n * - Docs: https://viem.sh/docs/actions/public/getBlock.html\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/blocks/fetching-blocks\n * - JSON-RPC Methods:\n *   - Calls [`eth_getBlockByNumber`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getblockbynumber) for `blockNumber` & `blockTag`.\n *   - Calls [`eth_getBlockByHash`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getblockbyhash) for `blockHash`.\n *\n * @param client - Client to use\n * @param parameters - {@link GetBlockParameters}\n * @returns Information about the block. {@link GetBlockReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getBlock } from 'viem/public'\n *\n * const client = createPublicClient({\n *   chain: mainnet,\n *   transport: http(),\n * })\n * const block = await getBlock(client)\n */\nexport async function getBlock<\n  TChain extends Chain | undefined,\n  TAccount extends Account | undefined,\n  TIncludeTransactions extends boolean = false,\n  TBlockTag extends BlockTag = 'latest',\n>(\n  client: Client<Transport, TChain, TAccount>,\n  {\n    blockHash,\n    blockNumber,\n    blockTag: blockTag_,\n    includeTransactions: includeTransactions_,\n  }: GetBlockParameters<TIncludeTransactions, TBlockTag> = {},\n): Promise<GetBlockReturnType<TChain, TIncludeTransactions, TBlockTag>> {\n  const blockTag = blockTag_ ?? 'latest'\n  const includeTransactions = includeTransactions_ ?? false\n\n  const blockNumberHex =\n    blockNumber !== undefined ? numberToHex(blockNumber) : undefined\n\n  let block: RpcBlock | null = null\n  if (blockHash) {\n    block = await client.request({\n      method: 'eth_getBlockByHash',\n      params: [blockHash, includeTransactions],\n    })\n  } else {\n    block = await client.request({\n      method: 'eth_getBlockByNumber',\n      params: [blockNumberHex || blockTag, includeTransactions],\n    })\n  }\n\n  if (!block) throw new BlockNotFoundError({ blockHash, blockNumber })\n\n  const format = client.chain?.formatters?.block?.format || formatBlock\n  return format(block)\n}\n","import type { Account } from '../../accounts/types.js'\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\n\nexport type GetGasPriceReturnType = bigint\n\nexport type GetGasPriceErrorType = RequestErrorType | ErrorType\n\n/**\n * Returns the current price of gas (in wei).\n *\n * - Docs: https://viem.sh/docs/actions/public/getGasPrice.html\n * - JSON-RPC Methods: [`eth_gasPrice`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_gasprice)\n *\n * @param client - Client to use\n * @returns The gas price (in wei). {@link GetGasPriceReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getGasPrice } from 'viem/public'\n *\n * const client = createPublicClient({\n *   chain: mainnet,\n *   transport: http(),\n * })\n * const gasPrice = await getGasPrice(client)\n */\nexport async function getGasPrice<\n  TChain extends Chain | undefined,\n  TAccount extends Account | undefined,\n>(client: Client<Transport, TChain, TAccount>): Promise<GetGasPriceReturnType> {\n  const gasPrice = await client.request({\n    method: 'eth_gasPrice',\n  })\n  return BigInt(gasPrice)\n}\n","import type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport {\n  BaseFeeScalarError,\n  type BaseFeeScalarErrorType,\n  Eip1559FeesNotSupportedError,\n  type Eip1559FeesNotSupportedErrorType,\n} from '../../errors/fee.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Block } from '../../types/block.js'\nimport type {\n  Chain,\n  ChainEstimateFeesPerGasFnParameters,\n  ChainFeesFnParameters,\n} from '../../types/chain.js'\nimport type { GetChain } from '../../types/chain.js'\nimport type {\n  FeeValuesEIP1559,\n  FeeValuesLegacy,\n  FeeValuesType,\n} from '../../types/fee.js'\nimport { getAction } from '../../utils/getAction.js'\nimport type { PrepareTransactionRequestParameters } from '../wallet/prepareTransactionRequest.js'\nimport {\n  type EstimateMaxPriorityFeePerGasErrorType,\n  internal_estimateMaxPriorityFeePerGas,\n} from './estimateMaxPriorityFeePerGas.js'\nimport { getBlock } from './getBlock.js'\nimport { type GetGasPriceErrorType, getGasPrice } from './getGasPrice.js'\n\nexport type EstimateFeesPerGasParameters<\n  chain extends Chain | undefined = Chain | undefined,\n  chainOverride extends Chain | undefined = Chain | undefined,\n  type extends FeeValuesType = FeeValuesType,\n> = {\n  /**\n   * The type of fee values to return.\n   *\n   * - `legacy`: Returns the legacy gas price.\n   * - `eip1559`: Returns the max fee per gas and max priority fee per gas.\n   *\n   * @default 'eip1559'\n   */\n  type?: type | FeeValuesType\n} & GetChain<chain, chainOverride>\n\nexport type EstimateFeesPerGasReturnType<\n  type extends FeeValuesType = FeeValuesType,\n> =\n  | (type extends 'legacy' ? FeeValuesLegacy : never)\n  | (type extends 'eip1559' ? FeeValuesEIP1559 : never)\n\nexport type EstimateFeesPerGasErrorType =\n  | BaseFeeScalarErrorType\n  | EstimateMaxPriorityFeePerGasErrorType\n  | GetGasPriceErrorType\n  | Eip1559FeesNotSupportedErrorType\n  | ErrorType\n\n/**\n * Returns an estimate for the fees per gas (in wei) for a\n * transaction to be likely included in the next block.\n * Defaults to [`chain.fees.estimateFeesPerGas`](/docs/clients/chains.html#fees-estimatefeespergas) if set.\n *\n * - Docs: https://viem.sh/docs/actions/public/estimateFeesPerGas.html\n *\n * @param client - Client to use\n * @param parameters - {@link EstimateFeesPerGasParameters}\n * @returns An estimate (in wei) for the fees per gas. {@link EstimateFeesPerGasReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { estimateFeesPerGas } from 'viem/actions'\n *\n * const client = createPublicClient({\n *   chain: mainnet,\n *   transport: http(),\n * })\n * const maxPriorityFeePerGas = await estimateFeesPerGas(client)\n * // { maxFeePerGas: ..., maxPriorityFeePerGas: ... }\n */\nexport async function estimateFeesPerGas<\n  chain extends Chain | undefined,\n  chainOverride extends Chain | undefined,\n  type extends FeeValuesType = 'eip1559',\n>(\n  client: Client<Transport, chain>,\n  args?: EstimateFeesPerGasParameters<chain, chainOverride, type>,\n): Promise<EstimateFeesPerGasReturnType<type>> {\n  return internal_estimateFeesPerGas(client, args as any)\n}\n\nexport async function internal_estimateFeesPerGas<\n  chain extends Chain | undefined,\n  chainOverride extends Chain | undefined,\n  type extends FeeValuesType = 'eip1559',\n>(\n  client: Client<Transport, chain>,\n  args: EstimateFeesPerGasParameters<chain, chainOverride, type> & {\n    block?: Block\n    request?: PrepareTransactionRequestParameters\n  },\n): Promise<EstimateFeesPerGasReturnType<type>> {\n  const {\n    block: block_,\n    chain = client.chain,\n    request,\n    type = 'eip1559',\n  } = args || {}\n\n  const baseFeeMultiplier = await (async () => {\n    if (typeof chain?.fees?.baseFeeMultiplier === 'function')\n      return chain.fees.baseFeeMultiplier({\n        block: block_ as Block,\n        client,\n        request,\n      } as ChainFeesFnParameters)\n    return chain?.fees?.baseFeeMultiplier ?? 1.2\n  })()\n  if (baseFeeMultiplier < 1) throw new BaseFeeScalarError()\n\n  const decimals = baseFeeMultiplier.toString().split('.')[1]?.length ?? 0\n  const denominator = 10 ** decimals\n  const multiply = (base: bigint) =>\n    (base * BigInt(Math.ceil(baseFeeMultiplier * denominator))) /\n    BigInt(denominator)\n\n  const block = block_\n    ? block_\n    : await getAction(client, getBlock, 'getBlock')({})\n\n  if (typeof chain?.fees?.estimateFeesPerGas === 'function')\n    return chain.fees.estimateFeesPerGas({\n      block: block_ as Block,\n      client,\n      multiply,\n      request,\n      type,\n    } as ChainEstimateFeesPerGasFnParameters) as unknown as EstimateFeesPerGasReturnType<type>\n\n  if (type === 'eip1559') {\n    if (typeof block.baseFeePerGas !== 'bigint')\n      throw new Eip1559FeesNotSupportedError()\n\n    const maxPriorityFeePerGas = request?.maxPriorityFeePerGas\n      ? request.maxPriorityFeePerGas\n      : await internal_estimateMaxPriorityFeePerGas(\n          client as Client<Transport, Chain>,\n          {\n            block,\n            chain,\n            request,\n          },\n        )\n\n    const baseFeePerGas = multiply(block.baseFeePerGas)\n    const maxFeePerGas =\n      request?.maxFeePerGas ?? baseFeePerGas + maxPriorityFeePerGas\n\n    return {\n      maxFeePerGas,\n      maxPriorityFeePerGas,\n    } as EstimateFeesPerGasReturnType<type>\n  }\n\n  const gasPrice =\n    request?.gasPrice ??\n    multiply(await getAction(client, getGasPrice, 'getGasPrice')({}))\n  return {\n    gasPrice,\n  } as EstimateFeesPerGasReturnType<type>\n}\n","import type { Address } from 'abitype'\n\nimport type { Account } from '../../accounts/types.js'\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { BlockTag } from '../../types/block.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport {\n  type HexToNumberErrorType,\n  hexToNumber,\n} from '../../utils/encoding/fromHex.js'\nimport {\n  type NumberToHexErrorType,\n  numberToHex,\n} from '../../utils/encoding/toHex.js'\n\nexport type GetTransactionCountParameters = {\n  /** The account address. */\n  address: Address\n} & (\n  | {\n      /** The block number. */\n      blockNumber?: bigint\n      blockTag?: never\n    }\n  | {\n      blockNumber?: never\n      /** The block tag. Defaults to 'latest'. */\n      blockTag?: BlockTag\n    }\n)\nexport type GetTransactionCountReturnType = number\n\nexport type GetTransactionCountErrorType =\n  | RequestErrorType\n  | NumberToHexErrorType\n  | HexToNumberErrorType\n  | ErrorType\n\n/**\n * Returns the number of [Transactions](https://viem.sh/docs/glossary/terms.html#transaction) an Account has broadcast / sent.\n *\n * - Docs: https://viem.sh/docs/actions/public/getTransactionCount.html\n * - JSON-RPC Methods: [`eth_getTransactionCount`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_gettransactioncount)\n *\n * @param client - Client to use\n * @param parameters - {@link GetTransactionCountParameters}\n * @returns The number of transactions an account has sent. {@link GetTransactionCountReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getTransactionCount } from 'viem/public'\n *\n * const client = createPublicClient({\n *   chain: mainnet,\n *   transport: http(),\n * })\n * const transactionCount = await getTransactionCount(client, {\n *   address: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',\n * })\n */\nexport async function getTransactionCount<\n  TChain extends Chain | undefined,\n  TAccount extends Account | undefined,\n>(\n  client: Client<Transport, TChain, TAccount>,\n  { address, blockTag = 'latest', blockNumber }: GetTransactionCountParameters,\n): Promise<GetTransactionCountReturnType> {\n  const count = await client.request({\n    method: 'eth_getTransactionCount',\n    params: [address, blockNumber ? numberToHex(blockNumber) : blockTag],\n  })\n  return hexToNumber(count)\n}\n","import {\n  InvalidSerializableTransactionError,\n  type InvalidSerializableTransactionErrorType,\n} from '../../errors/transaction.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type {\n  TransactionSerializable,\n  TransactionSerializableEIP1559,\n  TransactionSerializableEIP2930,\n  TransactionSerializableGeneric,\n  TransactionSerializableLegacy,\n} from '../../types/transaction.js'\n\nexport type GetTransactionType<\n  TTransactionSerializable extends\n    TransactionSerializable = TransactionSerializable,\n> =\n  | (TTransactionSerializable extends TransactionSerializableLegacy\n      ? 'legacy'\n      : never)\n  | (TTransactionSerializable extends TransactionSerializableEIP1559\n      ? 'eip1559'\n      : never)\n  | (TTransactionSerializable extends TransactionSerializableEIP2930\n      ? 'eip2930'\n      : never)\n  | (TTransactionSerializable extends TransactionSerializableGeneric\n      ? TTransactionSerializable['type']\n      : never)\n\nexport type GetTransationTypeErrorType =\n  | InvalidSerializableTransactionErrorType\n  | ErrorType\n\nexport function getTransactionType<\n  TTransactionSerializable extends TransactionSerializable,\n>(\n  transaction: TTransactionSerializable,\n): GetTransactionType<TTransactionSerializable> {\n  if (transaction.type)\n    return transaction.type as GetTransactionType<TTransactionSerializable>\n\n  if (\n    typeof transaction.maxFeePerGas !== 'undefined' ||\n    typeof transaction.maxPriorityFeePerGas !== 'undefined'\n  )\n    return 'eip1559' as GetTransactionType<TTransactionSerializable>\n\n  if (typeof transaction.gasPrice !== 'undefined') {\n    if (typeof transaction.accessList !== 'undefined')\n      return 'eip2930' as GetTransactionType<TTransactionSerializable>\n    return 'legacy' as GetTransactionType<TTransactionSerializable>\n  }\n\n  throw new InvalidSerializableTransactionError({ transaction })\n}\n","import type { Abi, Address } from 'abitype'\n\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { BlockNumber, BlockTag } from '../../types/block.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { GetEventArgs, InferEventName } from '../../types/contract.js'\nimport type { Log } from '../../types/log.js'\nimport type { Hash } from '../../types/misc.js'\nimport {\n  type GetAbiItemErrorType,\n  type GetAbiItemParameters,\n  getAbiItem,\n} from '../../utils/abi/getAbiItem.js'\nimport { getAction } from '../../utils/getAction.js'\nimport {\n  type GetLogsErrorType,\n  type GetLogsParameters,\n  getLogs,\n} from './getLogs.js'\n\nexport type GetContractEventsParameters<\n  TAbi extends Abi | readonly unknown[] = readonly unknown[],\n  TEventName extends string | undefined = string | undefined,\n  TStrict extends boolean | undefined = undefined,\n  TFromBlock extends BlockNumber | BlockTag | undefined = undefined,\n  TToBlock extends BlockNumber | BlockTag | undefined = undefined,\n> = {\n  /** The address of the contract. */\n  address?: Address | Address[]\n  /** Contract ABI. */\n  abi: TAbi\n  args?: TEventName extends string ? GetEventArgs<TAbi, TEventName> : undefined\n  /** Contract event. */\n  eventName?: InferEventName<TAbi, TEventName>\n  /**\n   * Whether or not the logs must match the indexed/non-indexed arguments on `event`.\n   * @default false\n   */\n  strict?: TStrict\n} & (\n  | {\n      /** Block number or tag after which to include logs */\n      fromBlock?: TFromBlock | BlockNumber | BlockTag\n      /** Block number or tag before which to include logs */\n      toBlock?: TToBlock | BlockNumber | BlockTag\n      blockHash?: never\n    }\n  | {\n      fromBlock?: never\n      toBlock?: never\n      /** Hash of block to include logs from */\n      blockHash?: Hash\n    }\n)\n\nexport type GetContractEventsReturnType<\n  TAbi extends Abi | readonly unknown[] = readonly unknown[],\n  TEventName extends string | undefined = string | undefined,\n  TStrict extends boolean | undefined = undefined,\n  TFromBlock extends BlockNumber | BlockTag | undefined = undefined,\n  TToBlock extends BlockNumber | BlockTag | undefined = undefined,\n  _Pending extends boolean =\n    | (TFromBlock extends 'pending' ? true : false)\n    | (TToBlock extends 'pending' ? true : false),\n> = Log<bigint, number, _Pending, undefined, TStrict, TAbi, TEventName>[]\n\nexport type GetContractEventsErrorType =\n  | GetAbiItemErrorType\n  | GetLogsErrorType\n  | ErrorType\n\n/**\n * Returns a list of event logs emitted by a contract.\n *\n * - Docs: https://viem.sh/docs/actions/public/getContractEvents.html\n * - JSON-RPC Methods: [`eth_getLogs`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getlogs)\n *\n * @param client - Client to use\n * @param parameters - {@link GetContractEventsParameters}\n * @returns A list of event logs. {@link GetContractEventsReturnType}\n *\n * @example\n * import { createClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getContractEvents } from 'viem/public'\n * import { wagmiAbi } from './abi'\n *\n * const client = createClient({\n *   chain: mainnet,\n *   transport: http(),\n * })\n * const logs = await getContractEvents(client, {\n *  address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\n *  abi: wagmiAbi,\n *  eventName: 'Transfer'\n * })\n */\nexport async function getContractEvents<\n  TChain extends Chain | undefined,\n  const TAbi extends Abi | readonly unknown[],\n  TEventName extends string | undefined = undefined,\n  TStrict extends boolean | undefined = undefined,\n  TFromBlock extends BlockNumber | BlockTag | undefined = undefined,\n  TToBlock extends BlockNumber | BlockTag | undefined = undefined,\n>(\n  client: Client<Transport, TChain>,\n  {\n    abi,\n    address,\n    args,\n    blockHash,\n    eventName,\n    fromBlock,\n    toBlock,\n    strict,\n  }: GetContractEventsParameters<\n    TAbi,\n    TEventName,\n    TStrict,\n    TFromBlock,\n    TToBlock\n  >,\n): Promise<\n  GetContractEventsReturnType<TAbi, TEventName, TStrict, TFromBlock, TToBlock>\n> {\n  const event = eventName\n    ? getAbiItem({ abi, name: eventName } as GetAbiItemParameters)\n    : undefined\n  const events = !event\n    ? (abi as Abi).filter((x) => x.type === 'event')\n    : undefined\n  return getAction(\n    client,\n    getLogs,\n    'getLogs',\n  )({\n    address,\n    args,\n    blockHash,\n    event,\n    events,\n    fromBlock,\n    toBlock,\n    strict,\n  } as {} as GetLogsParameters) as unknown as GetContractEventsReturnType<\n    TAbi,\n    TEventName,\n    TStrict,\n    TFromBlock,\n    TToBlock\n  >\n}\n","import type { Abi, AbiEvent, Address } from 'abitype'\n\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport {\n  DecodeLogDataMismatch,\n  DecodeLogTopicsMismatch,\n} from '../../errors/abi.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { BlockNumber, BlockTag } from '../../types/block.js'\nimport type { Chain } from '../../types/chain.js'\nimport type {\n  MaybeAbiEventName,\n  MaybeExtractEventArgsFromAbi,\n} from '../../types/contract.js'\nimport type { Log } from '../../types/log.js'\nimport type { Hash, LogTopic } from '../../types/misc.js'\nimport type { RpcLog } from '../../types/rpc.js'\nimport {\n  type DecodeEventLogErrorType,\n  decodeEventLog,\n} from '../../utils/abi/decodeEventLog.js'\nimport {\n  type EncodeEventTopicsErrorType,\n  type EncodeEventTopicsParameters,\n  encodeEventTopics,\n} from '../../utils/abi/encodeEventTopics.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport {\n  type NumberToHexErrorType,\n  numberToHex,\n} from '../../utils/encoding/toHex.js'\nimport {\n  type FormatLogErrorType,\n  formatLog,\n} from '../../utils/formatters/log.js'\n\nexport type GetLogsParameters<\n  TAbiEvent extends AbiEvent | undefined = undefined,\n  TAbiEvents extends\n    | readonly AbiEvent[]\n    | readonly unknown[]\n    | undefined = TAbiEvent extends AbiEvent ? [TAbiEvent] : undefined,\n  TStrict extends boolean | undefined = undefined,\n  TFromBlock extends BlockNumber | BlockTag | undefined = undefined,\n  TToBlock extends BlockNumber | BlockTag | undefined = undefined,\n  _EventName extends string | undefined = MaybeAbiEventName<TAbiEvent>,\n> = {\n  /** Address or list of addresses from which logs originated */\n  address?: Address | Address[]\n} & (\n  | {\n      event: TAbiEvent\n      events?: never\n      args?: MaybeExtractEventArgsFromAbi<TAbiEvents, _EventName>\n      /**\n       * Whether or not the logs must match the indexed/non-indexed arguments on `event`.\n       * @default false\n       */\n      strict?: TStrict\n    }\n  | {\n      event?: never\n      events: TAbiEvents\n      args?: never\n      /**\n       * Whether or not the logs must match the indexed/non-indexed arguments on `event`.\n       * @default false\n       */\n      strict?: TStrict\n    }\n  | {\n      event?: never\n      events?: never\n      args?: never\n      strict?: never\n    }\n) &\n  (\n    | {\n        /** Block number or tag after which to include logs */\n        fromBlock?: TFromBlock | BlockNumber | BlockTag\n        /** Block number or tag before which to include logs */\n        toBlock?: TToBlock | BlockNumber | BlockTag\n        blockHash?: never\n      }\n    | {\n        fromBlock?: never\n        toBlock?: never\n        /** Hash of block to include logs from */\n        blockHash?: Hash\n      }\n  )\n\nexport type GetLogsReturnType<\n  TAbiEvent extends AbiEvent | undefined = undefined,\n  TAbiEvents extends\n    | readonly AbiEvent[]\n    | readonly unknown[]\n    | undefined = TAbiEvent extends AbiEvent ? [TAbiEvent] : undefined,\n  TStrict extends boolean | undefined = undefined,\n  TFromBlock extends BlockNumber | BlockTag | undefined = undefined,\n  TToBlock extends BlockNumber | BlockTag | undefined = undefined,\n  _EventName extends string | undefined = MaybeAbiEventName<TAbiEvent>,\n  _Pending extends boolean =\n    | (TFromBlock extends 'pending' ? true : false)\n    | (TToBlock extends 'pending' ? true : false),\n> = Log<bigint, number, _Pending, TAbiEvent, TStrict, TAbiEvents, _EventName>[]\n\nexport type GetLogsErrorType =\n  | DecodeEventLogErrorType\n  | EncodeEventTopicsErrorType\n  | FormatLogErrorType\n  | NumberToHexErrorType\n  | RequestErrorType\n  | ErrorType\n\n/**\n * Returns a list of event logs matching the provided parameters.\n *\n * - Docs: https://viem.sh/docs/actions/public/getLogs.html\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/filters-and-logs/event-logs\n * - JSON-RPC Methods: [`eth_getLogs`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getlogs)\n *\n * @param client - Client to use\n * @param parameters - {@link GetLogsParameters}\n * @returns A list of event logs. {@link GetLogsReturnType}\n *\n * @example\n * import { createPublicClient, http, parseAbiItem } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getLogs } from 'viem/public'\n *\n * const client = createPublicClient({\n *   chain: mainnet,\n *   transport: http(),\n * })\n * const logs = await getLogs(client)\n */\nexport async function getLogs<\n  TChain extends Chain | undefined,\n  const TAbiEvent extends AbiEvent | undefined = undefined,\n  const TAbiEvents extends\n    | readonly AbiEvent[]\n    | readonly unknown[]\n    | undefined = TAbiEvent extends AbiEvent ? [TAbiEvent] : undefined,\n  TStrict extends boolean | undefined = undefined,\n  TFromBlock extends BlockNumber | BlockTag | undefined = undefined,\n  TToBlock extends BlockNumber | BlockTag | undefined = undefined,\n>(\n  client: Client<Transport, TChain>,\n  {\n    address,\n    blockHash,\n    fromBlock,\n    toBlock,\n    event,\n    events: events_,\n    args,\n    strict: strict_,\n  }: GetLogsParameters<\n    TAbiEvent,\n    TAbiEvents,\n    TStrict,\n    TFromBlock,\n    TToBlock\n  > = {},\n): Promise<\n  GetLogsReturnType<TAbiEvent, TAbiEvents, TStrict, TFromBlock, TToBlock>\n> {\n  const strict = strict_ ?? false\n  const events = events_ ?? (event ? [event] : undefined)\n\n  let topics: LogTopic[] = []\n  if (events) {\n    topics = [\n      (events as AbiEvent[]).flatMap((event) =>\n        encodeEventTopics({\n          abi: [event],\n          eventName: (event as AbiEvent).name,\n          args,\n        } as EncodeEventTopicsParameters),\n      ),\n    ]\n    if (event) topics = topics[0] as LogTopic[]\n  }\n\n  let logs: RpcLog[]\n  if (blockHash) {\n    logs = await client.request({\n      method: 'eth_getLogs',\n      params: [{ address, topics, blockHash }],\n    })\n  } else {\n    logs = await client.request({\n      method: 'eth_getLogs',\n      params: [\n        {\n          address,\n          topics,\n          fromBlock:\n            typeof fromBlock === 'bigint' ? numberToHex(fromBlock) : fromBlock,\n          toBlock: typeof toBlock === 'bigint' ? numberToHex(toBlock) : toBlock,\n        },\n      ],\n    })\n  }\n\n  return logs\n    .map((log) => {\n      try {\n        const { eventName, args } = events\n          ? decodeEventLog({\n              abi: events as Abi,\n              data: log.data,\n              topics: log.topics as any,\n              strict,\n            })\n          : { eventName: undefined, args: undefined }\n        return formatLog(log, { args, eventName: eventName as string })\n      } catch (err) {\n        let eventName\n        let isUnnamed\n        if (\n          err instanceof DecodeLogDataMismatch ||\n          err instanceof DecodeLogTopicsMismatch\n        ) {\n          // If strict mode is on, and log data/topics do not match event definition, skip.\n          if (strict) return\n          eventName = err.abiItem.name\n          isUnnamed = err.abiItem.inputs?.some((x) => !('name' in x && x.name))\n        }\n\n        // Set args to empty if there is an error decoding (e.g. indexed/non-indexed params mismatch).\n        return formatLog(log, { args: isUnnamed ? [] : {}, eventName })\n      }\n    })\n    .filter(Boolean) as unknown as GetLogsReturnType<\n    TAbiEvent,\n    TAbiEvents,\n    TStrict,\n    TFromBlock,\n    TToBlock\n  >\n}\n","import type { Abi, AbiParameter, ExtractAbiEventNames } from 'abitype'\n\nimport {\n  AbiDecodingDataSizeTooSmallError,\n  type AbiDecodingDataSizeTooSmallErrorType,\n  AbiEventSignatureEmptyTopicsError,\n  type AbiEventSignatureEmptyTopicsErrorType,\n  AbiEventSignatureNotFoundError,\n  type AbiEventSignatureNotFoundErrorType,\n  DecodeLogDataMismatch,\n  type DecodeLogDataMismatchErrorType,\n  DecodeLogTopicsMismatch,\n  type DecodeLogTopicsMismatchErrorType,\n} from '../../errors/abi.js'\nimport type {\n  EventDefinition,\n  GetEventArgsFromTopics,\n  InferEventName,\n} from '../../types/contract.js'\nimport type { Hex } from '../../types/misc.js'\nimport type { Prettify } from '../../types/utils.js'\nimport {\n  type GetEventSelectorErrorType,\n  getEventSelector,\n} from '../hash/getEventSelector.js'\n\nimport type { ErrorType } from '../../errors/utils.js'\nimport {\n  type DecodeAbiParametersErrorType,\n  decodeAbiParameters,\n} from './decodeAbiParameters.js'\nimport { type FormatAbiItemErrorType, formatAbiItem } from './formatAbiItem.js'\n\nexport type DecodeEventLogParameters<\n  TAbi extends Abi | readonly unknown[] = Abi,\n  TEventName extends string | undefined = string,\n  TTopics extends Hex[] = Hex[],\n  TData extends Hex | undefined = undefined,\n  TStrict extends boolean = true,\n> = {\n  abi: TAbi\n  data?: TData\n  eventName?: InferEventName<TAbi, TEventName>\n  strict?: TStrict\n  topics: [signature: Hex, ...args: TTopics] | []\n}\n\nexport type DecodeEventLogReturnType<\n  TAbi extends Abi | readonly unknown[] = Abi,\n  TEventName extends string | undefined = string,\n  TTopics extends Hex[] = Hex[],\n  TData extends Hex | undefined = undefined,\n  TStrict extends boolean = true,\n  _EventNames extends string = TAbi extends Abi\n    ? Abi extends TAbi\n      ? string\n      : ExtractAbiEventNames<TAbi>\n    : string,\n> = TEventName extends _EventNames[number]\n  ? Prettify<\n      {\n        eventName: TEventName\n      } & GetEventArgsFromTopics<TAbi, TEventName, TTopics, TData, TStrict>\n    >\n  : {\n      [TName in _EventNames]: Prettify<\n        {\n          eventName: TName\n        } & GetEventArgsFromTopics<TAbi, TName, TTopics, TData, TStrict>\n      >\n    }[_EventNames]\n\nexport type DecodeEventLogErrorType =\n  | AbiDecodingDataSizeTooSmallErrorType\n  | AbiEventSignatureEmptyTopicsErrorType\n  | AbiEventSignatureNotFoundErrorType\n  | DecodeAbiParametersErrorType\n  | DecodeLogTopicsMismatchErrorType\n  | DecodeLogDataMismatchErrorType\n  | FormatAbiItemErrorType\n  | GetEventSelectorErrorType\n  | ErrorType\n\nconst docsPath = '/docs/contract/decodeEventLog'\n\nexport function decodeEventLog<\n  const TAbi extends Abi | readonly unknown[],\n  TEventName extends string | undefined = undefined,\n  TTopics extends Hex[] = Hex[],\n  TData extends Hex | undefined = undefined,\n  TStrict extends boolean = true,\n>({\n  abi,\n  data,\n  strict: strict_,\n  topics,\n}: DecodeEventLogParameters<\n  TAbi,\n  TEventName,\n  TTopics,\n  TData,\n  TStrict\n>): DecodeEventLogReturnType<TAbi, TEventName, TTopics, TData, TStrict> {\n  const strict = strict_ ?? true\n  const [signature, ...argTopics] = topics\n  if (!signature)\n    throw new AbiEventSignatureEmptyTopicsError({\n      docsPath,\n    })\n  const abiItem = (abi as Abi).find(\n    (x) =>\n      x.type === 'event' &&\n      signature === getEventSelector(formatAbiItem(x) as EventDefinition),\n  )\n  if (!(abiItem && 'name' in abiItem) || abiItem.type !== 'event')\n    throw new AbiEventSignatureNotFoundError(signature, {\n      docsPath,\n    })\n\n  const { name, inputs } = abiItem\n  const isUnnamed = inputs?.some((x) => !('name' in x && x.name))\n\n  let args: any = isUnnamed ? [] : {}\n\n  // Decode topics (indexed args).\n  const indexedInputs = inputs.filter((x) => 'indexed' in x && x.indexed)\n  for (let i = 0; i < indexedInputs.length; i++) {\n    const param = indexedInputs[i]\n    const topic = argTopics[i]\n    if (!topic)\n      throw new DecodeLogTopicsMismatch({\n        abiItem,\n        param: param as AbiParameter & { indexed: boolean },\n      })\n    args[param.name || i] = decodeTopic({ param, value: topic })\n  }\n\n  // Decode data (non-indexed args).\n  const nonIndexedInputs = inputs.filter((x) => !('indexed' in x && x.indexed))\n  if (nonIndexedInputs.length > 0) {\n    if (data && data !== '0x') {\n      try {\n        const decodedData = decodeAbiParameters(nonIndexedInputs, data)\n        if (decodedData) {\n          if (isUnnamed) args = [...args, ...decodedData]\n          else {\n            for (let i = 0; i < nonIndexedInputs.length; i++) {\n              args[nonIndexedInputs[i].name!] = decodedData[i]\n            }\n          }\n        }\n      } catch (err) {\n        if (strict) {\n          if (err instanceof AbiDecodingDataSizeTooSmallError)\n            throw new DecodeLogDataMismatch({\n              abiItem,\n              data: err.data,\n              params: err.params,\n              size: err.size,\n            })\n          throw err\n        }\n      }\n    } else if (strict) {\n      throw new DecodeLogDataMismatch({\n        abiItem,\n        data: '0x',\n        params: nonIndexedInputs,\n        size: 0,\n      })\n    }\n  }\n\n  return {\n    eventName: name,\n    args: Object.values(args).length > 0 ? args : undefined,\n  } as unknown as DecodeEventLogReturnType<\n    TAbi,\n    TEventName,\n    TTopics,\n    TData,\n    TStrict\n  >\n}\n\nfunction decodeTopic({ param, value }: { param: AbiParameter; value: Hex }) {\n  if (\n    param.type === 'string' ||\n    param.type === 'bytes' ||\n    param.type === 'tuple' ||\n    param.type.match(/^(.*)\\[(\\d+)?\\]$/)\n  )\n    return value\n  const decodedArg = decodeAbiParameters([param], value) || []\n  return decodedArg[0]\n}\n","import type { Abi } from 'abitype'\n\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { BaseError } from '../../errors/base.js'\nimport type { Chain } from '../../types/chain.js'\nimport type {\n  ContractFunctionConfig,\n  ContractFunctionResult,\n} from '../../types/contract.js'\nimport {\n  type DecodeFunctionResultErrorType,\n  type DecodeFunctionResultParameters,\n  decodeFunctionResult,\n} from '../../utils/abi/decodeFunctionResult.js'\nimport {\n  type EncodeFunctionDataErrorType,\n  type EncodeFunctionDataParameters,\n  encodeFunctionData,\n} from '../../utils/abi/encodeFunctionData.js'\nimport {\n  type GetContractErrorReturnType,\n  getContractError,\n} from '../../utils/errors/getContractError.js'\nimport { getAction } from '../../utils/getAction.js'\n\nimport { type CallErrorType, type CallParameters, call } from './call.js'\n\nexport type ReadContractParameters<\n  TAbi extends Abi | readonly unknown[] = Abi,\n  TFunctionName extends string = string,\n> = Pick<CallParameters, 'account' | 'blockNumber' | 'blockTag'> &\n  ContractFunctionConfig<TAbi, TFunctionName, 'view' | 'pure'>\n\nexport type ReadContractReturnType<\n  TAbi extends Abi | readonly unknown[] = Abi,\n  TFunctionName extends string = string,\n> = ContractFunctionResult<TAbi, TFunctionName>\n\nexport type ReadContractErrorType = GetContractErrorReturnType<\n  CallErrorType | EncodeFunctionDataErrorType | DecodeFunctionResultErrorType\n>\n\n/**\n * Calls a read-only function on a contract, and returns the response.\n *\n * - Docs: https://viem.sh/docs/contract/readContract.html\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/contracts/reading-contracts\n *\n * A \"read-only\" function (constant function) on a Solidity contract is denoted by a `view` or `pure` keyword. They can only read the state of the contract, and cannot make any changes to it. Since read-only methods do not change the state of the contract, they do not require any gas to be executed, and can be called by any user without the need to pay for gas.\n *\n * Internally, uses a [Public Client](https://viem.sh/docs/clients/public.html) to call the [`call` action](https://viem.sh/docs/actions/public/call.html) with [ABI-encoded `data`](https://viem.sh/docs/contract/encodeFunctionData.html).\n *\n * @param client - Client to use\n * @param parameters - {@link ReadContractParameters}\n * @returns The response from the contract. Type is inferred. {@link ReadContractReturnType}\n *\n * @example\n * import { createPublicClient, http, parseAbi } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { readContract } from 'viem/contract'\n *\n * const client = createPublicClient({\n *   chain: mainnet,\n *   transport: http(),\n * })\n * const result = await readContract(client, {\n *   address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\n *   abi: parseAbi(['function balanceOf(address) view returns (uint256)']),\n *   functionName: 'balanceOf',\n *   args: ['0xA0Cf798816D4b9b9866b5330EEa46a18382f251e'],\n * })\n * // 424122n\n */\nexport async function readContract<\n  TChain extends Chain | undefined,\n  const TAbi extends Abi | readonly unknown[],\n  TFunctionName extends string,\n>(\n  client: Client<Transport, TChain>,\n  {\n    abi,\n    address,\n    args,\n    functionName,\n    ...callRequest\n  }: ReadContractParameters<TAbi, TFunctionName>,\n): Promise<ReadContractReturnType<TAbi, TFunctionName>> {\n  const calldata = encodeFunctionData({\n    abi,\n    args,\n    functionName,\n  } as unknown as EncodeFunctionDataParameters<TAbi, TFunctionName>)\n  try {\n    const { data } = await getAction(\n      client,\n      call,\n      'call',\n    )({\n      data: calldata,\n      to: address,\n      ...callRequest,\n    } as unknown as CallParameters)\n    return decodeFunctionResult({\n      abi,\n      args,\n      functionName,\n      data: data || '0x',\n    } as DecodeFunctionResultParameters<\n      TAbi,\n      TFunctionName\n    >) as ReadContractReturnType<TAbi, TFunctionName>\n  } catch (err) {\n    throw getContractError(err as BaseError, {\n      abi: abi as Abi,\n      address,\n      args,\n      docsPath: '/docs/contract/readContract',\n      functionName,\n    })\n  }\n}\n","import type { Abi } from 'abitype'\n\nimport {\n  type ParseAccountErrorType,\n  parseAccount,\n} from '../../accounts/utils/parseAccount.js'\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { BaseError } from '../../errors/base.js'\nimport type { Chain } from '../../types/chain.js'\nimport type {\n  ContractFunctionConfig,\n  ContractFunctionResult,\n  GetValue,\n} from '../../types/contract.js'\nimport type { Hex } from '../../types/misc.js'\nimport type { UnionOmit } from '../../types/utils.js'\nimport {\n  type DecodeFunctionResultErrorType,\n  type DecodeFunctionResultParameters,\n  decodeFunctionResult,\n} from '../../utils/abi/decodeFunctionResult.js'\nimport {\n  type EncodeFunctionDataErrorType,\n  type EncodeFunctionDataParameters,\n  encodeFunctionData,\n} from '../../utils/abi/encodeFunctionData.js'\nimport {\n  type GetContractErrorReturnType,\n  getContractError,\n} from '../../utils/errors/getContractError.js'\nimport type { WriteContractParameters } from '../wallet/writeContract.js'\n\nimport type { ErrorType } from '../../errors/utils.js'\nimport { getAction } from '../../utils/getAction.js'\nimport { type CallErrorType, type CallParameters, call } from './call.js'\n\nexport type SimulateContractParameters<\n  TAbi extends Abi | readonly unknown[] = Abi,\n  TFunctionName extends string = any,\n  TChain extends Chain | undefined = Chain | undefined,\n  TChainOverride extends Chain | undefined = Chain | undefined,\n> = {\n  chain?: TChainOverride\n  /** Data to append to the end of the calldata. Useful for adding a [\"domain\" tag](https://opensea.notion.site/opensea/Seaport-Order-Attributions-ec2d69bf455041a5baa490941aad307f). */\n  dataSuffix?: Hex\n} & ContractFunctionConfig<TAbi, TFunctionName, 'payable' | 'nonpayable'> &\n  UnionOmit<\n    CallParameters<TChainOverride extends Chain ? TChainOverride : TChain>,\n    'batch' | 'to' | 'data' | 'value'\n  > &\n  GetValue<\n    TAbi,\n    TFunctionName,\n    CallParameters<TChain> extends CallParameters\n      ? CallParameters<TChain>['value']\n      : CallParameters['value']\n  >\n\nexport type SimulateContractReturnType<\n  TAbi extends Abi | readonly unknown[] = Abi,\n  TFunctionName extends string = string,\n  TChain extends Chain | undefined = Chain | undefined,\n  TChainOverride extends Chain | undefined = Chain | undefined,\n> = {\n  result: ContractFunctionResult<TAbi, TFunctionName>\n  request: UnionOmit<\n    WriteContractParameters<\n      TAbi,\n      TFunctionName,\n      TChain,\n      undefined,\n      TChainOverride\n    >,\n    'chain' | 'functionName'\n  > & {\n    chain: TChainOverride\n    functionName: TFunctionName\n  } & ContractFunctionConfig<TAbi, TFunctionName, 'payable' | 'nonpayable'>\n}\n\nexport type SimulateContractErrorType =\n  | ParseAccountErrorType\n  | EncodeFunctionDataErrorType\n  | GetContractErrorReturnType<CallErrorType | DecodeFunctionResultErrorType>\n  | ErrorType\n\n/**\n * Simulates/validates a contract interaction. This is useful for retrieving **return data** and **revert reasons** of contract write functions.\n *\n * - Docs: https://viem.sh/docs/contract/simulateContract.html\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/contracts/writing-to-contracts\n *\n * This function does not require gas to execute and _**does not**_ change the state of the blockchain. It is almost identical to [`readContract`](https://viem.sh/docs/contract/readContract.html), but also supports contract write functions.\n *\n * Internally, uses a [Public Client](https://viem.sh/docs/clients/public.html) to call the [`call` action](https://viem.sh/docs/actions/public/call.html) with [ABI-encoded `data`](https://viem.sh/docs/contract/encodeFunctionData.html).\n *\n * @param client - Client to use\n * @param parameters - {@link SimulateContractParameters}\n * @returns The simulation result and write request. {@link SimulateContractReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { simulateContract } from 'viem/contract'\n *\n * const client = createPublicClient({\n *   chain: mainnet,\n *   transport: http(),\n * })\n * const result = await simulateContract(client, {\n *   address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\n *   abi: parseAbi(['function mint(uint32) view returns (uint32)']),\n *   functionName: 'mint',\n *   args: ['69420'],\n *   account: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',\n * })\n */\nexport async function simulateContract<\n  TChain extends Chain | undefined,\n  const TAbi extends Abi | readonly unknown[],\n  TFunctionName extends string,\n  TChainOverride extends Chain | undefined = undefined,\n>(\n  client: Client<Transport, TChain>,\n  {\n    abi,\n    address,\n    args,\n    dataSuffix,\n    functionName,\n    ...callRequest\n  }: SimulateContractParameters<TAbi, TFunctionName, TChain, TChainOverride>,\n): Promise<\n  SimulateContractReturnType<TAbi, TFunctionName, TChain, TChainOverride>\n> {\n  const account = callRequest.account\n    ? parseAccount(callRequest.account)\n    : undefined\n  const calldata = encodeFunctionData({\n    abi,\n    args,\n    functionName,\n  } as unknown as EncodeFunctionDataParameters<TAbi, TFunctionName>)\n  try {\n    const { data } = await getAction(\n      client,\n      call,\n      'call',\n    )({\n      batch: false,\n      data: `${calldata}${dataSuffix ? dataSuffix.replace('0x', '') : ''}`,\n      to: address,\n      ...callRequest,\n    } as unknown as CallParameters<TChain>)\n    const result = decodeFunctionResult({\n      abi,\n      args,\n      functionName,\n      data: data || '0x',\n    } as DecodeFunctionResultParameters)\n    return {\n      result,\n      request: {\n        abi,\n        address,\n        args,\n        dataSuffix,\n        functionName,\n        ...callRequest,\n      },\n    } as unknown as SimulateContractReturnType<\n      TAbi,\n      TFunctionName,\n      TChain,\n      TChainOverride\n    >\n  } catch (err) {\n    throw getContractError(err as BaseError, {\n      abi: abi as Abi,\n      address,\n      args,\n      docsPath: '/docs/contract/simulateContract',\n      functionName,\n      sender: account?.address,\n    })\n  }\n}\n","import type { ErrorType } from '../errors/utils.js'\nimport type { MaybePromise } from '../types/utils.js'\n\ntype Callback = ((...args: any[]) => any) | undefined\ntype Callbacks = Record<string, Callback>\n\nexport type ObserveErrorType = ErrorType\n\nexport const listenersCache = /*#__PURE__*/ new Map<\n  string,\n  { id: number; fns: Callbacks }[]\n>()\nexport const cleanupCache = /*#__PURE__*/ new Map<string, () => void>()\n\ntype EmitFunction<TCallbacks extends Callbacks> = (\n  emit: TCallbacks,\n) => MaybePromise<void | (() => void)>\n\nlet callbackCount = 0\n\n/**\n * @description Sets up an observer for a given function. If another function\n * is set up under the same observer id, the function will only be called once\n * for both instances of the observer.\n */\nexport function observe<TCallbacks extends Callbacks>(\n  observerId: string,\n  callbacks: TCallbacks,\n  fn: EmitFunction<TCallbacks>,\n) {\n  const callbackId = ++callbackCount\n\n  const getListeners = () => listenersCache.get(observerId) || []\n\n  const unsubscribe = () => {\n    const listeners = getListeners()\n    listenersCache.set(\n      observerId,\n      listeners.filter((cb: any) => cb.id !== callbackId),\n    )\n  }\n\n  const unwatch = () => {\n    const cleanup = cleanupCache.get(observerId)\n    if (getListeners().length === 1 && cleanup) cleanup()\n    unsubscribe()\n  }\n\n  const listeners = getListeners()\n  listenersCache.set(observerId, [\n    ...listeners,\n    { id: callbackId, fns: callbacks },\n  ])\n\n  if (listeners && listeners.length > 0) return unwatch\n\n  const emit: TCallbacks = {} as TCallbacks\n  for (const key in callbacks) {\n    emit[key] = ((\n      ...args: Parameters<NonNullable<TCallbacks[keyof TCallbacks]>>\n    ) => {\n      const listeners = getListeners()\n      if (listeners.length === 0) return\n      for (const listener of listeners) listener.fns[key]?.(...args)\n    }) as TCallbacks[Extract<keyof TCallbacks, string>]\n  }\n\n  const cleanup = fn(emit)\n  if (typeof cleanup === 'function') cleanupCache.set(observerId, cleanup)\n\n  return unwatch\n}\n","export async function wait(time: number) {\n  return new Promise((res) => setTimeout(res, time))\n}\n","import type { ErrorType } from '../errors/utils.js'\nimport { wait } from './wait.js'\n\ntype PollOptions<TData> = {\n  // Whether or not to emit when the polling starts.\n  emitOnBegin?: boolean\n  // The initial wait time (in ms) before polling.\n  initialWaitTime?: (data: TData | void) => Promise<number>\n  // The interval (in ms).\n  interval: number\n}\n\nexport type PollErrorType = ErrorType\n\n/**\n * @description Polls a function at a specified interval.\n */\nexport function poll<TData>(\n  fn: ({ unpoll }: { unpoll: () => void }) => Promise<TData | void>,\n  { emitOnBegin, initialWaitTime, interval }: PollOptions<TData>,\n) {\n  let active = true\n\n  const unwatch = () => (active = false)\n\n  const watch = async () => {\n    let data: TData | void = undefined\n    if (emitOnBegin) data = await fn({ unpoll: unwatch })\n\n    const initialWait = (await initialWaitTime?.(data)) ?? interval\n    await wait(initialWait)\n\n    const poll = async () => {\n      if (!active) return\n      await fn({ unpoll: unwatch })\n      await wait(interval)\n      poll()\n    }\n\n    poll()\n  }\n  watch()\n\n  return unwatch\n}\n","import type { Abi, Address, ExtractAbiEvent } from 'abitype'\n\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { GetEventArgs, InferEventName } from '../../types/contract.js'\nimport type { Filter } from '../../types/filter.js'\nimport type { Log } from '../../types/log.js'\nimport type { GetTransportConfig } from '../../types/transport.js'\n\nimport { type ObserveErrorType, observe } from '../../utils/observe.js'\nimport { poll } from '../../utils/poll.js'\nimport { type StringifyErrorType, stringify } from '../../utils/stringify.js'\n\nimport {\n  DecodeLogDataMismatch,\n  DecodeLogTopicsMismatch,\n} from '../../errors/abi.js'\nimport { InvalidInputRpcError } from '../../errors/rpc.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { LogTopic } from '../../types/misc.js'\nimport { decodeEventLog } from '../../utils/abi/decodeEventLog.js'\nimport {\n  type EncodeEventTopicsParameters,\n  encodeEventTopics,\n} from '../../utils/abi/encodeEventTopics.js'\nimport { formatLog } from '../../utils/formatters/log.js'\nimport { getAction } from '../../utils/getAction.js'\nimport {\n  type CreateContractEventFilterParameters,\n  createContractEventFilter,\n} from './createContractEventFilter.js'\nimport { getBlockNumber } from './getBlockNumber.js'\nimport {\n  type GetContractEventsParameters,\n  getContractEvents,\n} from './getContractEvents.js'\nimport { getFilterChanges } from './getFilterChanges.js'\nimport { uninstallFilter } from './uninstallFilter.js'\n\ntype PollOptions = {\n  /**\n   * Whether or not the transaction hashes should be batched on each invocation.\n   * @default true\n   */\n  batch?: boolean\n  /**\n   * Polling frequency (in ms). Defaults to Client's pollingInterval config.\n   * @default client.pollingInterval\n   */\n  pollingInterval?: number\n}\n\nexport type WatchContractEventOnLogsParameter<\n  TAbi extends Abi | readonly unknown[] = readonly unknown[],\n  TEventName extends string = string,\n  TStrict extends boolean | undefined = undefined,\n> = TAbi extends Abi\n  ? Log<bigint, number, false, ExtractAbiEvent<TAbi, TEventName>, TStrict>[]\n  : Log[]\nexport type WatchContractEventOnLogsFn<\n  TAbi extends Abi | readonly unknown[] = readonly unknown[],\n  TEventName extends string = string,\n  TStrict extends boolean | undefined = undefined,\n> = (logs: WatchContractEventOnLogsParameter<TAbi, TEventName, TStrict>) => void\n\nexport type WatchContractEventParameters<\n  TAbi extends Abi | readonly unknown[] = readonly unknown[],\n  TEventName extends string = string,\n  TStrict extends boolean | undefined = undefined,\n> = {\n  /** The address of the contract. */\n  address?: Address | Address[]\n  /** Contract ABI. */\n  abi: TAbi\n  args?: GetEventArgs<TAbi, TEventName>\n  /** Contract event. */\n  eventName?: InferEventName<TAbi, TEventName>\n  /** The callback to call when an error occurred when trying to get for a new block. */\n  onError?: (error: Error) => void\n  /** The callback to call when new event logs are received. */\n  onLogs: WatchContractEventOnLogsFn<TAbi, TEventName, TStrict>\n  /**\n   * Whether or not the logs must match the indexed/non-indexed arguments on `event`.\n   * @default false\n   */\n  strict?: TStrict\n} & (GetTransportConfig<Transport>['type'] extends 'webSocket'\n  ?\n      | {\n          batch?: never\n          /**\n           * Whether or not the WebSocket Transport should poll the JSON-RPC, rather than using `eth_subscribe`.\n           * @default false\n           */\n          poll?: false\n          pollingInterval?: never\n        }\n      | (PollOptions & {\n          /**\n           * Whether or not the WebSocket Transport should poll the JSON-RPC, rather than using `eth_subscribe`.\n           * @default true\n           */\n          poll?: true\n        })\n  : PollOptions & {\n      poll?: true\n    })\n\nexport type WatchContractEventReturnType = () => void\n\nexport type WatchContractEventErrorType =\n  | StringifyErrorType\n  | ObserveErrorType\n  | ErrorType\n\n/**\n * Watches and returns emitted contract event logs.\n *\n * - Docs: https://viem.sh/docs/contract/watchContractEvent.html\n *\n * This Action will batch up all the event logs found within the [`pollingInterval`](https://viem.sh/docs/contract/watchContractEvent.html#pollinginterval-optional), and invoke them via [`onLogs`](https://viem.sh/docs/contract/watchContractEvent.html#onLogs).\n *\n * `watchContractEvent` will attempt to create an [Event Filter](https://viem.sh/docs/contract/createContractEventFilter.html) and listen to changes to the Filter per polling interval, however, if the RPC Provider does not support Filters (e.g. `eth_newFilter`), then `watchContractEvent` will fall back to using [`getLogs`](https://viem.sh/docs/actions/public/getLogs) instead.\n *\n * @param client - Client to use\n * @param parameters - {@link WatchContractEventParameters}\n * @returns A function that can be invoked to stop watching for new event logs. {@link WatchContractEventReturnType}\n *\n * @example\n * import { createPublicClient, http, parseAbi } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { watchContractEvent } from 'viem/contract'\n *\n * const client = createPublicClient({\n *   chain: mainnet,\n *   transport: http(),\n * })\n * const unwatch = watchContractEvent(client, {\n *   address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\n *   abi: parseAbi(['event Transfer(address indexed from, address indexed to, uint256 value)']),\n *   eventName: 'Transfer',\n *   args: { from: '0xc961145a54C96E3aE9bAA048c4F4D6b04C13916b' },\n *   onLogs: (logs) => console.log(logs),\n * })\n */\nexport function watchContractEvent<\n  TChain extends Chain | undefined,\n  const TAbi extends Abi | readonly unknown[],\n  TEventName extends string,\n  TStrict extends boolean | undefined = undefined,\n>(\n  client: Client<Transport, TChain>,\n  {\n    abi,\n    address,\n    args,\n    batch = true,\n    eventName,\n    onError,\n    onLogs,\n    poll: poll_,\n    pollingInterval = client.pollingInterval,\n    strict: strict_,\n  }: WatchContractEventParameters<TAbi, TEventName, TStrict>,\n): WatchContractEventReturnType {\n  const enablePolling =\n    typeof poll_ !== 'undefined' ? poll_ : client.transport.type !== 'webSocket'\n\n  const pollContractEvent = () => {\n    const observerId = stringify([\n      'watchContractEvent',\n      address,\n      args,\n      batch,\n      client.uid,\n      eventName,\n      pollingInterval,\n    ])\n    const strict = strict_ ?? false\n\n    return observe(observerId, { onLogs, onError }, (emit) => {\n      let previousBlockNumber: bigint\n      let filter: Filter<'event', TAbi, TEventName> | undefined\n      let initialized = false\n\n      const unwatch = poll(\n        async () => {\n          if (!initialized) {\n            try {\n              filter = (await getAction(\n                client,\n                createContractEventFilter,\n                'createContractEventFilter',\n              )({\n                abi,\n                address,\n                args,\n                eventName,\n                strict,\n              } as unknown as CreateContractEventFilterParameters)) as Filter<\n                'event',\n                TAbi,\n                TEventName\n              >\n            } catch {}\n            initialized = true\n            return\n          }\n\n          try {\n            let logs: Log[]\n            if (filter) {\n              logs = await getAction(\n                client,\n                getFilterChanges,\n                'getFilterChanges',\n              )({ filter })\n            } else {\n              // If the filter doesn't exist, we will fall back to use `getLogs`.\n              // The fall back exists because some RPC Providers do not support filters.\n\n              // Fetch the block number to use for `getLogs`.\n              const blockNumber = await getAction(\n                client,\n                getBlockNumber,\n                'getBlockNumber',\n              )({})\n\n              // If the block number has changed, we will need to fetch the logs.\n              // If the block number doesn't exist, we are yet to reach the first poll interval,\n              // so do not emit any logs.\n              if (previousBlockNumber && previousBlockNumber !== blockNumber) {\n                logs = await getAction(\n                  client,\n                  getContractEvents,\n                  'getContractEvents',\n                )({\n                  abi,\n                  address,\n                  args,\n                  eventName,\n                  fromBlock: previousBlockNumber + 1n,\n                  toBlock: blockNumber,\n                  strict,\n                } as {} as GetContractEventsParameters)\n              } else {\n                logs = []\n              }\n              previousBlockNumber = blockNumber\n            }\n\n            if (logs.length === 0) return\n            if (batch) emit.onLogs(logs as any)\n            else for (const log of logs) emit.onLogs([log] as any)\n          } catch (err) {\n            // If a filter has been set and gets uninstalled, providers will throw an InvalidInput error.\n            // Reinitalize the filter when this occurs\n            if (filter && err instanceof InvalidInputRpcError)\n              initialized = false\n            emit.onError?.(err as Error)\n          }\n        },\n        {\n          emitOnBegin: true,\n          interval: pollingInterval,\n        },\n      )\n\n      return async () => {\n        if (filter)\n          await getAction(\n            client,\n            uninstallFilter,\n            'uninstallFilter',\n          )({ filter })\n        unwatch()\n      }\n    })\n  }\n\n  const subscribeContractEvent = () => {\n    let active = true\n    let unsubscribe = () => (active = false)\n    ;(async () => {\n      try {\n        const topics: LogTopic[] = eventName\n          ? encodeEventTopics({\n              abi: abi,\n              eventName: eventName,\n              args,\n            } as EncodeEventTopicsParameters)\n          : []\n\n        const { unsubscribe: unsubscribe_ } = await client.transport.subscribe({\n          params: ['logs', { address, topics }],\n          onData(data: any) {\n            if (!active) return\n            const log = data.result\n            try {\n              const { eventName, args } = decodeEventLog({\n                abi: abi,\n                data: log.data,\n                topics: log.topics as any,\n                strict: strict_,\n              })\n              const formatted = formatLog(log, {\n                args,\n                eventName: eventName as string,\n              })\n              onLogs([formatted] as any)\n            } catch (err) {\n              let eventName\n              let isUnnamed\n              if (\n                err instanceof DecodeLogDataMismatch ||\n                err instanceof DecodeLogTopicsMismatch\n              ) {\n                // If strict mode is on, and log data/topics do not match event definition, skip.\n                if (strict_) return\n                eventName = err.abiItem.name\n                isUnnamed = err.abiItem.inputs?.some(\n                  (x) => !('name' in x && x.name),\n                )\n              }\n\n              // Set args to empty if there is an error decoding (e.g. indexed/non-indexed params mismatch).\n              const formatted = formatLog(log, {\n                args: isUnnamed ? [] : {},\n                eventName,\n              })\n              onLogs([formatted] as any)\n            }\n          },\n          onError(error: Error) {\n            onError?.(error)\n          },\n        })\n        unsubscribe = unsubscribe_\n        if (!active) unsubscribe()\n      } catch (err) {\n        onError?.(err as Error)\n      }\n    })()\n    return unsubscribe\n  }\n\n  return enablePolling ? pollContractEvent() : subscribeContractEvent()\n}\n","import type { ErrorType } from '../../errors/utils.js'\n\nexport const promiseCache = /*#__PURE__*/ new Map()\nexport const responseCache = /*#__PURE__*/ new Map()\n\nexport type GetCacheErrorType = ErrorType\n\nexport function getCache<TData>(cacheKey: string) {\n  const buildCache = <TData>(cacheKey: string, cache: Map<string, TData>) => ({\n    clear: () => cache.delete(cacheKey),\n    get: () => cache.get(cacheKey),\n    set: (data: TData) => cache.set(cacheKey, data),\n  })\n\n  const promise = buildCache<Promise<TData>>(cacheKey, promiseCache)\n  const response = buildCache<{ created: Date; data: TData }>(\n    cacheKey,\n    responseCache,\n  )\n\n  return {\n    clear: () => {\n      promise.clear()\n      response.clear()\n    },\n    promise,\n    response,\n  }\n}\n\nexport type WithCacheParameters = {\n  /** The key to cache the data against. */\n  cacheKey: string\n  /** The time that cached data will remain in memory. Default: Infinity (no expiry) */\n  cacheTime?: number\n}\n\n/**\n * @description Returns the result of a given promise, and caches the result for\n * subsequent invocations against a provided cache key.\n */\nexport async function withCache<TData>(\n  fn: () => Promise<TData>,\n  { cacheKey, cacheTime = Infinity }: WithCacheParameters,\n) {\n  const cache = getCache<TData>(cacheKey)\n\n  // If a response exists in the cache, and it's not expired, return it\n  // and do not invoke the promise.\n  // If the max age is 0, the cache is disabled.\n  const response = cache.response.get()\n  if (response && cacheTime > 0) {\n    const age = new Date().getTime() - response.created.getTime()\n    if (age < cacheTime) return response.data\n  }\n\n  let promise = cache.promise.get()\n  if (!promise) {\n    promise = fn()\n\n    // Store the promise in the cache so that subsequent invocations\n    // will wait for the same promise to resolve (deduping).\n    cache.promise.set(promise)\n  }\n\n  try {\n    const data = await promise\n\n    // Store the response in the cache so that subsequent invocations\n    // will return the same response.\n    cache.response.set({ created: new Date(), data })\n\n    return data\n  } finally {\n    // Clear the promise cache so that subsequent invocations will\n    // invoke the promise again.\n    cache.promise.clear()\n  }\n}\n","import type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport { getCache, withCache } from '../../utils/promise/withCache.js'\n\nexport type GetBlockNumberParameters = {\n  /** Time (in ms) that cached block number will remain in memory. */\n  cacheTime?: number\n  /** @deprecated use `cacheTime` instead. */\n  maxAge?: number\n}\n\nexport type GetBlockNumberReturnType = bigint\n\nexport type GetBlockNumberErrorType = RequestErrorType | ErrorType\n\nconst cacheKey = (id: string) => `blockNumber.${id}`\n\nexport function getBlockNumberCache(id: string) {\n  return getCache(cacheKey(id))\n}\n\n/**\n * Returns the number of the most recent block seen.\n *\n * - Docs: https://viem.sh/docs/actions/public/getBlockNumber.html\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/blocks/fetching-blocks\n * - JSON-RPC Methods: [`eth_blockNumber`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_blocknumber)\n *\n * @param client - Client to use\n * @param parameters - {@link GetBlockNumberParameters}\n * @returns The number of the block. {@link GetBlockNumberReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getBlockNumber } from 'viem/public'\n *\n * const client = createPublicClient({\n *   chain: mainnet,\n *   transport: http(),\n * })\n * const blockNumber = await getBlockNumber(client)\n * // 69420n\n */\nexport async function getBlockNumber<TChain extends Chain | undefined>(\n  client: Client<Transport, TChain>,\n  { cacheTime = client.cacheTime, maxAge }: GetBlockNumberParameters = {},\n): Promise<GetBlockNumberReturnType> {\n  const blockNumberHex = await withCache(\n    () =>\n      client.request({\n        method: 'eth_blockNumber',\n      }),\n    { cacheKey: cacheKey(client.uid), cacheTime: maxAge ?? cacheTime },\n  )\n  return BigInt(blockNumberHex)\n}\n","import type { Abi, AbiEvent, ExtractAbiEvent } from 'abitype'\n\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport {\n  DecodeLogDataMismatch,\n  DecodeLogTopicsMismatch,\n} from '../../errors/abi.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { BlockNumber, BlockTag } from '../../types/block.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Filter, FilterType } from '../../types/filter.js'\nimport type { Log } from '../../types/log.js'\nimport type { Hash } from '../../types/misc.js'\nimport {\n  type DecodeEventLogErrorType,\n  decodeEventLog,\n} from '../../utils/abi/decodeEventLog.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport {\n  type FormatLogErrorType,\n  formatLog,\n} from '../../utils/formatters/log.js'\n\nexport type GetFilterChangesParameters<\n  TFilterType extends FilterType = FilterType,\n  TAbi extends Abi | readonly unknown[] | undefined = undefined,\n  TEventName extends string | undefined = undefined,\n  TStrict extends boolean | undefined = undefined,\n  TFromBlock extends BlockNumber | BlockTag | undefined = undefined,\n  TToBlock extends BlockNumber | BlockTag | undefined = undefined,\n> = {\n  filter: Filter<\n    TFilterType,\n    TAbi,\n    TEventName,\n    any,\n    TStrict,\n    TFromBlock,\n    TToBlock\n  >\n}\n\nexport type GetFilterChangesReturnType<\n  TFilterType extends FilterType = FilterType,\n  TAbi extends Abi | readonly unknown[] | undefined = undefined,\n  TEventName extends string | undefined = undefined,\n  TStrict extends boolean | undefined = undefined,\n  TFromBlock extends BlockNumber | BlockTag | undefined = undefined,\n  TToBlock extends BlockNumber | BlockTag | undefined = undefined,\n  _AbiEvent extends AbiEvent | undefined = TAbi extends Abi\n    ? TEventName extends string\n      ? ExtractAbiEvent<TAbi, TEventName>\n      : undefined\n    : undefined,\n  _Pending extends boolean =\n    | (TFromBlock extends 'pending' ? true : false)\n    | (TToBlock extends 'pending' ? true : false),\n> = TFilterType extends 'event'\n  ? Log<bigint, number, _Pending, _AbiEvent, TStrict, TAbi, TEventName>[]\n  : Hash[]\n\nexport type GetFilterChangesErrorType =\n  | RequestErrorType\n  | DecodeEventLogErrorType\n  | FormatLogErrorType\n  | ErrorType\n\n/**\n * Returns a list of logs or hashes based on a [Filter](/docs/glossary/terms#filter) since the last time it was called.\n *\n * - Docs: https://viem.sh/docs/actions/public/getFilterChanges.html\n * - JSON-RPC Methods: [`eth_getFilterChanges`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getfilterchanges)\n *\n * A Filter can be created from the following actions:\n *\n * - [`createBlockFilter`](https://viem.sh/docs/actions/public/createBlockFilter.html)\n * - [`createContractEventFilter`](https://viem.sh/docs/contract/createContractEventFilter.html)\n * - [`createEventFilter`](https://viem.sh/docs/actions/public/createEventFilter.html)\n * - [`createPendingTransactionFilter`](https://viem.sh/docs/actions/public/createPendingTransactionFilter.html)\n *\n * Depending on the type of filter, the return value will be different:\n *\n * - If the filter was created with `createContractEventFilter` or `createEventFilter`, it returns a list of logs.\n * - If the filter was created with `createPendingTransactionFilter`, it returns a list of transaction hashes.\n * - If the filter was created with `createBlockFilter`, it returns a list of block hashes.\n *\n * @param client - Client to use\n * @param parameters - {@link GetFilterChangesParameters}\n * @returns Logs or hashes. {@link GetFilterChangesReturnType}\n *\n * @example\n * // Blocks\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { createBlockFilter, getFilterChanges } from 'viem/public'\n *\n * const client = createPublicClient({\n *   chain: mainnet,\n *   transport: http(),\n * })\n * const filter = await createBlockFilter(client)\n * const hashes = await getFilterChanges(client, { filter })\n *\n * @example\n * // Contract Events\n * import { createPublicClient, http, parseAbi } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { createContractEventFilter, getFilterChanges } from 'viem/public'\n *\n * const client = createPublicClient({\n *   chain: mainnet,\n *   transport: http(),\n * })\n * const filter = await createContractEventFilter(client, {\n *   address: '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48',\n *   abi: parseAbi(['event Transfer(address indexed, address indexed, uint256)']),\n *   eventName: 'Transfer',\n * })\n * const logs = await getFilterChanges(client, { filter })\n *\n * @example\n * // Raw Events\n * import { createPublicClient, http, parseAbiItem } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { createEventFilter, getFilterChanges } from 'viem/public'\n *\n * const client = createPublicClient({\n *   chain: mainnet,\n *   transport: http(),\n * })\n * const filter = await createEventFilter(client, {\n *   address: '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48',\n *   event: parseAbiItem('event Transfer(address indexed, address indexed, uint256)'),\n * })\n * const logs = await getFilterChanges(client, { filter })\n *\n * @example\n * // Transactions\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { createPendingTransactionFilter, getFilterChanges } from 'viem/public'\n *\n * const client = createPublicClient({\n *   chain: mainnet,\n *   transport: http(),\n * })\n * const filter = await createPendingTransactionFilter(client)\n * const hashes = await getFilterChanges(client, { filter })\n */\nexport async function getFilterChanges<\n  TTransport extends Transport,\n  TChain extends Chain | undefined,\n  TFilterType extends FilterType,\n  const TAbi extends Abi | readonly unknown[] | undefined,\n  TEventName extends string | undefined,\n  TStrict extends boolean | undefined = undefined,\n  TFromBlock extends BlockNumber | BlockTag | undefined = undefined,\n  TToBlock extends BlockNumber | BlockTag | undefined = undefined,\n>(\n  _client: Client<TTransport, TChain>,\n  {\n    filter,\n  }: GetFilterChangesParameters<\n    TFilterType,\n    TAbi,\n    TEventName,\n    TStrict,\n    TFromBlock,\n    TToBlock\n  >,\n): Promise<\n  GetFilterChangesReturnType<\n    TFilterType,\n    TAbi,\n    TEventName,\n    TStrict,\n    TFromBlock,\n    TToBlock\n  >\n> {\n  const strict = 'strict' in filter && filter.strict\n\n  const logs = await filter.request({\n    method: 'eth_getFilterChanges',\n    params: [filter.id],\n  })\n  return logs\n    .map((log) => {\n      if (typeof log === 'string') return log\n      try {\n        const { eventName, args } =\n          'abi' in filter && filter.abi\n            ? decodeEventLog({\n                abi: filter.abi,\n                data: log.data,\n                topics: log.topics as any,\n                strict,\n              })\n            : { eventName: undefined, args: undefined }\n        return formatLog(log, { args, eventName })\n      } catch (err) {\n        let eventName\n        let isUnnamed\n        if (\n          err instanceof DecodeLogDataMismatch ||\n          err instanceof DecodeLogTopicsMismatch\n        ) {\n          // If strict mode is on, and log data/topics do not match event definition, skip.\n          if ('strict' in filter && filter.strict) return\n          eventName = err.abiItem.name\n          isUnnamed = err.abiItem.inputs?.some((x) => !('name' in x && x.name))\n        }\n\n        // Set args undefined if there is an error decoding (e.g. indexed/non-indexed params mismatch).\n        return formatLog(log, { args: isUnnamed ? [] : {}, eventName })\n      }\n    })\n    .filter(Boolean) as GetFilterChangesReturnType<\n    TFilterType,\n    TAbi,\n    TEventName,\n    TStrict,\n    TFromBlock,\n    TToBlock\n  >\n}\n","import type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Filter } from '../../types/filter.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\n\nexport type UninstallFilterParameters = {\n  filter: Filter<any>\n}\nexport type UninstallFilterReturnType = boolean\n\nexport type UninstallFilterErrorType = RequestErrorType | ErrorType\n\n/**\n * Destroys a [`Filter`](https://viem.sh/docs/glossary/types.html#filter).\n *\n * - Docs: https://viem.sh/docs/actions/public/uninstallFilter.html\n * - JSON-RPC Methods: [`eth_uninstallFilter`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_uninstallFilter)\n *\n * Destroys a Filter that was created from one of the following Actions:\n * - [`createBlockFilter`](https://viem.sh/docs/actions/public/createBlockFilter.html)\n * - [`createEventFilter`](https://viem.sh/docs/actions/public/createEventFilter.html)\n * - [`createPendingTransactionFilter`](https://viem.sh/docs/actions/public/createPendingTransactionFilter.html)\n *\n * @param client - Client to use\n * @param parameters - {@link UninstallFilterParameters}\n * @returns A boolean indicating if the Filter was successfully uninstalled. {@link UninstallFilterReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { createPendingTransactionFilter, uninstallFilter } from 'viem/public'\n *\n * const filter = await createPendingTransactionFilter(client)\n * const uninstalled = await uninstallFilter(client, { filter })\n * // true\n */\nexport async function uninstallFilter<\n  TTransport extends Transport,\n  TChain extends Chain | undefined,\n>(\n  _client: Client<TTransport, TChain>,\n  { filter }: UninstallFilterParameters,\n): Promise<UninstallFilterReturnType> {\n  return filter.request({\n    method: 'eth_uninstallFilter',\n    params: [filter.id],\n  })\n}\n","import type { Abi } from 'abitype'\n\nimport type { Account } from '../../accounts/types.js'\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { GetAccountParameter } from '../../types/account.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { GetChain } from '../../types/chain.js'\nimport type { ContractFunctionConfig, GetValue } from '../../types/contract.js'\nimport type { Hex } from '../../types/misc.js'\nimport type { UnionOmit } from '../../types/utils.js'\nimport {\n  type EncodeFunctionDataErrorType,\n  type EncodeFunctionDataParameters,\n  encodeFunctionData,\n} from '../../utils/abi/encodeFunctionData.js'\nimport type { FormattedTransactionRequest } from '../../utils/formatters/transactionRequest.js'\nimport { getAction } from '../../utils/getAction.js'\nimport {\n  type SendTransactionErrorType,\n  type SendTransactionParameters,\n  type SendTransactionReturnType,\n  sendTransaction,\n} from './sendTransaction.js'\n\nexport type WriteContractParameters<\n  TAbi extends Abi | readonly unknown[] = Abi,\n  TFunctionName extends string = string,\n  TChain extends Chain | undefined = Chain,\n  TAccount extends Account | undefined = Account | undefined,\n  TChainOverride extends Chain | undefined = Chain | undefined,\n> = ContractFunctionConfig<TAbi, TFunctionName, 'payable' | 'nonpayable'> &\n  GetAccountParameter<TAccount> &\n  GetChain<TChain, TChainOverride> &\n  UnionOmit<\n    FormattedTransactionRequest<\n      TChainOverride extends Chain ? TChainOverride : TChain\n    >,\n    'from' | 'to' | 'data' | 'value'\n  > &\n  GetValue<\n    TAbi,\n    TFunctionName,\n    FormattedTransactionRequest<\n      TChainOverride extends Chain ? TChainOverride : TChain\n    >['value']\n  > & {\n    /** Data to append to the end of the calldata. Useful for adding a [\"domain\" tag](https://opensea.notion.site/opensea/Seaport-Order-Attributions-ec2d69bf455041a5baa490941aad307f). */\n    dataSuffix?: Hex\n  }\n\nexport type WriteContractReturnType = SendTransactionReturnType\n\nexport type WriteContractErrorType =\n  | EncodeFunctionDataErrorType\n  | SendTransactionErrorType\n  | ErrorType\n\n/**\n * Executes a write function on a contract.\n *\n * - Docs: https://viem.sh/docs/contract/writeContract.html\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/contracts/writing-to-contracts\n *\n * A \"write\" function on a Solidity contract modifies the state of the blockchain. These types of functions require gas to be executed, and hence a [Transaction](https://viem.sh/docs/glossary/terms.html) is needed to be broadcast in order to change the state.\n *\n * Internally, uses a [Wallet Client](https://viem.sh/docs/clients/wallet.html) to call the [`sendTransaction` action](https://viem.sh/docs/actions/wallet/sendTransaction.html) with [ABI-encoded `data`](https://viem.sh/docs/contract/encodeFunctionData.html).\n *\n * __Warning: The `write` internally sends a transaction – it does not validate if the contract write will succeed (the contract may throw an error). It is highly recommended to [simulate the contract write with `contract.simulate`](https://viem.sh/docs/contract/writeContract.html#usage) before you execute it.__\n *\n * @param client - Client to use\n * @param parameters - {@link WriteContractParameters}\n * @returns A [Transaction Hash](https://viem.sh/docs/glossary/terms.html#hash). {@link WriteContractReturnType}\n *\n * @example\n * import { createWalletClient, custom, parseAbi } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { writeContract } from 'viem/contract'\n *\n * const client = createWalletClient({\n *   chain: mainnet,\n *   transport: custom(window.ethereum),\n * })\n * const hash = await writeContract(client, {\n *   address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\n *   abi: parseAbi(['function mint(uint32 tokenId) nonpayable']),\n *   functionName: 'mint',\n *   args: [69420],\n * })\n *\n * @example\n * // With Validation\n * import { createWalletClient, http, parseAbi } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { simulateContract, writeContract } from 'viem/contract'\n *\n * const client = createWalletClient({\n *   chain: mainnet,\n *   transport: http(),\n * })\n * const { request } = await simulateContract(client, {\n *   address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\n *   abi: parseAbi(['function mint(uint32 tokenId) nonpayable']),\n *   functionName: 'mint',\n *   args: [69420],\n * }\n * const hash = await writeContract(client, request)\n */\nexport async function writeContract<\n  TChain extends Chain | undefined,\n  TAccount extends Account | undefined,\n  const TAbi extends Abi | readonly unknown[],\n  TFunctionName extends string,\n  TChainOverride extends Chain | undefined = undefined,\n>(\n  client: Client<Transport, TChain, TAccount>,\n  {\n    abi,\n    address,\n    args,\n    dataSuffix,\n    functionName,\n    ...request\n  }: WriteContractParameters<\n    TAbi,\n    TFunctionName,\n    TChain,\n    TAccount,\n    TChainOverride\n  >,\n): Promise<WriteContractReturnType> {\n  const data = encodeFunctionData({\n    abi,\n    args,\n    functionName,\n  } as unknown as EncodeFunctionDataParameters<TAbi, TFunctionName>)\n  const hash = await getAction(\n    client,\n    sendTransaction,\n    'sendTransaction',\n  )({\n    data: `${data}${dataSuffix ? dataSuffix.replace('0x', '') : ''}`,\n    to: address,\n    ...request,\n  } as unknown as SendTransactionParameters<TChain, TAccount, TChainOverride>)\n  return hash\n}\n","import type { Account } from '../../accounts/types.js'\nimport {\n  type ParseAccountErrorType,\n  parseAccount,\n} from '../../accounts/utils/parseAccount.js'\nimport type { SignTransactionErrorType } from '../../accounts/utils/signTransaction.js'\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport { AccountNotFoundError } from '../../errors/account.js'\nimport type { BaseError } from '../../errors/base.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { GetAccountParameter } from '../../types/account.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { GetChain } from '../../types/chain.js'\nimport type { Hash } from '../../types/misc.js'\nimport type {\n  TransactionRequest,\n  TransactionSerializable,\n} from '../../types/transaction.js'\nimport type { UnionOmit } from '../../types/utils.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport {\n  type AssertCurrentChainErrorType,\n  assertCurrentChain,\n} from '../../utils/chain/assertCurrentChain.js'\nimport {\n  type GetTransactionErrorReturnType,\n  getTransactionError,\n} from '../../utils/errors/getTransactionError.js'\nimport { extract } from '../../utils/formatters/extract.js'\nimport {\n  type FormattedTransactionRequest,\n  formatTransactionRequest,\n} from '../../utils/formatters/transactionRequest.js'\nimport { getAction } from '../../utils/getAction.js'\nimport {\n  type AssertRequestErrorType,\n  type AssertRequestParameters,\n  assertRequest,\n} from '../../utils/transaction/assertRequest.js'\nimport { type GetChainIdErrorType, getChainId } from '../public/getChainId.js'\nimport {\n  type PrepareTransactionRequestErrorType,\n  prepareTransactionRequest,\n} from './prepareTransactionRequest.js'\nimport {\n  type SendRawTransactionReturnType,\n  sendRawTransaction,\n} from './sendRawTransaction.js'\n\nexport type SendTransactionParameters<\n  TChain extends Chain | undefined = Chain | undefined,\n  TAccount extends Account | undefined = Account | undefined,\n  TChainOverride extends Chain | undefined = Chain | undefined,\n> = UnionOmit<\n  FormattedTransactionRequest<\n    TChainOverride extends Chain ? TChainOverride : TChain\n  >,\n  'from'\n> &\n  GetAccountParameter<TAccount> &\n  GetChain<TChain, TChainOverride>\n\nexport type SendTransactionReturnType = Hash\n\nexport type SendTransactionErrorType =\n  | ParseAccountErrorType\n  | GetTransactionErrorReturnType<\n      | AssertCurrentChainErrorType\n      | AssertRequestErrorType\n      | GetChainIdErrorType\n      | PrepareTransactionRequestErrorType\n      | SendRawTransactionReturnType\n      | SignTransactionErrorType\n      | RequestErrorType\n    >\n  | ErrorType\n\n/**\n * Creates, signs, and sends a new transaction to the network.\n *\n * - Docs: https://viem.sh/docs/actions/wallet/sendTransaction.html\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/transactions/sending-transactions\n * - JSON-RPC Methods:\n *   - JSON-RPC Accounts: [`eth_sendTransaction`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_sendtransaction)\n *   - Local Accounts: [`eth_sendRawTransaction`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_sendrawtransaction)\n *\n * @param client - Client to use\n * @param parameters - {@link SendTransactionParameters}\n * @returns The [Transaction](https://viem.sh/docs/glossary/terms.html#transaction) hash. {@link SendTransactionReturnType}\n *\n * @example\n * import { createWalletClient, custom } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { sendTransaction } from 'viem/wallet'\n *\n * const client = createWalletClient({\n *   chain: mainnet,\n *   transport: custom(window.ethereum),\n * })\n * const hash = await sendTransaction(client, {\n *   account: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',\n *   to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',\n *   value: 1000000000000000000n,\n * })\n *\n * @example\n * // Account Hoisting\n * import { createWalletClient, http } from 'viem'\n * import { privateKeyToAccount } from 'viem/accounts'\n * import { mainnet } from 'viem/chains'\n * import { sendTransaction } from 'viem/wallet'\n *\n * const client = createWalletClient({\n *   account: privateKeyToAccount('0x…'),\n *   chain: mainnet,\n *   transport: http(),\n * })\n * const hash = await sendTransaction(client, {\n *   to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',\n *   value: 1000000000000000000n,\n * })\n */\nexport async function sendTransaction<\n  TChain extends Chain | undefined,\n  TAccount extends Account | undefined,\n  TChainOverride extends Chain | undefined = undefined,\n>(\n  client: Client<Transport, TChain, TAccount>,\n  args: SendTransactionParameters<TChain, TAccount, TChainOverride>,\n): Promise<SendTransactionReturnType> {\n  const {\n    account: account_ = client.account,\n    chain = client.chain,\n    accessList,\n    data,\n    gas,\n    gasPrice,\n    maxFeePerGas,\n    maxPriorityFeePerGas,\n    nonce,\n    to,\n    value,\n    ...rest\n  } = args\n\n  if (!account_)\n    throw new AccountNotFoundError({\n      docsPath: '/docs/actions/wallet/sendTransaction',\n    })\n  const account = parseAccount(account_)\n\n  try {\n    assertRequest(args as AssertRequestParameters)\n\n    let chainId\n    if (chain !== null) {\n      chainId = await getAction(client, getChainId, 'getChainId')({})\n      assertCurrentChain({\n        currentChainId: chainId,\n        chain,\n      })\n    }\n\n    if (account.type === 'local') {\n      // Prepare the request for signing (assign appropriate fees, etc.)\n      const request = await getAction(\n        client,\n        prepareTransactionRequest,\n        'prepareTransactionRequest',\n      )({\n        account,\n        accessList,\n        chain,\n        data,\n        gas,\n        gasPrice,\n        maxFeePerGas,\n        maxPriorityFeePerGas,\n        nonce,\n        to,\n        value,\n        ...rest,\n      } as any)\n\n      if (!chainId)\n        chainId = await getAction(client, getChainId, 'getChainId')({})\n\n      const serializer = chain?.serializers?.transaction\n      const serializedTransaction = (await account.signTransaction(\n        {\n          ...request,\n          chainId,\n        } as TransactionSerializable,\n        { serializer },\n      )) as Hash\n      return await getAction(\n        client,\n        sendRawTransaction,\n        'sendRawTransaction',\n      )({\n        serializedTransaction,\n      })\n    }\n\n    const chainFormat = client.chain?.formatters?.transactionRequest?.format\n    const format = chainFormat || formatTransactionRequest\n\n    const request = format({\n      // Pick out extra data that might exist on the chain's transaction request type.\n      ...extract(rest, { format: chainFormat }),\n      accessList,\n      data,\n      from: account.address,\n      gas,\n      gasPrice,\n      maxFeePerGas,\n      maxPriorityFeePerGas,\n      nonce,\n      to,\n      value,\n    } as TransactionRequest)\n    return await client.request({\n      method: 'eth_sendTransaction',\n      params: [request],\n    })\n  } catch (err) {\n    throw getTransactionError(err as BaseError, {\n      ...args,\n      account,\n      chain: args.chain || undefined,\n    })\n  }\n}\n","import {\n  ChainMismatchError,\n  type ChainMismatchErrorType,\n  ChainNotFoundError,\n  type ChainNotFoundErrorType,\n} from '../../errors/chain.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\n\nexport type AssertCurrentChainParameters = {\n  chain?: Chain\n  currentChainId: number\n}\n\nexport type AssertCurrentChainErrorType =\n  | ChainNotFoundErrorType\n  | ChainMismatchErrorType\n  | ErrorType\n\nexport function assertCurrentChain({\n  chain,\n  currentChainId,\n}: AssertCurrentChainParameters): void {\n  if (!chain) throw new ChainNotFoundError()\n  if (currentChainId !== chain.id)\n    throw new ChainMismatchError({ chain, currentChainId })\n}\n","import type { Account } from '../../accounts/types.js'\nimport type { SendTransactionParameters } from '../../actions/wallet/sendTransaction.js'\nimport type { BaseError } from '../../errors/base.js'\nimport { UnknownNodeError } from '../../errors/node.js'\nimport {\n  TransactionExecutionError,\n  type TransactionExecutionErrorType,\n} from '../../errors/transaction.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\n\nimport {\n  type GetNodeErrorParameters,\n  type GetNodeErrorReturnType,\n  getNodeError,\n} from './getNodeError.js'\n\nexport type GetTransactionErrorParameters = Omit<\n  SendTransactionParameters,\n  'account' | 'chain'\n> & {\n  account: Account\n  chain?: Chain\n  docsPath?: string\n}\n\nexport type GetTransactionErrorReturnType<cause = ErrorType> = Omit<\n  TransactionExecutionErrorType,\n  'cause'\n> & { cause: cause | GetNodeErrorReturnType }\n\nexport function getTransactionError<err extends ErrorType<string>>(\n  err: err,\n  { docsPath, ...args }: GetTransactionErrorParameters,\n): GetTransactionErrorReturnType<err> {\n  const cause = (() => {\n    const cause = getNodeError(\n      err as {} as BaseError,\n      args as GetNodeErrorParameters,\n    )\n    if (cause instanceof UnknownNodeError) return err as {} as BaseError\n    return cause\n  })()\n  return new TransactionExecutionError(cause, {\n    docsPath,\n    ...args,\n  }) as GetTransactionErrorReturnType<err>\n}\n","import type { Account } from '../../accounts/types.js'\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport {\n  type HexToNumberErrorType,\n  hexToNumber,\n} from '../../utils/encoding/fromHex.js'\n\nexport type GetChainIdReturnType = number\n\nexport type GetChainIdErrorType =\n  | HexToNumberErrorType\n  | RequestErrorType\n  | ErrorType\n\n/**\n * Returns the chain ID associated with the current network.\n *\n * - Docs: https://viem.sh/docs/actions/public/getChainId.html\n * - JSON-RPC Methods: [`eth_chainId`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_chainid)\n *\n * @param client - Client to use\n * @returns The current chain ID. {@link GetChainIdReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getChainId } from 'viem/public'\n *\n * const client = createPublicClient({\n *   chain: mainnet,\n *   transport: http(),\n * })\n * const chainId = await getChainId(client)\n * // 1\n */\nexport async function getChainId<\n  TChain extends Chain | undefined,\n  TAccount extends Account | undefined,\n>(client: Client<Transport, TChain, TAccount>): Promise<GetChainIdReturnType> {\n  const chainIdHex = await client.request({\n    method: 'eth_chainId',\n  })\n  return hexToNumber(chainIdHex)\n}\n","import type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Hash } from '../../types/misc.js'\nimport type { TransactionSerialized } from '../../types/transaction.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\n\nexport type SendRawTransactionParameters = {\n  /**\n   * The signed serialized tranasction.\n   */\n  serializedTransaction: TransactionSerialized\n}\n\nexport type SendRawTransactionReturnType = Hash\n\nexport type SendRawTransactionErrorType = RequestErrorType | ErrorType\n\n/**\n * Sends a **signed** transaction to the network\n *\n * - Docs: https://viem.sh/docs/actions/wallet/sendRawTransaction.html\n * - JSON-RPC Method: [`eth_sendRawTransaction`](https://ethereum.github.io/execution-apis/api-documentation/)\n *\n * @param client - Client to use\n * @param parameters - {@link SendRawTransactionParameters}\n * @returns The transaction hash. {@link SendRawTransactionReturnType}\n *\n * @example\n * import { createWalletClient, custom } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { sendRawTransaction } from 'viem/wallet'\n *\n * const client = createWalletClient({\n *   chain: mainnet,\n *   transport: custom(window.ethereum),\n * })\n *\n * const hash = await sendRawTransaction(client, {\n *   serializedTransaction: '0x02f850018203118080825208808080c080a04012522854168b27e5dc3d5839bab5e6b39e1a0ffd343901ce1622e3d64b48f1a04e00902ae0502c4728cbf12156290df99c3ed7de85b1dbfe20b5c36931733a33'\n * })\n */\nexport async function sendRawTransaction<TChain extends Chain | undefined>(\n  client: Client<Transport, TChain>,\n  { serializedTransaction }: SendRawTransactionParameters,\n): Promise<SendRawTransactionReturnType> {\n  return client.request({\n    method: 'eth_sendRawTransaction',\n    params: [serializedTransaction],\n  })\n}\n","import type { Account } from '../../accounts/types.js'\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport {\n  type NumberToHexErrorType,\n  numberToHex,\n} from '../../utils/encoding/toHex.js'\n\nexport type AddChainParameters = {\n  /** The chain to add to the wallet. */\n  chain: Chain\n}\n\nexport type AddChainErrorType =\n  | RequestErrorType\n  | NumberToHexErrorType\n  | ErrorType\n\n/**\n * Adds an EVM chain to the wallet.\n *\n * - Docs: https://viem.sh/docs/actions/wallet/addChain.html\n * - JSON-RPC Methods: [`eth_addEthereumChain`](https://eips.ethereum.org/EIPS/eip-3085)\n *\n * @param client - Client to use\n * @param parameters - {@link AddChainParameters}\n *\n * @example\n * import { createWalletClient, custom } from 'viem'\n * import { optimism } from 'viem/chains'\n * import { addChain } from 'viem/wallet'\n *\n * const client = createWalletClient({\n *   transport: custom(window.ethereum),\n * })\n * await addChain(client, { chain: optimism })\n */\nexport async function addChain<\n  TChain extends Chain | undefined,\n  TAccount extends Account | undefined,\n>(client: Client<Transport, TChain, TAccount>, { chain }: AddChainParameters) {\n  const { id, name, nativeCurrency, rpcUrls, blockExplorers } = chain\n  await client.request({\n    method: 'wallet_addEthereumChain',\n    params: [\n      {\n        chainId: numberToHex(id),\n        chainName: name,\n        nativeCurrency,\n        rpcUrls: rpcUrls.default.http,\n        blockExplorerUrls: blockExplorers\n          ? Object.values(blockExplorers).map(({ url }) => url)\n          : undefined,\n      },\n    ],\n  })\n}\n","// Tree-shaking doesn't work well when we import from an index entrypoint. We don't\n// want to bundle libs like `@noble/curves`, etc within the `/accounts` entrypoint\n// as that will dramatically increase bundle size. So we export the modules directly.\nexport { parseAccount } from '../accounts/utils/parseAccount.js'\nexport { publicKeyToAddress } from '../accounts/utils/publicKeyToAddress.js'\n","import type { Address } from 'abitype'\n\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Hex } from '../../types/misc.js'\nimport {\n  type ChecksumAddressErrorType,\n  checksumAddress,\n} from '../../utils/address/getAddress.js'\nimport {\n  type Keccak256ErrorType,\n  keccak256,\n} from '../../utils/hash/keccak256.js'\n\nexport type PublicKeyToAddressErrorType =\n  | ChecksumAddressErrorType\n  | Keccak256ErrorType\n  | ErrorType\n\n/**\n * @description Converts an ECDSA public key to an address.\n *\n * @param publicKey The public key to convert.\n *\n * @returns The address.\n */\nexport function publicKeyToAddress(publicKey: Hex): Address {\n  const address = keccak256(`0x${publicKey.substring(4)}`).substring(26)\n  return checksumAddress(`0x${address}`) as Address\n}\n","const size = 256\nlet index = size\nlet buffer: string\n\nexport function uid(length = 11) {\n  if (!buffer || index + length > size * 2) {\n    buffer = ''\n    index = 0\n    for (let i = 0; i < size; i++) {\n      buffer += ((256 + Math.random() * 256) | 0).toString(16).substring(1)\n    }\n  }\n  return buffer.substring(index, index++ + length)\n}\n","import type { Address } from 'abitype'\n\nimport type { JsonRpcAccount } from '../accounts/types.js'\nimport type { ParseAccountErrorType } from '../accounts/utils/parseAccount.js'\nimport type { ErrorType } from '../errors/utils.js'\nimport type { Account } from '../types/account.js'\nimport type { Chain } from '../types/chain.js'\nimport type {\n  EIP1193RequestFn,\n  EIP1474Methods,\n  RpcSchema,\n} from '../types/eip1193.js'\nimport type { Prettify } from '../types/utils.js'\nimport { parseAccount } from '../utils/accounts.js'\nimport { uid } from '../utils/uid.js'\nimport type { PublicActions } from './decorators/public.js'\nimport type { WalletActions } from './decorators/wallet.js'\nimport type { Transport } from './transports/createTransport.js'\n\nexport type ClientConfig<\n  transport extends Transport = Transport,\n  chain extends Chain | undefined = Chain | undefined,\n  accountOrAddress extends Account | Address | undefined =\n    | Account\n    | Address\n    | undefined,\n> = {\n  /** The Account to use for the Client. This will be used for Actions that require an account as an argument. */\n  account?: accountOrAddress | Account | Address | undefined\n  /** Flags for batch settings. */\n  batch?:\n    | {\n        /** Toggle to enable `eth_call` multicall aggregation. */\n        multicall?: boolean | Prettify<MulticallBatchOptions> | undefined\n      }\n    | undefined\n  /**\n   * Time (in ms) that cached data will remain in memory.\n   * @default 4_000\n   */\n  cacheTime?: number | undefined\n  /** Chain for the client. */\n  chain?: Chain | undefined | chain\n  /** A key for the client. */\n  key?: string | undefined\n  /** A name for the client. */\n  name?: string | undefined\n  /**\n   * Frequency (in ms) for polling enabled actions & events.\n   * @default 4_000\n   */\n  pollingInterval?: number | undefined\n  /** The RPC transport */\n  transport: transport\n  /** The type of client. */\n  type?: string | undefined\n}\n\n// Actions that are used internally by other Actions (ie. `call` is used by `readContract`).\n// They are allowed to be extended, but must conform to their parameter & return type interfaces.\n// Example: an extended `call` action must accept `CallParameters` as parameters,\n// and conform to the `CallReturnType` return type.\ntype ExtendableProtectedActions = Pick<\n  PublicActions,\n  | 'call'\n  | 'createContractEventFilter'\n  | 'createEventFilter'\n  | 'estimateContractGas'\n  | 'estimateGas'\n  | 'getBlock'\n  | 'getBlockNumber'\n  | 'getChainId'\n  | 'getContractEvents'\n  | 'getEnsText'\n  | 'getFilterChanges'\n  | 'getGasPrice'\n  | 'getLogs'\n  | 'getTransaction'\n  | 'getTransactionCount'\n  | 'getTransactionReceipt'\n  | 'prepareTransactionRequest'\n  | 'readContract'\n  | 'sendRawTransaction'\n  | 'simulateContract'\n  | 'uninstallFilter'\n  | 'watchBlockNumber'\n  | 'watchContractEvent'\n> &\n  Pick<WalletActions, 'sendTransaction' | 'writeContract'>\n\n// TODO: Move `transport` to slot index 2 since `chain` and `account` used more frequently.\n// Otherwise, we end up with a lot of `Client<Transport, chain, account>` in actions.\nexport type Client<\n  transport extends Transport = Transport,\n  chain extends Chain | undefined = Chain | undefined,\n  account extends Account | undefined = Account | undefined,\n  rpcSchema extends RpcSchema | undefined = undefined,\n  extended extends Extended | undefined = Extended | undefined,\n> = Client_Base<transport, chain, account, rpcSchema> &\n  (extended extends Extended ? extended : unknown) & {\n    extend: <\n      const client extends Extended & Partial<ExtendableProtectedActions>,\n    >(\n      fn: (\n        client: Client<transport, chain, account, rpcSchema, extended>,\n      ) => client,\n    ) => Client<\n      transport,\n      chain,\n      account,\n      rpcSchema,\n      Prettify<client> & (extended extends Extended ? extended : unknown)\n    >\n  }\n\ntype Client_Base<\n  transport extends Transport = Transport,\n  chain extends Chain | undefined = Chain | undefined,\n  account extends Account | undefined = Account | undefined,\n  rpcSchema extends RpcSchema | undefined = undefined,\n> = {\n  /** The Account of the Client. */\n  account: account\n  /** Flags for batch settings. */\n  batch?: ClientConfig['batch']\n  /** Time (in ms) that cached data will remain in memory. */\n  cacheTime: number\n  /** Chain for the client. */\n  chain: chain\n  /** A key for the client. */\n  key: string\n  /** A name for the client. */\n  name: string\n  /** Frequency (in ms) for polling enabled actions & events. Defaults to 4_000 milliseconds. */\n  pollingInterval: number\n  /** Request function wrapped with friendly error handling */\n  request: EIP1193RequestFn<\n    rpcSchema extends undefined ? EIP1474Methods : rpcSchema\n  >\n  /** The RPC transport */\n  transport: ReturnType<transport>['config'] & ReturnType<transport>['value']\n  /** The type of client. */\n  type: string\n  /** A unique ID for the client. */\n  uid: string\n}\n\ntype Extended = Prettify<\n  // disallow redefining base properties\n  { [_ in keyof Client_Base]?: undefined } & {\n    [key: string]: unknown\n  }\n>\n\nexport type MulticallBatchOptions = {\n  /** The maximum size (in bytes) for each calldata chunk. @default 1_024 */\n  batchSize?: number | undefined\n  /** The maximum number of milliseconds to wait before sending a batch. @default 0 */\n  wait?: number | undefined\n}\n\nexport type CreateClientErrorType = ParseAccountErrorType | ErrorType\n\n/**\n * Creates a base client with the given transport.\n */\nexport function createClient<\n  transport extends Transport,\n  chain extends Chain | undefined = undefined,\n  accountOrAddress extends Account | Address | undefined = undefined,\n>(\n  parameters: ClientConfig<transport, chain, accountOrAddress>,\n): Prettify<\n  Client<\n    transport,\n    chain,\n    accountOrAddress extends Address\n      ? Prettify<JsonRpcAccount<accountOrAddress>>\n      : accountOrAddress\n  >\n>\n\nexport function createClient(parameters: ClientConfig): Client {\n  const {\n    batch,\n    cacheTime = parameters.pollingInterval ?? 4_000,\n    key = 'base',\n    name = 'Base Client',\n    pollingInterval = 4_000,\n    type = 'base',\n  } = parameters\n\n  const chain = parameters.chain\n  const account = parameters.account\n    ? parseAccount(parameters.account)\n    : undefined\n  const { config, request, value } = parameters.transport({\n    chain,\n    pollingInterval,\n  })\n  const transport = { ...config, ...value }\n\n  const client = {\n    account,\n    batch,\n    cacheTime,\n    chain,\n    key,\n    name,\n    pollingInterval,\n    request,\n    transport,\n    type,\n    uid: uid(),\n  }\n\n  function extend(base: typeof client) {\n    type ExtendFn = (base: typeof client) => unknown\n    return (extendFn: ExtendFn) => {\n      const extended = extendFn(base) as Extended\n      for (const key in client) delete extended[key]\n      const combined = { ...base, ...extended }\n      return Object.assign(combined, { extend: extend(combined) })\n    }\n  }\n\n  return Object.assign(client, { extend: extend(client) as any })\n}\n","import { BaseError } from '../errors/base.js'\nimport {\n  HttpRequestError,\n  type HttpRequestErrorType,\n  type RpcRequestErrorType,\n  type TimeoutErrorType,\n  type WebSocketRequestErrorType,\n} from '../errors/request.js'\nimport {\n  ChainDisconnectedError,\n  type ChainDisconnectedErrorType,\n  InternalRpcError,\n  type InternalRpcErrorType,\n  InvalidInputRpcError,\n  type InvalidInputRpcErrorType,\n  InvalidParamsRpcError,\n  type InvalidParamsRpcErrorType,\n  InvalidRequestRpcError,\n  type InvalidRequestRpcErrorType,\n  JsonRpcVersionUnsupportedError,\n  type JsonRpcVersionUnsupportedErrorType,\n  LimitExceededRpcError,\n  type LimitExceededRpcErrorType,\n  MethodNotFoundRpcError,\n  type MethodNotFoundRpcErrorType,\n  MethodNotSupportedRpcError,\n  type MethodNotSupportedRpcErrorType,\n  ParseRpcError,\n  type ParseRpcErrorType,\n  ProviderDisconnectedError,\n  type ProviderDisconnectedErrorType,\n  type ProviderRpcErrorCode,\n  ResourceNotFoundRpcError,\n  type ResourceNotFoundRpcErrorType,\n  ResourceUnavailableRpcError,\n  type ResourceUnavailableRpcErrorType,\n  type RpcError,\n  type RpcErrorCode,\n  type RpcErrorType,\n  SwitchChainError,\n  type SwitchChainErrorType,\n  TransactionRejectedRpcError,\n  type TransactionRejectedRpcErrorType,\n  UnauthorizedProviderError,\n  type UnauthorizedProviderErrorType,\n  UnknownRpcError,\n  type UnknownRpcErrorType,\n  UnsupportedProviderMethodError,\n  type UnsupportedProviderMethodErrorType,\n  UserRejectedRequestError,\n  type UserRejectedRequestErrorType,\n} from '../errors/rpc.js'\nimport type { ErrorType } from '../errors/utils.js'\nimport type { CreateBatchSchedulerErrorType } from './promise/createBatchScheduler.js'\nimport { type WithRetryErrorType, withRetry } from './promise/withRetry.js'\nimport type { GetSocketErrorType } from './rpc.js'\n\nexport type IsDeterministicErrorType = ErrorType\n\nexport const isDeterministicError = (error: Error) => {\n  if ('code' in error)\n    return (\n      error.code !== -1 &&\n      error.code !== -32004 &&\n      error.code !== -32005 &&\n      error.code !== -32042 &&\n      error.code !== -32603\n    )\n  if (error instanceof HttpRequestError && error.status)\n    return (\n      error.status !== 403 &&\n      error.status !== 408 &&\n      error.status !== 413 &&\n      error.status !== 429 &&\n      error.status !== 500 &&\n      error.status !== 502 &&\n      error.status !== 503 &&\n      error.status !== 504\n    )\n  return false\n}\n\nexport type RequestErrorType =\n  | ChainDisconnectedErrorType\n  | CreateBatchSchedulerErrorType\n  | HttpRequestErrorType\n  | InternalRpcErrorType\n  | InvalidInputRpcErrorType\n  | InvalidParamsRpcErrorType\n  | InvalidRequestRpcErrorType\n  | GetSocketErrorType\n  | JsonRpcVersionUnsupportedErrorType\n  | LimitExceededRpcErrorType\n  | MethodNotFoundRpcErrorType\n  | MethodNotSupportedRpcErrorType\n  | ParseRpcErrorType\n  | ProviderDisconnectedErrorType\n  | ResourceNotFoundRpcErrorType\n  | ResourceUnavailableRpcErrorType\n  | RpcErrorType\n  | RpcRequestErrorType\n  | SwitchChainErrorType\n  | TimeoutErrorType\n  | TransactionRejectedRpcErrorType\n  | UnauthorizedProviderErrorType\n  | UnknownRpcErrorType\n  | UnsupportedProviderMethodErrorType\n  | UserRejectedRequestErrorType\n  | WebSocketRequestErrorType\n  | WithRetryErrorType\n  | ErrorType\n\nexport function buildRequest<TRequest extends (args: any) => Promise<any>>(\n  request: TRequest,\n  {\n    retryDelay = 150,\n    retryCount = 3,\n  }: {\n    // The base delay (in ms) between retries.\n    retryDelay?: number\n    // The max number of times to retry.\n    retryCount?: number\n  } = {},\n) {\n  return (async (args: any) =>\n    withRetry(\n      async () => {\n        try {\n          return await request(args)\n        } catch (err_) {\n          const err = err_ as unknown as RpcError<\n            RpcErrorCode | ProviderRpcErrorCode\n          >\n          switch (err.code) {\n            // -32700\n            case ParseRpcError.code:\n              throw new ParseRpcError(err)\n            // -32600\n            case InvalidRequestRpcError.code:\n              throw new InvalidRequestRpcError(err)\n            // -32601\n            case MethodNotFoundRpcError.code:\n              throw new MethodNotFoundRpcError(err)\n            // -32602\n            case InvalidParamsRpcError.code:\n              throw new InvalidParamsRpcError(err)\n            // -32603\n            case InternalRpcError.code:\n              throw new InternalRpcError(err)\n            // -32000\n            case InvalidInputRpcError.code:\n              throw new InvalidInputRpcError(err)\n            // -32001\n            case ResourceNotFoundRpcError.code:\n              throw new ResourceNotFoundRpcError(err)\n            // -32002\n            case ResourceUnavailableRpcError.code:\n              throw new ResourceUnavailableRpcError(err)\n            // -32003\n            case TransactionRejectedRpcError.code:\n              throw new TransactionRejectedRpcError(err)\n            // -32004\n            case MethodNotSupportedRpcError.code:\n              throw new MethodNotSupportedRpcError(err)\n            // -32005\n            case LimitExceededRpcError.code:\n              throw new LimitExceededRpcError(err)\n            // -32006\n            case JsonRpcVersionUnsupportedError.code:\n              throw new JsonRpcVersionUnsupportedError(err)\n            // 4001\n            case UserRejectedRequestError.code:\n              throw new UserRejectedRequestError(err)\n            // 4100\n            case UnauthorizedProviderError.code:\n              throw new UnauthorizedProviderError(err)\n            // 4200\n            case UnsupportedProviderMethodError.code:\n              throw new UnsupportedProviderMethodError(err)\n            // 4900\n            case ProviderDisconnectedError.code:\n              throw new ProviderDisconnectedError(err)\n            // 4901\n            case ChainDisconnectedError.code:\n              throw new ChainDisconnectedError(err)\n            // 4902\n            case SwitchChainError.code:\n              throw new SwitchChainError(err)\n            // CAIP-25: User Rejected Error\n            // https://docs.walletconnect.com/2.0/specs/clients/sign/error-codes#rejected-caip-25\n            case 5000:\n              throw new UserRejectedRequestError(err)\n            default:\n              if (err_ instanceof BaseError) throw err_\n              throw new UnknownRpcError(err as Error)\n          }\n        }\n      },\n      {\n        delay: ({ count, error }) => {\n          // If we find a Retry-After header, let's retry after the given time.\n          if (error && error instanceof HttpRequestError) {\n            const retryAfter = error?.headers?.get('Retry-After')\n            if (retryAfter?.match(/\\d/)) return parseInt(retryAfter) * 1000\n          }\n\n          // Otherwise, let's retry with an exponential backoff.\n          return ~~(1 << count) * retryDelay\n        },\n        retryCount,\n        shouldRetry: ({ error }) => !isDeterministicError(error),\n      },\n    )) as TRequest\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport { wait } from '../wait.js'\n\nexport type WithRetryErrorType = ErrorType\n\nexport function withRetry<TData>(\n  fn: () => Promise<TData>,\n  {\n    delay: delay_ = 100,\n    retryCount = 2,\n    shouldRetry = () => true,\n  }: {\n    // The delay (in ms) between retries.\n    delay?: ((config: { count: number; error: Error }) => number) | number\n    // The max number of times to retry.\n    retryCount?: number\n    // Whether or not to retry when an error is thrown.\n    shouldRetry?: ({\n      count,\n      error,\n    }: {\n      count: number\n      error: Error\n    }) => Promise<boolean> | boolean\n  } = {},\n) {\n  return new Promise<TData>((resolve, reject) => {\n    const attemptRetry = async ({ count = 0 } = {}) => {\n      const retry = async ({ error }: { error: Error }) => {\n        const delay =\n          typeof delay_ === 'function' ? delay_({ count, error }) : delay_\n        if (delay) await wait(delay)\n        attemptRetry({ count: count + 1 })\n      }\n\n      try {\n        const data = await fn()\n        resolve(data)\n      } catch (err) {\n        if (\n          count < retryCount &&\n          (await shouldRetry({ count, error: err as Error }))\n        )\n          return retry({ error: err as Error })\n        reject(err)\n      }\n    }\n    attemptRetry()\n  })\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { EIP1193RequestFn } from '../../types/eip1193.js'\nimport { buildRequest } from '../../utils/buildRequest.js'\nimport type { ClientConfig } from '../createClient.js'\n\nexport type TransportConfig<\n  TType extends string = string,\n  TEIP1193RequestFn extends EIP1193RequestFn = EIP1193RequestFn,\n> = {\n  /** The name of the transport. */\n  name: string\n  /** The key of the transport. */\n  key: string\n  /** The JSON-RPC request function that matches the EIP-1193 request spec. */\n  request: TEIP1193RequestFn\n  /** The base delay (in ms) between retries. */\n  retryDelay?: number\n  /** The max number of times to retry. */\n  retryCount?: number\n  /** The timeout (in ms) for requests. */\n  timeout?: number\n  /** The type of the transport. */\n  type: TType\n}\n\nexport type Transport<\n  TType extends string = string,\n  TRpcAttributes = Record<string, any>,\n  TEIP1193RequestFn extends EIP1193RequestFn = EIP1193RequestFn,\n> = <TChain extends Chain | undefined = Chain>({\n  chain,\n}: {\n  chain?: TChain\n  pollingInterval?: ClientConfig['pollingInterval']\n  retryCount?: TransportConfig['retryCount']\n  timeout?: TransportConfig['timeout']\n}) => {\n  config: TransportConfig<TType>\n  request: TEIP1193RequestFn\n  value?: TRpcAttributes\n}\n\nexport type CreateTransportErrorType = ErrorType\n\n/**\n * @description Creates an transport intended to be used with a client.\n */\nexport function createTransport<\n  TType extends string,\n  TRpcAttributes extends Record<string, any>,\n>(\n  {\n    key,\n    name,\n    request,\n    retryCount = 3,\n    retryDelay = 150,\n    timeout,\n    type,\n  }: TransportConfig<TType>,\n  value?: TRpcAttributes,\n): ReturnType<Transport<TType, TRpcAttributes>> {\n  return {\n    config: { key, name, request, retryCount, retryDelay, timeout, type },\n    request: buildRequest(request, { retryCount, retryDelay }),\n    value,\n  }\n}\n","import { RpcRequestError } from '../../errors/request.js'\nimport {\n  UrlRequiredError,\n  type UrlRequiredErrorType,\n} from '../../errors/transport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport { createBatchScheduler } from '../../utils/promise/createBatchScheduler.js'\nimport { type HttpOptions, type RpcRequest, rpc } from '../../utils/rpc.js'\n\nimport {\n  type CreateTransportErrorType,\n  type Transport,\n  type TransportConfig,\n  createTransport,\n} from './createTransport.js'\n\nexport type BatchOptions = {\n  /** The maximum number of JSON-RPC requests to send in a batch. @default 1_000 */\n  batchSize?: number\n  /** The maximum number of milliseconds to wait before sending a batch. @default 0 */\n  wait?: number\n}\n\nexport type HttpTransportConfig = {\n  /**\n   * Whether to enable Batch JSON-RPC.\n   * @link https://www.jsonrpc.org/specification#batch\n   */\n  batch?: boolean | BatchOptions\n  /**\n   * Request configuration to pass to `fetch`.\n   * @link https://developer.mozilla.org/en-US/docs/Web/API/fetch\n   */\n  fetchOptions?: HttpOptions['fetchOptions']\n  /** The key of the HTTP transport. */\n  key?: TransportConfig['key']\n  /** The name of the HTTP transport. */\n  name?: TransportConfig['name']\n  /** The max number of times to retry. */\n  retryCount?: TransportConfig['retryCount']\n  /** The base delay (in ms) between retries. */\n  retryDelay?: TransportConfig['retryDelay']\n  /** The timeout (in ms) for the HTTP request. Default: 10_000 */\n  timeout?: TransportConfig['timeout']\n}\n\nexport type HttpTransport = Transport<\n  'http',\n  {\n    fetchOptions?: HttpTransportConfig['fetchOptions']\n    url?: string\n  }\n>\n\nexport type HttpTransportErrorType =\n  | CreateTransportErrorType\n  | UrlRequiredErrorType\n  | ErrorType\n\n/**\n * @description Creates a HTTP transport that connects to a JSON-RPC API.\n */\nexport function http(\n  /** URL of the JSON-RPC API. Defaults to the chain's public RPC URL. */\n  url?: string,\n  config: HttpTransportConfig = {},\n): HttpTransport {\n  const {\n    batch,\n    fetchOptions,\n    key = 'http',\n    name = 'HTTP JSON-RPC',\n    retryDelay,\n  } = config\n  return ({ chain, retryCount: retryCount_, timeout: timeout_ }) => {\n    const { batchSize = 1000, wait = 0 } =\n      typeof batch === 'object' ? batch : {}\n    const retryCount = config.retryCount ?? retryCount_\n    const timeout = timeout_ ?? config.timeout ?? 10_000\n    const url_ = url || chain?.rpcUrls.default.http[0]\n    if (!url_) throw new UrlRequiredError()\n    return createTransport(\n      {\n        key,\n        name,\n        async request({ method, params }) {\n          const body = { method, params }\n\n          const { schedule } = createBatchScheduler({\n            id: `${url}`,\n            wait,\n            shouldSplitBatch(requests) {\n              return requests.length > batchSize\n            },\n            fn: (body: RpcRequest[]) =>\n              rpc.http(url_, {\n                body,\n                fetchOptions,\n                timeout,\n              }),\n            sort: (a, b) => a.id - b.id,\n          })\n\n          const fn = async (body: RpcRequest) =>\n            batch\n              ? schedule(body)\n              : [await rpc.http(url_, { body, fetchOptions, timeout })]\n\n          const [{ error, result }] = await fn(body)\n          if (error)\n            throw new RpcRequestError({\n              body,\n              error,\n              url: url_,\n            })\n          return result\n        },\n        retryCount,\n        retryDelay,\n        timeout,\n        type: 'http',\n      },\n      {\n        fetchOptions,\n        url,\n      },\n    )\n  }\n}\n","import { BaseError } from './base.js'\n\nexport type UrlRequiredErrorType = UrlRequiredError & {\n  name: 'UrlRequiredError'\n}\nexport class UrlRequiredError extends BaseError {\n  constructor() {\n    super(\n      'No URL was provided to the Transport. Please provide a valid RPC URL to the Transport.',\n      {\n        docsPath: '/docs/clients/intro',\n      },\n    )\n  }\n}\n","import { WebSocket } from 'isows'\nimport type { MessageEvent } from 'isows'\n\nimport {\n  HttpRequestError,\n  type HttpRequestErrorType,\n  TimeoutError,\n  type TimeoutErrorType,\n  WebSocketRequestError,\n} from '../errors/request.js'\nimport type { ErrorType } from '../errors/utils.js'\nimport {\n  type CreateBatchSchedulerErrorType,\n  createBatchScheduler,\n} from './promise/createBatchScheduler.js'\nimport {\n  type WithTimeoutErrorType,\n  withTimeout,\n} from './promise/withTimeout.js'\nimport { stringify } from './stringify.js'\n\nlet id = 0\n\ntype SuccessResult<T> = {\n  method?: never\n  result: T\n  error?: never\n}\ntype ErrorResult<T> = {\n  method?: never\n  result?: never\n  error: T\n}\ntype Subscription<TResult, TError> = {\n  method: 'eth_subscription'\n  error?: never\n  result?: never\n  params: {\n    subscription: string\n  } & (\n    | {\n        result: TResult\n        error?: never\n      }\n    | {\n        result?: never\n        error: TError\n      }\n  )\n}\n\nexport type RpcRequest = { method: string; params?: any; id?: number }\n\nexport type RpcResponse<TResult = any, TError = any> = {\n  jsonrpc: `${number}`\n  id: number\n} & (\n  | SuccessResult<TResult>\n  | ErrorResult<TError>\n  | Subscription<TResult, TError>\n)\n\n///////////////////////////////////////////////////\n// HTTP\n\nexport type HttpOptions<TBody extends RpcRequest | RpcRequest[] = RpcRequest> =\n  {\n    // The RPC request body.\n    body: TBody\n    // Request configuration to pass to `fetch`.\n    fetchOptions?: Omit<RequestInit, 'body'>\n    // The timeout (in ms) for the request.\n    timeout?: number\n  }\n\nexport type HttpReturnType<\n  TBody extends RpcRequest | RpcRequest[] = RpcRequest,\n> = TBody extends RpcRequest[] ? RpcResponse[] : RpcResponse\n\nexport type HttpErrorType =\n  | HttpRequestErrorType\n  | TimeoutErrorType\n  | WithTimeoutErrorType\n  | ErrorType\n\nasync function http<TBody extends RpcRequest | RpcRequest[]>(\n  url: string,\n  { body, fetchOptions = {}, timeout = 10_000 }: HttpOptions<TBody>,\n): Promise<HttpReturnType<TBody>> {\n  const { headers, method, signal: signal_ } = fetchOptions\n  try {\n    const response = await withTimeout(\n      async ({ signal }) => {\n        const response = await fetch(url, {\n          ...fetchOptions,\n          body: Array.isArray(body)\n            ? stringify(\n                body.map((body) => ({\n                  jsonrpc: '2.0',\n                  id: body.id ?? id++,\n                  ...body,\n                })),\n              )\n            : stringify({ jsonrpc: '2.0', id: body.id ?? id++, ...body }),\n          headers: {\n            ...headers,\n            'Content-Type': 'application/json',\n          },\n          method: method || 'POST',\n          signal: signal_ || (timeout > 0 ? signal : undefined),\n        })\n        return response\n      },\n      {\n        errorInstance: new TimeoutError({ body, url }),\n        timeout,\n        signal: true,\n      },\n    )\n\n    let data\n    if (response.headers.get('Content-Type')?.startsWith('application/json')) {\n      data = await response.json()\n    } else {\n      data = await response.text()\n    }\n\n    if (!response.ok) {\n      throw new HttpRequestError({\n        body,\n        details: stringify(data.error) || response.statusText,\n        headers: response.headers,\n        status: response.status,\n        url,\n      })\n    }\n\n    return data\n  } catch (err) {\n    if (err instanceof HttpRequestError) throw err\n    if (err instanceof TimeoutError) throw err\n    throw new HttpRequestError({\n      body,\n      details: (err as Error).message,\n      url,\n    })\n  }\n}\n\n///////////////////////////////////////////////////\n// WebSocket\n\ntype Id = string | number\ntype CallbackFn = (message: any) => void\ntype CallbackMap = Map<Id, CallbackFn>\n\nexport type Socket = WebSocket & {\n  requests: CallbackMap\n  subscriptions: CallbackMap\n}\n\nexport type GetSocketErrorType = CreateBatchSchedulerErrorType | ErrorType\n\nexport const socketsCache = /*#__PURE__*/ new Map<string, Socket>()\n\nexport async function getSocket(url: string) {\n  let socket = socketsCache.get(url)\n\n  // If the socket already exists, return it.\n  if (socket) return socket\n\n  const { schedule } = createBatchScheduler<undefined, [Socket]>({\n    id: url,\n    fn: async () => {\n      const webSocket = new WebSocket(url)\n\n      // Set up a cache for incoming \"synchronous\" requests.\n      const requests = new Map<Id, CallbackFn>()\n\n      // Set up a cache for subscriptions (eth_subscribe).\n      const subscriptions = new Map<Id, CallbackFn>()\n\n      const onMessage: (event: MessageEvent) => void = ({ data }) => {\n        const message: RpcResponse = JSON.parse(data as string)\n        const isSubscription = message.method === 'eth_subscription'\n        const id = isSubscription ? message.params.subscription : message.id\n        const cache = isSubscription ? subscriptions : requests\n        const callback = cache.get(id)\n        if (callback) callback({ data })\n        if (!isSubscription) cache.delete(id)\n      }\n      const onClose = () => {\n        socketsCache.delete(url)\n        webSocket.removeEventListener('close', onClose)\n        webSocket.removeEventListener('message', onMessage)\n      }\n\n      // Setup event listeners for RPC & subscription responses.\n      webSocket.addEventListener('close', onClose)\n      webSocket.addEventListener('message', onMessage)\n\n      // Wait for the socket to open.\n      if (webSocket.readyState === WebSocket.CONNECTING) {\n        await new Promise((resolve, reject) => {\n          if (!webSocket) return\n          webSocket.onopen = resolve\n          webSocket.onerror = reject\n        })\n      }\n\n      // Create a new socket instance.\n      socket = Object.assign(webSocket, {\n        requests,\n        subscriptions,\n      })\n      socketsCache.set(url, socket)\n\n      return [socket]\n    },\n  })\n\n  const [_, [socket_]] = await schedule()\n  return socket_\n}\n\nexport type WebSocketOptions = {\n  /** The RPC request body. */\n  body: RpcRequest\n  /** The callback to invoke on response. */\n  onResponse?: (message: RpcResponse) => void\n}\n\nexport type WebSocketReturnType = Socket\n\nexport type WebSocketErrorType = WebSocketRequestError | ErrorType\n\nfunction webSocket(\n  socket: Socket,\n  { body, onResponse }: WebSocketOptions,\n): WebSocketReturnType {\n  if (\n    socket.readyState === socket.CLOSED ||\n    socket.readyState === socket.CLOSING\n  )\n    throw new WebSocketRequestError({\n      body,\n      url: socket.url,\n      details: 'Socket is closed.',\n    })\n\n  const id_ = id++\n\n  const callback = ({ data }: { data: any }) => {\n    const message: RpcResponse = JSON.parse(data)\n\n    if (typeof message.id === 'number' && id_ !== message.id) return\n\n    onResponse?.(message)\n\n    // If we are subscribing to a topic, we want to set up a listener for incoming\n    // messages.\n    if (body.method === 'eth_subscribe' && typeof message.result === 'string') {\n      socket.subscriptions.set(message.result, callback)\n    }\n\n    // If we are unsubscribing from a topic, we want to remove the listener.\n    if (body.method === 'eth_unsubscribe') {\n      socket.subscriptions.delete(body.params?.[0])\n    }\n  }\n  socket.requests.set(id_, callback)\n\n  socket.send(JSON.stringify({ jsonrpc: '2.0', ...body, id: id_ }))\n\n  return socket\n}\n\nexport type WebSocketAsyncOptions = {\n  /** The RPC request body. */\n  body: RpcRequest\n  /** The timeout (in ms) for the request. */\n  timeout?: number\n}\n\nexport type WebSocketAsyncReturnType = RpcResponse\n\nexport type WebSocketAsyncErrorType =\n  | WebSocketErrorType\n  | TimeoutErrorType\n  | WithTimeoutErrorType\n  | ErrorType\n\nasync function webSocketAsync(\n  socket: Socket,\n  { body, timeout = 10_000 }: WebSocketAsyncOptions,\n): Promise<WebSocketAsyncReturnType> {\n  return withTimeout(\n    () =>\n      new Promise<RpcResponse>((onResponse) =>\n        rpc.webSocket(socket, {\n          body,\n          onResponse,\n        }),\n      ),\n    {\n      errorInstance: new TimeoutError({ body, url: socket.url }),\n      timeout,\n    },\n  )\n}\n\n///////////////////////////////////////////////////\n\nexport const rpc = {\n  http,\n  webSocket,\n  webSocketAsync,\n}\n","import type { ErrorType } from '../../errors/utils.js'\n\nexport type WithTimeoutErrorType = ErrorType\n\nexport function withTimeout<TData>(\n  fn: ({ signal }: { signal?: AbortController['signal'] }) => Promise<TData>,\n  {\n    errorInstance = new Error('timed out'),\n    timeout,\n    signal,\n  }: {\n    // The error instance to throw when the timeout is reached.\n    errorInstance?: Error\n    // The timeout (in ms).\n    timeout: number\n    // Whether or not the timeout should use an abort signal.\n    signal?: boolean\n  },\n): Promise<TData> {\n  return new Promise((resolve, reject) => {\n    ;(async () => {\n      let timeoutId!: NodeJS.Timeout\n      try {\n        const controller = new AbortController()\n        if (timeout > 0) {\n          timeoutId = setTimeout(() => {\n            if (signal) {\n              controller.abort()\n            } else {\n              reject(errorInstance)\n            }\n          }, timeout)\n        }\n        resolve(await fn({ signal: controller?.signal }))\n      } catch (err) {\n        if ((err as Error).name === 'AbortError') reject(errorInstance)\n        reject(err)\n      } finally {\n        clearTimeout(timeoutId)\n      }\n    })()\n  })\n}\n","import type { Address } from 'abitype'\n\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport {\n  addressResolverAbi,\n  universalResolverResolveAbi,\n} from '../../constants/abis.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Prettify } from '../../types/utils.js'\nimport {\n  type DecodeFunctionResultErrorType,\n  decodeFunctionResult,\n} from '../../utils/abi/decodeFunctionResult.js'\nimport {\n  type EncodeFunctionDataErrorType,\n  encodeFunctionData,\n} from '../../utils/abi/encodeFunctionData.js'\nimport {\n  type GetChainContractAddressErrorType,\n  getChainContractAddress,\n} from '../../utils/chain/getChainContractAddress.js'\nimport { type TrimErrorType, trim } from '../../utils/data/trim.js'\nimport { type ToHexErrorType, toHex } from '../../utils/encoding/toHex.js'\nimport { isNullUniversalResolverError } from '../../utils/ens/errors.js'\nimport { type NamehashErrorType, namehash } from '../../utils/ens/namehash.js'\nimport {\n  type PacketToBytesErrorType,\n  packetToBytes,\n} from '../../utils/ens/packetToBytes.js'\nimport { getAction } from '../../utils/getAction.js'\nimport {\n  type ReadContractParameters,\n  readContract,\n} from '../public/readContract.js'\n\nexport type GetEnsAddressParameters = Prettify<\n  Pick<ReadContractParameters, 'blockNumber' | 'blockTag'> & {\n    /** ENSIP-9 compliant coinType used to resolve addresses for other chains */\n    coinType?: number\n    /** Name to get the address for. */\n    name: string\n    /** Address of ENS Universal Resolver Contract. */\n    universalResolverAddress?: Address\n  }\n>\n\nexport type GetEnsAddressReturnType = Address | null\n\nexport type GetEnsAddressErrorType =\n  | GetChainContractAddressErrorType\n  | EncodeFunctionDataErrorType\n  | NamehashErrorType\n  | ToHexErrorType\n  | PacketToBytesErrorType\n  | DecodeFunctionResultErrorType\n  | TrimErrorType\n  | ErrorType\n\n/**\n * Gets address for ENS name.\n *\n * - Docs: https://viem.sh/docs/ens/actions/getEnsAddress.html\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/ens\n *\n * Calls `resolve(bytes, bytes)` on ENS Universal Resolver Contract.\n *\n * Since ENS names prohibit certain forbidden characters (e.g. underscore) and have other validation rules, you likely want to [normalize ENS names](https://docs.ens.domains/contract-api-reference/name-processing#normalising-names) with [UTS-46 normalization](https://unicode.org/reports/tr46) before passing them to `getEnsAddress`. You can use the built-in [`normalize`](https://viem.sh/docs/ens/utilities/normalize.html) function for this.\n *\n * @param client - Client to use\n * @param parameters - {@link GetEnsAddressParameters}\n * @returns Address for ENS name or `null` if not found. {@link GetEnsAddressReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getEnsAddress, normalize } from 'viem/ens'\n *\n * const client = createPublicClient({\n *   chain: mainnet,\n *   transport: http(),\n * })\n * const ensAddress = await getEnsAddress(client, {\n *   name: normalize('wevm.eth'),\n * })\n * // '0xd2135CfB216b74109775236E36d4b433F1DF507B'\n */\nexport async function getEnsAddress<TChain extends Chain | undefined>(\n  client: Client<Transport, TChain>,\n  {\n    blockNumber,\n    blockTag,\n    coinType,\n    name,\n    universalResolverAddress: universalResolverAddress_,\n  }: GetEnsAddressParameters,\n): Promise<GetEnsAddressReturnType> {\n  let universalResolverAddress = universalResolverAddress_\n  if (!universalResolverAddress) {\n    if (!client.chain)\n      throw new Error(\n        'client chain not configured. universalResolverAddress is required.',\n      )\n\n    universalResolverAddress = getChainContractAddress({\n      blockNumber,\n      chain: client.chain,\n      contract: 'ensUniversalResolver',\n    })\n  }\n\n  try {\n    const functionData = encodeFunctionData({\n      abi: addressResolverAbi,\n      functionName: 'addr',\n      ...(coinType != null\n        ? { args: [namehash(name), BigInt(coinType)] }\n        : { args: [namehash(name)] }),\n    })\n\n    const res = await getAction(\n      client,\n      readContract,\n      'readContract',\n    )({\n      address: universalResolverAddress,\n      abi: universalResolverResolveAbi,\n      functionName: 'resolve',\n      args: [toHex(packetToBytes(name)), functionData],\n      blockNumber,\n      blockTag,\n    })\n\n    if (res[0] === '0x') return null\n\n    const address = decodeFunctionResult({\n      abi: addressResolverAbi,\n      args: coinType != null ? [namehash(name), BigInt(coinType)] : undefined,\n      functionName: 'addr',\n      data: res[0],\n    })\n\n    if (address === '0x') return null\n    if (trim(address) === '0x00') return null\n    return address\n  } catch (err) {\n    if (isNullUniversalResolverError(err, 'resolve')) return null\n    throw err\n  }\n}\n","import { panicReasons } from '../../constants/solidity.js'\nimport { BaseError } from '../../errors/base.js'\nimport { ContractFunctionRevertedError } from '../../errors/contract.js'\nimport type { ErrorType } from '../../errors/utils.js'\n\nexport type IsNullUniversalResolverErrorErrorType = ErrorType\n\n/*\n * @description Checks if error is a valid null result UniversalResolver error\n */\nexport function isNullUniversalResolverError(\n  err: unknown,\n  callType: 'resolve' | 'reverse',\n): boolean {\n  if (!(err instanceof BaseError)) return false\n  const cause = err.walk((e) => e instanceof ContractFunctionRevertedError)\n  if (!(cause instanceof ContractFunctionRevertedError)) return false\n  if (cause.data?.errorName === 'ResolverNotFound') return true\n  if (cause.data?.errorName === 'ResolverWildcardNotSupported') return true\n  // Backwards compatibility for older UniversalResolver contracts\n  if (\n    cause.reason?.includes(\n      'Wildcard on non-extended resolvers is not supported',\n    )\n  )\n    return true\n  // No primary name set for address.\n  if (callType === 'reverse' && cause.reason === panicReasons[50]) return true\n  return false\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport { type ConcatErrorType, concat } from '../data/concat.js'\nimport {\n  type StringToBytesErrorType,\n  type ToBytesErrorType,\n  stringToBytes,\n  toBytes,\n} from '../encoding/toBytes.js'\nimport { type BytesToHexErrorType, bytesToHex } from '../encoding/toHex.js'\nimport { type Keccak256ErrorType, keccak256 } from '../hash/keccak256.js'\nimport {\n  type EncodedLabelToLabelhashErrorType,\n  encodedLabelToLabelhash,\n} from './encodedLabelToLabelhash.js'\n\nexport type NamehashErrorType =\n  | BytesToHexErrorType\n  | EncodedLabelToLabelhashErrorType\n  | ToBytesErrorType\n  | Keccak256ErrorType\n  | StringToBytesErrorType\n  | ConcatErrorType\n  | ErrorType\n\n/**\n * @description Hashes ENS name\n *\n * - Since ENS names prohibit certain forbidden characters (e.g. underscore) and have other validation rules, you likely want to [normalize ENS names](https://docs.ens.domains/contract-api-reference/name-processing#normalising-names) with [UTS-46 normalization](https://unicode.org/reports/tr46) before passing them to `namehash`. You can use the built-in [`normalize`](https://viem.sh/docs/ens/utilities/normalize.html) function for this.\n *\n * @example\n * namehash('wevm.eth')\n * '0xf246651c1b9a6b141d19c2604e9a58f567973833990f830d882534a747801359'\n *\n * @link https://eips.ethereum.org/EIPS/eip-137\n */\nexport function namehash(name: string) {\n  let result = new Uint8Array(32).fill(0)\n  if (!name) return bytesToHex(result)\n\n  const labels = name.split('.')\n  // Iterate in reverse order building up hash\n  for (let i = labels.length - 1; i >= 0; i -= 1) {\n    const hashFromEncodedLabel = encodedLabelToLabelhash(labels[i])\n    const hashed = hashFromEncodedLabel\n      ? toBytes(hashFromEncodedLabel)\n      : keccak256(stringToBytes(labels[i]), 'bytes')\n    result = keccak256(concat([result, hashed]), 'bytes')\n  }\n\n  return bytesToHex(result)\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { Hex } from '../../types/misc.js'\nimport { type IsHexErrorType, isHex } from '../data/isHex.js'\n\nexport type EncodedLabelToLabelhashErrorType = IsHexErrorType | ErrorType\n\nexport function encodedLabelToLabelhash(label: string): Hex | null {\n  if (label.length !== 66) return null\n  if (label.indexOf('[') !== 0) return null\n  if (label.indexOf(']') !== 65) return null\n  const hash = `0x${label.slice(1, 65)}`\n  if (!isHex(hash)) return null\n  return hash\n}\n","// Adapted from https://github.com/mafintosh/dns-packet\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray } from '../../types/misc.js'\nimport {\n  type StringToBytesErrorType,\n  stringToBytes,\n} from '../encoding/toBytes.js'\nimport {\n  type EncodeLabelhashErrorType,\n  encodeLabelhash,\n} from './encodeLabelhash.js'\nimport { type LabelhashErrorType, labelhash } from './labelhash.js'\n\nexport type PacketToBytesErrorType =\n  | EncodeLabelhashErrorType\n  | LabelhashErrorType\n  | StringToBytesErrorType\n  | ErrorType\n\n/*\n * @description Encodes a DNS packet into a ByteArray containing a UDP payload.\n */\nexport function packetToBytes(packet: string): ByteArray {\n  // strip leading and trailing `.`\n  const value = packet.replace(/^\\.|\\.$/gm, '')\n  if (value.length === 0) return new Uint8Array(1)\n\n  const bytes = new Uint8Array(stringToBytes(value).byteLength + 2)\n\n  let offset = 0\n  const list = value.split('.')\n  for (let i = 0; i < list.length; i++) {\n    let encoded = stringToBytes(list[i])\n    // if the length is > 255, make the encoded label value a labelhash\n    // this is compatible with the universal resolver\n    if (encoded.byteLength > 255)\n      encoded = stringToBytes(encodeLabelhash(labelhash(list[i])))\n    bytes[offset] = encoded.length\n    bytes.set(encoded, offset + 1)\n    offset += encoded.length + 1\n  }\n\n  if (bytes.byteLength !== offset + 1) return bytes.slice(0, offset + 1)\n\n  return bytes\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { Hex } from '../../types/misc.js'\n\nexport type EncodeLabelhashErrorType = ErrorType\n\nexport function encodeLabelhash(hash: Hex): `[${string}]` {\n  return `[${hash.slice(2)}]`\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport {\n  type StringToBytesErrorType,\n  stringToBytes,\n} from '../encoding/toBytes.js'\nimport { type BytesToHexErrorType, bytesToHex } from '../encoding/toHex.js'\nimport { type Keccak256ErrorType, keccak256 } from '../hash/keccak256.js'\nimport {\n  type EncodedLabelToLabelhashErrorType,\n  encodedLabelToLabelhash,\n} from './encodedLabelToLabelhash.js'\n\nexport type LabelhashErrorType =\n  | BytesToHexErrorType\n  | EncodedLabelToLabelhashErrorType\n  | Keccak256ErrorType\n  | StringToBytesErrorType\n  | ErrorType\n\n/**\n * @description Hashes ENS label\n *\n * - Since ENS labels prohibit certain forbidden characters (e.g. underscore) and have other validation rules, you likely want to [normalize ENS labels](https://docs.ens.domains/contract-api-reference/name-processing#normalising-names) with [UTS-46 normalization](https://unicode.org/reports/tr46) before passing them to `labelhash`. You can use the built-in [`normalize`](https://viem.sh/docs/ens/utilities/normalize.html) function for this.\n *\n * @example\n * labelhash('eth')\n * '0x4f5b812789fc606be1b3b16908db13fc7a9adf7ca72641f84d75b47069d3d7f0'\n */\nexport function labelhash(label: string) {\n  const result = new Uint8Array(32).fill(0)\n  if (!label) return bytesToHex(result)\n  return encodedLabelToLabelhash(label) || keccak256(stringToBytes(label))\n}\n","import { BaseError } from './base.js'\n\nexport type EnsAvatarInvalidMetadataErrorType =\n  EnsAvatarInvalidMetadataError & {\n    name: 'EnsAvatarInvalidMetadataError'\n  }\nexport class EnsAvatarInvalidMetadataError extends BaseError {\n  override name = 'EnsAvatarInvalidMetadataError'\n  constructor({ data }: { data: any }) {\n    super(\n      'Unable to extract image from metadata. The metadata may be malformed or invalid.',\n      {\n        metaMessages: [\n          '- Metadata must be a JSON object with at least an `image`, `image_url` or `image_data` property.',\n          '',\n          `Provided data: ${JSON.stringify(data)}`,\n        ],\n      },\n    )\n  }\n}\n\nexport type EnsAvatarInvalidNftUriErrorType = EnsAvatarInvalidNftUriError & {\n  name: 'EnsAvatarInvalidNftUriError'\n}\nexport class EnsAvatarInvalidNftUriError extends BaseError {\n  override name = 'EnsAvatarInvalidNftUriError'\n  constructor({ reason }: { reason: string }) {\n    super(`ENS NFT avatar URI is invalid. ${reason}`)\n  }\n}\n\nexport type EnsAvatarUriResolutionErrorType = EnsAvatarUriResolutionError & {\n  name: 'EnsAvatarUriResolutionError'\n}\nexport class EnsAvatarUriResolutionError extends BaseError {\n  override name = 'EnsAvatarUriResolutionError'\n  constructor({ uri }: { uri: string }) {\n    super(\n      `Unable to resolve ENS avatar URI \"${uri}\". The URI may be malformed, invalid, or does not respond with a valid image.`,\n    )\n  }\n}\n\nexport type EnsAvatarUnsupportedNamespaceErrorType =\n  EnsAvatarUnsupportedNamespaceError & {\n    name: 'EnsAvatarUnsupportedNamespaceError'\n  }\nexport class EnsAvatarUnsupportedNamespaceError extends BaseError {\n  override name = 'EnsAvatarUnsupportedNamespaceError'\n  constructor({ namespace }: { namespace: string }) {\n    super(\n      `ENS NFT avatar namespace \"${namespace}\" is not supported. Must be \"erc721\" or \"erc1155\".`,\n    )\n  }\n}\n","import type { Address } from 'abitype'\n\nimport {\n  type ReadContractErrorType,\n  readContract,\n} from '../../../actions/public/readContract.js'\nimport type { Client } from '../../../clients/createClient.js'\nimport type { Transport } from '../../../clients/transports/createTransport.js'\nimport {\n  EnsAvatarInvalidMetadataError,\n  type EnsAvatarInvalidMetadataErrorType,\n  EnsAvatarInvalidNftUriError,\n  type EnsAvatarInvalidNftUriErrorType,\n  EnsAvatarUnsupportedNamespaceError,\n  type EnsAvatarUnsupportedNamespaceErrorType,\n  EnsAvatarUriResolutionError,\n  type EnsAvatarUriResolutionErrorType,\n} from '../../../errors/ens.js'\nimport type { ErrorType } from '../../../errors/utils.js'\nimport type { Chain } from '../../../types/chain.js'\nimport type { AssetGatewayUrls } from '../../../types/ens.js'\n\ntype UriItem = {\n  uri: string\n  isOnChain: boolean\n  isEncoded: boolean\n}\n\nconst networkRegex =\n  /(?<protocol>https?:\\/\\/[^\\/]*|ipfs:\\/|ipns:\\/|ar:\\/)?(?<root>\\/)?(?<subpath>ipfs\\/|ipns\\/)?(?<target>[\\w\\-.]+)(?<subtarget>\\/.*)?/\nconst ipfsHashRegex =\n  /^(Qm[1-9A-HJ-NP-Za-km-z]{44,}|b[A-Za-z2-7]{58,}|B[A-Z2-7]{58,}|z[1-9A-HJ-NP-Za-km-z]{48,}|F[0-9A-F]{50,})(\\/(?<target>[\\w\\-.]+))?(?<subtarget>\\/.*)?$/\nconst base64Regex = /^data:([a-zA-Z\\-/+]*);base64,([^\"].*)/\nconst dataURIRegex = /^data:([a-zA-Z\\-/+]*)?(;[a-zA-Z0-9].*?)?(,)/\n\nexport type IsImageUriErrorType = ErrorType\n\nexport async function isImageUri(uri: string) {\n  try {\n    const res = await fetch(uri, { method: 'HEAD' })\n    // retrieve content type header to check if content is image\n    if (res.status === 200) {\n      const contentType = res.headers.get('content-type')\n      return contentType?.startsWith('image/')\n    }\n    return false\n  } catch (error: any) {\n    // if error is not cors related then fail\n    if (typeof error === 'object' && typeof error.response !== 'undefined') {\n      return false\n    }\n    // fail in NodeJS, since the error is not cors but any other network issue\n    // biome-ignore lint/suspicious/noPrototypeBuiltins:\n    if (!globalThis.hasOwnProperty('Image')) return false\n    // in case of cors, use image api to validate if given url is an actual image\n    return new Promise((resolve) => {\n      const img = new Image()\n      img.onload = () => {\n        resolve(true)\n      }\n      img.onerror = () => {\n        resolve(false)\n      }\n      img.src = uri\n    })\n  }\n}\n\nexport type GetGatewayErrorType = ErrorType\n\nexport function getGateway(custom: string | undefined, defaultGateway: string) {\n  if (!custom) return defaultGateway\n  if (custom.endsWith('/')) return custom.slice(0, -1)\n  return custom\n}\n\nexport type ResolveAvatarUriErrorType =\n  | GetGatewayErrorType\n  | EnsAvatarUriResolutionErrorType\n  | ErrorType\n\nexport function resolveAvatarUri({\n  uri,\n  gatewayUrls,\n}: {\n  uri: string\n  gatewayUrls?: AssetGatewayUrls | undefined\n}): UriItem {\n  const isEncoded = base64Regex.test(uri)\n  if (isEncoded) return { uri, isOnChain: true, isEncoded }\n\n  const ipfsGateway = getGateway(gatewayUrls?.ipfs, 'https://ipfs.io')\n  const arweaveGateway = getGateway(gatewayUrls?.arweave, 'https://arweave.net')\n\n  const networkRegexMatch = uri.match(networkRegex)\n  const {\n    protocol,\n    subpath,\n    target,\n    subtarget = '',\n  } = networkRegexMatch?.groups || {}\n\n  const isIPNS = protocol === 'ipns:/' || subpath === 'ipns/'\n  const isIPFS =\n    protocol === 'ipfs:/' || subpath === 'ipfs/' || ipfsHashRegex.test(uri)\n\n  if (uri.startsWith('http') && !isIPNS && !isIPFS) {\n    let replacedUri = uri\n    if (gatewayUrls?.arweave)\n      replacedUri = uri.replace(/https:\\/\\/arweave.net/g, gatewayUrls?.arweave)\n    return { uri: replacedUri, isOnChain: false, isEncoded: false }\n  }\n\n  if ((isIPNS || isIPFS) && target) {\n    return {\n      uri: `${ipfsGateway}/${isIPNS ? 'ipns' : 'ipfs'}/${target}${subtarget}`,\n      isOnChain: false,\n      isEncoded: false,\n    }\n  }\n\n  if (protocol === 'ar:/' && target) {\n    return {\n      uri: `${arweaveGateway}/${target}${subtarget || ''}`,\n      isOnChain: false,\n      isEncoded: false,\n    }\n  }\n\n  let parsedUri = uri.replace(dataURIRegex, '')\n  if (parsedUri.startsWith('<svg')) {\n    // if svg, base64 encode\n    parsedUri = `data:image/svg+xml;base64,${btoa(parsedUri)}`\n  }\n\n  if (parsedUri.startsWith('data:') || parsedUri.startsWith('{')) {\n    return {\n      uri: parsedUri,\n      isOnChain: true,\n      isEncoded: false,\n    }\n  }\n\n  throw new EnsAvatarUriResolutionError({ uri })\n}\n\nexport type GetJsonImageErrorType =\n  | EnsAvatarInvalidMetadataErrorType\n  | ErrorType\n\nexport function getJsonImage(data: any) {\n  // validation check for json data, must include one of theses properties\n  if (\n    typeof data !== 'object' ||\n    (!('image' in data) && !('image_url' in data) && !('image_data' in data))\n  ) {\n    throw new EnsAvatarInvalidMetadataError({ data })\n  }\n\n  return data.image || data.image_url || data.image_data\n}\n\nexport type GetMetadataAvatarUriErrorType =\n  | EnsAvatarUriResolutionErrorType\n  | ParseAvatarUriErrorType\n  | GetJsonImageErrorType\n  | ErrorType\n\nexport async function getMetadataAvatarUri({\n  gatewayUrls,\n  uri,\n}: {\n  gatewayUrls?: AssetGatewayUrls | undefined\n  uri: string\n}): Promise<string> {\n  try {\n    const res = await fetch(uri).then((res) => res.json())\n    const image = await parseAvatarUri({\n      gatewayUrls,\n      uri: getJsonImage(res),\n    })\n    return image\n  } catch {\n    throw new EnsAvatarUriResolutionError({ uri })\n  }\n}\n\nexport type ParseAvatarUriErrorType =\n  | ResolveAvatarUriErrorType\n  | IsImageUriErrorType\n  | EnsAvatarUriResolutionErrorType\n  | ErrorType\n\nexport async function parseAvatarUri({\n  gatewayUrls,\n  uri,\n}: {\n  gatewayUrls?: AssetGatewayUrls | undefined\n  uri: string\n}): Promise<string> {\n  const { uri: resolvedURI, isOnChain } = resolveAvatarUri({ uri, gatewayUrls })\n  if (isOnChain) return resolvedURI\n\n  // check if resolvedURI is an image, if it is return the url\n  const isImage = await isImageUri(resolvedURI)\n  if (isImage) return resolvedURI\n\n  throw new EnsAvatarUriResolutionError({ uri })\n}\n\ntype ParsedNft = {\n  chainID: number\n  namespace: string\n  contractAddress: Address\n  tokenID: string\n}\n\nexport type ParseNftUriErrorType = EnsAvatarInvalidNftUriErrorType | ErrorType\n\nexport function parseNftUri(uri_: string): ParsedNft {\n  let uri = uri_\n  // parse valid nft spec (CAIP-22/CAIP-29)\n  // @see: https://github.com/ChainAgnostic/CAIPs/tree/master/CAIPs\n  if (uri.startsWith('did:nft:')) {\n    // convert DID to CAIP\n    uri = uri.replace('did:nft:', '').replace(/_/g, '/')\n  }\n\n  const [reference, asset_namespace, tokenID] = uri.split('/')\n  const [eip_namespace, chainID] = reference.split(':')\n  const [erc_namespace, contractAddress] = asset_namespace.split(':')\n\n  if (!eip_namespace || eip_namespace.toLowerCase() !== 'eip155')\n    throw new EnsAvatarInvalidNftUriError({ reason: 'Only EIP-155 supported' })\n  if (!chainID)\n    throw new EnsAvatarInvalidNftUriError({ reason: 'Chain ID not found' })\n  if (!contractAddress)\n    throw new EnsAvatarInvalidNftUriError({\n      reason: 'Contract address not found',\n    })\n  if (!tokenID)\n    throw new EnsAvatarInvalidNftUriError({ reason: 'Token ID not found' })\n  if (!erc_namespace)\n    throw new EnsAvatarInvalidNftUriError({ reason: 'ERC namespace not found' })\n\n  return {\n    chainID: parseInt(chainID),\n    namespace: erc_namespace.toLowerCase(),\n    contractAddress: contractAddress as Address,\n    tokenID,\n  }\n}\n\nexport type GetNftTokenUriErrorType =\n  | ReadContractErrorType\n  | EnsAvatarUnsupportedNamespaceErrorType\n  | ErrorType\n\nexport async function getNftTokenUri<TChain extends Chain | undefined>(\n  client: Client<Transport, TChain>,\n  { nft }: { nft: ParsedNft },\n) {\n  if (nft.namespace === 'erc721') {\n    return readContract(client, {\n      address: nft.contractAddress,\n      abi: [\n        {\n          name: 'tokenURI',\n          type: 'function',\n          stateMutability: 'view',\n          inputs: [{ name: 'tokenId', type: 'uint256' }],\n          outputs: [{ name: '', type: 'string' }],\n        },\n      ],\n      functionName: 'tokenURI',\n      args: [BigInt(nft.tokenID)],\n    })\n  }\n  if (nft.namespace === 'erc1155') {\n    return readContract(client, {\n      address: nft.contractAddress,\n      abi: [\n        {\n          name: 'uri',\n          type: 'function',\n          stateMutability: 'view',\n          inputs: [{ name: '_id', type: 'uint256' }],\n          outputs: [{ name: '', type: 'string' }],\n        },\n      ],\n      functionName: 'uri',\n      args: [BigInt(nft.tokenID)],\n    })\n  }\n  throw new EnsAvatarUnsupportedNamespaceError({ namespace: nft.namespace })\n}\n","import type { Client } from '../../../clients/createClient.js'\nimport type { Transport } from '../../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../../errors/utils.js'\nimport type { Chain } from '../../../types/chain.js'\nimport type { AssetGatewayUrls } from '../../../types/ens.js'\n\nimport {\n  type GetJsonImageErrorType,\n  type GetMetadataAvatarUriErrorType,\n  type GetNftTokenUriErrorType,\n  type ParseAvatarUriErrorType,\n  type ParseNftUriErrorType,\n  type ResolveAvatarUriErrorType,\n  getJsonImage,\n  getMetadataAvatarUri,\n  getNftTokenUri,\n  parseAvatarUri,\n  parseNftUri,\n  resolveAvatarUri,\n} from './utils.js'\n\nexport type ParseAvatarRecordErrorType =\n  | ParseNftAvatarUriErrorType\n  | ParseAvatarUriErrorType\n  | ErrorType\n\nexport async function parseAvatarRecord<TChain extends Chain | undefined>(\n  client: Client<Transport, TChain>,\n  {\n    gatewayUrls,\n    record,\n  }: {\n    gatewayUrls?: AssetGatewayUrls\n    record: string\n  },\n): Promise<string> {\n  if (/eip155:/i.test(record))\n    return parseNftAvatarUri(client, { gatewayUrls, record })\n  return parseAvatarUri({ uri: record, gatewayUrls })\n}\n\nexport type ParseNftAvatarUriErrorType =\n  | ParseNftUriErrorType\n  | GetNftTokenUriErrorType\n  | ResolveAvatarUriErrorType\n  | ParseAvatarUriErrorType\n  | GetJsonImageErrorType\n  | GetMetadataAvatarUriErrorType\n  | ErrorType\n\nasync function parseNftAvatarUri<TChain extends Chain | undefined>(\n  client: Client<Transport, TChain>,\n  {\n    gatewayUrls,\n    record,\n  }: {\n    gatewayUrls?: AssetGatewayUrls\n    record: string\n  },\n): Promise<string> {\n  // parse NFT URI into properties\n  const nft = parseNftUri(record)\n  // fetch tokenURI from the NFT contract\n  const nftUri = await getNftTokenUri(client, { nft })\n  // resolve the URI from the fetched tokenURI\n  const {\n    uri: resolvedNftUri,\n    isOnChain,\n    isEncoded,\n  } = resolveAvatarUri({ uri: nftUri, gatewayUrls })\n\n  // if the resolved URI is on chain, return the data\n  if (\n    isOnChain &&\n    (resolvedNftUri.includes('data:application/json;base64,') ||\n      resolvedNftUri.startsWith('{'))\n  ) {\n    const encodedJson = isEncoded\n      ? // if it is encoded, decode it\n        atob(resolvedNftUri.replace('data:application/json;base64,', ''))\n      : // if it isn't encoded assume it is a JSON string, but it could be anything (it will error if it is)\n        resolvedNftUri\n\n    const decoded = JSON.parse(encodedJson)\n    return parseAvatarUri({ uri: getJsonImage(decoded), gatewayUrls })\n  }\n\n  let uriTokenId = nft.tokenID\n  if (nft.namespace === 'erc1155')\n    uriTokenId = uriTokenId.replace('0x', '').padStart(64, '0')\n\n  return getMetadataAvatarUri({\n    gatewayUrls,\n    uri: resolvedNftUri.replace(/(?:0x)?{id}/, uriTokenId),\n  })\n}\n","import type { Address } from 'abitype'\n\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport {\n  textResolverAbi,\n  universalResolverResolveAbi,\n} from '../../constants/abis.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Prettify } from '../../types/utils.js'\nimport {\n  type DecodeFunctionResultErrorType,\n  decodeFunctionResult,\n} from '../../utils/abi/decodeFunctionResult.js'\nimport {\n  type EncodeFunctionDataErrorType,\n  encodeFunctionData,\n} from '../../utils/abi/encodeFunctionData.js'\nimport {\n  type GetChainContractAddressErrorType,\n  getChainContractAddress,\n} from '../../utils/chain/getChainContractAddress.js'\nimport { type ToHexErrorType, toHex } from '../../utils/encoding/toHex.js'\nimport { isNullUniversalResolverError } from '../../utils/ens/errors.js'\nimport { type NamehashErrorType, namehash } from '../../utils/ens/namehash.js'\nimport {\n  type PacketToBytesErrorType,\n  packetToBytes,\n} from '../../utils/ens/packetToBytes.js'\nimport { getAction } from '../../utils/getAction.js'\nimport {\n  type ReadContractErrorType,\n  type ReadContractParameters,\n  readContract,\n} from '../public/readContract.js'\n\nexport type GetEnsTextParameters = Prettify<\n  Pick<ReadContractParameters, 'blockNumber' | 'blockTag'> & {\n    /** ENS name to get Text for. */\n    name: string\n    /** Text record to retrieve. */\n    key: string\n    /** Address of ENS Universal Resolver Contract. */\n    universalResolverAddress?: Address\n  }\n>\n\nexport type GetEnsTextReturnType = string | null\n\nexport type GetEnsTextErrorType =\n  | GetChainContractAddressErrorType\n  | ReadContractErrorType\n  | ToHexErrorType\n  | PacketToBytesErrorType\n  | EncodeFunctionDataErrorType\n  | NamehashErrorType\n  | DecodeFunctionResultErrorType\n\n/**\n * Gets a text record for specified ENS name.\n *\n * - Docs: https://viem.sh/docs/ens/actions/getEnsResolver.html\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/ens\n *\n * Calls `resolve(bytes, bytes)` on ENS Universal Resolver Contract.\n *\n * Since ENS names prohibit certain forbidden characters (e.g. underscore) and have other validation rules, you likely want to [normalize ENS names](https://docs.ens.domains/contract-api-reference/name-processing#normalising-names) with [UTS-46 normalization](https://unicode.org/reports/tr46) before passing them to `getEnsAddress`. You can use the built-in [`normalize`](https://viem.sh/docs/ens/utilities/normalize.html) function for this.\n *\n * @param client - Client to use\n * @param parameters - {@link GetEnsTextParameters}\n * @returns Address for ENS resolver. {@link GetEnsTextReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getEnsText, normalize } from 'viem/ens'\n *\n * const client = createPublicClient({\n *   chain: mainnet,\n *   transport: http(),\n * })\n * const twitterRecord = await getEnsText(client, {\n *   name: normalize('wevm.eth'),\n *   key: 'com.twitter',\n * })\n * // 'wagmi_sh'\n */\nexport async function getEnsText<TChain extends Chain | undefined>(\n  client: Client<Transport, TChain>,\n  {\n    blockNumber,\n    blockTag,\n    name,\n    key,\n    universalResolverAddress: universalResolverAddress_,\n  }: GetEnsTextParameters,\n): Promise<GetEnsTextReturnType> {\n  let universalResolverAddress = universalResolverAddress_\n  if (!universalResolverAddress) {\n    if (!client.chain)\n      throw new Error(\n        'client chain not configured. universalResolverAddress is required.',\n      )\n\n    universalResolverAddress = getChainContractAddress({\n      blockNumber,\n      chain: client.chain,\n      contract: 'ensUniversalResolver',\n    })\n  }\n\n  try {\n    const res = await getAction(\n      client,\n      readContract,\n      'readContract',\n    )({\n      address: universalResolverAddress,\n      abi: universalResolverResolveAbi,\n      functionName: 'resolve',\n      args: [\n        toHex(packetToBytes(name)),\n        encodeFunctionData({\n          abi: textResolverAbi,\n          functionName: 'text',\n          args: [namehash(name), key],\n        }),\n      ],\n      blockNumber,\n      blockTag,\n    })\n\n    if (res[0] === '0x') return null\n\n    const record = decodeFunctionResult({\n      abi: textResolverAbi,\n      functionName: 'text',\n      data: res[0],\n    })\n\n    return record === '' ? null : record\n  } catch (err) {\n    if (isNullUniversalResolverError(err, 'resolve')) return null\n    throw err\n  }\n}\n","import type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { AssetGatewayUrls } from '../../types/ens.js'\nimport type { Prettify } from '../../types/utils.js'\nimport {\n  type ParseAvatarRecordErrorType,\n  parseAvatarRecord,\n} from '../../utils/ens/avatar/parseAvatarRecord.js'\nimport { getAction } from '../../utils/getAction.js'\n\nimport {\n  type GetEnsTextErrorType,\n  type GetEnsTextParameters,\n  getEnsText,\n} from './getEnsText.js'\n\nexport type GetEnsAvatarParameters = Prettify<\n  Omit<GetEnsTextParameters, 'key'> & {\n    /** Gateway urls to resolve IPFS and/or Arweave assets. */\n    gatewayUrls?: AssetGatewayUrls\n  }\n>\n\nexport type GetEnsAvatarReturnType = string | null\n\nexport type GetEnsAvatarErrorType =\n  | GetEnsTextErrorType\n  | ParseAvatarRecordErrorType\n  | ErrorType\n\n/**\n * Gets the avatar of an ENS name.\n *\n * - Docs: https://viem.sh/docs/ens/actions/getEnsAvatar.html\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/ens\n *\n * Calls [`getEnsText`](https://viem.sh/docs/ens/actions/getEnsText.html) with `key` set to `'avatar'`.\n *\n * Since ENS names prohibit certain forbidden characters (e.g. underscore) and have other validation rules, you likely want to [normalize ENS names](https://docs.ens.domains/contract-api-reference/name-processing#normalising-names) with [UTS-46 normalization](https://unicode.org/reports/tr46) before passing them to `getEnsAddress`. You can use the built-in [`normalize`](https://viem.sh/docs/ens/utilities/normalize.html) function for this.\n *\n * @param client - Client to use\n * @param parameters - {@link GetEnsAvatarParameters}\n * @returns Avatar URI or `null` if not found. {@link GetEnsAvatarReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getEnsAvatar, normalize } from 'viem/ens'\n *\n * const client = createPublicClient({\n *   chain: mainnet,\n *   transport: http(),\n * })\n * const ensAvatar = await getEnsAvatar(client, {\n *   name: normalize('wevm.eth'),\n * })\n * // 'https://ipfs.io/ipfs/Qma8mnp6xV3J2cRNf3mTth5C8nV11CAnceVinc3y8jSbio'\n */\nexport async function getEnsAvatar<TChain extends Chain | undefined>(\n  client: Client<Transport, TChain>,\n  {\n    blockNumber,\n    blockTag,\n    gatewayUrls,\n    name,\n    universalResolverAddress,\n  }: GetEnsAvatarParameters,\n): Promise<GetEnsAvatarReturnType> {\n  const record = await getAction(\n    client,\n    getEnsText,\n    'getEnsText',\n  )({\n    blockNumber,\n    blockTag,\n    key: 'avatar',\n    name,\n    universalResolverAddress,\n  })\n  if (!record) return null\n  try {\n    return await parseAvatarRecord(client, { record, gatewayUrls })\n  } catch {\n    return null\n  }\n}\n","import type { Address } from 'abitype'\n\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport { universalResolverReverseAbi } from '../../constants/abis.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Prettify } from '../../types/utils.js'\nimport {\n  type GetChainContractAddressErrorType,\n  getChainContractAddress,\n} from '../../utils/chain/getChainContractAddress.js'\nimport { type ToHexErrorType, toHex } from '../../utils/encoding/toHex.js'\nimport { isNullUniversalResolverError } from '../../utils/ens/errors.js'\nimport {\n  type PacketToBytesErrorType,\n  packetToBytes,\n} from '../../utils/ens/packetToBytes.js'\nimport { getAction } from '../../utils/getAction.js'\nimport {\n  type ReadContractErrorType,\n  type ReadContractParameters,\n  readContract,\n} from '../public/readContract.js'\n\nexport type GetEnsNameParameters = Prettify<\n  Pick<ReadContractParameters, 'blockNumber' | 'blockTag'> & {\n    /** Address to get ENS name for. */\n    address: Address\n    /** Address of ENS Universal Resolver Contract. */\n    universalResolverAddress?: Address\n  }\n>\n\nexport type GetEnsNameReturnType = string | null\n\nexport type GetEnsNameErrorType =\n  | GetChainContractAddressErrorType\n  | ReadContractErrorType\n  | ToHexErrorType\n  | PacketToBytesErrorType\n  | ErrorType\n\n/**\n * Gets primary name for specified address.\n *\n * - Docs: https://viem.sh/docs/ens/actions/getEnsName.html\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/ens\n *\n * Calls `reverse(bytes)` on ENS Universal Resolver Contract to \"reverse resolve\" the address to the primary ENS name.\n *\n * @param client - Client to use\n * @param parameters - {@link GetEnsNameParameters}\n * @returns Name or `null` if not found. {@link GetEnsNameReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getEnsName } from 'viem/ens'\n *\n * const client = createPublicClient({\n *   chain: mainnet,\n *   transport: http(),\n * })\n * const ensName = await getEnsName(client, {\n *   address: '0xd2135CfB216b74109775236E36d4b433F1DF507B',\n * })\n * // 'wevm.eth'\n */\nexport async function getEnsName<TChain extends Chain | undefined>(\n  client: Client<Transport, TChain>,\n  {\n    address,\n    blockNumber,\n    blockTag,\n    universalResolverAddress: universalResolverAddress_,\n  }: GetEnsNameParameters,\n): Promise<GetEnsNameReturnType> {\n  let universalResolverAddress = universalResolverAddress_\n  if (!universalResolverAddress) {\n    if (!client.chain)\n      throw new Error(\n        'client chain not configured. universalResolverAddress is required.',\n      )\n\n    universalResolverAddress = getChainContractAddress({\n      blockNumber,\n      chain: client.chain,\n      contract: 'ensUniversalResolver',\n    })\n  }\n\n  const reverseNode = `${address.toLowerCase().substring(2)}.addr.reverse`\n  try {\n    const [name, resolvedAddress] = await getAction(\n      client,\n      readContract,\n      'readContract',\n    )({\n      address: universalResolverAddress,\n      abi: universalResolverReverseAbi,\n      functionName: 'reverse',\n      args: [toHex(packetToBytes(reverseNode))],\n      blockNumber,\n      blockTag,\n    })\n    if (address.toLowerCase() !== resolvedAddress.toLowerCase()) return null\n    return name\n  } catch (err) {\n    if (isNullUniversalResolverError(err, 'reverse')) return null\n    throw err\n  }\n}\n","import type { Address } from 'abitype'\n\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Prettify } from '../../types/utils.js'\nimport {\n  type GetChainContractAddressErrorType,\n  getChainContractAddress,\n} from '../../utils/chain/getChainContractAddress.js'\nimport { type ToHexErrorType, toHex } from '../../utils/encoding/toHex.js'\nimport {\n  type PacketToBytesErrorType,\n  packetToBytes,\n} from '../../utils/ens/packetToBytes.js'\nimport { getAction } from '../../utils/getAction.js'\nimport {\n  type ReadContractParameters,\n  readContract,\n} from '../public/readContract.js'\n\nexport type GetEnsResolverParameters = Prettify<\n  Pick<ReadContractParameters, 'blockNumber' | 'blockTag'> & {\n    /** Name to get the address for. */\n    name: string\n    /** Address of ENS Universal Resolver Contract. */\n    universalResolverAddress?: Address\n  }\n>\n\nexport type GetEnsResolverReturnType = Address\n\nexport type GetEnsResolverErrorType =\n  | GetChainContractAddressErrorType\n  | ToHexErrorType\n  | PacketToBytesErrorType\n  | ErrorType\n\n/**\n * Gets resolver for ENS name.\n *\n * - Docs: https://viem.sh/docs/ens/actions/getEnsResolver.html\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/ens\n *\n * Calls `findResolver(bytes)` on ENS Universal Resolver Contract to retrieve the resolver of an ENS name.\n *\n * Since ENS names prohibit certain forbidden characters (e.g. underscore) and have other validation rules, you likely want to [normalize ENS names](https://docs.ens.domains/contract-api-reference/name-processing#normalising-names) with [UTS-46 normalization](https://unicode.org/reports/tr46) before passing them to `getEnsAddress`. You can use the built-in [`normalize`](https://viem.sh/docs/ens/utilities/normalize.html) function for this.\n *\n * @param client - Client to use\n * @param parameters - {@link GetEnsResolverParameters}\n * @returns Address for ENS resolver. {@link GetEnsResolverReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getEnsResolver, normalize } from 'viem/ens'\n *\n * const client = createPublicClient({\n *   chain: mainnet,\n *   transport: http(),\n * })\n * const resolverAddress = await getEnsResolver(client, {\n *   name: normalize('wevm.eth'),\n * })\n * // '0x4976fb03C32e5B8cfe2b6cCB31c09Ba78EBaBa41'\n */\nexport async function getEnsResolver<TChain extends Chain | undefined>(\n  client: Client<Transport, TChain>,\n  {\n    blockNumber,\n    blockTag,\n    name,\n    universalResolverAddress: universalResolverAddress_,\n  }: GetEnsResolverParameters,\n) {\n  let universalResolverAddress = universalResolverAddress_\n  if (!universalResolverAddress) {\n    if (!client.chain)\n      throw new Error(\n        'client chain not configured. universalResolverAddress is required.',\n      )\n\n    universalResolverAddress = getChainContractAddress({\n      blockNumber,\n      chain: client.chain,\n      contract: 'ensUniversalResolver',\n    })\n  }\n\n  const [resolverAddress] = await getAction(\n    client,\n    readContract,\n    'readContract',\n  )({\n    address: universalResolverAddress,\n    abi: [\n      {\n        inputs: [{ type: 'bytes' }],\n        name: 'findResolver',\n        outputs: [{ type: 'address' }, { type: 'bytes32' }],\n        stateMutability: 'view',\n        type: 'function',\n      },\n    ],\n    functionName: 'findResolver',\n    args: [toHex(packetToBytes(name))],\n    blockNumber,\n    blockTag,\n  })\n  return resolverAddress\n}\n","import type { Abi, AbiEvent } from 'abitype'\n\nimport {\n  type GetEnsAddressParameters,\n  type GetEnsAddressReturnType,\n  getEnsAddress,\n} from '../../actions/ens/getEnsAddress.js'\nimport {\n  type GetEnsAvatarParameters,\n  type GetEnsAvatarReturnType,\n  getEnsAvatar,\n} from '../../actions/ens/getEnsAvatar.js'\nimport {\n  type GetEnsNameParameters,\n  type GetEnsNameReturnType,\n  getEnsName,\n} from '../../actions/ens/getEnsName.js'\nimport {\n  type GetEnsResolverParameters,\n  type GetEnsResolverReturnType,\n  getEnsResolver,\n} from '../../actions/ens/getEnsResolver.js'\nimport {\n  type GetEnsTextParameters,\n  type GetEnsTextReturnType,\n  getEnsText,\n} from '../../actions/ens/getEnsText.js'\nimport {\n  type CallParameters,\n  type CallReturnType,\n  call,\n} from '../../actions/public/call.js'\nimport {\n  type CreateBlockFilterReturnType,\n  createBlockFilter,\n} from '../../actions/public/createBlockFilter.js'\nimport {\n  type CreateContractEventFilterParameters,\n  type CreateContractEventFilterReturnType,\n  createContractEventFilter,\n} from '../../actions/public/createContractEventFilter.js'\nimport {\n  type CreateEventFilterParameters,\n  type CreateEventFilterReturnType,\n  createEventFilter,\n} from '../../actions/public/createEventFilter.js'\nimport {\n  type CreatePendingTransactionFilterReturnType,\n  createPendingTransactionFilter,\n} from '../../actions/public/createPendingTransactionFilter.js'\nimport {\n  type EstimateContractGasParameters,\n  type EstimateContractGasReturnType,\n  estimateContractGas,\n} from '../../actions/public/estimateContractGas.js'\nimport {\n  type EstimateFeesPerGasParameters,\n  type EstimateFeesPerGasReturnType,\n  estimateFeesPerGas,\n} from '../../actions/public/estimateFeesPerGas.js'\nimport {\n  type EstimateGasParameters,\n  type EstimateGasReturnType,\n  estimateGas,\n} from '../../actions/public/estimateGas.js'\nimport {\n  type EstimateMaxPriorityFeePerGasParameters,\n  type EstimateMaxPriorityFeePerGasReturnType,\n  estimateMaxPriorityFeePerGas,\n} from '../../actions/public/estimateMaxPriorityFeePerGas.js'\nimport {\n  type GetBalanceParameters,\n  type GetBalanceReturnType,\n  getBalance,\n} from '../../actions/public/getBalance.js'\nimport {\n  type GetBlockParameters,\n  type GetBlockReturnType,\n  getBlock,\n} from '../../actions/public/getBlock.js'\nimport {\n  type GetBlockNumberParameters,\n  type GetBlockNumberReturnType,\n  getBlockNumber,\n} from '../../actions/public/getBlockNumber.js'\nimport {\n  type GetBlockTransactionCountParameters,\n  type GetBlockTransactionCountReturnType,\n  getBlockTransactionCount,\n} from '../../actions/public/getBlockTransactionCount.js'\nimport {\n  type GetBytecodeParameters,\n  type GetBytecodeReturnType,\n  getBytecode,\n} from '../../actions/public/getBytecode.js'\nimport {\n  type GetChainIdReturnType,\n  getChainId,\n} from '../../actions/public/getChainId.js'\nimport {\n  type GetContractEventsParameters,\n  type GetContractEventsReturnType,\n  getContractEvents,\n} from '../../actions/public/getContractEvents.js'\nimport {\n  type GetFeeHistoryParameters,\n  type GetFeeHistoryReturnType,\n  getFeeHistory,\n} from '../../actions/public/getFeeHistory.js'\nimport {\n  type GetFilterChangesParameters,\n  type GetFilterChangesReturnType,\n  getFilterChanges,\n} from '../../actions/public/getFilterChanges.js'\nimport {\n  type GetFilterLogsParameters,\n  type GetFilterLogsReturnType,\n  getFilterLogs,\n} from '../../actions/public/getFilterLogs.js'\nimport {\n  type GetGasPriceReturnType,\n  getGasPrice,\n} from '../../actions/public/getGasPrice.js'\nimport {\n  type GetLogsParameters,\n  type GetLogsReturnType,\n  getLogs,\n} from '../../actions/public/getLogs.js'\nimport {\n  type GetProofParameters,\n  type GetProofReturnType,\n  getProof,\n} from '../../actions/public/getProof.js'\nimport {\n  type GetStorageAtParameters,\n  type GetStorageAtReturnType,\n  getStorageAt,\n} from '../../actions/public/getStorageAt.js'\nimport {\n  type GetTransactionParameters,\n  type GetTransactionReturnType,\n  getTransaction,\n} from '../../actions/public/getTransaction.js'\nimport {\n  type GetTransactionConfirmationsParameters,\n  type GetTransactionConfirmationsReturnType,\n  getTransactionConfirmations,\n} from '../../actions/public/getTransactionConfirmations.js'\nimport {\n  type GetTransactionCountParameters,\n  type GetTransactionCountReturnType,\n  getTransactionCount,\n} from '../../actions/public/getTransactionCount.js'\nimport {\n  type GetTransactionReceiptParameters,\n  type GetTransactionReceiptReturnType,\n  getTransactionReceipt,\n} from '../../actions/public/getTransactionReceipt.js'\nimport {\n  type MulticallParameters,\n  type MulticallReturnType,\n  multicall,\n} from '../../actions/public/multicall.js'\nimport {\n  type ReadContractParameters,\n  type ReadContractReturnType,\n  readContract,\n} from '../../actions/public/readContract.js'\nimport {\n  type SimulateContractParameters,\n  type SimulateContractReturnType,\n  simulateContract,\n} from '../../actions/public/simulateContract.js'\nimport {\n  type UninstallFilterParameters,\n  type UninstallFilterReturnType,\n  uninstallFilter,\n} from '../../actions/public/uninstallFilter.js'\nimport {\n  type VerifyMessageParameters,\n  type VerifyMessageReturnType,\n  verifyMessage,\n} from '../../actions/public/verifyMessage.js'\nimport {\n  type VerifyTypedDataParameters,\n  type VerifyTypedDataReturnType,\n  verifyTypedData,\n} from '../../actions/public/verifyTypedData.js'\nimport {\n  type WaitForTransactionReceiptParameters,\n  type WaitForTransactionReceiptReturnType,\n  waitForTransactionReceipt,\n} from '../../actions/public/waitForTransactionReceipt.js'\nimport {\n  type WatchBlockNumberParameters,\n  type WatchBlockNumberReturnType,\n  watchBlockNumber,\n} from '../../actions/public/watchBlockNumber.js'\nimport {\n  type WatchBlocksParameters,\n  type WatchBlocksReturnType,\n  watchBlocks,\n} from '../../actions/public/watchBlocks.js'\nimport {\n  type WatchContractEventParameters,\n  type WatchContractEventReturnType,\n  watchContractEvent,\n} from '../../actions/public/watchContractEvent.js'\nimport {\n  type WatchEventParameters,\n  type WatchEventReturnType,\n  watchEvent,\n} from '../../actions/public/watchEvent.js'\nimport {\n  type WatchPendingTransactionsParameters,\n  type WatchPendingTransactionsReturnType,\n  watchPendingTransactions,\n} from '../../actions/public/watchPendingTransactions.js'\nimport {\n  type PrepareTransactionRequestParameters,\n  type PrepareTransactionRequestReturnType,\n  prepareTransactionRequest,\n} from '../../actions/wallet/prepareTransactionRequest.js'\nimport {\n  type SendRawTransactionParameters,\n  type SendRawTransactionReturnType,\n  sendRawTransaction,\n} from '../../actions/wallet/sendRawTransaction.js'\nimport type { Account } from '../../types/account.js'\nimport type { BlockNumber, BlockTag } from '../../types/block.js'\nimport type { Chain } from '../../types/chain.js'\nimport type {\n  ContractFunctionConfig,\n  MaybeAbiEventName,\n  MaybeExtractEventArgsFromAbi,\n} from '../../types/contract.js'\nimport type { FeeValuesType } from '../../types/fee.js'\nimport type { FilterType } from '../../types/filter.js'\nimport type { Client } from '../createClient.js'\nimport type { Transport } from '../transports/createTransport.js'\n\nexport type PublicActions<\n  TTransport extends Transport = Transport,\n  TChain extends Chain | undefined = Chain | undefined,\n  TAccount extends Account | undefined = Account | undefined,\n> = {\n  /**\n   * Executes a new message call immediately without submitting a transaction to the network.\n   *\n   * - Docs: https://viem.sh/docs/actions/public/call.html\n   * - JSON-RPC Methods: [`eth_call`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_call)\n   *\n   * @param args - {@link CallParameters}\n   * @returns The call data. {@link CallReturnType}\n   *\n   * @example\n   * import { createPublicClient, http } from 'viem'\n   * import { mainnet } from 'viem/chains'\n   *\n   * const client = createPublicClient({\n   *   chain: mainnet,\n   *   transport: http(),\n   * })\n   * const data = await client.call({\n   *   account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266',\n   *   data: '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2',\n   *   to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',\n   * })\n   */\n  call: (parameters: CallParameters<TChain>) => Promise<CallReturnType>\n  /**\n   * Creates a Filter to listen for new block hashes that can be used with [`getFilterChanges`](https://viem.sh/docs/actions/public/getFilterChanges.html).\n   *\n   * - Docs: https://viem.sh/docs/actions/public/createBlockFilter.html\n   * - JSON-RPC Methods: [`eth_newBlockFilter`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_newBlockFilter)\n   *\n   * @returns Filter. {@link CreateBlockFilterReturnType}\n   *\n   * @example\n   * import { createPublicClient, createBlockFilter, http } from 'viem'\n   * import { mainnet } from 'viem/chains'\n   *\n   * const client = createPublicClient({\n   *   chain: mainnet,\n   *   transport: http(),\n   * })\n   * const filter = await createBlockFilter(client)\n   * // { id: \"0x345a6572337856574a76364e457a4366\", type: 'block' }\n   */\n  createBlockFilter: () => Promise<CreateBlockFilterReturnType>\n  /**\n   * Creates a Filter to retrieve event logs that can be used with [`getFilterChanges`](https://viem.sh/docs/actions/public/getFilterChanges.html) or [`getFilterLogs`](https://viem.sh/docs/actions/public/getFilterLogs.html).\n   *\n   * - Docs: https://viem.sh/docs/contract/createContractEventFilter.html\n   *\n   * @param args - {@link CreateContractEventFilterParameters}\n   * @returns [`Filter`](https://viem.sh/docs/glossary/types.html#filter). {@link CreateContractEventFilterReturnType}\n   *\n   * @example\n   * import { createPublicClient, http, parseAbi } from 'viem'\n   * import { mainnet } from 'viem/chains'\n   *\n   * const client = createPublicClient({\n   *   chain: mainnet,\n   *   transport: http(),\n   * })\n   * const filter = await client.createContractEventFilter({\n   *   abi: parseAbi(['event Transfer(address indexed, address indexed, uint256)']),\n   * })\n   */\n  createContractEventFilter: <\n    const TAbi extends Abi | readonly unknown[],\n    TEventName extends string | undefined,\n    TArgs extends MaybeExtractEventArgsFromAbi<TAbi, TEventName> | undefined,\n    TStrict extends boolean | undefined = undefined,\n    TFromBlock extends BlockNumber | BlockTag | undefined = undefined,\n    TToBlock extends BlockNumber | BlockTag | undefined = undefined,\n  >(\n    args: CreateContractEventFilterParameters<\n      TAbi,\n      TEventName,\n      TArgs,\n      TStrict,\n      TFromBlock,\n      TToBlock\n    >,\n  ) => Promise<\n    CreateContractEventFilterReturnType<\n      TAbi,\n      TEventName,\n      TArgs,\n      TStrict,\n      TFromBlock,\n      TToBlock\n    >\n  >\n  /**\n   * Creates a [`Filter`](https://viem.sh/docs/glossary/types.html#filter) to listen for new events that can be used with [`getFilterChanges`](https://viem.sh/docs/actions/public/getFilterChanges.html).\n   *\n   * - Docs: https://viem.sh/docs/actions/public/createEventFilter.html\n   * - JSON-RPC Methods: [`eth_newFilter`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_newfilter)\n   *\n   * @param args - {@link CreateEventFilterParameters}\n   * @returns [`Filter`](https://viem.sh/docs/glossary/types.html#filter). {@link CreateEventFilterReturnType}\n   *\n   * @example\n   * import { createPublicClient, http } from 'viem'\n   * import { mainnet } from 'viem/chains'\n   *\n   * const client = createPublicClient({\n   *   chain: mainnet,\n   *   transport: http(),\n   * })\n   * const filter = await client.createEventFilter({\n   *   address: '0xfba3912ca04dd458c843e2ee08967fc04f3579c2',\n   * })\n   */\n  createEventFilter: <\n    const TAbiEvent extends AbiEvent | undefined = undefined,\n    const TAbiEvents extends\n      | readonly AbiEvent[]\n      | readonly unknown[]\n      | undefined = TAbiEvent extends AbiEvent ? [TAbiEvent] : undefined,\n    TStrict extends boolean | undefined = undefined,\n    TFromBlock extends BlockNumber | BlockTag | undefined = undefined,\n    TToBlock extends BlockNumber | BlockTag | undefined = undefined,\n    _EventName extends string | undefined = MaybeAbiEventName<TAbiEvent>,\n    _Args extends\n      | MaybeExtractEventArgsFromAbi<TAbiEvents, _EventName>\n      | undefined = undefined,\n  >(\n    args?: CreateEventFilterParameters<\n      TAbiEvent,\n      TAbiEvents,\n      TStrict,\n      TFromBlock,\n      TToBlock,\n      _EventName,\n      _Args\n    >,\n  ) => Promise<\n    CreateEventFilterReturnType<\n      TAbiEvent,\n      TAbiEvents,\n      TStrict,\n      TFromBlock,\n      TToBlock,\n      _EventName,\n      _Args\n    >\n  >\n  /**\n   * Creates a Filter to listen for new pending transaction hashes that can be used with [`getFilterChanges`](https://viem.sh/docs/actions/public/getFilterChanges.html).\n   *\n   * - Docs: https://viem.sh/docs/actions/public/createPendingTransactionFilter.html\n   * - JSON-RPC Methods: [`eth_newPendingTransactionFilter`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_newpendingtransactionfilter)\n   *\n   * @returns [`Filter`](https://viem.sh/docs/glossary/types.html#filter). {@link CreateBlockFilterReturnType}\n   *\n   * @example\n   * import { createPublicClient, http } from 'viem'\n   * import { mainnet } from 'viem/chains'\n   *\n   * const client = createPublicClient({\n   *   chain: mainnet,\n   *   transport: http(),\n   * })\n   * const filter = await client.createPendingTransactionFilter()\n   * // { id: \"0x345a6572337856574a76364e457a4366\", type: 'transaction' }\n   */\n  createPendingTransactionFilter: () => Promise<CreatePendingTransactionFilterReturnType>\n  /**\n   * Estimates the gas required to successfully execute a contract write function call.\n   *\n   * - Docs: https://viem.sh/docs/contract/estimateContractGas.html\n   *\n   * @remarks\n   * Internally, uses a [Public Client](https://viem.sh/docs/clients/public.html) to call the [`estimateGas` action](https://viem.sh/docs/actions/public/estimateGas.html) with [ABI-encoded `data`](https://viem.sh/docs/contract/encodeFunctionData.html).\n   *\n   * @param args - {@link EstimateContractGasParameters}\n   * @returns The gas estimate (in wei). {@link EstimateContractGasReturnType}\n   *\n   * @example\n   * import { createPublicClient, http, parseAbi } from 'viem'\n   * import { mainnet } from 'viem/chains'\n   *\n   * const client = createPublicClient({\n   *   chain: mainnet,\n   *   transport: http(),\n   * })\n   * const gas = await client.estimateContractGas({\n   *   address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\n   *   abi: parseAbi(['function mint() public']),\n   *   functionName: 'mint',\n   *   account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266',\n   * })\n   */\n  estimateContractGas: <\n    TChain extends Chain | undefined,\n    const TAbi extends Abi | readonly unknown[],\n    TFunctionName extends string,\n  >(\n    args: EstimateContractGasParameters<TAbi, TFunctionName, TChain, TAccount>,\n  ) => Promise<EstimateContractGasReturnType>\n  /**\n   * Estimates the gas necessary to complete a transaction without submitting it to the network.\n   *\n   * - Docs: https://viem.sh/docs/actions/public/estimateGas.html\n   * - JSON-RPC Methods: [`eth_estimateGas`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_estimategas)\n   *\n   * @param args - {@link EstimateGasParameters}\n   * @returns The gas estimate (in wei). {@link EstimateGasReturnType}\n   *\n   * @example\n   * import { createPublicClient, http, parseEther } from 'viem'\n   * import { mainnet } from 'viem/chains'\n   *\n   * const client = createPublicClient({\n   *   chain: mainnet,\n   *   transport: http(),\n   * })\n   * const gasEstimate = await client.estimateGas({\n   *   account: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',\n   *   to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',\n   *   value: parseEther('1'),\n   * })\n   */\n  estimateGas: (\n    args: EstimateGasParameters<TChain, TAccount>,\n  ) => Promise<EstimateGasReturnType>\n  /**\n   * Returns the balance of an address in wei.\n   *\n   * - Docs: https://viem.sh/docs/actions/public/getBalance.html\n   * - JSON-RPC Methods: [`eth_getBalance`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getbalance)\n   *\n   * @remarks\n   * You can convert the balance to ether units with [`formatEther`](https://viem.sh/docs/utilities/formatEther.html).\n   *\n   * ```ts\n   * const balance = await getBalance(client, {\n   *   address: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',\n   *   blockTag: 'safe'\n   * })\n   * const balanceAsEther = formatEther(balance)\n   * // \"6.942\"\n   * ```\n   *\n   * @param args - {@link GetBalanceParameters}\n   * @returns The balance of the address in wei. {@link GetBalanceReturnType}\n   *\n   * @example\n   * import { createPublicClient, http } from 'viem'\n   * import { mainnet } from 'viem/chains'\n   *\n   * const client = createPublicClient({\n   *   chain: mainnet,\n   *   transport: http(),\n   * })\n   * const balance = await client.getBalance({\n   *   address: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',\n   * })\n   * // 10000000000000000000000n (wei)\n   */\n  getBalance: (args: GetBalanceParameters) => Promise<GetBalanceReturnType>\n  /**\n   * Returns information about a block at a block number, hash, or tag.\n   *\n   * - Docs: https://viem.sh/docs/actions/public/getBlock.html\n   * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/blocks/fetching-blocks\n   * - JSON-RPC Methods:\n   *   - Calls [`eth_getBlockByNumber`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getblockbynumber) for `blockNumber` & `blockTag`.\n   *   - Calls [`eth_getBlockByHash`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getblockbyhash) for `blockHash`.\n   *\n   * @param args - {@link GetBlockParameters}\n   * @returns Information about the block. {@link GetBlockReturnType}\n   *\n   * @example\n   * import { createPublicClient, http } from 'viem'\n   * import { mainnet } from 'viem/chains'\n   *\n   * const client = createPublicClient({\n   *   chain: mainnet,\n   *   transport: http(),\n   * })\n   * const block = await client.getBlock()\n   */\n  getBlock: <\n    TIncludeTransactions extends boolean = false,\n    TBlockTag extends BlockTag = 'latest',\n  >(\n    args?: GetBlockParameters<TIncludeTransactions, TBlockTag>,\n  ) => Promise<GetBlockReturnType<TChain, TIncludeTransactions, TBlockTag>>\n  /**\n   * Returns the number of the most recent block seen.\n   *\n   * - Docs: https://viem.sh/docs/actions/public/getBlockNumber.html\n   * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/blocks/fetching-blocks\n   * - JSON-RPC Methods: [`eth_blockNumber`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_blocknumber)\n   *\n   * @param args - {@link GetBlockNumberParameters}\n   * @returns The number of the block. {@link GetBlockNumberReturnType}\n   *\n   * @example\n   * import { createPublicClient, http } from 'viem'\n   * import { mainnet } from 'viem/chains'\n   *\n   * const client = createPublicClient({\n   *   chain: mainnet,\n   *   transport: http(),\n   * })\n   * const blockNumber = await client.getBlockNumber()\n   * // 69420n\n   */\n  getBlockNumber: (\n    args?: GetBlockNumberParameters,\n  ) => Promise<GetBlockNumberReturnType>\n  /**\n   * Returns the number of Transactions at a block number, hash, or tag.\n   *\n   * - Docs: https://viem.sh/docs/actions/public/getBlockTransactionCount.html\n   * - JSON-RPC Methods:\n   *   - Calls [`eth_getBlockTransactionCountByNumber`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getblocktransactioncountbynumber) for `blockNumber` & `blockTag`.\n   *   - Calls [`eth_getBlockTransactionCountByHash`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getblocktransactioncountbyhash) for `blockHash`.\n   *\n   * @param args - {@link GetBlockTransactionCountParameters}\n   * @returns The block transaction count. {@link GetBlockTransactionCountReturnType}\n   *\n   * @example\n   * import { createPublicClient, http } from 'viem'\n   * import { mainnet } from 'viem/chains'\n   *\n   * const client = createPublicClient({\n   *   chain: mainnet,\n   *   transport: http(),\n   * })\n   * const count = await client.getBlockTransactionCount()\n   */\n  getBlockTransactionCount: (\n    args?: GetBlockTransactionCountParameters,\n  ) => Promise<GetBlockTransactionCountReturnType>\n  /**\n   * Retrieves the bytecode at an address.\n   *\n   * - Docs: https://viem.sh/docs/contract/getBytecode.html\n   * - JSON-RPC Methods: [`eth_getCode`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getcode)\n   *\n   * @param args - {@link GetBytecodeParameters}\n   * @returns The contract's bytecode. {@link GetBytecodeReturnType}\n   *\n   * @example\n   * import { createPublicClient, http } from 'viem'\n   * import { mainnet } from 'viem/chains'\n   *\n   * const client = createPublicClient({\n   *   chain: mainnet,\n   *   transport: http(),\n   * })\n   * const code = await client.getBytecode({\n   *   address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\n   * })\n   */\n  getBytecode: (args: GetBytecodeParameters) => Promise<GetBytecodeReturnType>\n  /**\n   * Returns the chain ID associated with the current network.\n   *\n   * - Docs: https://viem.sh/docs/actions/public/getChainId.html\n   * - JSON-RPC Methods: [`eth_chainId`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_chainid)\n   *\n   * @returns The current chain ID. {@link GetChainIdReturnType}\n   *\n   * @example\n   * import { createPublicClient, http } from 'viem'\n   * import { mainnet } from 'viem/chains'\n   *\n   * const client = createPublicClient({\n   *   chain: mainnet,\n   *   transport: http(),\n   * })\n   * const chainId = await client.getChainId()\n   * // 1\n   */\n  getChainId: () => Promise<GetChainIdReturnType>\n  /**\n   * Returns a list of event logs emitted by a contract.\n   *\n   * - Docs: https://viem.sh/docs/actions/public/getContractEvents.html\n   * - JSON-RPC Methods: [`eth_getLogs`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getlogs)\n   *\n   * @param client - Client to use\n   * @param parameters - {@link GetContractEventsParameters}\n   * @returns A list of event logs. {@link GetContractEventsReturnType}\n   *\n   * @example\n   * import { createPublicClient, http } from 'viem'\n   * import { mainnet } from 'viem/chains'\n   * import { wagmiAbi } from './abi'\n   *\n   * const client = createPublicClient({\n   *   chain: mainnet,\n   *   transport: http(),\n   * })\n   * const logs = await client.getContractEvents(client, {\n   *  address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\n   *  abi: wagmiAbi,\n   *  eventName: 'Transfer'\n   * })\n   */\n  getContractEvents: <\n    const TAbi extends Abi | readonly unknown[],\n    TEventName extends string | undefined = undefined,\n    TStrict extends boolean | undefined = undefined,\n    TFromBlock extends BlockNumber | BlockTag | undefined = undefined,\n    TToBlock extends BlockNumber | BlockTag | undefined = undefined,\n  >(\n    args: GetContractEventsParameters<\n      TAbi,\n      TEventName,\n      TStrict,\n      TFromBlock,\n      TToBlock\n    >,\n  ) => Promise<\n    GetContractEventsReturnType<TAbi, TEventName, TStrict, TFromBlock, TToBlock>\n  >\n  /**\n   * Gets address for ENS name.\n   *\n   * - Docs: https://viem.sh/docs/ens/actions/getEnsAddress.html\n   * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/ens\n   *\n   * @remarks\n   * Calls `resolve(bytes, bytes)` on ENS Universal Resolver Contract.\n   *\n   * Since ENS names prohibit certain forbidden characters (e.g. underscore) and have other validation rules, you likely want to [normalize ENS names](https://docs.ens.domains/contract-api-reference/name-processing#normalising-names) with [UTS-46 normalization](https://unicode.org/reports/tr46) before passing them to `getEnsAddress`. You can use the built-in [`normalize`](https://viem.sh/docs/ens/utilities/normalize.html) function for this.\n   *\n   * @param args - {@link GetEnsAddressParameters}\n   * @returns Address for ENS name or `null` if not found. {@link GetEnsAddressReturnType}\n   *\n   * @example\n   * import { createPublicClient, http } from 'viem'\n   * import { mainnet } from 'viem/chains'\n   * import { normalize } from 'viem/ens'\n   *\n   * const client = createPublicClient({\n   *   chain: mainnet,\n   *   transport: http(),\n   * })\n   * const ensAddress = await client.getEnsAddress({\n   *   name: normalize('wevm.eth'),\n   * })\n   * // '0xd2135CfB216b74109775236E36d4b433F1DF507B'\n   */\n  getEnsAddress: (\n    args: GetEnsAddressParameters,\n  ) => Promise<GetEnsAddressReturnType>\n  /**\n   * Gets the avatar of an ENS name.\n   *\n   * - Docs: https://viem.sh/docs/ens/actions/getEnsAvatar.html\n   * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/ens\n   *\n   * @remarks\n   * Calls [`getEnsText`](https://viem.sh/docs/ens/actions/getEnsText.html) with `key` set to `'avatar'`.\n   *\n   * Since ENS names prohibit certain forbidden characters (e.g. underscore) and have other validation rules, you likely want to [normalize ENS names](https://docs.ens.domains/contract-api-reference/name-processing#normalising-names) with [UTS-46 normalization](https://unicode.org/reports/tr46) before passing them to `getEnsAddress`. You can use the built-in [`normalize`](https://viem.sh/docs/ens/utilities/normalize.html) function for this.\n   *\n   * @param args - {@link GetEnsAvatarParameters}\n   * @returns Avatar URI or `null` if not found. {@link GetEnsAvatarReturnType}\n   *\n   * @example\n   * import { createPublicClient, http } from 'viem'\n   * import { mainnet } from 'viem/chains'\n   * import { normalize } from 'viem/ens'\n   *\n   * const client = createPublicClient({\n   *   chain: mainnet,\n   *   transport: http(),\n   * })\n   * const ensAvatar = await client.getEnsAvatar({\n   *   name: normalize('wevm.eth'),\n   * })\n   * // 'https://ipfs.io/ipfs/Qma8mnp6xV3J2cRNf3mTth5C8nV11CAnceVinc3y8jSbio'\n   */\n  getEnsAvatar: (\n    args: GetEnsAvatarParameters,\n  ) => Promise<GetEnsAvatarReturnType>\n  /**\n   * Gets primary name for specified address.\n   *\n   * - Docs: https://viem.sh/docs/ens/actions/getEnsName.html\n   * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/ens\n   *\n   * @remarks\n   * Calls `reverse(bytes)` on ENS Universal Resolver Contract to \"reverse resolve\" the address to the primary ENS name.\n   *\n   * @param args - {@link GetEnsNameParameters}\n   * @returns Name or `null` if not found. {@link GetEnsNameReturnType}\n   *\n   * @example\n   * import { createPublicClient, http } from 'viem'\n   * import { mainnet } from 'viem/chains'\n   *\n   * const client = createPublicClient({\n   *   chain: mainnet,\n   *   transport: http(),\n   * })\n   * const ensName = await client.getEnsName({\n   *   address: '0xd2135CfB216b74109775236E36d4b433F1DF507B',\n   * })\n   * // 'wevm.eth'\n   */\n  getEnsName: (args: GetEnsNameParameters) => Promise<GetEnsNameReturnType>\n  /**\n   * Gets resolver for ENS name.\n   *\n   * - Docs: https://viem.sh/docs/ens/actions/getEnsResolver.html\n   * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/ens\n   *\n   * @remarks\n   * Calls `findResolver(bytes)` on ENS Universal Resolver Contract to retrieve the resolver of an ENS name.\n   *\n   * Since ENS names prohibit certain forbidden characters (e.g. underscore) and have other validation rules, you likely want to [normalize ENS names](https://docs.ens.domains/contract-api-reference/name-processing#normalising-names) with [UTS-46 normalization](https://unicode.org/reports/tr46) before passing them to `getEnsAddress`. You can use the built-in [`normalize`](https://viem.sh/docs/ens/utilities/normalize.html) function for this.\n   *\n   * @param args - {@link GetEnsResolverParameters}\n   * @returns Address for ENS resolver. {@link GetEnsResolverReturnType}\n   *\n   * @example\n   * import { createPublicClient, http } from 'viem'\n   * import { mainnet } from 'viem/chains'\n   * import { normalize } from 'viem/ens'\n   *\n   * const client = createPublicClient({\n   *   chain: mainnet,\n   *   transport: http(),\n   * })\n   * const resolverAddress = await client.getEnsResolver({\n   *   name: normalize('wevm.eth'),\n   * })\n   * // '0x4976fb03C32e5B8cfe2b6cCB31c09Ba78EBaBa41'\n   */\n  getEnsResolver: (\n    args: GetEnsResolverParameters,\n  ) => Promise<GetEnsResolverReturnType>\n  /**\n   * Gets a text record for specified ENS name.\n   *\n   * - Docs: https://viem.sh/docs/ens/actions/getEnsResolver.html\n   * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/ens\n   *\n   * @remarks\n   * Calls `resolve(bytes, bytes)` on ENS Universal Resolver Contract.\n   *\n   * Since ENS names prohibit certain forbidden characters (e.g. underscore) and have other validation rules, you likely want to [normalize ENS names](https://docs.ens.domains/contract-api-reference/name-processing#normalising-names) with [UTS-46 normalization](https://unicode.org/reports/tr46) before passing them to `getEnsAddress`. You can use the built-in [`normalize`](https://viem.sh/docs/ens/utilities/normalize.html) function for this.\n   *\n   * @param args - {@link GetEnsTextParameters}\n   * @returns Address for ENS resolver. {@link GetEnsTextReturnType}\n   *\n   * @example\n   * import { createPublicClient, http } from 'viem'\n   * import { mainnet } from 'viem/chains'\n   * import { normalize } from 'viem/ens'\n   *\n   * const client = createPublicClient({\n   *   chain: mainnet,\n   *   transport: http(),\n   * })\n   * const twitterRecord = await client.getEnsText({\n   *   name: normalize('wevm.eth'),\n   *   key: 'com.twitter',\n   * })\n   * // 'wagmi_sh'\n   */\n  getEnsText: (args: GetEnsTextParameters) => Promise<GetEnsTextReturnType>\n  /**\n   * Returns a collection of historical gas information.\n   *\n   * - Docs: https://viem.sh/docs/actions/public/getFeeHistory.html\n   * - JSON-RPC Methods: [`eth_feeHistory`](https://docs.alchemy.com/reference/eth-feehistory)\n   *\n   * @param args - {@link GetFeeHistoryParameters}\n   * @returns The gas estimate (in wei). {@link GetFeeHistoryReturnType}\n   *\n   * @example\n   * import { createPublicClient, http } from 'viem'\n   * import { mainnet } from 'viem/chains'\n   *\n   * const client = createPublicClient({\n   *   chain: mainnet,\n   *   transport: http(),\n   * })\n   * const feeHistory = await client.getFeeHistory({\n   *   blockCount: 4,\n   *   rewardPercentiles: [25, 75],\n   * })\n   */\n  getFeeHistory: (\n    args: GetFeeHistoryParameters,\n  ) => Promise<GetFeeHistoryReturnType>\n  /**\n   * Returns an estimate for the fees per gas for a transaction to be included\n   * in the next block.\n   *\n   * - Docs: https://viem.sh/docs/actions/public/estimateFeesPerGas.html\n   *\n   * @param client - Client to use\n   * @param parameters - {@link EstimateFeesPerGasParameters}\n   * @returns An estimate (in wei) for the fees per gas. {@link EstimateFeesPerGasReturnType}\n   *\n   * @example\n   * import { createPublicClient, http } from 'viem'\n   * import { mainnet } from 'viem/chains'\n   *\n   * const client = createPublicClient({\n   *   chain: mainnet,\n   *   transport: http(),\n   * })\n   * const maxPriorityFeePerGas = await client.estimateFeesPerGas()\n   * // { maxFeePerGas: ..., maxPriorityFeePerGas: ... }\n   */\n  estimateFeesPerGas: <\n    TChainOverride extends Chain | undefined = undefined,\n    TType extends FeeValuesType = 'eip1559',\n  >(\n    args?: EstimateFeesPerGasParameters<TChain, TChainOverride, TType>,\n  ) => Promise<EstimateFeesPerGasReturnType>\n  /**\n   * Returns a list of logs or hashes based on a [Filter](/docs/glossary/terms#filter) since the last time it was called.\n   *\n   * - Docs: https://viem.sh/docs/actions/public/getFilterChanges.html\n   * - JSON-RPC Methods: [`eth_getFilterChanges`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getfilterchanges)\n   *\n   * @remarks\n   * A Filter can be created from the following actions:\n   *\n   * - [`createBlockFilter`](https://viem.sh/docs/actions/public/createBlockFilter.html)\n   * - [`createContractEventFilter`](https://viem.sh/docs/contract/createContractEventFilter.html)\n   * - [`createEventFilter`](https://viem.sh/docs/actions/public/createEventFilter.html)\n   * - [`createPendingTransactionFilter`](https://viem.sh/docs/actions/public/createPendingTransactionFilter.html)\n   *\n   * Depending on the type of filter, the return value will be different:\n   *\n   * - If the filter was created with `createContractEventFilter` or `createEventFilter`, it returns a list of logs.\n   * - If the filter was created with `createPendingTransactionFilter`, it returns a list of transaction hashes.\n   * - If the filter was created with `createBlockFilter`, it returns a list of block hashes.\n   *\n   * @param args - {@link GetFilterChangesParameters}\n   * @returns Logs or hashes. {@link GetFilterChangesReturnType}\n   *\n   * @example\n   * // Blocks\n   * import { createPublicClient, http } from 'viem'\n   * import { mainnet } from 'viem/chains'\n   *\n   * const client = createPublicClient({\n   *   chain: mainnet,\n   *   transport: http(),\n   * })\n   * const filter = await client.createBlockFilter()\n   * const hashes = await client.getFilterChanges({ filter })\n   *\n   * @example\n   * // Contract Events\n   * import { createPublicClient, http, parseAbi } from 'viem'\n   * import { mainnet } from 'viem/chains'\n   *\n   * const client = createPublicClient({\n   *   chain: mainnet,\n   *   transport: http(),\n   * })\n   * const filter = await client.createContractEventFilter({\n   *   address: '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48',\n   *   abi: parseAbi(['event Transfer(address indexed, address indexed, uint256)']),\n   *   eventName: 'Transfer',\n   * })\n   * const logs = await client.getFilterChanges({ filter })\n   *\n   * @example\n   * // Raw Events\n   * import { createPublicClient, http, parseAbiItem } from 'viem'\n   * import { mainnet } from 'viem/chains'\n   *\n   * const client = createPublicClient({\n   *   chain: mainnet,\n   *   transport: http(),\n   * })\n   * const filter = await client.createEventFilter({\n   *   address: '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48',\n   *   event: parseAbiItem('event Transfer(address indexed, address indexed, uint256)'),\n   * })\n   * const logs = await client.getFilterChanges({ filter })\n   *\n   * @example\n   * // Transactions\n   * import { createPublicClient, http } from 'viem'\n   * import { mainnet } from 'viem/chains'\n   *\n   * const client = createPublicClient({\n   *   chain: mainnet,\n   *   transport: http(),\n   * })\n   * const filter = await client.createPendingTransactionFilter()\n   * const hashes = await client.getFilterChanges({ filter })\n   */\n  getFilterChanges: <\n    TFilterType extends FilterType,\n    const TAbi extends Abi | readonly unknown[] | undefined,\n    TEventName extends string | undefined,\n    TStrict extends boolean | undefined = undefined,\n    TFromBlock extends BlockNumber | BlockTag | undefined = undefined,\n    TToBlock extends BlockNumber | BlockTag | undefined = undefined,\n  >(\n    args: GetFilterChangesParameters<\n      TFilterType,\n      TAbi,\n      TEventName,\n      TStrict,\n      TFromBlock,\n      TToBlock\n    >,\n  ) => Promise<\n    GetFilterChangesReturnType<\n      TFilterType,\n      TAbi,\n      TEventName,\n      TStrict,\n      TFromBlock,\n      TToBlock\n    >\n  >\n  /**\n   * Returns a list of event logs since the filter was created.\n   *\n   * - Docs: https://viem.sh/docs/actions/public/getFilterLogs.html\n   * - JSON-RPC Methods: [`eth_getFilterLogs`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getfilterlogs)\n   *\n   * @remarks\n   * `getFilterLogs` is only compatible with **event filters**.\n   *\n   * @param args - {@link GetFilterLogsParameters}\n   * @returns A list of event logs. {@link GetFilterLogsReturnType}\n   *\n   * @example\n   * import { createPublicClient, http, parseAbiItem } from 'viem'\n   * import { mainnet } from 'viem/chains'\n   *\n   * const client = createPublicClient({\n   *   chain: mainnet,\n   *   transport: http(),\n   * })\n   * const filter = await client.createEventFilter({\n   *   address: '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48',\n   *   event: parseAbiItem('event Transfer(address indexed, address indexed, uint256)'),\n   * })\n   * const logs = await client.getFilterLogs({ filter })\n   */\n  getFilterLogs: <\n    const TAbi extends Abi | readonly unknown[] | undefined,\n    TEventName extends string | undefined,\n    TStrict extends boolean | undefined = undefined,\n    TFromBlock extends BlockNumber | BlockTag | undefined = undefined,\n    TToBlock extends BlockNumber | BlockTag | undefined = undefined,\n  >(\n    args: GetFilterLogsParameters<\n      TAbi,\n      TEventName,\n      TStrict,\n      TFromBlock,\n      TToBlock\n    >,\n  ) => Promise<\n    GetFilterLogsReturnType<TAbi, TEventName, TStrict, TFromBlock, TToBlock>\n  >\n  /**\n   * Returns the current price of gas (in wei).\n   *\n   * - Docs: https://viem.sh/docs/actions/public/getGasPrice.html\n   * - JSON-RPC Methods: [`eth_gasPrice`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_gasprice)\n   *\n   * @returns The gas price (in wei). {@link GetGasPriceReturnType}\n   *\n   * @example\n   * import { createPublicClient, http } from 'viem'\n   * import { mainnet } from 'viem/chains'\n   *\n   * const client = createPublicClient({\n   *   chain: mainnet,\n   *   transport: http(),\n   * })\n   * const gasPrice = await client.getGasPrice()\n   */\n  getGasPrice: () => Promise<GetGasPriceReturnType>\n  /**\n   * Returns a list of event logs matching the provided parameters.\n   *\n   * - Docs: https://viem.sh/docs/actions/public/getLogs.html\n   * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/filters-and-logs/event-logs\n   * - JSON-RPC Methods: [`eth_getLogs`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getlogs)\n   *\n   * @param args - {@link GetLogsParameters}\n   * @returns A list of event logs. {@link GetLogsReturnType}\n   *\n   * @example\n   * import { createPublicClient, http, parseAbiItem } from 'viem'\n   * import { mainnet } from 'viem/chains'\n   *\n   * const client = createPublicClient({\n   *   chain: mainnet,\n   *   transport: http(),\n   * })\n   * const logs = await client.getLogs()\n   */\n  getLogs: <\n    const TAbiEvent extends AbiEvent | undefined = undefined,\n    const TAbiEvents extends\n      | readonly AbiEvent[]\n      | readonly unknown[]\n      | undefined = TAbiEvent extends AbiEvent ? [TAbiEvent] : undefined,\n    TStrict extends boolean | undefined = undefined,\n    TFromBlock extends BlockNumber | BlockTag | undefined = undefined,\n    TToBlock extends BlockNumber | BlockTag | undefined = undefined,\n  >(\n    args?: GetLogsParameters<\n      TAbiEvent,\n      TAbiEvents,\n      TStrict,\n      TFromBlock,\n      TToBlock\n    >,\n  ) => Promise<\n    GetLogsReturnType<TAbiEvent, TAbiEvents, TStrict, TFromBlock, TToBlock>\n  >\n  /**\n   * Returns the account and storage values of the specified account including the Merkle-proof.\n   *\n   * - Docs: https://viem.sh/docs/actions/public/getProof.html\n   * - JSON-RPC Methods:\n   *   - Calls [`eth_getProof`](https://eips.ethereum.org/EIPS/eip-1186)\n   *\n   * @param client - Client to use\n   * @param parameters - {@link GetProofParameters}\n   * @returns Proof data. {@link GetProofReturnType}\n   *\n   * @example\n   * import { createPublicClient, http } from 'viem'\n   * import { mainnet } from 'viem/chains'\n   *\n   * const client = createPublicClient({\n   *   chain: mainnet,\n   *   transport: http(),\n   * })\n   * const block = await client.getProof({\n   *  address: '0x...',\n   *  storageKeys: ['0x...'],\n   * })\n   */\n  getProof: (args: GetProofParameters) => Promise<GetProofReturnType>\n  /**\n   * Returns an estimate for the max priority fee per gas (in wei) for a transaction\n   * to be included in the next block.\n   *\n   * - Docs: https://viem.sh/docs/actions/public/estimateMaxPriorityFeePerGas.html\n   *\n   * @param client - Client to use\n   * @returns An estimate (in wei) for the max priority fee per gas. {@link EstimateMaxPriorityFeePerGasReturnType}\n   *\n   * @example\n   * import { createPublicClient, http } from 'viem'\n   * import { mainnet } from 'viem/chains'\n   *\n   * const client = createPublicClient({\n   *   chain: mainnet,\n   *   transport: http(),\n   * })\n   * const maxPriorityFeePerGas = await client.estimateMaxPriorityFeePerGas()\n   * // 10000000n\n   */\n  estimateMaxPriorityFeePerGas: <\n    TChainOverride extends Chain | undefined = undefined,\n  >(\n    args?: EstimateMaxPriorityFeePerGasParameters<TChain, TChainOverride>,\n  ) => Promise<EstimateMaxPriorityFeePerGasReturnType>\n  /**\n   * Returns the value from a storage slot at a given address.\n   *\n   * - Docs: https://viem.sh/docs/contract/getStorageAt.html\n   * - JSON-RPC Methods: [`eth_getStorageAt`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getstorageat)\n   *\n   * @param args - {@link GetStorageAtParameters}\n   * @returns The value of the storage slot. {@link GetStorageAtReturnType}\n   *\n   * @example\n   * import { createPublicClient, http } from 'viem'\n   * import { mainnet } from 'viem/chains'\n   * import { getStorageAt } from 'viem/contract'\n   *\n   * const client = createPublicClient({\n   *   chain: mainnet,\n   *   transport: http(),\n   * })\n   * const code = await client.getStorageAt({\n   *   address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\n   *   slot: toHex(0),\n   * })\n   */\n  getStorageAt: (\n    args: GetStorageAtParameters,\n  ) => Promise<GetStorageAtReturnType>\n  /**\n   * Returns information about a [Transaction](https://viem.sh/docs/glossary/terms.html#transaction) given a hash or block identifier.\n   *\n   * - Docs: https://viem.sh/docs/actions/public/getTransaction.html\n   * - Example: https://stackblitz.com/github/wevm/viem/tree/main/examples/transactions/fetching-transactions\n   * - JSON-RPC Methods: [`eth_getTransactionByHash`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getTransactionByHash)\n   *\n   * @param args - {@link GetTransactionParameters}\n   * @returns The transaction information. {@link GetTransactionReturnType}\n   *\n   * @example\n   * import { createPublicClient, http } from 'viem'\n   * import { mainnet } from 'viem/chains'\n   *\n   * const client = createPublicClient({\n   *   chain: mainnet,\n   *   transport: http(),\n   * })\n   * const transaction = await client.getTransaction({\n   *   hash: '0x4ca7ee652d57678f26e887c149ab0735f41de37bcad58c9f6d3ed5824f15b74d',\n   * })\n   */\n  getTransaction: <TBlockTag extends BlockTag = 'latest'>(\n    args: GetTransactionParameters<TBlockTag>,\n  ) => Promise<GetTransactionReturnType<TChain, TBlockTag>>\n  /**\n   * Returns the number of blocks passed (confirmations) since the transaction was processed on a block.\n   *\n   * - Docs: https://viem.sh/docs/actions/public/getTransactionConfirmations.html\n   * - Example: https://stackblitz.com/github/wevm/viem/tree/main/examples/transactions/fetching-transactions\n   * - JSON-RPC Methods: [`eth_getTransactionConfirmations`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getTransactionConfirmations)\n   *\n   * @param args - {@link GetTransactionConfirmationsParameters}\n   * @returns The number of blocks passed since the transaction was processed. If confirmations is 0, then the Transaction has not been confirmed & processed yet. {@link GetTransactionConfirmationsReturnType}\n   *\n   * @example\n   * import { createPublicClient, http } from 'viem'\n   * import { mainnet } from 'viem/chains'\n   *\n   * const client = createPublicClient({\n   *   chain: mainnet,\n   *   transport: http(),\n   * })\n   * const confirmations = await client.getTransactionConfirmations({\n   *   hash: '0x4ca7ee652d57678f26e887c149ab0735f41de37bcad58c9f6d3ed5824f15b74d',\n   * })\n   */\n  getTransactionConfirmations: (\n    args: GetTransactionConfirmationsParameters<TChain>,\n  ) => Promise<GetTransactionConfirmationsReturnType>\n  /**\n   * Returns the number of [Transactions](https://viem.sh/docs/glossary/terms.html#transaction) an Account has broadcast / sent.\n   *\n   * - Docs: https://viem.sh/docs/actions/public/getTransactionCount.html\n   * - JSON-RPC Methods: [`eth_getTransactionCount`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_gettransactioncount)\n   *\n   * @param args - {@link GetTransactionCountParameters}\n   * @returns The number of transactions an account has sent. {@link GetTransactionCountReturnType}\n   *\n   * @example\n   * import { createPublicClient, http } from 'viem'\n   * import { mainnet } from 'viem/chains'\n   *\n   * const client = createPublicClient({\n   *   chain: mainnet,\n   *   transport: http(),\n   * })\n   * const transactionCount = await client.getTransactionCount({\n   *   address: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',\n   * })\n   */\n  getTransactionCount: (\n    args: GetTransactionCountParameters,\n  ) => Promise<GetTransactionCountReturnType>\n  /**\n   * Returns the [Transaction Receipt](https://viem.sh/docs/glossary/terms.html#transaction-receipt) given a [Transaction](https://viem.sh/docs/glossary/terms.html#transaction) hash.\n   *\n   * - Docs: https://viem.sh/docs/actions/public/getTransactionReceipt.html\n   * - Example: https://stackblitz.com/github/wevm/viem/tree/main/examples/transactions/fetching-transactions\n   * - JSON-RPC Methods: [`eth_getTransactionReceipt`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getTransactionReceipt)\n   *\n   * @param args - {@link GetTransactionReceiptParameters}\n   * @returns The transaction receipt. {@link GetTransactionReceiptReturnType}\n   *\n   * @example\n   * import { createPublicClient, http } from 'viem'\n   * import { mainnet } from 'viem/chains'\n   *\n   * const client = createPublicClient({\n   *   chain: mainnet,\n   *   transport: http(),\n   * })\n   * const transactionReceipt = await client.getTransactionReceipt({\n   *   hash: '0x4ca7ee652d57678f26e887c149ab0735f41de37bcad58c9f6d3ed5824f15b74d',\n   * })\n   */\n  getTransactionReceipt: (\n    args: GetTransactionReceiptParameters,\n  ) => Promise<GetTransactionReceiptReturnType<TChain>>\n  /**\n   * Similar to [`readContract`](https://viem.sh/docs/contract/readContract.html), but batches up multiple functions on a contract in a single RPC call via the [`multicall3` contract](https://github.com/mds1/multicall).\n   *\n   * - Docs: https://viem.sh/docs/contract/multicall.html\n   *\n   * @param args - {@link MulticallParameters}\n   * @returns An array of results with accompanying status. {@link MulticallReturnType}\n   *\n   * @example\n   * import { createPublicClient, http, parseAbi } from 'viem'\n   * import { mainnet } from 'viem/chains'\n   *\n   * const client = createPublicClient({\n   *   chain: mainnet,\n   *   transport: http(),\n   * })\n   * const abi = parseAbi([\n   *   'function balanceOf(address) view returns (uint256)',\n   *   'function totalSupply() view returns (uint256)',\n   * ])\n   * const result = await client.multicall({\n   *   contracts: [\n   *     {\n   *       address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\n   *       abi,\n   *       functionName: 'balanceOf',\n   *       args: ['0xA0Cf798816D4b9b9866b5330EEa46a18382f251e'],\n   *     },\n   *     {\n   *       address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\n   *       abi,\n   *       functionName: 'totalSupply',\n   *     },\n   *   ],\n   * })\n   * // [{ result: 424122n, status: 'success' }, { result: 1000000n, status: 'success' }]\n   */\n  multicall: <\n    TContracts extends ContractFunctionConfig[],\n    TAllowFailure extends boolean = true,\n  >(\n    args: MulticallParameters<TContracts, TAllowFailure>,\n  ) => Promise<MulticallReturnType<TContracts, TAllowFailure>>\n  /**\n   * Prepares a transaction request for signing.\n   *\n   * - Docs: https://viem.sh/docs/actions/wallet/prepareTransactionRequest.html\n   *\n   * @param args - {@link PrepareTransactionRequestParameters}\n   * @returns The transaction request. {@link PrepareTransactionRequestReturnType}\n   *\n   * @example\n   * import { createWalletClient, custom } from 'viem'\n   * import { mainnet } from 'viem/chains'\n   *\n   * const client = createWalletClient({\n   *   chain: mainnet,\n   *   transport: custom(window.ethereum),\n   * })\n   * const request = await client.prepareTransactionRequest({\n   *   account: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',\n   *   to: '0x0000000000000000000000000000000000000000',\n   *   value: 1n,\n   * })\n   *\n   * @example\n   * // Account Hoisting\n   * import { createWalletClient, http } from 'viem'\n   * import { privateKeyToAccount } from 'viem/accounts'\n   * import { mainnet } from 'viem/chains'\n   *\n   * const client = createWalletClient({\n   *   account: privateKeyToAccount('0x…'),\n   *   chain: mainnet,\n   *   transport: custom(window.ethereum),\n   * })\n   * const request = await client.prepareTransactionRequest({\n   *   to: '0x0000000000000000000000000000000000000000',\n   *   value: 1n,\n   * })\n   */\n  prepareTransactionRequest: <\n    TChainOverride extends Chain | undefined = undefined,\n  >(\n    args: PrepareTransactionRequestParameters<TChain, TAccount, TChainOverride>,\n  ) => Promise<PrepareTransactionRequestReturnType>\n  /**\n   * Calls a read-only function on a contract, and returns the response.\n   *\n   * - Docs: https://viem.sh/docs/contract/readContract.html\n   * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/contracts/reading-contracts\n   *\n   * @remarks\n   * A \"read-only\" function (constant function) on a Solidity contract is denoted by a `view` or `pure` keyword. They can only read the state of the contract, and cannot make any changes to it. Since read-only methods do not change the state of the contract, they do not require any gas to be executed, and can be called by any user without the need to pay for gas.\n   *\n   * Internally, uses a [Public Client](https://viem.sh/docs/clients/public.html) to call the [`call` action](https://viem.sh/docs/actions/public/call.html) with [ABI-encoded `data`](https://viem.sh/docs/contract/encodeFunctionData.html).\n   *\n   * @param args - {@link ReadContractParameters}\n   * @returns The response from the contract. Type is inferred. {@link ReadContractReturnType}\n   *\n   * @example\n   * import { createPublicClient, http, parseAbi } from 'viem'\n   * import { mainnet } from 'viem/chains'\n   * import { readContract } from 'viem/contract'\n   *\n   * const client = createPublicClient({\n   *   chain: mainnet,\n   *   transport: http(),\n   * })\n   * const result = await client.readContract({\n   *   address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\n   *   abi: parseAbi(['function balanceOf(address) view returns (uint256)']),\n   *   functionName: 'balanceOf',\n   *   args: ['0xA0Cf798816D4b9b9866b5330EEa46a18382f251e'],\n   * })\n   * // 424122n\n   */\n  readContract: <\n    const TAbi extends Abi | readonly unknown[],\n    TFunctionName extends string,\n  >(\n    args: ReadContractParameters<TAbi, TFunctionName>,\n  ) => Promise<ReadContractReturnType<TAbi, TFunctionName>>\n  /**\n   * Sends a **signed** transaction to the network\n   *\n   * - Docs: https://viem.sh/docs/actions/wallet/sendRawTransaction.html\n   * - JSON-RPC Method: [`eth_sendRawTransaction`](https://ethereum.github.io/execution-apis/api-documentation/)\n   *\n   * @param client - Client to use\n   * @param parameters - {@link SendRawTransactionParameters}\n   * @returns The transaction hash. {@link SendRawTransactionReturnType}\n   *\n   * @example\n   * import { createWalletClient, custom } from 'viem'\n   * import { mainnet } from 'viem/chains'\n   * import { sendRawTransaction } from 'viem/wallet'\n   *\n   * const client = createWalletClient({\n   *   chain: mainnet,\n   *   transport: custom(window.ethereum),\n   * })\n   *\n   * const hash = await client.sendRawTransaction({\n   *   serializedTransaction: '0x02f850018203118080825208808080c080a04012522854168b27e5dc3d5839bab5e6b39e1a0ffd343901ce1622e3d64b48f1a04e00902ae0502c4728cbf12156290df99c3ed7de85b1dbfe20b5c36931733a33'\n   * })\n   */\n  sendRawTransaction: (\n    args: SendRawTransactionParameters,\n  ) => Promise<SendRawTransactionReturnType>\n  /**\n   * Simulates/validates a contract interaction. This is useful for retrieving **return data** and **revert reasons** of contract write functions.\n   *\n   * - Docs: https://viem.sh/docs/contract/simulateContract.html\n   * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/contracts/writing-to-contracts\n   *\n   * @remarks\n   * This function does not require gas to execute and _**does not**_ change the state of the blockchain. It is almost identical to [`readContract`](https://viem.sh/docs/contract/readContract.html), but also supports contract write functions.\n   *\n   * Internally, uses a [Public Client](https://viem.sh/docs/clients/public.html) to call the [`call` action](https://viem.sh/docs/actions/public/call.html) with [ABI-encoded `data`](https://viem.sh/docs/contract/encodeFunctionData.html).\n   *\n   * @param args - {@link SimulateContractParameters}\n   * @returns The simulation result and write request. {@link SimulateContractReturnType}\n   *\n   * @example\n   * import { createPublicClient, http } from 'viem'\n   * import { mainnet } from 'viem/chains'\n   *\n   * const client = createPublicClient({\n   *   chain: mainnet,\n   *   transport: http(),\n   * })\n   * const result = await client.simulateContract({\n   *   address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\n   *   abi: parseAbi(['function mint(uint32) view returns (uint32)']),\n   *   functionName: 'mint',\n   *   args: ['69420'],\n   *   account: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',\n   * })\n   */\n  simulateContract: <\n    const TAbi extends Abi | readonly unknown[],\n    TFunctionName extends string,\n    TChainOverride extends Chain | undefined = undefined,\n  >(\n    args: SimulateContractParameters<\n      TAbi,\n      TFunctionName,\n      TChain,\n      TChainOverride\n    >,\n  ) => Promise<\n    SimulateContractReturnType<TAbi, TFunctionName, TChain, TChainOverride>\n  >\n  verifyMessage: (\n    args: VerifyMessageParameters,\n  ) => Promise<VerifyMessageReturnType>\n  verifyTypedData: (\n    args: VerifyTypedDataParameters,\n  ) => Promise<VerifyTypedDataReturnType>\n  /**\n   * Destroys a Filter that was created from one of the following Actions:\n   *\n   * - [`createBlockFilter`](https://viem.sh/docs/actions/public/createBlockFilter.html)\n   * - [`createEventFilter`](https://viem.sh/docs/actions/public/createEventFilter.html)\n   * - [`createPendingTransactionFilter`](https://viem.sh/docs/actions/public/createPendingTransactionFilter.html)\n   *\n   * - Docs: https://viem.sh/docs/actions/public/uninstallFilter.html\n   * - JSON-RPC Methods: [`eth_uninstallFilter`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_uninstallFilter)\n   *\n   * @param args - {@link UninstallFilterParameters}\n   * @returns A boolean indicating if the Filter was successfully uninstalled. {@link UninstallFilterReturnType}\n   *\n   * @example\n   * import { createPublicClient, http } from 'viem'\n   * import { mainnet } from 'viem/chains'\n   * import { createPendingTransactionFilter, uninstallFilter } from 'viem/public'\n   *\n   * const filter = await client.createPendingTransactionFilter()\n   * const uninstalled = await client.uninstallFilter({ filter })\n   * // true\n   */\n  uninstallFilter: (\n    args: UninstallFilterParameters,\n  ) => Promise<UninstallFilterReturnType>\n  /**\n   * Waits for the [Transaction](https://viem.sh/docs/glossary/terms.html#transaction) to be included on a [Block](https://viem.sh/docs/glossary/terms.html#block) (one confirmation), and then returns the [Transaction Receipt](https://viem.sh/docs/glossary/terms.html#transaction-receipt). If the Transaction reverts, then the action will throw an error.\n   *\n   * - Docs: https://viem.sh/docs/actions/public/waitForTransactionReceipt.html\n   * - Example: https://stackblitz.com/github/wevm/viem/tree/main/examples/transactions/sending-transactions\n   * - JSON-RPC Methods:\n   *   - Polls [`eth_getTransactionReceipt`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getTransactionReceipt) on each block until it has been processed.\n   *   - If a Transaction has been replaced:\n   *     - Calls [`eth_getBlockByNumber`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getblockbynumber) and extracts the transactions\n   *     - Checks if one of the Transactions is a replacement\n   *     - If so, calls [`eth_getTransactionReceipt`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getTransactionReceipt).\n   *\n   * @remarks\n   * The `waitForTransactionReceipt` action additionally supports Replacement detection (e.g. sped up Transactions).\n   *\n   * Transactions can be replaced when a user modifies their transaction in their wallet (to speed up or cancel). Transactions are replaced when they are sent from the same nonce.\n   *\n   * There are 3 types of Transaction Replacement reasons:\n   *\n   * - `repriced`: The gas price has been modified (e.g. different `maxFeePerGas`)\n   * - `cancelled`: The Transaction has been cancelled (e.g. `value === 0n`)\n   * - `replaced`: The Transaction has been replaced (e.g. different `value` or `data`)\n   *\n   * @param args - {@link WaitForTransactionReceiptParameters}\n   * @returns The transaction receipt. {@link WaitForTransactionReceiptReturnType}\n   *\n   * @example\n   * import { createPublicClient, http } from 'viem'\n   * import { mainnet } from 'viem/chains'\n   *\n   * const client = createPublicClient({\n   *   chain: mainnet,\n   *   transport: http(),\n   * })\n   * const transactionReceipt = await client.waitForTransactionReceipt({\n   *   hash: '0x4ca7ee652d57678f26e887c149ab0735f41de37bcad58c9f6d3ed5824f15b74d',\n   * })\n   */\n  waitForTransactionReceipt: (\n    args: WaitForTransactionReceiptParameters<TChain>,\n  ) => Promise<WaitForTransactionReceiptReturnType<TChain>>\n  /**\n   * Watches and returns incoming block numbers.\n   *\n   * - Docs: https://viem.sh/docs/actions/public/watchBlockNumber.html\n   * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/blocks/watching-blocks\n   * - JSON-RPC Methods:\n   *   - When `poll: true`, calls [`eth_blockNumber`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_blocknumber) on a polling interval.\n   *   - When `poll: false` & WebSocket Transport, uses a WebSocket subscription via [`eth_subscribe`](https://docs.alchemy.com/reference/eth-subscribe-polygon) and the `\"newHeads\"` event.\n   *\n   * @param args - {@link WatchBlockNumberParameters}\n   * @returns A function that can be invoked to stop watching for new block numbers. {@link WatchBlockNumberReturnType}\n   *\n   * @example\n   * import { createPublicClient, http } from 'viem'\n   * import { mainnet } from 'viem/chains'\n   *\n   * const client = createPublicClient({\n   *   chain: mainnet,\n   *   transport: http(),\n   * })\n   * const unwatch = await client.watchBlockNumber({\n   *   onBlockNumber: (blockNumber) => console.log(blockNumber),\n   * })\n   */\n  watchBlockNumber: (\n    args: WatchBlockNumberParameters,\n  ) => WatchBlockNumberReturnType\n  /**\n   * Watches and returns information for incoming blocks.\n   *\n   * - Docs: https://viem.sh/docs/actions/public/watchBlocks.html\n   * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/blocks/watching-blocks\n   * - JSON-RPC Methods:\n   *   - When `poll: true`, calls [`eth_getBlockByNumber`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getBlockByNumber) on a polling interval.\n   *   - When `poll: false` & WebSocket Transport, uses a WebSocket subscription via [`eth_subscribe`](https://docs.alchemy.com/reference/eth-subscribe-polygon) and the `\"newHeads\"` event.\n   *\n   * @param args - {@link WatchBlocksParameters}\n   * @returns A function that can be invoked to stop watching for new block numbers. {@link WatchBlocksReturnType}\n   *\n   * @example\n   * import { createPublicClient, http } from 'viem'\n   * import { mainnet } from 'viem/chains'\n   *\n   * const client = createPublicClient({\n   *   chain: mainnet,\n   *   transport: http(),\n   * })\n   * const unwatch = await client.watchBlocks({\n   *   onBlock: (block) => console.log(block),\n   * })\n   */\n  watchBlocks: <\n    TIncludeTransactions extends boolean = false,\n    TBlockTag extends BlockTag = 'latest',\n  >(\n    args: WatchBlocksParameters<\n      TTransport,\n      TChain,\n      TIncludeTransactions,\n      TBlockTag\n    >,\n  ) => WatchBlocksReturnType\n  /**\n   * Watches and returns emitted contract event logs.\n   *\n   * - Docs: https://viem.sh/docs/contract/watchContractEvent.html\n   *\n   * @remarks\n   * This Action will batch up all the event logs found within the [`pollingInterval`](https://viem.sh/docs/contract/watchContractEvent.html#pollinginterval-optional), and invoke them via [`onLogs`](https://viem.sh/docs/contract/watchContractEvent.html#onLogs).\n   *\n   * `watchContractEvent` will attempt to create an [Event Filter](https://viem.sh/docs/contract/createContractEventFilter.html) and listen to changes to the Filter per polling interval, however, if the RPC Provider does not support Filters (e.g. `eth_newFilter`), then `watchContractEvent` will fall back to using [`getLogs`](https://viem.sh/docs/actions/public/getLogs.html) instead.\n   *\n   * @param args - {@link WatchContractEventParameters}\n   * @returns A function that can be invoked to stop watching for new event logs. {@link WatchContractEventReturnType}\n   *\n   * @example\n   * import { createPublicClient, http, parseAbi } from 'viem'\n   * import { mainnet } from 'viem/chains'\n   *\n   * const client = createPublicClient({\n   *   chain: mainnet,\n   *   transport: http(),\n   * })\n   * const unwatch = client.watchContractEvent({\n   *   address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\n   *   abi: parseAbi(['event Transfer(address indexed from, address indexed to, uint256 value)']),\n   *   eventName: 'Transfer',\n   *   args: { from: '0xc961145a54C96E3aE9bAA048c4F4D6b04C13916b' },\n   *   onLogs: (logs) => console.log(logs),\n   * })\n   */\n  watchContractEvent: <\n    const TAbi extends Abi | readonly unknown[],\n    TEventName extends string,\n    TStrict extends boolean | undefined = undefined,\n  >(\n    args: WatchContractEventParameters<TAbi, TEventName, TStrict>,\n  ) => WatchContractEventReturnType\n  /**\n   * Watches and returns emitted [Event Logs](https://viem.sh/docs/glossary/terms.html#event-log).\n   *\n   * - Docs: https://viem.sh/docs/actions/public/watchEvent.html\n   * - JSON-RPC Methods:\n   *   - **RPC Provider supports `eth_newFilter`:**\n   *     - Calls [`eth_newFilter`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_newfilter) to create a filter (called on initialize).\n   *     - On a polling interval, it will call [`eth_getFilterChanges`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getfilterchanges).\n   *   - **RPC Provider does not support `eth_newFilter`:**\n   *     - Calls [`eth_getLogs`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getlogs) for each block between the polling interval.\n   *\n   * @remarks\n   * This Action will batch up all the Event Logs found within the [`pollingInterval`](https://viem.sh/docs/actions/public/watchEvent.html#pollinginterval-optional), and invoke them via [`onLogs`](https://viem.sh/docs/actions/public/watchEvent.html#onLogs).\n   *\n   * `watchEvent` will attempt to create an [Event Filter](https://viem.sh/docs/actions/public/createEventFilter.html) and listen to changes to the Filter per polling interval, however, if the RPC Provider does not support Filters (e.g. `eth_newFilter`), then `watchEvent` will fall back to using [`getLogs`](https://viem.sh/docs/actions/public/getLogs.html) instead.\n   *\n   * @param args - {@link WatchEventParameters}\n   * @returns A function that can be invoked to stop watching for new Event Logs. {@link WatchEventReturnType}\n   *\n   * @example\n   * import { createPublicClient, http } from 'viem'\n   * import { mainnet } from 'viem/chains'\n   *\n   * const client = createPublicClient({\n   *   chain: mainnet,\n   *   transport: http(),\n   * })\n   * const unwatch = client.watchEvent({\n   *   onLogs: (logs) => console.log(logs),\n   * })\n   */\n  watchEvent: <\n    const TAbiEvent extends AbiEvent | undefined = undefined,\n    const TAbiEvents extends\n      | readonly AbiEvent[]\n      | readonly unknown[]\n      | undefined = TAbiEvent extends AbiEvent ? [TAbiEvent] : undefined,\n    TStrict extends boolean | undefined = undefined,\n  >(\n    args: WatchEventParameters<TAbiEvent, TAbiEvents, TStrict>,\n  ) => WatchEventReturnType\n  /**\n   * Watches and returns pending transaction hashes.\n   *\n   * - Docs: https://viem.sh/docs/actions/public/watchPendingTransactions.html\n   * - JSON-RPC Methods:\n   *   - When `poll: true`\n   *     - Calls [`eth_newPendingTransactionFilter`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_newpendingtransactionfilter) to initialize the filter.\n   *     - Calls [`eth_getFilterChanges`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getFilterChanges) on a polling interval.\n   *   - When `poll: false` & WebSocket Transport, uses a WebSocket subscription via [`eth_subscribe`](https://docs.alchemy.com/reference/eth-subscribe-polygon) and the `\"newPendingTransactions\"` event.\n   *\n   * @remarks\n   * This Action will batch up all the pending transactions found within the [`pollingInterval`](https://viem.sh/docs/actions/public/watchPendingTransactions.html#pollinginterval-optional), and invoke them via [`onTransactions`](https://viem.sh/docs/actions/public/watchPendingTransactions.html#ontransactions).\n   *\n   * @param args - {@link WatchPendingTransactionsParameters}\n   * @returns A function that can be invoked to stop watching for new pending transaction hashes. {@link WatchPendingTransactionsReturnType}\n   *\n   * @example\n   * import { createPublicClient, http } from 'viem'\n   * import { mainnet } from 'viem/chains'\n   *\n   * const client = createPublicClient({\n   *   chain: mainnet,\n   *   transport: http(),\n   * })\n   * const unwatch = await client.watchPendingTransactions({\n   *   onTransactions: (hashes) => console.log(hashes),\n   * })\n   */\n  watchPendingTransactions: (\n    args: WatchPendingTransactionsParameters<TTransport>,\n  ) => WatchPendingTransactionsReturnType\n}\n\nexport function publicActions<\n  TTransport extends Transport = Transport,\n  TChain extends Chain | undefined = Chain | undefined,\n  TAccount extends Account | undefined = Account | undefined,\n>(\n  client: Client<TTransport, TChain, TAccount>,\n): PublicActions<TTransport, TChain, TAccount> {\n  return {\n    call: (args) => call(client, args),\n    createBlockFilter: () => createBlockFilter(client),\n    createContractEventFilter: (args) =>\n      createContractEventFilter(client, args),\n    createEventFilter: (args) => createEventFilter(client, args),\n    createPendingTransactionFilter: () =>\n      createPendingTransactionFilter(client),\n    estimateContractGas: (args) => estimateContractGas(client, args as any),\n    estimateGas: (args) => estimateGas(client, args),\n    getBalance: (args) => getBalance(client, args),\n    getBlock: (args) => getBlock(client, args),\n    getBlockNumber: (args) => getBlockNumber(client, args),\n    getBlockTransactionCount: (args) => getBlockTransactionCount(client, args),\n    getBytecode: (args) => getBytecode(client, args),\n    getChainId: () => getChainId(client),\n    getContractEvents: (args) => getContractEvents(client, args),\n    getEnsAddress: (args) => getEnsAddress(client, args),\n    getEnsAvatar: (args) => getEnsAvatar(client, args),\n    getEnsName: (args) => getEnsName(client, args),\n    getEnsResolver: (args) => getEnsResolver(client, args),\n    getEnsText: (args) => getEnsText(client, args),\n    getFeeHistory: (args) => getFeeHistory(client, args),\n    estimateFeesPerGas: (args) => estimateFeesPerGas(client, args),\n    getFilterChanges: (args) => getFilterChanges(client, args),\n    getFilterLogs: (args) => getFilterLogs(client, args),\n    getGasPrice: () => getGasPrice(client),\n    getLogs: (args) => getLogs(client, args as any),\n    getProof: (args) => getProof(client, args),\n    estimateMaxPriorityFeePerGas: (args) =>\n      estimateMaxPriorityFeePerGas(client, args),\n    getStorageAt: (args) => getStorageAt(client, args),\n    getTransaction: (args) => getTransaction(client, args),\n    getTransactionConfirmations: (args) =>\n      getTransactionConfirmations(client, args),\n    getTransactionCount: (args) => getTransactionCount(client, args),\n    getTransactionReceipt: (args) => getTransactionReceipt(client, args),\n    multicall: (args) => multicall(client, args as any) as any,\n    prepareTransactionRequest: (args) =>\n      prepareTransactionRequest(client as any, args as any),\n    readContract: (args) => readContract(client, args),\n    sendRawTransaction: (args) => sendRawTransaction(client, args),\n    simulateContract: (args) => simulateContract(client, args),\n    verifyMessage: (args) => verifyMessage(client, args),\n    verifyTypedData: (args) => verifyTypedData(client, args),\n    uninstallFilter: (args) => uninstallFilter(client, args),\n    waitForTransactionReceipt: (args) =>\n      waitForTransactionReceipt(client, args),\n    watchBlocks: (args) => watchBlocks(client, args),\n    watchBlockNumber: (args) => watchBlockNumber(client, args),\n    watchContractEvent: (args) => watchContractEvent(client, args),\n    watchEvent: (args) => watchEvent(client, args),\n    watchPendingTransactions: (args) => watchPendingTransactions(client, args),\n  }\n}\n","import type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Filter } from '../../types/filter.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport { createFilterRequestScope } from '../../utils/filters/createFilterRequestScope.js'\n\nexport type CreateBlockFilterReturnType = Filter<'block'>\n\nexport type CreateBlockFilterErrorType = RequestErrorType | ErrorType\n\n/**\n * Creates a [`Filter`](https://viem.sh/docs/glossary/types.html#filter) to listen for new block hashes that can be used with [`getFilterChanges`](https://viem.sh/docs/actions/public/getFilterChanges.html).\n *\n * - Docs: https://viem.sh/docs/actions/public/createBlockFilter.html\n * - JSON-RPC Methods: [`eth_newBlockFilter`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_newBlockFilter)\n *\n * @param client - Client to use\n * @returns [`Filter`](https://viem.sh/docs/glossary/types.html#filter). {@link CreateBlockFilterReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { createBlockFilter } from 'viem/public'\n *\n * const client = createPublicClient({\n *   chain: mainnet,\n *   transport: http(),\n * })\n * const filter = await createBlockFilter(client)\n * // { id: \"0x345a6572337856574a76364e457a4366\", type: 'block' }\n */\nexport async function createBlockFilter<TChain extends Chain | undefined>(\n  client: Client<Transport, TChain>,\n): Promise<CreateBlockFilterReturnType> {\n  const getRequest = createFilterRequestScope(client, {\n    method: 'eth_newBlockFilter',\n  })\n  const id = await client.request({\n    method: 'eth_newBlockFilter',\n  })\n  return { id, request: getRequest(id), type: 'block' }\n}\n","import type { AbiEvent, Address } from 'abitype'\n\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { BlockNumber, BlockTag } from '../../types/block.js'\nimport type { Chain } from '../../types/chain.js'\nimport type {\n  MaybeAbiEventName,\n  MaybeExtractEventArgsFromAbi,\n} from '../../types/contract.js'\nimport type { Filter } from '../../types/filter.js'\nimport type { Hex, LogTopic } from '../../types/misc.js'\nimport type { Prettify } from '../../types/utils.js'\nimport {\n  type EncodeEventTopicsErrorType,\n  type EncodeEventTopicsParameters,\n  encodeEventTopics,\n} from '../../utils/abi/encodeEventTopics.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport {\n  type NumberToHexErrorType,\n  numberToHex,\n} from '../../utils/encoding/toHex.js'\nimport { createFilterRequestScope } from '../../utils/filters/createFilterRequestScope.js'\n\nexport type CreateEventFilterParameters<\n  TAbiEvent extends AbiEvent | undefined = undefined,\n  TAbiEvents extends\n    | readonly AbiEvent[]\n    | readonly unknown[]\n    | undefined = TAbiEvent extends AbiEvent ? [TAbiEvent] : undefined,\n  TStrict extends boolean | undefined = undefined,\n  TFromBlock extends BlockNumber | BlockTag | undefined = undefined,\n  TToBlock extends BlockNumber | BlockTag | undefined = undefined,\n  _EventName extends string | undefined = MaybeAbiEventName<TAbiEvent>,\n  _Args extends\n    | MaybeExtractEventArgsFromAbi<TAbiEvents, _EventName>\n    | undefined = undefined,\n> = {\n  address?: Address | Address[]\n  fromBlock?: TFromBlock | BlockNumber | BlockTag\n  toBlock?: TToBlock | BlockNumber | BlockTag\n} & (MaybeExtractEventArgsFromAbi<\n  TAbiEvents,\n  _EventName\n> extends infer TEventFilterArgs\n  ?\n      | {\n          args:\n            | TEventFilterArgs\n            | (_Args extends TEventFilterArgs ? _Args : never)\n          event: TAbiEvent\n          events?: never\n          /**\n           * Whether or not the logs must match the indexed/non-indexed arguments on `event`.\n           * @default false\n           */\n          strict?: TStrict\n        }\n      | {\n          args?: never\n          event?: TAbiEvent\n          events?: never\n          /**\n           * Whether or not the logs must match the indexed/non-indexed arguments on `event`.\n           * @default false\n           */\n          strict?: TStrict\n        }\n      | {\n          args?: never\n          event?: never\n          events: TAbiEvents\n          /**\n           * Whether or not the logs must match the indexed/non-indexed arguments on `event`.\n           * @default false\n           */\n          strict?: TStrict\n        }\n      | {\n          args?: never\n          event?: never\n          events?: never\n          strict?: never\n        }\n  : {\n      args?: never\n      event?: never\n      events?: never\n      strict?: never\n    })\n\nexport type CreateEventFilterReturnType<\n  TAbiEvent extends AbiEvent | undefined = undefined,\n  TAbiEvents extends\n    | readonly AbiEvent[]\n    | readonly unknown[]\n    | undefined = TAbiEvent extends AbiEvent ? [TAbiEvent] : undefined,\n  TStrict extends boolean | undefined = undefined,\n  TFromBlock extends BlockNumber | BlockTag | undefined = undefined,\n  TToBlock extends BlockNumber | BlockTag | undefined = undefined,\n  _EventName extends string | undefined = MaybeAbiEventName<TAbiEvent>,\n  _Args extends\n    | MaybeExtractEventArgsFromAbi<TAbiEvents, _EventName>\n    | undefined = undefined,\n> = Prettify<\n  Filter<'event', TAbiEvents, _EventName, _Args, TStrict, TFromBlock, TToBlock>\n>\n\nexport type CreateEventFilterErrorType =\n  | EncodeEventTopicsErrorType\n  | RequestErrorType\n  | NumberToHexErrorType\n  | ErrorType\n\n/**\n * Creates a [`Filter`](https://viem.sh/docs/glossary/types.html#filter) to listen for new events that can be used with [`getFilterChanges`](https://viem.sh/docs/actions/public/getFilterChanges.html).\n *\n * - Docs: https://viem.sh/docs/actions/public/createEventFilter.html\n * - JSON-RPC Methods: [`eth_newFilter`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_newfilter)\n *\n * @param client - Client to use\n * @param parameters - {@link CreateEventFilterParameters}\n * @returns [`Filter`](https://viem.sh/docs/glossary/types.html#filter). {@link CreateEventFilterReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { createEventFilter } from 'viem/public'\n *\n * const client = createPublicClient({\n *   chain: mainnet,\n *   transport: http(),\n * })\n * const filter = await createEventFilter(client, {\n *   address: '0xfba3912ca04dd458c843e2ee08967fc04f3579c2',\n * })\n */\nexport async function createEventFilter<\n  TChain extends Chain | undefined,\n  const TAbiEvent extends AbiEvent | undefined = undefined,\n  const TAbiEvents extends\n    | readonly AbiEvent[]\n    | readonly unknown[]\n    | undefined = TAbiEvent extends AbiEvent ? [TAbiEvent] : undefined,\n  TStrict extends boolean | undefined = undefined,\n  TFromBlock extends BlockNumber<bigint> | BlockTag | undefined = undefined,\n  TToBlock extends BlockNumber<bigint> | BlockTag | undefined = undefined,\n  _EventName extends string | undefined = MaybeAbiEventName<TAbiEvent>,\n  _Args extends\n    | MaybeExtractEventArgsFromAbi<TAbiEvents, _EventName>\n    | undefined = undefined,\n>(\n  client: Client<Transport, TChain>,\n  {\n    address,\n    args,\n    event,\n    events: events_,\n    fromBlock,\n    strict,\n    toBlock,\n  }: CreateEventFilterParameters<\n    TAbiEvent,\n    TAbiEvents,\n    TStrict,\n    TFromBlock,\n    TToBlock,\n    _EventName,\n    _Args\n  > = {} as any,\n): Promise<\n  CreateEventFilterReturnType<\n    TAbiEvent,\n    TAbiEvents,\n    TStrict,\n    TFromBlock,\n    TToBlock,\n    _EventName,\n    _Args\n  >\n> {\n  const events = events_ ?? (event ? [event] : undefined)\n\n  const getRequest = createFilterRequestScope(client, {\n    method: 'eth_newFilter',\n  })\n\n  let topics: LogTopic[] = []\n  if (events) {\n    topics = [\n      (events as AbiEvent[]).flatMap((event) =>\n        encodeEventTopics({\n          abi: [event],\n          eventName: (event as AbiEvent).name,\n          args,\n        } as EncodeEventTopicsParameters),\n      ),\n    ]\n    if (event) topics = topics[0] as LogTopic[]\n  }\n\n  const id: Hex = await client.request({\n    method: 'eth_newFilter',\n    params: [\n      {\n        address,\n        fromBlock:\n          typeof fromBlock === 'bigint' ? numberToHex(fromBlock) : fromBlock,\n        toBlock: typeof toBlock === 'bigint' ? numberToHex(toBlock) : toBlock,\n        ...(topics.length ? { topics } : {}),\n      },\n    ],\n  })\n\n  return {\n    abi: events,\n    args,\n    eventName: event ? (event as AbiEvent).name : undefined,\n    fromBlock,\n    id,\n    request: getRequest(id),\n    strict,\n    toBlock,\n    type: 'event',\n  } as unknown as CreateEventFilterReturnType<\n    TAbiEvent,\n    TAbiEvents,\n    TStrict,\n    TFromBlock,\n    TToBlock,\n    _EventName,\n    _Args\n  >\n}\n","import type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Filter } from '../../types/filter.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport { createFilterRequestScope } from '../../utils/filters/createFilterRequestScope.js'\n\nexport type CreatePendingTransactionFilterReturnType = Filter<'transaction'>\n\nexport type CreatePendingTransactionFilterErrorType =\n  | RequestErrorType\n  | ErrorType\n\n/**\n * Creates a Filter to listen for new pending transaction hashes that can be used with [`getFilterChanges`](https://viem.sh/docs/actions/public/getFilterChanges.html).\n *\n * - Docs: https://viem.sh/docs/actions/public/createPendingTransactionFilter.html\n * - JSON-RPC Methods: [`eth_newPendingTransactionFilter`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_newpendingtransactionfilter)\n *\n * @param client - Client to use\n * @returns [`Filter`](https://viem.sh/docs/glossary/types.html#filter). {@link CreateBlockFilterReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { createPendingTransactionFilter } from 'viem/public'\n *\n * const client = createPublicClient({\n *   chain: mainnet,\n *   transport: http(),\n * })\n * const filter = await createPendingTransactionFilter(client)\n * // { id: \"0x345a6572337856574a76364e457a4366\", type: 'transaction' }\n */\nexport async function createPendingTransactionFilter<\n  TTransport extends Transport,\n  TChain extends Chain | undefined,\n>(\n  client: Client<TTransport, TChain>,\n): Promise<CreatePendingTransactionFilterReturnType> {\n  const getRequest = createFilterRequestScope(client, {\n    method: 'eth_newPendingTransactionFilter',\n  })\n  const id = await client.request({\n    method: 'eth_newPendingTransactionFilter',\n  })\n  return { id, request: getRequest(id), type: 'transaction' }\n}\n","import type { Address } from 'abitype'\n\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { BlockTag } from '../../types/block.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport {\n  type NumberToHexErrorType,\n  numberToHex,\n} from '../../utils/encoding/toHex.js'\n\nexport type GetBalanceParameters = {\n  /** The address of the account. */\n  address: Address\n} & (\n  | {\n      /** The balance of the account at a block number. */\n      blockNumber?: bigint\n      blockTag?: never\n    }\n  | {\n      blockNumber?: never\n      /** The balance of the account at a block tag. */\n      blockTag?: BlockTag\n    }\n)\n\nexport type GetBalanceReturnType = bigint\n\nexport type GetBalanceErrorType =\n  | NumberToHexErrorType\n  | RequestErrorType\n  | ErrorType\n\n/**\n * Returns the balance of an address in wei.\n *\n * - Docs: https://viem.sh/docs/actions/public/getBalance.html\n * - JSON-RPC Methods: [`eth_getBalance`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getbalance)\n *\n * You can convert the balance to ether units with [`formatEther`](https://viem.sh/docs/utilities/formatEther.html).\n *\n * ```ts\n * const balance = await getBalance(client, {\n *   address: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',\n *   blockTag: 'safe'\n * })\n * const balanceAsEther = formatEther(balance)\n * // \"6.942\"\n * ```\n *\n * @param client - Client to use\n * @param parameters - {@link GetBalanceParameters}\n * @returns The balance of the address in wei. {@link GetBalanceReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getBalance } from 'viem/public'\n *\n * const client = createPublicClient({\n *   chain: mainnet,\n *   transport: http(),\n * })\n * const balance = await getBalance(client, {\n *   address: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',\n * })\n * // 10000000000000000000000n (wei)\n */\nexport async function getBalance<TChain extends Chain | undefined>(\n  client: Client<Transport, TChain>,\n  { address, blockNumber, blockTag = 'latest' }: GetBalanceParameters,\n): Promise<GetBalanceReturnType> {\n  const blockNumberHex = blockNumber ? numberToHex(blockNumber) : undefined\n\n  const balance = await client.request({\n    method: 'eth_getBalance',\n    params: [address, blockNumberHex || blockTag],\n  })\n  return BigInt(balance)\n}\n","import type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { BlockTag } from '../../types/block.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Hash } from '../../types/misc.js'\nimport type { Quantity } from '../../types/rpc.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport {\n  type HexToNumberErrorType,\n  hexToNumber,\n} from '../../utils/encoding/fromHex.js'\nimport {\n  type NumberToHexErrorType,\n  numberToHex,\n} from '../../utils/encoding/toHex.js'\n\nexport type GetBlockTransactionCountParameters =\n  | {\n      /** Hash of the block. */\n      blockHash?: Hash\n      blockNumber?: never\n      blockTag?: never\n    }\n  | {\n      blockHash?: never\n      /** The block number. */\n      blockNumber?: bigint\n      blockTag?: never\n    }\n  | {\n      blockHash?: never\n      blockNumber?: never\n      /** The block tag. Defaults to 'latest'. */\n      blockTag?: BlockTag\n    }\n\nexport type GetBlockTransactionCountReturnType = number\n\nexport type GetBlockTransactionCountErrorType =\n  | NumberToHexErrorType\n  | HexToNumberErrorType\n  | RequestErrorType\n  | ErrorType\n\n/**\n * Returns the number of Transactions at a block number, hash, or tag.\n *\n * - Docs: https://viem.sh/docs/actions/public/getBlockTransactionCount.html\n * - JSON-RPC Methods:\n *   - Calls [`eth_getBlockTransactionCountByNumber`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getblocktransactioncountbynumber) for `blockNumber` & `blockTag`.\n *   - Calls [`eth_getBlockTransactionCountByHash`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getblocktransactioncountbyhash) for `blockHash`.\n *\n * @param client - Client to use\n * @param parameters - {@link GetBlockTransactionCountParameters}\n * @returns The block transaction count. {@link GetBlockTransactionCountReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getBlockTransactionCount } from 'viem/public'\n *\n * const client = createPublicClient({\n *   chain: mainnet,\n *   transport: http(),\n * })\n * const count = await getBlockTransactionCount(client)\n */\nexport async function getBlockTransactionCount<\n  TChain extends Chain | undefined,\n>(\n  client: Client<Transport, TChain>,\n  {\n    blockHash,\n    blockNumber,\n    blockTag = 'latest',\n  }: GetBlockTransactionCountParameters = {},\n): Promise<GetBlockTransactionCountReturnType> {\n  const blockNumberHex =\n    blockNumber !== undefined ? numberToHex(blockNumber) : undefined\n\n  let count: Quantity\n  if (blockHash) {\n    count = await client.request({\n      method: 'eth_getBlockTransactionCountByHash',\n      params: [blockHash],\n    })\n  } else {\n    count = await client.request({\n      method: 'eth_getBlockTransactionCountByNumber',\n      params: [blockNumberHex || blockTag],\n    })\n  }\n\n  return hexToNumber(count)\n}\n","import type { Address } from 'abitype'\n\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { BlockTag } from '../../types/block.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Hex } from '../../types/misc.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport {\n  type NumberToHexErrorType,\n  numberToHex,\n} from '../../utils/encoding/toHex.js'\n\nexport type GetBytecodeParameters = {\n  address: Address\n} & (\n  | {\n      blockNumber?: never\n      blockTag?: BlockTag\n    }\n  | {\n      blockNumber?: bigint\n      blockTag?: never\n    }\n)\n\nexport type GetBytecodeReturnType = Hex | undefined\n\nexport type GetBytecodeErrorType =\n  | NumberToHexErrorType\n  | RequestErrorType\n  | ErrorType\n\n/**\n * Retrieves the bytecode at an address.\n *\n * - Docs: https://viem.sh/docs/contract/getBytecode.html\n * - JSON-RPC Methods: [`eth_getCode`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getcode)\n *\n * @param client - Client to use\n * @param parameters - {@link GetBytecodeParameters}\n * @returns The contract's bytecode. {@link GetBytecodeReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getBytecode } from 'viem/contract'\n *\n * const client = createPublicClient({\n *   chain: mainnet,\n *   transport: http(),\n * })\n * const code = await getBytecode(client, {\n *   address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\n * })\n */\nexport async function getBytecode<TChain extends Chain | undefined>(\n  client: Client<Transport, TChain>,\n  { address, blockNumber, blockTag = 'latest' }: GetBytecodeParameters,\n): Promise<GetBytecodeReturnType> {\n  const blockNumberHex =\n    blockNumber !== undefined ? numberToHex(blockNumber) : undefined\n  const hex = await client.request({\n    method: 'eth_getCode',\n    params: [address, blockNumberHex || blockTag],\n  })\n  if (hex === '0x') return undefined\n  return hex\n}\n","import type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { BlockTag } from '../../types/block.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { FeeHistory } from '../../types/fee.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport {\n  type NumberToHexErrorType,\n  numberToHex,\n} from '../../utils/encoding/toHex.js'\nimport {\n  type FormatFeeHistoryErrorType,\n  formatFeeHistory,\n} from '../../utils/formatters/feeHistory.js'\n\nexport type GetFeeHistoryParameters = {\n  /**\n   * Number of blocks in the requested range. Between 1 and 1024 blocks can be requested in a single query. Less than requested may be returned if not all blocks are available.\n   */\n  blockCount: number\n  /**\n   * A monotonically increasing list of percentile values to sample from each block's effective priority fees per gas in ascending order, weighted by gas used.\n   */\n  rewardPercentiles: number[]\n} & (\n  | {\n      blockNumber?: never\n      /**\n       * Highest number block of the requested range.\n       * @default 'latest'\n       */\n      blockTag?: BlockTag\n    }\n  | {\n      /** Highest number block of the requested range. */\n      blockNumber?: bigint\n      blockTag?: never\n    }\n)\nexport type GetFeeHistoryReturnType = FeeHistory\n\nexport type GetFeeHistoryErrorType =\n  | NumberToHexErrorType\n  | RequestErrorType\n  | FormatFeeHistoryErrorType\n\n/**\n * Returns a collection of historical gas information.\n *\n * - Docs: https://viem.sh/docs/actions/public/getFeeHistory.html\n * - JSON-RPC Methods: [`eth_feeHistory`](https://docs.alchemy.com/reference/eth-feehistory)\n *\n * @param client - Client to use\n * @param parameters - {@link GetFeeHistoryParameters}\n * @returns The gas estimate (in wei). {@link GetFeeHistoryReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getFeeHistory } from 'viem/public'\n *\n * const client = createPublicClient({\n *   chain: mainnet,\n *   transport: http(),\n * })\n * const feeHistory = await getFeeHistory(client, {\n *   blockCount: 4,\n *   rewardPercentiles: [25, 75],\n * })\n */\nexport async function getFeeHistory<TChain extends Chain | undefined>(\n  client: Client<Transport, TChain>,\n  {\n    blockCount,\n    blockNumber,\n    blockTag = 'latest',\n    rewardPercentiles,\n  }: GetFeeHistoryParameters,\n): Promise<GetFeeHistoryReturnType> {\n  const blockNumberHex = blockNumber ? numberToHex(blockNumber) : undefined\n  const feeHistory = await client.request({\n    method: 'eth_feeHistory',\n    params: [\n      numberToHex(blockCount),\n      blockNumberHex || blockTag,\n      rewardPercentiles,\n    ],\n  })\n  return formatFeeHistory(feeHistory)\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { FeeHistory } from '../../types/fee.js'\nimport type { RpcFeeHistory } from '../../types/rpc.js'\n\nexport type FormatFeeHistoryErrorType = ErrorType\n\nexport function formatFeeHistory(feeHistory: RpcFeeHistory): FeeHistory {\n  return {\n    baseFeePerGas: feeHistory.baseFeePerGas.map((value) => BigInt(value)),\n    gasUsedRatio: feeHistory.gasUsedRatio,\n    oldestBlock: BigInt(feeHistory.oldestBlock),\n    reward: feeHistory.reward?.map((reward) =>\n      reward.map((value) => BigInt(value)),\n    ),\n  }\n}\n","import type { Abi, AbiEvent, ExtractAbiEvent } from 'abitype'\n\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport {\n  DecodeLogDataMismatch,\n  DecodeLogTopicsMismatch,\n} from '../../errors/abi.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { BlockNumber, BlockTag } from '../../types/block.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Filter } from '../../types/filter.js'\nimport type { Log } from '../../types/log.js'\nimport {\n  type DecodeEventLogErrorType,\n  decodeEventLog,\n} from '../../utils/abi/decodeEventLog.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport {\n  type FormatLogErrorType,\n  formatLog,\n} from '../../utils/formatters/log.js'\n\nexport type GetFilterLogsParameters<\n  TAbi extends Abi | readonly unknown[] | undefined = undefined,\n  TEventName extends string | undefined = undefined,\n  TStrict extends boolean | undefined = undefined,\n  TFromBlock extends BlockNumber | BlockTag | undefined = undefined,\n  TToBlock extends BlockNumber | BlockTag | undefined = undefined,\n> = {\n  filter: Filter<'event', TAbi, TEventName, any, TStrict, TFromBlock, TToBlock>\n}\nexport type GetFilterLogsReturnType<\n  TAbi extends Abi | readonly unknown[] | undefined = undefined,\n  TEventName extends string | undefined = undefined,\n  TStrict extends boolean | undefined = undefined,\n  TFromBlock extends BlockNumber | BlockTag | undefined = undefined,\n  TToBlock extends BlockNumber | BlockTag | undefined = undefined,\n  _AbiEvent extends AbiEvent | undefined = TAbi extends Abi\n    ? TEventName extends string\n      ? ExtractAbiEvent<TAbi, TEventName>\n      : undefined\n    : undefined,\n  _Pending extends boolean =\n    | (TFromBlock extends 'pending' ? true : false)\n    | (TToBlock extends 'pending' ? true : false),\n> = Log<bigint, number, _Pending, _AbiEvent, TStrict, TAbi, TEventName>[]\n\nexport type GetFilterLogsErrorType =\n  | RequestErrorType\n  | DecodeEventLogErrorType\n  | FormatLogErrorType\n  | ErrorType\n\n/**\n * Returns a list of event logs since the filter was created.\n *\n * - Docs: https://viem.sh/docs/actions/public/getFilterLogs.html\n * - JSON-RPC Methods: [`eth_getFilterLogs`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getfilterlogs)\n *\n * `getFilterLogs` is only compatible with **event filters**.\n *\n * @param client - Client to use\n * @param parameters - {@link GetFilterLogsParameters}\n * @returns A list of event logs. {@link GetFilterLogsReturnType}\n *\n * @example\n * import { createPublicClient, http, parseAbiItem } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { createEventFilter, getFilterLogs } from 'viem/public'\n *\n * const client = createPublicClient({\n *   chain: mainnet,\n *   transport: http(),\n * })\n * const filter = await createEventFilter(client, {\n *   address: '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48',\n *   event: parseAbiItem('event Transfer(address indexed, address indexed, uint256)'),\n * })\n * const logs = await getFilterLogs(client, { filter })\n */\nexport async function getFilterLogs<\n  TChain extends Chain | undefined,\n  const TAbi extends Abi | readonly unknown[] | undefined,\n  TEventName extends string | undefined,\n  TStrict extends boolean | undefined = undefined,\n  TFromBlock extends BlockNumber | BlockTag | undefined = undefined,\n  TToBlock extends BlockNumber | BlockTag | undefined = undefined,\n>(\n  _client: Client<Transport, TChain>,\n  {\n    filter,\n  }: GetFilterLogsParameters<TAbi, TEventName, TStrict, TFromBlock, TToBlock>,\n): Promise<\n  GetFilterLogsReturnType<TAbi, TEventName, TStrict, TFromBlock, TToBlock>\n> {\n  const strict = filter.strict ?? false\n\n  const logs = await filter.request({\n    method: 'eth_getFilterLogs',\n    params: [filter.id],\n  })\n  return logs\n    .map((log) => {\n      try {\n        const { eventName, args } =\n          'abi' in filter && filter.abi\n            ? decodeEventLog({\n                abi: filter.abi,\n                data: log.data,\n                topics: log.topics as any,\n                strict,\n              })\n            : { eventName: undefined, args: undefined }\n        return formatLog(log, { args, eventName })\n      } catch (err) {\n        let eventName\n        let isUnnamed\n        if (\n          err instanceof DecodeLogDataMismatch ||\n          err instanceof DecodeLogTopicsMismatch\n        ) {\n          // If strict mode is on, and log data/topics do not match event definition, skip.\n          if ('strict' in filter && filter.strict) return\n          eventName = err.abiItem.name\n          isUnnamed = err.abiItem.inputs?.some((x) => !('name' in x && x.name))\n        }\n\n        // Set args to empty if there is an error decoding (e.g. indexed/non-indexed params mismatch).\n        return formatLog(log, { args: isUnnamed ? [] : {}, eventName })\n      }\n    })\n    .filter(Boolean) as unknown as GetFilterLogsReturnType<\n    TAbi,\n    TEventName,\n    TStrict,\n    TFromBlock,\n    TToBlock\n  >\n}\n","import type { Address } from 'abitype'\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { BlockTag } from '../../types/block.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Hash } from '../../types/misc.js'\nimport type { Proof } from '../../types/proof.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport {\n  type NumberToHexErrorType,\n  numberToHex,\n} from '../../utils/encoding/toHex.js'\nimport {\n  type FormatProofErrorType,\n  formatProof,\n} from '../../utils/formatters/proof.js'\n\nexport type GetProofParameters = {\n  /** Account address. */\n  address: Address\n  /** Array of storage-keys that should be proofed and included. */\n  storageKeys: Hash[]\n} & (\n  | {\n      /** The block number. */\n      blockNumber?: bigint\n      blockTag?: never\n    }\n  | {\n      blockNumber?: never\n      /**\n       * The block tag.\n       * @default 'latest'\n       */\n      blockTag?: BlockTag\n    }\n)\n\nexport type GetProofReturnType = Proof\n\nexport type GetProofErrorType =\n  | NumberToHexErrorType\n  | FormatProofErrorType\n  | RequestErrorType\n  | ErrorType\n\n/**\n * Returns the account and storage values of the specified account including the Merkle-proof.\n *\n * - Docs: https://viem.sh/docs/actions/public/getProof.html\n * - JSON-RPC Methods:\n *   - Calls [`eth_getProof`](https://eips.ethereum.org/EIPS/eip-1186)\n *\n * @param client - Client to use\n * @param parameters - {@link GetProofParameters}\n * @returns Proof data. {@link GetProofReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getProof } from 'viem/public'\n *\n * const client = createPublicClient({\n *   chain: mainnet,\n *   transport: http(),\n * })\n * const block = await getProof(client, {\n *  address: '0x...',\n *  storageKeys: ['0x...'],\n * })\n */\nexport async function getProof<TChain extends Chain | undefined>(\n  client: Client<Transport, TChain>,\n  {\n    address,\n    blockNumber,\n    blockTag: blockTag_,\n    storageKeys,\n  }: GetProofParameters,\n): Promise<GetProofReturnType> {\n  const blockTag = blockTag_ ?? 'latest'\n\n  const blockNumberHex =\n    blockNumber !== undefined ? numberToHex(blockNumber) : undefined\n\n  const proof = await client.request({\n    method: 'eth_getProof',\n    params: [address, storageKeys, blockNumberHex || blockTag],\n  })\n\n  return formatProof(proof)\n}\n","export const arrayRegex = /^(.*)\\[([0-9]*)\\]$/\n\n// `bytes<M>`: binary type of `M` bytes, `0 < M <= 32`\n// https://regexr.com/6va55\nexport const bytesRegex = /^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/\n\n// `(u)int<M>`: (un)signed integer type of `M` bits, `0 < M <= 256`, `M % 8 == 0`\n// https://regexr.com/6v8hp\nexport const integerRegex =\n  /^(u?int)(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/\n","import type {\n  TypedData,\n  TypedDataDomain,\n  TypedDataParameter,\n  TypedDataType,\n} from 'abitype'\n\nimport { BytesSizeMismatchError } from '../errors/abi.js'\nimport { InvalidAddressError } from '../errors/address.js'\nimport type { Hex } from '../types/misc.js'\nimport type { TypedDataDefinition } from '../types/typedData.js'\n\nimport type { ErrorType } from '../errors/utils.js'\nimport { type IsAddressErrorType, isAddress } from './address/isAddress.js'\nimport { type SizeErrorType, size } from './data/size.js'\nimport { type NumberToHexErrorType, numberToHex } from './encoding/toHex.js'\nimport { bytesRegex, integerRegex } from './regex.js'\nimport {\n  type HashDomainErrorType,\n  hashDomain,\n} from './signature/hashTypedData.js'\n\nexport type ValidateTypedDataErrorType =\n  | HashDomainErrorType\n  | IsAddressErrorType\n  | NumberToHexErrorType\n  | SizeErrorType\n  | ErrorType\n\nexport function validateTypedData<\n  const TTypedData extends TypedData | { [key: string]: unknown },\n  TPrimaryType extends string = string,\n>({\n  domain,\n  message,\n  primaryType,\n  types: types_,\n}: TypedDataDefinition<TTypedData, TPrimaryType>) {\n  const types = types_ as TypedData\n\n  const validateData = (\n    struct: readonly TypedDataParameter[],\n    value_: Record<string, unknown>,\n  ) => {\n    for (const param of struct) {\n      const { name, type: type_ } = param\n      const type = type_ as TypedDataType\n      const value = value_[name]\n\n      const integerMatch = type.match(integerRegex)\n      if (\n        integerMatch &&\n        (typeof value === 'number' || typeof value === 'bigint')\n      ) {\n        const [_type, base, size_] = integerMatch\n        // If number cannot be cast to a sized hex value, it is out of range\n        // and will throw.\n        numberToHex(value, {\n          signed: base === 'int',\n          size: parseInt(size_) / 8,\n        })\n      }\n\n      if (type === 'address' && typeof value === 'string' && !isAddress(value))\n        throw new InvalidAddressError({ address: value })\n\n      const bytesMatch = type.match(bytesRegex)\n      if (bytesMatch) {\n        const [_type, size_] = bytesMatch\n        if (size_ && size(value as Hex) !== parseInt(size_))\n          throw new BytesSizeMismatchError({\n            expectedSize: parseInt(size_),\n            givenSize: size(value as Hex),\n          })\n      }\n\n      const struct = types[type]\n      if (struct) validateData(struct, value as Record<string, unknown>)\n    }\n  }\n\n  // Validate domain types.\n  if (types.EIP712Domain && domain) validateData(types.EIP712Domain, domain)\n\n  if (primaryType !== 'EIP712Domain') {\n    // Validate message types.\n    const type = types[primaryType]\n    validateData(type, message as Record<string, unknown>)\n  }\n}\n\nexport type GetTypesForEIP712DomainErrorType = ErrorType\n\nexport function getTypesForEIP712Domain({\n  domain,\n}: { domain?: TypedDataDomain }): TypedDataParameter[] {\n  return [\n    typeof domain?.name === 'string' && { name: 'name', type: 'string' },\n    domain?.version && { name: 'version', type: 'string' },\n    typeof domain?.chainId === 'number' && {\n      name: 'chainId',\n      type: 'uint256',\n    },\n    domain?.verifyingContract && {\n      name: 'verifyingContract',\n      type: 'address',\n    },\n    domain?.salt && { name: 'salt', type: 'bytes32' },\n  ].filter(Boolean) as TypedDataParameter[]\n}\n\nexport type DomainSeparatorErrorType =\n  | GetTypesForEIP712DomainErrorType\n  | HashDomainErrorType\n  | ErrorType\n\nexport function domainSeparator({ domain }: { domain: TypedDataDomain }): Hex {\n  return hashDomain({\n    domain,\n    types: {\n      EIP712Domain: getTypesForEIP712Domain({ domain }),\n    },\n  })\n}\n","// Implementation forked and adapted from https://github.com/MetaMask/eth-sig-util/blob/main/src/sign-typed-data.ts\n\nimport type { AbiParameter, TypedData, TypedDataDomain } from 'abitype'\n\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Hex } from '../../types/misc.js'\nimport type { TypedDataDefinition } from '../../types/typedData.js'\nimport {\n  type EncodeAbiParametersErrorType,\n  encodeAbiParameters,\n} from '../abi/encodeAbiParameters.js'\nimport { concat } from '../data/concat.js'\nimport { type ToHexErrorType, toHex } from '../encoding/toHex.js'\nimport { type Keccak256ErrorType, keccak256 } from '../hash/keccak256.js'\nimport {\n  type GetTypesForEIP712DomainErrorType,\n  type ValidateTypedDataErrorType,\n  getTypesForEIP712Domain,\n  validateTypedData,\n} from '../typedData.js'\n\ntype MessageTypeProperty = {\n  name: string\n  type: string\n}\n\nexport type HashTypedDataParameters<\n  TTypedData extends TypedData | { [key: string]: unknown } = TypedData,\n  TPrimaryType extends string = string,\n> = TypedDataDefinition<TTypedData, TPrimaryType>\n\nexport type HashTypedDataReturnType = Hex\n\nexport type HashTypedDataErrorType =\n  | GetTypesForEIP712DomainErrorType\n  | HashDomainErrorType\n  | HashStructErrorType\n  | ValidateTypedDataErrorType\n  | ErrorType\n\nexport function hashTypedData<\n  const TTypedData extends TypedData | { [key: string]: unknown },\n  TPrimaryType extends string = string,\n>({\n  domain: domain_,\n  message,\n  primaryType,\n  types: types_,\n}: HashTypedDataParameters<TTypedData, TPrimaryType>): HashTypedDataReturnType {\n  const domain: TypedDataDomain = typeof domain_ === 'undefined' ? {} : domain_\n  const types = {\n    EIP712Domain: getTypesForEIP712Domain({ domain }),\n    ...(types_ as TTypedData),\n  }\n\n  // Need to do a runtime validation check on addresses, byte ranges, integer ranges, etc\n  // as we can't statically check this with TypeScript.\n  validateTypedData({\n    domain,\n    message,\n    primaryType,\n    types,\n  } as TypedDataDefinition)\n\n  const parts: Hex[] = ['0x1901']\n  if (domain)\n    parts.push(\n      hashDomain({\n        domain,\n        types: types as Record<string, MessageTypeProperty[]>,\n      }),\n    )\n\n  if (primaryType !== 'EIP712Domain') {\n    parts.push(\n      hashStruct({\n        data: message,\n        primaryType: primaryType as string,\n        types: types as Record<string, MessageTypeProperty[]>,\n      }),\n    )\n  }\n\n  return keccak256(concat(parts))\n}\n\nexport type HashDomainErrorType = HashStructErrorType | ErrorType\n\nexport function hashDomain({\n  domain,\n  types,\n}: {\n  domain: TypedDataDomain\n  types: Record<string, MessageTypeProperty[]>\n}) {\n  return hashStruct({\n    data: domain,\n    primaryType: 'EIP712Domain',\n    types,\n  })\n}\n\ntype HashStructErrorType = EncodeDataErrorType | Keccak256ErrorType | ErrorType\n\nfunction hashStruct({\n  data,\n  primaryType,\n  types,\n}: {\n  data: Record<string, unknown>\n  primaryType: string\n  types: Record<string, MessageTypeProperty[]>\n}) {\n  const encoded = encodeData({\n    data,\n    primaryType,\n    types,\n  })\n  return keccak256(encoded)\n}\n\ntype EncodeDataErrorType =\n  | EncodeAbiParametersErrorType\n  | EncodeFieldErrorType\n  | HashTypeErrorType\n  | ErrorType\n\nfunction encodeData({\n  data,\n  primaryType,\n  types,\n}: {\n  data: Record<string, unknown>\n  primaryType: string\n  types: Record<string, MessageTypeProperty[]>\n}) {\n  const encodedTypes: AbiParameter[] = [{ type: 'bytes32' }]\n  const encodedValues: unknown[] = [hashType({ primaryType, types })]\n\n  for (const field of types[primaryType]) {\n    const [type, value] = encodeField({\n      types,\n      name: field.name,\n      type: field.type,\n      value: data[field.name],\n    })\n    encodedTypes.push(type)\n    encodedValues.push(value)\n  }\n\n  return encodeAbiParameters(encodedTypes, encodedValues)\n}\n\ntype HashTypeErrorType =\n  | ToHexErrorType\n  | EncodeTypeErrorType\n  | Keccak256ErrorType\n  | ErrorType\n\nfunction hashType({\n  primaryType,\n  types,\n}: {\n  primaryType: string\n  types: Record<string, MessageTypeProperty[]>\n}) {\n  const encodedHashType = toHex(encodeType({ primaryType, types }))\n  return keccak256(encodedHashType)\n}\n\ntype EncodeTypeErrorType = FindTypeDependenciesErrorType\n\nfunction encodeType({\n  primaryType,\n  types,\n}: {\n  primaryType: string\n  types: Record<string, MessageTypeProperty[]>\n}) {\n  let result = ''\n  const unsortedDeps = findTypeDependencies({ primaryType, types })\n  unsortedDeps.delete(primaryType)\n\n  const deps = [primaryType, ...Array.from(unsortedDeps).sort()]\n  for (const type of deps) {\n    result += `${type}(${types[type]\n      .map(({ name, type: t }) => `${t} ${name}`)\n      .join(',')})`\n  }\n\n  return result\n}\n\ntype FindTypeDependenciesErrorType = ErrorType\n\nfunction findTypeDependencies(\n  {\n    primaryType: primaryType_,\n    types,\n  }: {\n    primaryType: string\n    types: Record<string, MessageTypeProperty[]>\n  },\n  results: Set<string> = new Set(),\n): Set<string> {\n  const match = primaryType_.match(/^\\w*/u)\n  const primaryType = match?.[0]!\n  if (results.has(primaryType) || types[primaryType] === undefined) {\n    return results\n  }\n\n  results.add(primaryType)\n\n  for (const field of types[primaryType]) {\n    findTypeDependencies({ primaryType: field.type, types }, results)\n  }\n  return results\n}\n\ntype EncodeFieldErrorType =\n  | Keccak256ErrorType\n  | EncodeAbiParametersErrorType\n  | ToHexErrorType\n  | ErrorType\n\nfunction encodeField({\n  types,\n  name,\n  type,\n  value,\n}: {\n  types: Record<string, MessageTypeProperty[]>\n  name: string\n  type: string\n  value: any\n}): [type: AbiParameter, value: any] {\n  if (types[type] !== undefined) {\n    return [\n      { type: 'bytes32' },\n      keccak256(encodeData({ data: value, primaryType: type, types })),\n    ]\n  }\n\n  if (type === 'bytes') {\n    const prepend = value.length % 2 ? '0' : ''\n    value = `0x${prepend + value.slice(2)}`\n    return [{ type: 'bytes32' }, keccak256(value)]\n  }\n\n  if (type === 'string') return [{ type: 'bytes32' }, keccak256(toHex(value))]\n\n  if (type.lastIndexOf(']') === type.length - 1) {\n    const parsedType = type.slice(0, type.lastIndexOf('['))\n    const typeValuePairs = (value as [AbiParameter, any][]).map((item) =>\n      encodeField({\n        name,\n        type: parsedType,\n        types,\n        value: item,\n      }),\n    )\n    return [\n      { type: 'bytes32' },\n      keccak256(\n        encodeAbiParameters(\n          typeValuePairs.map(([t]) => t),\n          typeValuePairs.map(([, v]) => v),\n        ),\n      ),\n    ]\n  }\n\n  return [{ type }, value]\n}\n","import type { Abi } from 'abitype'\n\nimport {\n  AbiConstructorNotFoundError,\n  type AbiConstructorNotFoundErrorType,\n  AbiConstructorParamsNotFoundError,\n} from '../../errors/abi.js'\nimport type { GetConstructorArgs } from '../../types/contract.js'\nimport type { Hex } from '../../types/misc.js'\nimport { type ConcatHexErrorType, concatHex } from '../data/concat.js'\n\nimport type { ErrorType } from '../../errors/utils.js'\nimport {\n  type EncodeAbiParametersErrorType,\n  encodeAbiParameters,\n} from './encodeAbiParameters.js'\n\nconst docsPath = '/docs/contract/encodeDeployData'\n\nexport type EncodeDeployDataParameters<\n  TAbi extends Abi | readonly unknown[] = Abi,\n> = {\n  abi: TAbi\n  bytecode: Hex\n} & GetConstructorArgs<TAbi>\n\nexport type EncodeDeployDataErrorType =\n  | AbiConstructorNotFoundErrorType\n  | ConcatHexErrorType\n  | EncodeAbiParametersErrorType\n  | ErrorType\n\nexport function encodeDeployData<const TAbi extends Abi | readonly unknown[]>({\n  abi,\n  args,\n  bytecode,\n}: EncodeDeployDataParameters<TAbi>) {\n  if (!args || args.length === 0) return bytecode\n\n  const description = (abi as Abi).find(\n    (x) => 'type' in x && x.type === 'constructor',\n  )\n  if (!description) throw new AbiConstructorNotFoundError({ docsPath })\n  if (!('inputs' in description))\n    throw new AbiConstructorParamsNotFoundError({ docsPath })\n  if (!description.inputs || description.inputs.length === 0)\n    throw new AbiConstructorParamsNotFoundError({ docsPath })\n\n  const data = encodeAbiParameters(\n    description.inputs,\n    args as readonly unknown[],\n  )\n  return concatHex([bytecode, data!])\n}\n","import type {\n  AbiParameterToPrimitiveType,\n  AbiType,\n  Address,\n  SolidityAddress,\n  SolidityArrayWithoutTuple,\n  SolidityBool,\n  SolidityBytes,\n  SolidityInt,\n  SolidityString,\n} from 'abitype'\n\nimport {\n  AbiEncodingLengthMismatchError,\n  type AbiEncodingLengthMismatchErrorType,\n  BytesSizeMismatchError,\n  type BytesSizeMismatchErrorType,\n  UnsupportedPackedAbiType,\n} from '../../errors/abi.js'\nimport {\n  InvalidAddressError,\n  type InvalidAddressErrorType,\n} from '../../errors/address.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Hex } from '../../types/misc.js'\nimport { type IsAddressErrorType, isAddress } from '../address/isAddress.js'\nimport { type ConcatHexErrorType, concatHex } from '../data/concat.js'\nimport { type PadErrorType, pad } from '../data/pad.js'\nimport {\n  type BoolToHexErrorType,\n  type NumberToHexErrorType,\n  type StringToHexErrorType,\n  boolToHex,\n  numberToHex,\n  stringToHex,\n} from '../encoding/toHex.js'\nimport { arrayRegex, bytesRegex, integerRegex } from '../regex.js'\n\ntype PackedAbiType =\n  | SolidityAddress\n  | SolidityBool\n  | SolidityBytes\n  | SolidityInt\n  | SolidityString\n  | SolidityArrayWithoutTuple\n\ntype EncodePackedValues<\n  TPackedAbiTypes extends readonly PackedAbiType[] | readonly unknown[],\n> = {\n  [K in keyof TPackedAbiTypes]: TPackedAbiTypes[K] extends AbiType\n    ? AbiParameterToPrimitiveType<{ type: TPackedAbiTypes[K] }>\n    : unknown\n}\n\nexport type EncodePackedErrorType =\n  | AbiEncodingLengthMismatchErrorType\n  | ConcatHexErrorType\n  | EncodeErrorType\n  | ErrorType\n\nexport function encodePacked<\n  const TPackedAbiTypes extends readonly PackedAbiType[] | readonly unknown[],\n>(types: TPackedAbiTypes, values: EncodePackedValues<TPackedAbiTypes>): Hex {\n  if (types.length !== values.length)\n    throw new AbiEncodingLengthMismatchError({\n      expectedLength: types.length as number,\n      givenLength: values.length as number,\n    })\n\n  const data: Hex[] = []\n  for (let i = 0; i < (types as unknown[]).length; i++) {\n    const type = types[i]\n    const value = values[i]\n    data.push(encode(type, value))\n  }\n  return concatHex(data)\n}\n\ntype EncodeErrorType =\n  | BoolToHexErrorType\n  | BytesSizeMismatchErrorType\n  | InvalidAddressErrorType\n  | IsAddressErrorType\n  | NumberToHexErrorType\n  | PadErrorType\n  | StringToHexErrorType\n  | UnsupportedPackedAbiType\n  | ErrorType\n\nfunction encode<const TPackedAbiType extends PackedAbiType | unknown>(\n  type: TPackedAbiType,\n  value: EncodePackedValues<[TPackedAbiType]>[0],\n  isArray = false,\n): Hex {\n  if (type === 'address') {\n    const address = value as Address\n    if (!isAddress(address)) throw new InvalidAddressError({ address })\n    return pad(address.toLowerCase() as Hex, {\n      size: isArray ? 32 : null,\n    }) as Address\n  }\n  if (type === 'string') return stringToHex(value as string)\n  if (type === 'bytes') return value as Hex\n  if (type === 'bool')\n    return pad(boolToHex(value as boolean), { size: isArray ? 32 : 1 })\n\n  const intMatch = (type as string).match(integerRegex)\n  if (intMatch) {\n    const [_type, baseType, bits = '256'] = intMatch\n    const size = parseInt(bits) / 8\n    return numberToHex(value as number, {\n      size: isArray ? 32 : size,\n      signed: baseType === 'int',\n    })\n  }\n\n  const bytesMatch = (type as string).match(bytesRegex)\n  if (bytesMatch) {\n    const [_type, size] = bytesMatch\n    if (parseInt(size) !== ((value as Hex).length - 2) / 2)\n      throw new BytesSizeMismatchError({\n        expectedSize: parseInt(size),\n        givenSize: ((value as Hex).length - 2) / 2,\n      })\n    return pad(value as Hex, { dir: 'right', size: isArray ? 32 : null }) as Hex\n  }\n\n  const arrayMatch = (type as string).match(arrayRegex)\n  if (arrayMatch && Array.isArray(value)) {\n    const [_type, childType] = arrayMatch\n    const data: Hex[] = []\n    for (let i = 0; i < value.length; i++) {\n      data.push(encode(childType, value[i], true))\n    }\n    if (data.length === 0) return '0x'\n    return concatHex(data)\n  }\n\n  throw new UnsupportedPackedAbiType(type)\n}\n","export {\n  type IsDeterministicErrorType,\n  type RequestErrorType,\n  isDeterministicError,\n  buildRequest,\n} from './buildRequest.js'\n\nexport {\n  type CcipFetchErrorType,\n  type OffchainLookupErrorType,\n  ccipFetch,\n  offchainLookup,\n  offchainLookupAbiItem,\n  offchainLookupSignature,\n} from './ccip.js'\n\nexport {\n  type AssertCurrentChainErrorType,\n  type AssertCurrentChainParameters,\n  assertCurrentChain,\n} from './chain/assertCurrentChain.js'\nexport { defineChain } from './chain/defineChain.js'\nexport {\n  type ExtractChainErrorType,\n  type ExtractChainParameters,\n  type ExtractChainReturnType,\n  extractChain,\n} from './chain/extractChain.js'\nexport {\n  type GetChainContractAddressErrorType,\n  getChainContractAddress,\n} from './chain/getChainContractAddress.js'\n\nexport { arrayRegex, bytesRegex, integerRegex } from './regex.js'\n\nexport {\n  type GetSocketErrorType,\n  type HttpErrorType,\n  type HttpOptions,\n  type HttpReturnType,\n  type RpcRequest,\n  type RpcResponse,\n  type Socket,\n  type WebSocketAsyncErrorType,\n  type WebSocketAsyncOptions,\n  type WebSocketAsyncReturnType,\n  type WebSocketErrorType,\n  type WebSocketOptions,\n  type WebSocketReturnType,\n  getSocket,\n  rpc,\n} from './rpc.js'\nexport { type StringifyErrorType, stringify } from './stringify.js'\nexport {\n  type DomainSeparatorErrorType,\n  validateTypedData,\n} from './typedData.js'\nexport {\n  type DecodeAbiParametersErrorType,\n  type DecodeAbiParametersReturnType,\n  decodeAbiParameters,\n} from './abi/decodeAbiParameters.js'\nexport {\n  type DecodeErrorResultErrorType,\n  type DecodeErrorResultParameters,\n  type DecodeErrorResultReturnType,\n  decodeErrorResult,\n} from './abi/decodeErrorResult.js'\nexport {\n  type DecodeEventLogErrorType,\n  type DecodeEventLogParameters,\n  type DecodeEventLogReturnType,\n  decodeEventLog,\n} from './abi/decodeEventLog.js'\nexport {\n  type DecodeFunctionDataErrorType,\n  type DecodeFunctionDataParameters,\n  decodeFunctionData,\n} from './abi/decodeFunctionData.js'\nexport {\n  type DecodeFunctionResultErrorType,\n  type DecodeFunctionResultParameters,\n  type DecodeFunctionResultReturnType,\n  decodeFunctionResult,\n} from './abi/decodeFunctionResult.js'\nexport {\n  type EncodeAbiParametersErrorType,\n  type EncodeAbiParametersReturnType,\n  encodeAbiParameters,\n} from './abi/encodeAbiParameters.js'\nexport {\n  type EncodeDeployDataErrorType,\n  type EncodeDeployDataParameters,\n  encodeDeployData,\n} from './abi/encodeDeployData.js'\nexport {\n  type EncodeErrorResultErrorType,\n  type EncodeErrorResultParameters,\n  encodeErrorResult,\n} from './abi/encodeErrorResult.js'\nexport {\n  type EncodeArgErrorType,\n  type EncodeEventTopicsParameters,\n  encodeEventTopics,\n} from './abi/encodeEventTopics.js'\nexport {\n  type EncodeFunctionDataErrorType,\n  type EncodeFunctionDataParameters,\n  encodeFunctionData,\n} from './abi/encodeFunctionData.js'\nexport {\n  type EncodeFunctionResultErrorType,\n  type EncodeFunctionResultParameters,\n  encodeFunctionResult,\n} from './abi/encodeFunctionResult.js'\nexport {\n  type GetAbiItemErrorType,\n  type GetAbiItemParameters,\n  getAbiItem,\n} from './abi/getAbiItem.js'\nexport {\n  type ParseAbi,\n  type ParseAbiItem,\n  type ParseAbiParameter,\n  type ParseAbiParameters,\n  parseAbi,\n  parseAbiItem,\n  parseAbiParameter,\n  parseAbiParameters,\n} from 'abitype'\nexport { type EncodePackedErrorType, encodePacked } from './abi/encodePacked.js'\nexport {\n  type FormatAbiItemWithArgsErrorType,\n  formatAbiItemWithArgs,\n} from './abi/formatAbiItemWithArgs.js'\nexport {\n  type FormatAbiItemErrorType,\n  type FormatAbiParamErrorType,\n  type FormatAbiParamsErrorType,\n  formatAbiItem,\n  formatAbiParams,\n} from './abi/formatAbiItem.js'\nexport {\n  type ParseAccountErrorType,\n  parseAccount,\n} from '../accounts/utils/parseAccount.js'\nexport {\n  type PublicKeyToAddressErrorType,\n  publicKeyToAddress,\n} from '../accounts/utils/publicKeyToAddress.js'\nexport {\n  type GetContractAddressOptions,\n  type GetCreate2AddressErrorType,\n  type GetCreate2AddressOptions,\n  type GetCreateAddressErrorType,\n  type GetCreateAddressOptions,\n  getContractAddress,\n  getCreateAddress,\n  getCreate2Address,\n} from './address/getContractAddress.js'\nexport {\n  type ChecksumAddressErrorType,\n  getAddress,\n} from './address/getAddress.js'\nexport { type IsAddressErrorType, isAddress } from './address/isAddress.js'\nexport {\n  type IsAddressEqualErrorType,\n  isAddressEqual,\n} from './address/isAddressEqual.js'\nexport {\n  type ExtractFunctionNameErrorType,\n  type ExtractFunctionParamsErrorType,\n  type ExtractFunctionPartsErrorType,\n  type ExtractFunctionTypeErrorType,\n  extractFunctionName,\n  extractFunctionParams,\n  extractFunctionType,\n  extractFunctionParts,\n} from './contract/extractFunctionParts.js'\nexport {\n  type ConcatBytesErrorType,\n  type ConcatErrorType,\n  type ConcatHexErrorType,\n  concat,\n  concatBytes,\n  concatHex,\n} from './data/concat.js'\nexport { type IsBytesErrorType, isBytes } from './data/isBytes.js'\nexport { type IsHexErrorType, isHex } from './data/isHex.js'\nexport {\n  type PadBytesErrorType,\n  type PadErrorType,\n  type PadHexErrorType,\n  pad,\n  padBytes,\n  padHex,\n} from './data/pad.js'\nexport { type SizeErrorType, size } from './data/size.js'\nexport {\n  type AssertEndOffsetErrorType,\n  type AssertStartOffsetErrorType,\n  type SliceBytesErrorType,\n  type SliceErrorType,\n  type SliceHexErrorType,\n  type SliceReturnType,\n  slice,\n  sliceBytes,\n  sliceHex,\n} from './data/slice.js'\nexport { type TrimErrorType, type TrimReturnType, trim } from './data/trim.js'\nexport {\n  type DefineBlockErrorType,\n  type FormattedBlock,\n  type FormatBlockErrorType,\n  defineBlock,\n  formatBlock,\n} from './formatters/block.js'\nexport {\n  type DefineTransactionErrorType,\n  type FormattedTransaction,\n  type FormatTransactionErrorType,\n  defineTransaction,\n  formatTransaction,\n  transactionType,\n} from './formatters/transaction.js'\nexport { type FormatLogErrorType, formatLog } from './formatters/log.js'\nexport {\n  type DefineTransactionReceiptErrorType,\n  type FormatTransactionReceiptErrorType,\n  type FormattedTransactionReceipt,\n  defineTransactionReceipt,\n} from './formatters/transactionReceipt.js'\nexport {\n  type DefineTransactionRequestErrorType,\n  type FormatTransactionRequestErrorType,\n  type FormattedTransactionRequest,\n  defineTransactionRequest,\n  formatTransactionRequest,\n} from './formatters/transactionRequest.js'\nexport { type ExtractErrorType, extract } from './formatters/extract.js'\nexport {\n  type BytesToRlpErrorType,\n  type HexToRlpErrorType,\n  type ToRlpErrorType,\n  type ToRlpReturnType,\n  toRlp,\n} from './encoding/toRlp.js'\nexport {\n  type BoolToBytesErrorType,\n  type BoolToBytesOpts,\n  type HexToBytesErrorType,\n  type HexToBytesOpts,\n  type NumberToBytesErrorType,\n  type StringToBytesErrorType,\n  type StringToBytesOpts,\n  type ToBytesErrorType,\n  type ToBytesParameters,\n  boolToBytes,\n  toBytes,\n  hexToBytes,\n  numberToBytes,\n  stringToBytes,\n} from './encoding/toBytes.js'\nexport {\n  type BoolToHexErrorType,\n  type BoolToHexOpts,\n  type BytesToHexErrorType,\n  type BytesToHexOpts,\n  type NumberToHexErrorType,\n  type NumberToHexOpts,\n  type StringToHexErrorType,\n  type StringToHexOpts,\n  type ToHexErrorType,\n  type ToHexParameters,\n  boolToHex,\n  bytesToHex,\n  toHex,\n  numberToHex,\n  stringToHex,\n} from './encoding/toHex.js'\nexport {\n  type BytesToBigIntErrorType,\n  type BytesToBigIntOpts,\n  type BytesToBoolErrorType,\n  type BytesToBoolOpts,\n  type BytesToNumberErrorType,\n  type BytesToNumberOpts,\n  type BytesToStringErrorType,\n  type BytesToStringOpts,\n  type FromBytesErrorType,\n  type FromBytesParameters,\n  type FromBytesReturnType,\n  bytesToBigInt,\n  /** @deprecated – use `bytesToBigInt` */\n  bytesToBigInt as bytesToBigint,\n  bytesToBool,\n  bytesToNumber,\n  bytesToString,\n  fromBytes,\n} from './encoding/fromBytes.js'\nexport {\n  type AssertSizeErrorType,\n  type FromHexErrorType,\n  type FromHexParameters,\n  type FromHexReturnType,\n  type HexToBigIntErrorType,\n  type HexToBigIntOpts,\n  type HexToBoolErrorType,\n  type HexToBoolOpts,\n  type HexToNumberErrorType,\n  type HexToNumberOpts,\n  type HexToStringErrorType,\n  type HexToStringOpts,\n  fromHex,\n  hexToBool,\n  hexToBigInt,\n  hexToNumber,\n  hexToString,\n} from './encoding/fromHex.js'\nexport {\n  type FromRlpErrorType,\n  fromRlp,\n} from './encoding/fromRlp.js'\nexport {\n  type GetNodeErrorParameters,\n  type GetNodeErrorReturnType,\n  containsNodeError,\n  getNodeError,\n} from './errors/getNodeError.js'\nexport {\n  type GetCallErrorReturnType,\n  getCallError,\n} from './errors/getCallError.js'\nexport {\n  type GetContractErrorReturnType,\n  getContractError,\n} from './errors/getContractError.js'\nexport {\n  type GetEstimateGasErrorReturnType,\n  getEstimateGasError,\n} from './errors/getEstimateGasError.js'\nexport {\n  type GetTransactionErrorParameters,\n  type GetTransactionErrorReturnType,\n  getTransactionError,\n} from './errors/getTransactionError.js'\nexport {\n  type DefineFormatterErrorType,\n  defineFormatter,\n} from './formatters/formatter.js'\nexport {\n  type GetEventSelectorErrorType,\n  getEventSelector,\n} from './hash/getEventSelector.js'\nexport {\n  type GetFunctionSelectorErrorType,\n  getFunctionSelector,\n} from './hash/getFunctionSelector.js'\nexport { type IsHashErrorType, isHash } from './hash/isHash.js'\nexport { type Keccak256ErrorType, keccak256 } from './hash/keccak256.js'\nexport { type Sha256ErrorType, sha256 } from './hash/sha256.js'\nexport { type Ripemd160ErrorType, ripemd160 } from './hash/ripemd160.js'\nexport {\n  type HashDomainErrorType,\n  type HashTypedDataParameters,\n  type HashTypedDataReturnType,\n  hashTypedData,\n} from './signature/hashTypedData.js'\nexport {\n  type RecoverAddressErrorType,\n  type RecoverAddressParameters,\n  type RecoverAddressReturnType,\n  recoverAddress,\n} from './signature/recoverAddress.js'\nexport {\n  type RecoverMessageAddressErrorType,\n  type RecoverMessageAddressParameters,\n  type RecoverMessageAddressReturnType,\n  recoverMessageAddress,\n} from './signature/recoverMessageAddress.js'\nexport {\n  type RecoverPublicKeyErrorType,\n  type RecoverPublicKeyParameters,\n  type RecoverPublicKeyReturnType,\n  recoverPublicKey,\n} from './signature/recoverPublicKey.js'\nexport {\n  type RecoverTypedDataAddressErrorType,\n  type RecoverTypedDataAddressParameters,\n  type RecoverTypedDataAddressReturnType,\n  recoverTypedDataAddress,\n} from './signature/recoverTypedDataAddress.js'\nexport {\n  type VerifyMessageErrorType,\n  type VerifyMessageParameters,\n  type VerifyMessageReturnType,\n  verifyMessage,\n} from './signature/verifyMessage.js'\nexport {\n  type VerifyTypedDataErrorType,\n  type VerifyTypedDataParameters,\n  type VerifyTypedDataReturnType,\n  verifyTypedData,\n} from './signature/verifyTypedData.js'\nexport {\n  type HashMessage,\n  type HashMessageErrorType,\n  hashMessage,\n} from './signature/hashMessage.js'\nexport {\n  type GetSerializedTransactionTypeErrorType,\n  type GetSerializedTransactionType,\n  getSerializedTransactionType,\n} from './transaction/getSerializedTransactionType.js'\nexport {\n  type GetTransationTypeErrorType,\n  type GetTransactionType,\n  getTransactionType,\n} from './transaction/getTransactionType.js'\nexport {\n  type AssertRequestErrorType,\n  assertRequest,\n} from './transaction/assertRequest.js'\nexport {\n  type AssertTransactionEIP1559ErrorType,\n  type AssertTransactionEIP2930ErrorType,\n  type AssertTransactionLegacyErrorType,\n  assertTransactionEIP1559,\n  assertTransactionEIP2930,\n  assertTransactionLegacy,\n} from './transaction/assertTransaction.js'\nexport {\n  type ParseTransactionErrorType,\n  parseTransaction,\n} from './transaction/parseTransaction.js'\nexport {\n  /** @deprecated import `prepareTransactionRequest` from `viem/actions` instead. */\n  prepareTransactionRequest,\n} from '../actions/wallet/prepareTransactionRequest.js'\nexport {\n  serializeTransaction,\n  type SerializeTransactionErrorType,\n  type SerializeTransactionFn,\n} from './transaction/serializeTransaction.js'\nexport {\n  type SerializeAccessListErrorType,\n  serializeAccessList,\n} from './transaction/serializeAccessList.js'\nexport { type FormatEtherErrorType, formatEther } from './unit/formatEther.js'\nexport { type FormatGweiErrorType, formatGwei } from './unit/formatGwei.js'\nexport { type FormatUnitsErrorType, formatUnits } from './unit/formatUnits.js'\nexport { type ParseUnitsErrorType, parseUnits } from './unit/parseUnits.js'\nexport { type ParseEtherErrorType, parseEther } from './unit/parseEther.js'\nexport { type ParseGweiErrorType, parseGwei } from './unit/parseGwei.js'\n","import { BaseError } from './base.js'\n\nexport type NegativeOffsetErrorType = NegativeOffsetError & {\n  name: 'NegativeOffsetError'\n}\nexport class NegativeOffsetError extends BaseError {\n  override name = 'NegativeOffsetError'\n  constructor({ offset }: { offset: number }) {\n    super(`Offset \\`${offset}\\` cannot be negative.`)\n  }\n}\n\nexport type PositionOutOfBoundsErrorType = PositionOutOfBoundsError & {\n  name: 'PositionOutOfBoundsError'\n}\nexport class PositionOutOfBoundsError extends BaseError {\n  override name = 'PositionOutOfBoundsError'\n  constructor({ length, position }: { length: number; position: number }) {\n    super(\n      `Position \\`${position}\\` is out of bounds (\\`0 < position < ${length}\\`).`,\n    )\n  }\n}\n","import {\n  NegativeOffsetError,\n  PositionOutOfBoundsError,\n} from '../errors/cursor.js'\nimport type { ErrorType } from '../errors/utils.js'\nimport type { ByteArray } from '../types/misc.js'\n\nexport type Cursor = {\n  bytes: ByteArray\n  dataView: DataView\n  position: number\n  assertPosition(position: number): void\n  decrementPosition(offset: number): void\n  incrementPosition(offset: number): void\n  inspectByte(position?: number): ByteArray[number]\n  inspectBytes(length: number, position?: number): ByteArray\n  inspectUint8(position?: number): number\n  inspectUint16(position?: number): number\n  inspectUint24(position?: number): number\n  inspectUint32(position?: number): number\n  pushByte(byte: ByteArray[number]): void\n  pushBytes(bytes: ByteArray): void\n  pushUint8(value: number): void\n  pushUint16(value: number): void\n  pushUint24(value: number): void\n  pushUint32(value: number): void\n  readByte(): ByteArray[number]\n  readBytes(length: number): ByteArray\n  readUint8(): number\n  readUint16(): number\n  readUint24(): number\n  readUint32(): number\n  setPosition(position: number): void\n}\n\nexport type CreateCursorErrorType = ErrorType\n\nexport type CursorErrorType =\n  | CursorAssertPositionErrorType\n  | CursorDecrementPositionErrorType\n  | CursorIncrementPositionErrorType\n  | ErrorType\n\nexport type CursorAssertPositionErrorType = PositionOutOfBoundsError | ErrorType\n\nexport type CursorDecrementPositionErrorType = NegativeOffsetError | ErrorType\n\nexport type CursorIncrementPositionErrorType = NegativeOffsetError | ErrorType\n\nconst staticCursor: Cursor = {\n  bytes: new Uint8Array(),\n  dataView: new DataView(new ArrayBuffer(0)),\n  position: 0,\n  assertPosition(position) {\n    if (position < 0 || position > this.bytes.length - 1)\n      throw new PositionOutOfBoundsError({\n        length: this.bytes.length,\n        position,\n      })\n  },\n  decrementPosition(offset) {\n    if (offset < 0) throw new NegativeOffsetError({ offset })\n    const position = this.position - offset\n    this.assertPosition(position)\n    this.position = position\n  },\n  incrementPosition(offset) {\n    if (offset < 0) throw new NegativeOffsetError({ offset })\n    const position = this.position + offset\n    this.assertPosition(position)\n    this.position = position\n  },\n  inspectByte(position_) {\n    const position = position_ ?? this.position\n    this.assertPosition(position)\n    return this.bytes[position]\n  },\n  inspectBytes(length, position_) {\n    const position = position_ ?? this.position\n    this.assertPosition(position + length - 1)\n    return this.bytes.subarray(position, position + length)\n  },\n  inspectUint8(position_) {\n    const position = position_ ?? this.position\n    this.assertPosition(position)\n    return this.bytes[position]\n  },\n  inspectUint16(position_) {\n    const position = position_ ?? this.position\n    this.assertPosition(position + 1)\n    return this.dataView.getUint16(position)\n  },\n  inspectUint24(position_) {\n    const position = position_ ?? this.position\n    this.assertPosition(position + 2)\n    return (\n      (this.dataView.getUint16(position) << 8) +\n      this.dataView.getUint8(position + 2)\n    )\n  },\n  inspectUint32(position_) {\n    const position = position_ ?? this.position\n    this.assertPosition(position + 3)\n    return this.dataView.getUint32(position)\n  },\n  pushByte(byte: ByteArray[number]) {\n    this.assertPosition(this.position)\n    this.bytes[this.position] = byte\n    this.position++\n  },\n  pushBytes(bytes: ByteArray) {\n    this.assertPosition(this.position + bytes.length - 1)\n    this.bytes.set(bytes, this.position)\n    this.position += bytes.length\n  },\n  pushUint8(value: number) {\n    this.assertPosition(this.position)\n    this.bytes[this.position] = value\n    this.position++\n  },\n  pushUint16(value: number) {\n    this.assertPosition(this.position + 1)\n    this.dataView.setUint16(this.position, value)\n    this.position += 2\n  },\n  pushUint24(value: number) {\n    this.assertPosition(this.position + 2)\n    this.dataView.setUint16(this.position, value >> 8)\n    this.dataView.setUint8(this.position + 2, value & ~4294967040)\n    this.position += 3\n  },\n  pushUint32(value: number) {\n    this.assertPosition(this.position + 3)\n    this.dataView.setUint32(this.position, value)\n    this.position += 4\n  },\n  readByte() {\n    const value = this.inspectByte()\n    this.position++\n    return value\n  },\n  readBytes(length) {\n    const value = this.inspectBytes(length)\n    this.position += length\n    return value\n  },\n  readUint8() {\n    const value = this.inspectUint8()\n    this.position += 1\n    return value\n  },\n  readUint16() {\n    const value = this.inspectUint16()\n    this.position += 2\n    return value\n  },\n  readUint24() {\n    const value = this.inspectUint24()\n    this.position += 3\n    return value\n  },\n  readUint32() {\n    const value = this.inspectUint32()\n    this.position += 4\n    return value\n  },\n  setPosition(position) {\n    this.assertPosition(position)\n    this.position = position\n  },\n}\n\nexport function createCursor(bytes: ByteArray): Cursor {\n  const cursor = Object.create(staticCursor)\n  cursor.bytes = bytes\n  cursor.dataView = new DataView(\n    bytes.buffer,\n    bytes.byteOffset,\n    bytes.byteLength,\n  )\n  return cursor\n}\n","export const presignMessagePrefix = '\\x19Ethereum Signed Message:\\n'\n","import { presignMessagePrefix } from '../../constants/strings.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray, Hex, SignableMessage } from '../../types/misc.js'\nimport { type ConcatErrorType, concat } from '../data/concat.js'\nimport {\n  type StringToBytesErrorType,\n  type ToBytesErrorType,\n  stringToBytes,\n  toBytes,\n} from '../encoding/toBytes.js'\nimport { type Keccak256ErrorType, keccak256 } from '../hash/keccak256.js'\n\ntype To = 'hex' | 'bytes'\n\nexport type HashMessage<TTo extends To> =\n  | (TTo extends 'bytes' ? ByteArray : never)\n  | (TTo extends 'hex' ? Hex : never)\n\nexport type HashMessageErrorType =\n  | ConcatErrorType\n  | Keccak256ErrorType\n  | StringToBytesErrorType\n  | ToBytesErrorType\n  | ErrorType\n\nexport function hashMessage<TTo extends To = 'hex'>(\n  message: SignableMessage,\n  to_?: TTo,\n): HashMessage<TTo> {\n  const messageBytes = (() => {\n    if (typeof message === 'string') return stringToBytes(message)\n    if (message.raw instanceof Uint8Array) return message.raw\n    return toBytes(message.raw)\n  })()\n  const prefixBytes = stringToBytes(\n    `${presignMessagePrefix}${messageBytes.length}`,\n  )\n  return keccak256(concat([prefixBytes, messageBytes]), to_)\n}\n","import {\n  InvalidAddressError,\n  type InvalidAddressErrorType,\n} from '../../errors/address.js'\nimport { BaseError, type BaseErrorType } from '../../errors/base.js'\nimport {\n  InvalidChainIdError,\n  type InvalidChainIdErrorType,\n} from '../../errors/chain.js'\nimport {\n  FeeCapTooHighError,\n  type FeeCapTooHighErrorType,\n  TipAboveFeeCapError,\n  type TipAboveFeeCapErrorType,\n} from '../../errors/node.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type {\n  TransactionSerializableEIP1559,\n  TransactionSerializableEIP2930,\n  TransactionSerializableLegacy,\n} from '../../types/transaction.js'\nimport { type IsAddressErrorType, isAddress } from '../address/isAddress.js'\n\nexport type AssertTransactionEIP1559ErrorType =\n  | BaseErrorType\n  | IsAddressErrorType\n  | InvalidAddressErrorType\n  | InvalidChainIdErrorType\n  | FeeCapTooHighErrorType\n  | TipAboveFeeCapErrorType\n  | ErrorType\n\nexport function assertTransactionEIP1559(\n  transaction: TransactionSerializableEIP1559,\n) {\n  const { chainId, maxPriorityFeePerGas, gasPrice, maxFeePerGas, to } =\n    transaction\n  if (chainId <= 0) throw new InvalidChainIdError({ chainId })\n  if (to && !isAddress(to)) throw new InvalidAddressError({ address: to })\n  if (gasPrice)\n    throw new BaseError(\n      '`gasPrice` is not a valid EIP-1559 Transaction attribute.',\n    )\n  if (maxFeePerGas && maxFeePerGas > 2n ** 256n - 1n)\n    throw new FeeCapTooHighError({ maxFeePerGas })\n  if (\n    maxPriorityFeePerGas &&\n    maxFeePerGas &&\n    maxPriorityFeePerGas > maxFeePerGas\n  )\n    throw new TipAboveFeeCapError({ maxFeePerGas, maxPriorityFeePerGas })\n}\n\nexport type AssertTransactionEIP2930ErrorType =\n  | BaseErrorType\n  | IsAddressErrorType\n  | InvalidAddressErrorType\n  | InvalidChainIdErrorType\n  | FeeCapTooHighErrorType\n  | ErrorType\n\nexport function assertTransactionEIP2930(\n  transaction: TransactionSerializableEIP2930,\n) {\n  const { chainId, maxPriorityFeePerGas, gasPrice, maxFeePerGas, to } =\n    transaction\n  if (chainId <= 0) throw new InvalidChainIdError({ chainId })\n  if (to && !isAddress(to)) throw new InvalidAddressError({ address: to })\n  if (maxPriorityFeePerGas || maxFeePerGas)\n    throw new BaseError(\n      '`maxFeePerGas`/`maxPriorityFeePerGas` is not a valid EIP-2930 Transaction attribute.',\n    )\n  if (gasPrice && gasPrice > 2n ** 256n - 1n)\n    throw new FeeCapTooHighError({ maxFeePerGas: gasPrice })\n}\n\nexport type AssertTransactionLegacyErrorType =\n  | BaseErrorType\n  | IsAddressErrorType\n  | InvalidAddressErrorType\n  | InvalidChainIdErrorType\n  | FeeCapTooHighErrorType\n  | ErrorType\n\nexport function assertTransactionLegacy(\n  transaction: TransactionSerializableLegacy,\n) {\n  const {\n    chainId,\n    maxPriorityFeePerGas,\n    gasPrice,\n    maxFeePerGas,\n    to,\n    accessList,\n  } = transaction\n  if (to && !isAddress(to)) throw new InvalidAddressError({ address: to })\n  if (typeof chainId !== 'undefined' && chainId <= 0)\n    throw new InvalidChainIdError({ chainId })\n  if (maxPriorityFeePerGas || maxFeePerGas)\n    throw new BaseError(\n      '`maxFeePerGas`/`maxPriorityFeePerGas` is not a valid Legacy Transaction attribute.',\n    )\n  if (gasPrice && gasPrice > 2n ** 256n - 1n)\n    throw new FeeCapTooHighError({ maxFeePerGas: gasPrice })\n  if (accessList)\n    throw new BaseError(\n      '`accessList` is not a valid Legacy Transaction attribute.',\n    )\n}\n","import {\n  InvalidLegacyVError,\n  type InvalidLegacyVErrorType,\n} from '../../errors/transaction.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Signature } from '../../types/misc.js'\nimport type {\n  TransactionSerializable,\n  TransactionSerializableEIP1559,\n  TransactionSerializableEIP2930,\n  TransactionSerializableLegacy,\n  TransactionSerialized,\n  TransactionSerializedEIP1559,\n  TransactionSerializedEIP2930,\n  TransactionSerializedLegacy,\n  TransactionType,\n} from '../../types/transaction.js'\nimport { type ConcatHexErrorType, concatHex } from '../data/concat.js'\nimport { trim } from '../data/trim.js'\nimport { type ToHexErrorType, toHex } from '../encoding/toHex.js'\nimport { type ToRlpErrorType, toRlp } from '../encoding/toRlp.js'\n\nimport {\n  type AssertTransactionEIP1559ErrorType,\n  type AssertTransactionEIP2930ErrorType,\n  type AssertTransactionLegacyErrorType,\n  assertTransactionEIP1559,\n  assertTransactionEIP2930,\n  assertTransactionLegacy,\n} from './assertTransaction.js'\nimport {\n  type GetTransactionType,\n  type GetTransationTypeErrorType,\n  getTransactionType,\n} from './getTransactionType.js'\nimport {\n  type SerializeAccessListErrorType,\n  serializeAccessList,\n} from './serializeAccessList.js'\n\nexport type SerializedTransactionReturnType<\n  TTransactionSerializable extends\n    TransactionSerializable = TransactionSerializable,\n  TTransactionType extends\n    TransactionType = GetTransactionType<TTransactionSerializable>,\n> = TransactionSerialized<TTransactionType>\n\nexport type SerializeTransactionFn<\n  TTransactionSerializable extends\n    TransactionSerializable = TransactionSerializable,\n> = typeof serializeTransaction<TTransactionSerializable>\n\nexport type SerializeTransactionErrorType =\n  | GetTransationTypeErrorType\n  | SerializeTransactionEIP1559ErrorType\n  | SerializeTransactionEIP2930ErrorType\n  | SerializeTransactionLegacyErrorType\n  | ErrorType\n\nexport function serializeTransaction<\n  TTransactionSerializable extends TransactionSerializable,\n>(\n  transaction: TTransactionSerializable,\n  signature?: Signature,\n): SerializedTransactionReturnType<TTransactionSerializable> {\n  const type = getTransactionType(transaction) as GetTransactionType\n\n  if (type === 'eip1559')\n    return serializeTransactionEIP1559(\n      transaction as TransactionSerializableEIP1559,\n      signature,\n    ) as SerializedTransactionReturnType<TTransactionSerializable>\n\n  if (type === 'eip2930')\n    return serializeTransactionEIP2930(\n      transaction as TransactionSerializableEIP2930,\n      signature,\n    ) as SerializedTransactionReturnType<TTransactionSerializable>\n\n  return serializeTransactionLegacy(\n    transaction as TransactionSerializableLegacy,\n    signature,\n  ) as SerializedTransactionReturnType<TTransactionSerializable>\n}\n\ntype SerializeTransactionEIP1559ErrorType =\n  | AssertTransactionEIP1559ErrorType\n  | ConcatHexErrorType\n  | InvalidLegacyVErrorType\n  | ToHexErrorType\n  | ToRlpErrorType\n  | SerializeAccessListErrorType\n  | ErrorType\n\nfunction serializeTransactionEIP1559(\n  transaction: TransactionSerializableEIP1559,\n  signature?: Signature,\n): TransactionSerializedEIP1559 {\n  const {\n    chainId,\n    gas,\n    nonce,\n    to,\n    value,\n    maxFeePerGas,\n    maxPriorityFeePerGas,\n    accessList,\n    data,\n  } = transaction\n\n  assertTransactionEIP1559(transaction)\n\n  const serializedAccessList = serializeAccessList(accessList)\n\n  const serializedTransaction = [\n    toHex(chainId),\n    nonce ? toHex(nonce) : '0x',\n    maxPriorityFeePerGas ? toHex(maxPriorityFeePerGas) : '0x',\n    maxFeePerGas ? toHex(maxFeePerGas) : '0x',\n    gas ? toHex(gas) : '0x',\n    to ?? '0x',\n    value ? toHex(value) : '0x',\n    data ?? '0x',\n    serializedAccessList,\n  ]\n\n  if (signature) {\n    const yParity = (() => {\n      if (signature.v === 0n) return '0x'\n      if (signature.v === 1n) return toHex(1)\n\n      return signature.v === 27n ? '0x' : toHex(1)\n    })()\n    serializedTransaction.push(yParity, trim(signature.r), trim(signature.s))\n  }\n\n  return concatHex([\n    '0x02',\n    toRlp(serializedTransaction),\n  ]) as TransactionSerializedEIP1559\n}\n\ntype SerializeTransactionEIP2930ErrorType =\n  | AssertTransactionEIP2930ErrorType\n  | ConcatHexErrorType\n  | InvalidLegacyVErrorType\n  | ToHexErrorType\n  | ToRlpErrorType\n  | SerializeAccessListErrorType\n  | ErrorType\n\nfunction serializeTransactionEIP2930(\n  transaction: TransactionSerializableEIP2930,\n  signature?: Signature,\n): TransactionSerializedEIP2930 {\n  const { chainId, gas, data, nonce, to, value, accessList, gasPrice } =\n    transaction\n\n  assertTransactionEIP2930(transaction)\n\n  const serializedAccessList = serializeAccessList(accessList)\n\n  const serializedTransaction = [\n    toHex(chainId),\n    nonce ? toHex(nonce) : '0x',\n    gasPrice ? toHex(gasPrice) : '0x',\n    gas ? toHex(gas) : '0x',\n    to ?? '0x',\n    value ? toHex(value) : '0x',\n    data ?? '0x',\n    serializedAccessList,\n  ]\n\n  if (signature) {\n    const yParity = (() => {\n      if (signature.v === 0n) return '0x'\n      if (signature.v === 1n) return toHex(1)\n\n      return signature.v === 27n ? '0x' : toHex(1)\n    })()\n    serializedTransaction.push(yParity, trim(signature.r), trim(signature.s))\n  }\n\n  return concatHex([\n    '0x01',\n    toRlp(serializedTransaction),\n  ]) as TransactionSerializedEIP2930\n}\n\ntype SerializeTransactionLegacyErrorType =\n  | AssertTransactionLegacyErrorType\n  | InvalidLegacyVErrorType\n  | ToHexErrorType\n  | ToRlpErrorType\n  | ErrorType\n\nfunction serializeTransactionLegacy(\n  transaction: TransactionSerializableLegacy,\n  signature?: Signature,\n): TransactionSerializedLegacy {\n  const { chainId = 0, gas, data, nonce, to, value, gasPrice } = transaction\n\n  assertTransactionLegacy(transaction)\n\n  let serializedTransaction = [\n    nonce ? toHex(nonce) : '0x',\n    gasPrice ? toHex(gasPrice) : '0x',\n    gas ? toHex(gas) : '0x',\n    to ?? '0x',\n    value ? toHex(value) : '0x',\n    data ?? '0x',\n  ]\n\n  if (signature) {\n    const v = (() => {\n      // EIP-155 (explicit chainId)\n      if (chainId > 0)\n        return BigInt(chainId * 2) + BigInt(35n + signature.v - 27n)\n\n      // EIP-155 (inferred chainId)\n      if (signature.v >= 35n) {\n        const inferredChainId = (signature.v - 35n) / 2n\n        if (inferredChainId > 0) return signature.v\n        return 27n + (signature.v === 35n ? 0n : 1n)\n      }\n\n      // Pre-EIP-155 (no chainId)\n      const v = 27n + (signature.v === 27n ? 0n : 1n)\n      if (signature.v !== v) throw new InvalidLegacyVError({ v: signature.v })\n      return v\n    })()\n\n    serializedTransaction = [\n      ...serializedTransaction,\n      toHex(v),\n      signature.r,\n      signature.s,\n    ]\n  } else if (chainId > 0) {\n    serializedTransaction = [\n      ...serializedTransaction,\n      toHex(chainId),\n      '0x',\n      '0x',\n    ]\n  }\n\n  return toRlp(serializedTransaction)\n}\n","import {\n  InvalidAddressError,\n  type InvalidAddressErrorType,\n} from '../../errors/address.js'\nimport {\n  InvalidStorageKeySizeError,\n  type InvalidStorageKeySizeErrorType,\n} from '../../errors/transaction.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Hex } from '../../types/misc.js'\nimport type { AccessList } from '../../types/transaction.js'\nimport { type IsAddressErrorType, isAddress } from '../address/isAddress.js'\nimport { type RecursiveArray } from '../encoding/toRlp.js'\n\nexport type SerializeAccessListErrorType =\n  | InvalidStorageKeySizeErrorType\n  | InvalidAddressErrorType\n  | IsAddressErrorType\n  | ErrorType\n\n/*\n * Serialize an  EIP-2930 access list\n * @remarks\n * Use to create a transaction serializer with support for EIP-2930 access lists\n *\n * @param accessList - Array of objects of address and arrays of Storage Keys\n * @throws InvalidAddressError, InvalidStorageKeySizeError\n * @returns Array of hex strings\n */\nexport function serializeAccessList(\n  accessList?: AccessList,\n): RecursiveArray<Hex> {\n  if (!accessList || accessList.length === 0) return []\n\n  const serializedAccessList: RecursiveArray<Hex> = []\n  for (let i = 0; i < accessList.length; i++) {\n    const { address, storageKeys } = accessList[i]\n\n    for (let j = 0; j < storageKeys.length; j++) {\n      if (storageKeys[j].length - 2 !== 64) {\n        throw new InvalidStorageKeySizeError({ storageKey: storageKeys[j] })\n      }\n    }\n\n    if (!isAddress(address)) {\n      throw new InvalidAddressError({ address })\n    }\n\n    serializedAccessList.push([address, storageKeys])\n  }\n  return serializedAccessList\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { Proof } from '../../types/proof.js'\nimport type { RpcProof } from '../../types/rpc.js'\nimport { hexToNumber } from '../index.js'\n\nexport type FormatProofErrorType = ErrorType\n\nfunction formatStorageProof(storageProof: RpcProof['storageProof']) {\n  return storageProof.map((proof) => ({\n    ...proof,\n    value: BigInt(proof.value),\n  }))\n}\n\nexport function formatProof(proof: Partial<RpcProof>) {\n  return {\n    ...proof,\n    balance: proof.balance ? BigInt(proof.balance) : undefined,\n    nonce: proof.nonce ? hexToNumber(proof.nonce) : undefined,\n    storageProof: proof.storageProof\n      ? formatStorageProof(proof.storageProof)\n      : undefined,\n  } as Proof\n}\n","import type { Address } from 'abitype'\n\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { BlockTag } from '../../types/block.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Hex } from '../../types/misc.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport {\n  type NumberToHexErrorType,\n  numberToHex,\n} from '../../utils/encoding/toHex.js'\n\nexport type GetStorageAtParameters = {\n  address: Address\n  slot: Hex\n} & (\n  | {\n      blockNumber?: never\n      blockTag?: BlockTag\n    }\n  | {\n      blockNumber?: bigint\n      blockTag?: never\n    }\n)\n\nexport type GetStorageAtReturnType = Hex | undefined\n\nexport type GetStorageAtErrorType =\n  | NumberToHexErrorType\n  | RequestErrorType\n  | ErrorType\n\n/**\n * Returns the value from a storage slot at a given address.\n *\n * - Docs: https://viem.sh/docs/contract/getStorageAt.html\n * - JSON-RPC Methods: [`eth_getStorageAt`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getstorageat)\n *\n * @param client - Client to use\n * @param parameters - {@link GetStorageAtParameters}\n * @returns The value of the storage slot. {@link GetStorageAtReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getStorageAt } from 'viem/contract'\n *\n * const client = createPublicClient({\n *   chain: mainnet,\n *   transport: http(),\n * })\n * const code = await getStorageAt(client, {\n *   address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\n *   slot: toHex(0),\n * })\n */\nexport async function getStorageAt<TChain extends Chain | undefined>(\n  client: Client<Transport, TChain>,\n  { address, blockNumber, blockTag = 'latest', slot }: GetStorageAtParameters,\n): Promise<GetStorageAtReturnType> {\n  const blockNumberHex =\n    blockNumber !== undefined ? numberToHex(blockNumber) : undefined\n  const data = await client.request({\n    method: 'eth_getStorageAt',\n    params: [address, slot, blockNumberHex || blockTag],\n  })\n  return data\n}\n","import type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport { TransactionNotFoundError } from '../../errors/transaction.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { BlockTag } from '../../types/block.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Hash } from '../../types/misc.js'\nimport type { RpcTransaction } from '../../types/rpc.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport {\n  type NumberToHexErrorType,\n  numberToHex,\n} from '../../utils/encoding/toHex.js'\nimport {\n  type FormattedTransaction,\n  formatTransaction,\n} from '../../utils/formatters/transaction.js'\n\nexport type GetTransactionParameters<TBlockTag extends BlockTag = 'latest'> =\n  | {\n      /** The block hash */\n      blockHash: Hash\n      blockNumber?: never\n      blockTag?: never\n      hash?: never\n      /** The index of the transaction on the block. */\n      index: number\n    }\n  | {\n      blockHash?: never\n      /** The block number */\n      blockNumber: bigint\n      blockTag?: never\n      hash?: never\n      /** The index of the transaction on the block. */\n      index: number\n    }\n  | {\n      blockHash?: never\n      blockNumber?: never\n      /** The block tag. */\n      blockTag: TBlockTag | BlockTag\n      hash?: never\n      /** The index of the transaction on the block. */\n      index: number\n    }\n  | {\n      blockHash?: never\n      blockNumber?: never\n      blockTag?: never\n      /** The hash of the transaction. */\n      hash: Hash\n      index?: number\n    }\n\nexport type GetTransactionReturnType<\n  TChain extends Chain | undefined = Chain,\n  TBlockTag extends BlockTag = 'latest',\n> = FormattedTransaction<TChain, TBlockTag>\n\nexport type GetTransactionErrorType =\n  | NumberToHexErrorType\n  | RequestErrorType\n  | ErrorType\n\n/**\n * Returns information about a [Transaction](https://viem.sh/docs/glossary/terms.html#transaction) given a hash or block identifier.\n *\n * - Docs: https://viem.sh/docs/actions/public/getTransaction.html\n * - Example: https://stackblitz.com/github/wevm/viem/tree/main/examples/transactions/fetching-transactions\n * - JSON-RPC Methods: [`eth_getTransactionByHash`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getTransactionByHash)\n *\n * @param client - Client to use\n * @param parameters - {@link GetTransactionParameters}\n * @returns The transaction information. {@link GetTransactionReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getTransaction } from 'viem/public'\n *\n * const client = createPublicClient({\n *   chain: mainnet,\n *   transport: http(),\n * })\n * const transaction = await getTransaction(client, {\n *   hash: '0x4ca7ee652d57678f26e887c149ab0735f41de37bcad58c9f6d3ed5824f15b74d',\n * })\n */\nexport async function getTransaction<\n  TChain extends Chain | undefined,\n  TBlockTag extends BlockTag = 'latest',\n>(\n  client: Client<Transport, TChain>,\n  {\n    blockHash,\n    blockNumber,\n    blockTag: blockTag_,\n    hash,\n    index,\n  }: GetTransactionParameters<TBlockTag>,\n): Promise<GetTransactionReturnType<TChain, TBlockTag>> {\n  const blockTag = blockTag_ || 'latest'\n\n  const blockNumberHex =\n    blockNumber !== undefined ? numberToHex(blockNumber) : undefined\n\n  let transaction: RpcTransaction | null = null\n  if (hash) {\n    transaction = await client.request({\n      method: 'eth_getTransactionByHash',\n      params: [hash],\n    })\n  } else if (blockHash) {\n    transaction = await client.request({\n      method: 'eth_getTransactionByBlockHashAndIndex',\n      params: [blockHash, numberToHex(index)],\n    })\n  } else if (blockNumberHex || blockTag) {\n    transaction = await client.request({\n      method: 'eth_getTransactionByBlockNumberAndIndex',\n      params: [blockNumberHex || blockTag, numberToHex(index)],\n    })\n  }\n\n  if (!transaction)\n    throw new TransactionNotFoundError({\n      blockHash,\n      blockNumber,\n      blockTag,\n      hash,\n      index,\n    })\n\n  const format =\n    client.chain?.formatters?.transaction?.format || formatTransaction\n  return format(transaction)\n}\n","import type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Hash } from '../../types/misc.js'\nimport type { FormattedTransactionReceipt } from '../../utils/formatters/transactionReceipt.js'\nimport { getAction } from '../../utils/getAction.js'\n\nimport {\n  type GetBlockNumberErrorType,\n  getBlockNumber,\n} from './getBlockNumber.js'\nimport {\n  type GetTransactionErrorType,\n  getTransaction,\n} from './getTransaction.js'\n\nexport type GetTransactionConfirmationsParameters<\n  TChain extends Chain | undefined = Chain,\n> =\n  | {\n      /** The transaction hash. */\n      hash: Hash\n      transactionReceipt?: never\n    }\n  | {\n      hash?: never\n      /** The transaction receipt. */\n      transactionReceipt: FormattedTransactionReceipt<TChain>\n    }\n\nexport type GetTransactionConfirmationsReturnType = bigint\n\nexport type GetTransactionConfirmationsErrorType =\n  | GetBlockNumberErrorType\n  | GetTransactionErrorType\n  | ErrorType\n\n/**\n * Returns the number of blocks passed (confirmations) since the transaction was processed on a block.\n *\n * - Docs: https://viem.sh/docs/actions/public/getTransactionConfirmations.html\n * - Example: https://stackblitz.com/github/wevm/viem/tree/main/examples/transactions/fetching-transactions\n * - JSON-RPC Methods: [`eth_getTransactionConfirmations`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getTransactionConfirmations)\n *\n * @param client - Client to use\n * @param parameters - {@link GetTransactionConfirmationsParameters}\n * @returns The number of blocks passed since the transaction was processed. If confirmations is 0, then the Transaction has not been confirmed & processed yet. {@link GetTransactionConfirmationsReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getTransactionConfirmations } from 'viem/public'\n *\n * const client = createPublicClient({\n *   chain: mainnet,\n *   transport: http(),\n * })\n * const confirmations = await getTransactionConfirmations(client, {\n *   hash: '0x4ca7ee652d57678f26e887c149ab0735f41de37bcad58c9f6d3ed5824f15b74d',\n * })\n */\nexport async function getTransactionConfirmations<\n  TChain extends Chain | undefined,\n>(\n  client: Client<Transport, TChain>,\n  { hash, transactionReceipt }: GetTransactionConfirmationsParameters<TChain>,\n): Promise<GetTransactionConfirmationsReturnType> {\n  const [blockNumber, transaction] = await Promise.all([\n    getAction(client, getBlockNumber, 'getBlockNumber')({}),\n    hash\n      ? getAction(client, getTransaction, 'getBlockNumber')({ hash })\n      : undefined,\n  ])\n  const transactionBlockNumber =\n    transactionReceipt?.blockNumber || transaction?.blockNumber\n  if (!transactionBlockNumber) return 0n\n  return blockNumber - transactionBlockNumber! + 1n\n}\n","import type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport {\n  TransactionReceiptNotFoundError,\n  type TransactionReceiptNotFoundErrorType,\n} from '../../errors/transaction.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Hash } from '../../types/misc.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport {\n  type FormattedTransactionReceipt,\n  formatTransactionReceipt,\n} from '../../utils/formatters/transactionReceipt.js'\n\nexport type GetTransactionReceiptParameters = {\n  /** The hash of the transaction. */\n  hash: Hash\n}\n\nexport type GetTransactionReceiptReturnType<\n  TChain extends Chain | undefined = Chain | undefined,\n> = FormattedTransactionReceipt<TChain>\n\nexport type GetTransactionReceiptErrorType =\n  | RequestErrorType\n  | TransactionReceiptNotFoundErrorType\n  | ErrorType\n\n/**\n * Returns the [Transaction Receipt](https://viem.sh/docs/glossary/terms.html#transaction-receipt) given a [Transaction](https://viem.sh/docs/glossary/terms.html#transaction) hash.\n *\n * - Docs: https://viem.sh/docs/actions/public/getTransactionReceipt.html\n * - Example: https://stackblitz.com/github/wevm/viem/tree/main/examples/transactions/fetching-transactions\n * - JSON-RPC Methods: [`eth_getTransactionReceipt`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_gettransactionreceipt)\n *\n * @param client - Client to use\n * @param parameters - {@link GetTransactionReceiptParameters}\n * @returns The transaction receipt. {@link GetTransactionReceiptReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getTransactionReceipt } from 'viem/public'\n *\n * const client = createPublicClient({\n *   chain: mainnet,\n *   transport: http(),\n * })\n * const transactionReceipt = await getTransactionReceipt(client, {\n *   hash: '0x4ca7ee652d57678f26e887c149ab0735f41de37bcad58c9f6d3ed5824f15b74d',\n * })\n */\nexport async function getTransactionReceipt<TChain extends Chain | undefined>(\n  client: Client<Transport, TChain>,\n  { hash }: GetTransactionReceiptParameters,\n) {\n  const receipt = await client.request({\n    method: 'eth_getTransactionReceipt',\n    params: [hash],\n  })\n\n  if (!receipt) throw new TransactionReceiptNotFoundError({ hash })\n\n  const format =\n    client.chain?.formatters?.transactionReceipt?.format ||\n    formatTransactionReceipt\n  return format(receipt) as GetTransactionReceiptReturnType<TChain>\n}\n","import type { Address, Narrow } from 'abitype'\n\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport { multicall3Abi } from '../../constants/abis.js'\nimport { AbiDecodingZeroDataError } from '../../errors/abi.js'\nimport { BaseError } from '../../errors/base.js'\nimport { RawContractError } from '../../errors/contract.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { ContractFunctionConfig } from '../../types/contract.js'\nimport type { Hex } from '../../types/misc.js'\nimport type {\n  MulticallContracts,\n  MulticallResults,\n} from '../../types/multicall.js'\nimport {\n  type DecodeFunctionResultErrorType,\n  decodeFunctionResult,\n} from '../../utils/abi/decodeFunctionResult.js'\nimport {\n  type EncodeFunctionDataErrorType,\n  type EncodeFunctionDataParameters,\n  encodeFunctionData,\n} from '../../utils/abi/encodeFunctionData.js'\nimport {\n  type GetChainContractAddressErrorType,\n  getChainContractAddress,\n} from '../../utils/chain/getChainContractAddress.js'\nimport {\n  type GetContractErrorReturnType,\n  getContractError,\n} from '../../utils/errors/getContractError.js'\n\nimport type { ErrorType } from '../../errors/utils.js'\nimport { getAction } from '../../utils/getAction.js'\nimport type { CallParameters } from './call.js'\nimport { type ReadContractErrorType, readContract } from './readContract.js'\n\nexport type MulticallParameters<\n  TContracts extends ContractFunctionConfig[] = ContractFunctionConfig[],\n  TAllowFailure extends boolean = true,\n> = Pick<CallParameters, 'blockNumber' | 'blockTag'> & {\n  allowFailure?: TAllowFailure\n  /** The maximum size (in bytes) for each calldata chunk. Set to `0` to disable the size limit. @default 1_024 */\n  batchSize?: number\n  contracts: Narrow<readonly [...MulticallContracts<TContracts>]>\n  multicallAddress?: Address\n}\n\nexport type MulticallReturnType<\n  TContracts extends ContractFunctionConfig[] = ContractFunctionConfig[],\n  TAllowFailure extends boolean = true,\n> = MulticallResults<TContracts, TAllowFailure>\n\nexport type MulticallErrorType =\n  | GetChainContractAddressErrorType\n  | ReadContractErrorType\n  | GetContractErrorReturnType<\n      EncodeFunctionDataErrorType | DecodeFunctionResultErrorType\n    >\n  | ErrorType\n\n/**\n * Similar to [`readContract`](https://viem.sh/docs/contract/readContract.html), but batches up multiple functions on a contract in a single RPC call via the [`multicall3` contract](https://github.com/mds1/multicall).\n *\n * - Docs: https://viem.sh/docs/contract/multicall.html\n *\n * @param client - Client to use\n * @param parameters - {@link MulticallParameters}\n * @returns An array of results with accompanying status. {@link MulticallReturnType}\n *\n * @example\n * import { createPublicClient, http, parseAbi } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { multicall } from 'viem/contract'\n *\n * const client = createPublicClient({\n *   chain: mainnet,\n *   transport: http(),\n * })\n * const abi = parseAbi([\n *   'function balanceOf(address) view returns (uint256)',\n *   'function totalSupply() view returns (uint256)',\n * ])\n * const results = await multicall(client, {\n *   contracts: [\n *     {\n *       address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\n *       abi,\n *       functionName: 'balanceOf',\n *       args: ['0xA0Cf798816D4b9b9866b5330EEa46a18382f251e'],\n *     },\n *     {\n *       address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\n *       abi,\n *       functionName: 'totalSupply',\n *     },\n *   ],\n * })\n * // [{ result: 424122n, status: 'success' }, { result: 1000000n, status: 'success' }]\n */\nexport async function multicall<\n  TContracts extends ContractFunctionConfig[],\n  TChain extends Chain | undefined,\n  TAllowFailure extends boolean = true,\n>(\n  client: Client<Transport, TChain>,\n  args: MulticallParameters<TContracts, TAllowFailure>,\n): Promise<MulticallReturnType<TContracts, TAllowFailure>> {\n  const {\n    allowFailure = true,\n    batchSize: batchSize_,\n    blockNumber,\n    blockTag,\n    contracts,\n    multicallAddress: multicallAddress_,\n  } = args\n\n  const batchSize =\n    batchSize_ ??\n    ((typeof client.batch?.multicall === 'object' &&\n      client.batch.multicall.batchSize) ||\n      1_024)\n\n  let multicallAddress = multicallAddress_\n  if (!multicallAddress) {\n    if (!client.chain)\n      throw new Error(\n        'client chain not configured. multicallAddress is required.',\n      )\n\n    multicallAddress = getChainContractAddress({\n      blockNumber,\n      chain: client.chain,\n      contract: 'multicall3',\n    })\n  }\n\n  type Aggregate3Calls = {\n    allowFailure: boolean\n    callData: Hex\n    target: Address\n  }[]\n\n  const chunkedCalls: Aggregate3Calls[] = [[]]\n  let currentChunk = 0\n  let currentChunkSize = 0\n  for (let i = 0; i < contracts.length; i++) {\n    const { abi, address, args, functionName } = contracts[\n      i\n    ] as ContractFunctionConfig\n    try {\n      const callData = encodeFunctionData({\n        abi,\n        args,\n        functionName,\n      } as unknown as EncodeFunctionDataParameters)\n\n      currentChunkSize += (callData.length - 2) / 2\n      // Check to see if we need to create a new chunk.\n      if (\n        // Check if batching is enabled.\n        batchSize > 0 &&\n        // Check if the current size of the batch exceeds the size limit.\n        currentChunkSize > batchSize &&\n        // Check if the current chunk is not already empty.\n        chunkedCalls[currentChunk].length > 0\n      ) {\n        currentChunk++\n        currentChunkSize = (callData.length - 2) / 2\n        chunkedCalls[currentChunk] = []\n      }\n\n      chunkedCalls[currentChunk] = [\n        ...chunkedCalls[currentChunk],\n        {\n          allowFailure: true,\n          callData,\n          target: address,\n        },\n      ]\n    } catch (err) {\n      const error = getContractError(err as BaseError, {\n        abi,\n        address,\n        args,\n        docsPath: '/docs/contract/multicall',\n        functionName,\n      })\n      if (!allowFailure) throw error\n      chunkedCalls[currentChunk] = [\n        ...chunkedCalls[currentChunk],\n        {\n          allowFailure: true,\n          callData: '0x' as Hex,\n          target: address,\n        },\n      ]\n    }\n  }\n\n  const aggregate3Results = await Promise.allSettled(\n    chunkedCalls.map((calls) =>\n      getAction(\n        client,\n        readContract,\n        'readContract',\n      )({\n        abi: multicall3Abi,\n        address: multicallAddress!,\n        args: [calls],\n        blockNumber,\n        blockTag,\n        functionName: 'aggregate3',\n      }),\n    ),\n  )\n\n  const results = []\n  for (let i = 0; i < aggregate3Results.length; i++) {\n    const result = aggregate3Results[i]\n\n    // If an error occurred in a `readContract` invocation (ie. network error),\n    // then append the failure reason to each contract result.\n    if (result.status === 'rejected') {\n      if (!allowFailure) throw result.reason\n      for (let j = 0; j < chunkedCalls[i].length; j++) {\n        results.push({\n          status: 'failure',\n          error: result.reason,\n          result: undefined,\n        })\n      }\n      continue\n    }\n\n    // If the `readContract` call was successful, then decode the results.\n    const aggregate3Result = result.value\n    for (let j = 0; j < aggregate3Result.length; j++) {\n      // Extract the response from `readContract`\n      const { returnData, success } = aggregate3Result[j]\n\n      // Extract the request call data from the original call.\n      const { callData } = chunkedCalls[i][j]\n\n      // Extract the contract config for this call from the `contracts` argument\n      // for decoding.\n      const { abi, address, functionName, args } = contracts[\n        results.length\n      ] as ContractFunctionConfig\n\n      try {\n        if (callData === '0x') throw new AbiDecodingZeroDataError()\n        if (!success) throw new RawContractError({ data: returnData })\n        const result = decodeFunctionResult({\n          abi,\n          args,\n          data: returnData,\n          functionName,\n        })\n        results.push(allowFailure ? { result, status: 'success' } : result)\n      } catch (err) {\n        const error = getContractError(err as BaseError, {\n          abi,\n          address,\n          args,\n          docsPath: '/docs/contract/multicall',\n          functionName,\n        })\n        if (!allowFailure) throw error\n        results.push({ error, result: undefined, status: 'failure' })\n      }\n    }\n  }\n\n  if (results.length !== contracts.length)\n    throw new BaseError('multicall results mismatch')\n  return results as MulticallResults<TContracts, TAllowFailure>\n}\n","import type { Address } from 'abitype'\n\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport { universalSignatureValidatorAbi } from '../../constants/abis.js'\nimport { universalSignatureValidatorByteCode } from '../../constants/contracts.js'\nimport { CallExecutionError } from '../../errors/contract.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { ByteArray, Hex } from '../../types/misc.js'\nimport type { EncodeDeployDataErrorType } from '../../utils/abi/encodeDeployData.js'\nimport {\n  type IsBytesEqualErrorType,\n  isBytesEqual,\n} from '../../utils/data/isBytesEqual.js'\nimport type { IsHexErrorType } from '../../utils/data/isHex.js'\nimport type { ToHexErrorType } from '../../utils/encoding/toHex.js'\nimport { getAction } from '../../utils/getAction.js'\nimport { encodeDeployData, isHex, toHex } from '../../utils/index.js'\nimport { type CallErrorType, type CallParameters, call } from './call.js'\n\nexport type VerifyHashParameters = Pick<\n  CallParameters,\n  'blockNumber' | 'blockTag'\n> & {\n  /** The address that signed the original message. */\n  address: Address\n  /** The hash to be verified. */\n  hash: Hex\n  /** The signature that was generated by signing the message with the address's private key. */\n  signature: Hex | ByteArray\n}\n\nexport type VerifyHashReturnType = boolean\n\nexport type VerifyHashErrorType =\n  | CallErrorType\n  | IsHexErrorType\n  | ToHexErrorType\n  | IsBytesEqualErrorType\n  | EncodeDeployDataErrorType\n  | ErrorType\n\n/**\n * Verifies a message hash on chain using ERC-6492.\n *\n * @param client - Client to use.\n * @param parameters - {@link VerifyHashParameters}\n * @returns Whether or not the signature is valid. {@link VerifyHashReturnType}\n */\nexport async function verifyHash<TChain extends Chain | undefined>(\n  client: Client<Transport, TChain>,\n  { address, hash, signature, ...callRequest }: VerifyHashParameters,\n): Promise<VerifyHashReturnType> {\n  const signatureHex = isHex(signature) ? signature : toHex(signature)\n\n  try {\n    const { data } = await getAction(\n      client,\n      call,\n      'call',\n    )({\n      data: encodeDeployData({\n        abi: universalSignatureValidatorAbi,\n        args: [address, hash, signatureHex],\n        bytecode: universalSignatureValidatorByteCode,\n      }),\n      ...callRequest,\n    } as unknown as CallParameters)\n\n    return isBytesEqual(data ?? '0x0', '0x1')\n  } catch (error) {\n    if (error instanceof CallExecutionError) {\n      // if the execution fails, the signature was not valid and an internal method inside of the validator reverted\n      // this can happen for many reasons, for example if signer can not be recovered from the signature\n      // or if the signature has no valid format\n      return false\n    }\n\n    throw error\n  }\n}\n","export const universalSignatureValidatorByteCode =\n  '0x60806040523480156200001157600080fd5b50604051620007003803806200070083398101604081905262000034916200056f565b6000620000438484846200004f565b9050806000526001601ff35b600080846001600160a01b0316803b806020016040519081016040528181526000908060200190933c90507f6492649264926492649264926492649264926492649264926492649264926492620000a68462000451565b036200021f57600060608085806020019051810190620000c79190620005ce565b8651929550909350915060000362000192576000836001600160a01b031683604051620000f5919062000643565b6000604051808303816000865af19150503d806000811462000134576040519150601f19603f3d011682016040523d82523d6000602084013e62000139565b606091505b5050905080620001905760405162461bcd60e51b815260206004820152601e60248201527f5369676e617475726556616c696461746f723a206465706c6f796d656e74000060448201526064015b60405180910390fd5b505b604051630b135d3f60e11b808252906001600160a01b038a1690631626ba7e90620001c4908b90869060040162000661565b602060405180830381865afa158015620001e2573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906200020891906200069d565b6001600160e01b031916149450505050506200044a565b805115620002b157604051630b135d3f60e11b808252906001600160a01b03871690631626ba7e9062000259908890889060040162000661565b602060405180830381865afa15801562000277573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906200029d91906200069d565b6001600160e01b031916149150506200044a565b8251604114620003195760405162461bcd60e51b815260206004820152603a6024820152600080516020620006e083398151915260448201527f3a20696e76616c6964207369676e6174757265206c656e677468000000000000606482015260840162000187565b620003236200046b565b506020830151604080850151855186939260009185919081106200034b576200034b620006c9565b016020015160f81c9050601b81148015906200036b57508060ff16601c14155b15620003cf5760405162461bcd60e51b815260206004820152603b6024820152600080516020620006e083398151915260448201527f3a20696e76616c6964207369676e617475726520762076616c75650000000000606482015260840162000187565b6040805160008152602081018083528a905260ff83169181019190915260608101849052608081018390526001600160a01b038a169060019060a0016020604051602081039080840390855afa1580156200042e573d6000803e3d6000fd5b505050602060405103516001600160a01b031614955050505050505b9392505050565b60006020825110156200046357600080fd5b508051015190565b60405180606001604052806003906020820280368337509192915050565b6001600160a01b03811681146200049f57600080fd5b50565b634e487b7160e01b600052604160045260246000fd5b60005b83811015620004d5578181015183820152602001620004bb565b50506000910152565b600082601f830112620004f057600080fd5b81516001600160401b03808211156200050d576200050d620004a2565b604051601f8301601f19908116603f01168101908282118183101715620005385762000538620004a2565b816040528381528660208588010111156200055257600080fd5b62000565846020830160208901620004b8565b9695505050505050565b6000806000606084860312156200058557600080fd5b8351620005928162000489565b6020850151604086015191945092506001600160401b03811115620005b657600080fd5b620005c486828701620004de565b9150509250925092565b600080600060608486031215620005e457600080fd5b8351620005f18162000489565b60208501519093506001600160401b03808211156200060f57600080fd5b6200061d87838801620004de565b935060408601519150808211156200063457600080fd5b50620005c486828701620004de565b6000825162000657818460208701620004b8565b9190910192915050565b828152604060208201526000825180604084015262000688816060850160208701620004b8565b601f01601f1916919091016060019392505050565b600060208284031215620006b057600080fd5b81516001600160e01b0319811681146200044a57600080fd5b634e487b7160e01b600052603260045260246000fdfe5369676e617475726556616c696461746f72237265636f7665725369676e6572'\n","import { equalBytes } from '@noble/curves/abstract/utils'\n\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray, Hex } from '../../types/misc.js'\nimport { type ToBytesErrorType, toBytes } from '../encoding/toBytes.js'\nimport { type IsHexErrorType, isHex } from './isHex.js'\n\nexport type IsBytesEqualErrorType =\n  | IsHexErrorType\n  | ToBytesErrorType\n  | ErrorType\n\nexport function isBytesEqual(a_: ByteArray | Hex, b_: ByteArray | Hex) {\n  const a = isHex(a_) ? toBytes(a_) : a_\n  const b = isHex(b_) ? toBytes(b_) : b_\n  return equalBytes(a, b)\n}\n","import type { Address } from 'abitype'\n\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { ByteArray, Hex, SignableMessage } from '../../types/misc.js'\nimport { hashMessage } from '../../utils/index.js'\nimport type { HashMessageErrorType } from '../../utils/signature/hashMessage.js'\nimport {\n  type VerifyHashErrorType,\n  type VerifyHashParameters,\n  verifyHash,\n} from './verifyHash.js'\n\nexport type VerifyMessageParameters = Omit<VerifyHashParameters, 'hash'> & {\n  /** The address that signed the original message. */\n  address: Address\n  /** The message to be verified. */\n  message: SignableMessage\n  /** The signature that was generated by signing the message with the address's private key. */\n  signature: Hex | ByteArray\n}\n\nexport type VerifyMessageReturnType = boolean\n\nexport type VerifyMessageErrorType =\n  | HashMessageErrorType\n  | VerifyHashErrorType\n  | ErrorType\n\n/**\n * Verify that a message was signed by the provided address.\n *\n * Compatible with Smart Contract Accounts & Externally Owned Accounts via [ERC-6492](https://eips.ethereum.org/EIPS/eip-6492).\n *\n * - Docs {@link https://viem.sh/docs/actions/public/verifyMessage.html}\n *\n * @param client - Client to use.\n * @param parameters - {@link VerifyMessageParameters}\n * @returns Whether or not the signature is valid. {@link VerifyMessageReturnType}\n */\nexport async function verifyMessage<TChain extends Chain | undefined>(\n  client: Client<Transport, TChain>,\n  { address, message, signature, ...callRequest }: VerifyMessageParameters,\n): Promise<VerifyMessageReturnType> {\n  const hash = hashMessage(message)\n  return verifyHash(client, {\n    address,\n    hash,\n    signature,\n    ...callRequest,\n  })\n}\n","import type { Address, TypedData } from 'abitype'\n\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { ByteArray, Hex } from '../../types/misc.js'\nimport type { TypedDataDefinition } from '../../types/typedData.js'\nimport {\n  type HashTypedDataErrorType,\n  hashTypedData,\n} from '../../utils/signature/hashTypedData.js'\nimport {\n  type VerifyHashErrorType,\n  type VerifyHashParameters,\n  verifyHash,\n} from './verifyHash.js'\n\nexport type VerifyTypedDataParameters<\n  TTypedData extends TypedData | { [key: string]: unknown } = TypedData,\n  TPrimaryType extends string = string,\n> = Omit<VerifyHashParameters, 'hash'> &\n  TypedDataDefinition<TTypedData, TPrimaryType> & {\n    /** The address to verify the typed data for. */\n    address: Address\n    /** The signature to verify */\n    signature: Hex | ByteArray\n  }\n\nexport type VerifyTypedDataReturnType = boolean\n\nexport type VerifyTypedDataErrorType =\n  | HashTypedDataErrorType\n  | VerifyHashErrorType\n  | ErrorType\n\n/**\n * Verify that typed data was signed by the provided address.\n *\n * - Docs {@link https://viem.sh/docs/actions/public/verifyTypedData.html}\n *\n * @param client - Client to use.\n * @param parameters - {@link VerifyTypedDataParameters}\n * @returns Whether or not the signature is valid. {@link VerifyTypedDataReturnType}\n */\nexport async function verifyTypedData<TChain extends Chain | undefined>(\n  client: Client<Transport, TChain>,\n  {\n    address,\n    signature,\n    message,\n    primaryType,\n    types,\n    domain,\n    ...callRequest\n  }: VerifyTypedDataParameters,\n): Promise<VerifyTypedDataReturnType> {\n  const hash = hashTypedData({ message, primaryType, types, domain })\n  return verifyHash(client, {\n    address,\n    hash,\n    signature,\n    ...callRequest,\n  })\n}\n","import type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport { BlockNotFoundError } from '../../errors/block.js'\nimport {\n  TransactionNotFoundError,\n  TransactionReceiptNotFoundError,\n  WaitForTransactionReceiptTimeoutError,\n} from '../../errors/transaction.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Hash } from '../../types/misc.js'\nimport type { Transaction } from '../../types/transaction.js'\nimport { getAction } from '../../utils/getAction.js'\nimport { type ObserveErrorType, observe } from '../../utils/observe.js'\nimport { withRetry } from '../../utils/promise/withRetry.js'\nimport { stringify } from '../../utils/stringify.js'\n\nimport { type GetBlockErrorType, getBlock } from './getBlock.js'\nimport {\n  type GetTransactionErrorType,\n  type GetTransactionReturnType,\n  getTransaction,\n} from './getTransaction.js'\nimport {\n  type GetTransactionReceiptErrorType,\n  type GetTransactionReceiptReturnType,\n  getTransactionReceipt,\n} from './getTransactionReceipt.js'\nimport {\n  type WatchBlockNumberErrorType,\n  watchBlockNumber,\n} from './watchBlockNumber.js'\n\nexport type ReplacementReason = 'cancelled' | 'replaced' | 'repriced'\nexport type ReplacementReturnType<\n  TChain extends Chain | undefined = Chain | undefined,\n> = {\n  reason: ReplacementReason\n  replacedTransaction: Transaction\n  transaction: Transaction\n  transactionReceipt: GetTransactionReceiptReturnType<TChain>\n}\n\nexport type WaitForTransactionReceiptReturnType<\n  TChain extends Chain | undefined = Chain | undefined,\n> = GetTransactionReceiptReturnType<TChain>\n\nexport type WaitForTransactionReceiptParameters<\n  TChain extends Chain | undefined = Chain | undefined,\n> = {\n  /**\n   * The number of confirmations (blocks that have passed) to wait before resolving.\n   * @default 1\n   */\n  confirmations?: number\n  /** The hash of the transaction. */\n  hash: Hash\n  /** Optional callback to emit if the transaction has been replaced. */\n  onReplaced?: (response: ReplacementReturnType<TChain>) => void\n  /**\n   * Polling frequency (in ms). Defaults to the client's pollingInterval config.\n   * @default client.pollingInterval\n   */\n  pollingInterval?: number\n  /** Optional timeout (in milliseconds) to wait before stopping polling. */\n  timeout?: number\n}\n\nexport type WaitForTransactionReceiptErrorType =\n  | ObserveErrorType\n  | GetBlockErrorType\n  | GetTransactionErrorType\n  | GetTransactionReceiptErrorType\n  | WatchBlockNumberErrorType\n  | ErrorType\n\n/**\n * Waits for the [Transaction](https://viem.sh/docs/glossary/terms.html#transaction) to be included on a [Block](https://viem.sh/docs/glossary/terms.html#block) (one confirmation), and then returns the [Transaction Receipt](https://viem.sh/docs/glossary/terms.html#transaction-receipt). If the Transaction reverts, then the action will throw an error.\n *\n * - Docs: https://viem.sh/docs/actions/public/waitForTransactionReceipt.html\n * - Example: https://stackblitz.com/github/wevm/viem/tree/main/examples/transactions/sending-transactions\n * - JSON-RPC Methods:\n *   - Polls [`eth_getTransactionReceipt`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getTransactionReceipt) on each block until it has been processed.\n *   - If a Transaction has been replaced:\n *     - Calls [`eth_getBlockByNumber`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getblockbynumber) and extracts the transactions\n *     - Checks if one of the Transactions is a replacement\n *     - If so, calls [`eth_getTransactionReceipt`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getTransactionReceipt).\n *\n * The `waitForTransactionReceipt` action additionally supports Replacement detection (e.g. sped up Transactions).\n *\n * Transactions can be replaced when a user modifies their transaction in their wallet (to speed up or cancel). Transactions are replaced when they are sent from the same nonce.\n *\n * There are 3 types of Transaction Replacement reasons:\n *\n * - `repriced`: The gas price has been modified (e.g. different `maxFeePerGas`)\n * - `cancelled`: The Transaction has been cancelled (e.g. `value === 0n`)\n * - `replaced`: The Transaction has been replaced (e.g. different `value` or `data`)\n *\n * @param client - Client to use\n * @param parameters - {@link WaitForTransactionReceiptParameters}\n * @returns The transaction receipt. {@link WaitForTransactionReceiptReturnType}\n *\n * @example\n * import { createPublicClient, waitForTransactionReceipt, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n *   chain: mainnet,\n *   transport: http(),\n * })\n * const transactionReceipt = await waitForTransactionReceipt(client, {\n *   hash: '0x4ca7ee652d57678f26e887c149ab0735f41de37bcad58c9f6d3ed5824f15b74d',\n * })\n */\nexport async function waitForTransactionReceipt<\n  TChain extends Chain | undefined,\n>(\n  client: Client<Transport, TChain>,\n  {\n    confirmations = 1,\n    hash,\n    onReplaced,\n    pollingInterval = client.pollingInterval,\n    timeout,\n  }: WaitForTransactionReceiptParameters<TChain>,\n): Promise<WaitForTransactionReceiptReturnType<TChain>> {\n  const observerId = stringify(['waitForTransactionReceipt', client.uid, hash])\n\n  let transaction: GetTransactionReturnType<TChain> | undefined\n  let replacedTransaction: GetTransactionReturnType<TChain> | undefined\n  let receipt: GetTransactionReceiptReturnType<TChain>\n  let retrying = false\n\n  return new Promise((resolve, reject) => {\n    if (timeout)\n      setTimeout(\n        () => reject(new WaitForTransactionReceiptTimeoutError({ hash })),\n        timeout,\n      )\n\n    const _unobserve = observe(\n      observerId,\n      { onReplaced, resolve, reject },\n      (emit) => {\n        const _unwatch = getAction(\n          client,\n          watchBlockNumber,\n          'watchBlockNumber',\n        )({\n          emitMissed: true,\n          emitOnBegin: true,\n          poll: true,\n          pollingInterval,\n          async onBlockNumber(blockNumber_) {\n            if (retrying) return\n\n            let blockNumber = blockNumber_\n\n            const done = (fn: () => void) => {\n              _unwatch()\n              fn()\n              _unobserve()\n            }\n\n            try {\n              // If we already have a valid receipt, let's check if we have enough\n              // confirmations. If we do, then we can resolve.\n              if (receipt) {\n                if (\n                  confirmations > 1 &&\n                  (!receipt.blockNumber ||\n                    blockNumber - receipt.blockNumber + 1n < confirmations)\n                )\n                  return\n\n                done(() => emit.resolve(receipt))\n                return\n              }\n\n              // Get the transaction to check if it's been replaced.\n              // We need to retry as some RPC Providers may be slow to sync\n              // up mined transactions.\n              if (!transaction) {\n                retrying = true\n                await withRetry(\n                  async () => {\n                    transaction = (await getAction(\n                      client,\n                      getTransaction,\n                      'getTransaction',\n                    )({ hash })) as GetTransactionReturnType<TChain>\n                    if (transaction.blockNumber)\n                      blockNumber = transaction.blockNumber\n                  },\n                  {\n                    // exponential backoff\n                    delay: ({ count }) => ~~(1 << count) * 200,\n                    retryCount: 6,\n                  },\n                )\n                retrying = false\n              }\n\n              // Get the receipt to check if it's been processed.\n              receipt = await getAction(\n                client,\n                getTransactionReceipt,\n                'getTransactionReceipt',\n              )({ hash })\n\n              // Check if we have enough confirmations. If not, continue polling.\n              if (\n                confirmations > 1 &&\n                (!receipt.blockNumber ||\n                  blockNumber - receipt.blockNumber + 1n < confirmations)\n              )\n                return\n\n              done(() => emit.resolve(receipt))\n            } catch (err) {\n              // If the receipt is not found, the transaction will be pending.\n              // We need to check if it has potentially been replaced.\n              if (\n                transaction &&\n                (err instanceof TransactionNotFoundError ||\n                  err instanceof TransactionReceiptNotFoundError)\n              ) {\n                try {\n                  replacedTransaction = transaction\n\n                  // Let's retrieve the transactions from the current block.\n                  // We need to retry as some RPC Providers may be slow to sync\n                  // up mined blocks.\n                  retrying = true\n                  const block = await withRetry(\n                    () =>\n                      getAction(\n                        client,\n                        getBlock,\n                        'getBlock',\n                      )({\n                        blockNumber,\n                        includeTransactions: true,\n                      }),\n                    {\n                      // exponential backoff\n                      delay: ({ count }) => ~~(1 << count) * 200,\n                      retryCount: 6,\n                      shouldRetry: ({ error }) =>\n                        error instanceof BlockNotFoundError,\n                    },\n                  )\n                  retrying = false\n\n                  const replacementTransaction = (\n                    block.transactions as {} as Transaction[]\n                  ).find(\n                    ({ from, nonce }) =>\n                      from === replacedTransaction!.from &&\n                      nonce === replacedTransaction!.nonce,\n                  )\n\n                  // If we couldn't find a replacement transaction, continue polling.\n                  if (!replacementTransaction) return\n\n                  // If we found a replacement transaction, return it's receipt.\n                  receipt = await getAction(\n                    client,\n                    getTransactionReceipt,\n                    'getTransactionReceipt',\n                  )({\n                    hash: replacementTransaction.hash,\n                  })\n\n                  // Check if we have enough confirmations. If not, continue polling.\n                  if (\n                    confirmations > 1 &&\n                    (!receipt.blockNumber ||\n                      blockNumber - receipt.blockNumber + 1n < confirmations)\n                  )\n                    return\n\n                  let reason: ReplacementReason = 'replaced'\n                  if (\n                    replacementTransaction.to === replacedTransaction.to &&\n                    replacementTransaction.value === replacedTransaction.value\n                  ) {\n                    reason = 'repriced'\n                  } else if (\n                    replacementTransaction.from === replacementTransaction.to &&\n                    replacementTransaction.value === 0n\n                  ) {\n                    reason = 'cancelled'\n                  }\n\n                  done(() => {\n                    emit.onReplaced?.({\n                      reason,\n                      replacedTransaction: replacedTransaction!,\n                      transaction: replacementTransaction,\n                      transactionReceipt: receipt,\n                    })\n                    emit.resolve(receipt)\n                  })\n                } catch (err_) {\n                  done(() => emit.reject(err_))\n                }\n              } else {\n                done(() => emit.reject(err))\n              }\n            }\n          },\n        })\n      },\n    )\n  })\n}\n","import type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { GetTransportConfig } from '../../types/transport.js'\nimport { hexToBigInt } from '../../utils/encoding/fromHex.js'\nimport { getAction } from '../../utils/getAction.js'\nimport { observe } from '../../utils/observe.js'\nimport { type PollErrorType, poll } from '../../utils/poll.js'\nimport { stringify } from '../../utils/stringify.js'\n\nimport {\n  type GetBlockNumberReturnType,\n  getBlockNumber,\n} from './getBlockNumber.js'\n\nexport type OnBlockNumberParameter = GetBlockNumberReturnType\nexport type OnBlockNumberFn = (\n  blockNumber: OnBlockNumberParameter,\n  prevBlockNumber: OnBlockNumberParameter | undefined,\n) => void\n\nexport type PollOptions = {\n  /** Whether or not to emit the missed block numbers to the callback. */\n  emitMissed?: boolean\n  /** Whether or not to emit the latest block number to the callback when the subscription opens. */\n  emitOnBegin?: boolean\n  /** Polling frequency (in ms). Defaults to Client's pollingInterval config. */\n  pollingInterval?: number\n}\n\nexport type WatchBlockNumberParameters<\n  TTransport extends Transport = Transport,\n> = {\n  /** The callback to call when a new block number is received. */\n  onBlockNumber: OnBlockNumberFn\n  /** The callback to call when an error occurred when trying to get for a new block. */\n  onError?: (error: Error) => void\n} & (GetTransportConfig<TTransport>['type'] extends 'webSocket'\n  ?\n      | {\n          emitMissed?: never\n          emitOnBegin?: never\n          /** Whether or not the WebSocket Transport should poll the JSON-RPC, rather than using `eth_subscribe`. */\n          poll?: false\n          pollingInterval?: never\n        }\n      | (PollOptions & { poll: true })\n  : PollOptions & { poll?: true })\n\nexport type WatchBlockNumberReturnType = () => void\n\nexport type WatchBlockNumberErrorType = PollErrorType | ErrorType\n\n/**\n * Watches and returns incoming block numbers.\n *\n * - Docs: https://viem.sh/docs/actions/public/watchBlockNumber.html\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/blocks/watching-blocks\n * - JSON-RPC Methods:\n *   - When `poll: true`, calls [`eth_blockNumber`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_blocknumber) on a polling interval.\n *   - When `poll: false` & WebSocket Transport, uses a WebSocket subscription via [`eth_subscribe`](https://docs.alchemy.com/reference/eth-subscribe-polygon) and the `\"newHeads\"` event.\n *\n * @param client - Client to use\n * @param parameters - {@link WatchBlockNumberParameters}\n * @returns A function that can be invoked to stop watching for new block numbers. {@link WatchBlockNumberReturnType}\n *\n * @example\n * import { createPublicClient, watchBlockNumber, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n *   chain: mainnet,\n *   transport: http(),\n * })\n * const unwatch = watchBlockNumber(client, {\n *   onBlockNumber: (blockNumber) => console.log(blockNumber),\n * })\n */\nexport function watchBlockNumber<\n  TChain extends Chain | undefined,\n  TTransport extends Transport,\n>(\n  client: Client<TTransport, TChain>,\n  {\n    emitOnBegin = false,\n    emitMissed = false,\n    onBlockNumber,\n    onError,\n    poll: poll_,\n    pollingInterval = client.pollingInterval,\n  }: WatchBlockNumberParameters<TTransport>,\n): WatchBlockNumberReturnType {\n  const enablePolling =\n    typeof poll_ !== 'undefined' ? poll_ : client.transport.type !== 'webSocket'\n\n  let prevBlockNumber: GetBlockNumberReturnType | undefined\n\n  const pollBlockNumber = () => {\n    const observerId = stringify([\n      'watchBlockNumber',\n      client.uid,\n      emitOnBegin,\n      emitMissed,\n      pollingInterval,\n    ])\n\n    return observe(observerId, { onBlockNumber, onError }, (emit) =>\n      poll(\n        async () => {\n          try {\n            const blockNumber = await getAction(\n              client,\n              getBlockNumber,\n              'getBlockNumber',\n            )({ cacheTime: 0 })\n\n            if (prevBlockNumber) {\n              // If the current block number is the same as the previous,\n              // we can skip.\n              if (blockNumber === prevBlockNumber) return\n\n              // If we have missed out on some previous blocks, and the\n              // `emitMissed` flag is truthy, let's emit those blocks.\n              if (blockNumber - prevBlockNumber > 1 && emitMissed) {\n                for (let i = prevBlockNumber + 1n; i < blockNumber; i++) {\n                  emit.onBlockNumber(i, prevBlockNumber)\n                  prevBlockNumber = i\n                }\n              }\n            }\n\n            // If the next block number is greater than the previous,\n            // it is not in the past, and we can emit the new block number.\n            if (!prevBlockNumber || blockNumber > prevBlockNumber) {\n              emit.onBlockNumber(blockNumber, prevBlockNumber)\n              prevBlockNumber = blockNumber\n            }\n          } catch (err) {\n            emit.onError?.(err as Error)\n          }\n        },\n        {\n          emitOnBegin,\n          interval: pollingInterval,\n        },\n      ),\n    )\n  }\n\n  const subscribeBlockNumber = () => {\n    let active = true\n    let unsubscribe = () => (active = false)\n    ;(async () => {\n      try {\n        const { unsubscribe: unsubscribe_ } = await client.transport.subscribe({\n          params: ['newHeads'],\n          onData(data: any) {\n            if (!active) return\n            const blockNumber = hexToBigInt(data.result?.number)\n            onBlockNumber(blockNumber, prevBlockNumber)\n            prevBlockNumber = blockNumber\n          },\n          onError(error: Error) {\n            onError?.(error)\n          },\n        })\n        unsubscribe = unsubscribe_\n        if (!active) unsubscribe()\n      } catch (err) {\n        onError?.(err as Error)\n      }\n    })()\n    return unsubscribe\n  }\n\n  return enablePolling ? pollBlockNumber() : subscribeBlockNumber()\n}\n","import type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { BlockTag } from '../../types/block.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { GetTransportConfig } from '../../types/transport.js'\nimport { formatBlock } from '../../utils/formatters/block.js'\nimport { getAction } from '../../utils/getAction.js'\nimport { observe } from '../../utils/observe.js'\nimport { type PollErrorType, poll } from '../../utils/poll.js'\nimport { type StringifyErrorType, stringify } from '../../utils/stringify.js'\n\nimport { type GetBlockReturnType, getBlock } from './getBlock.js'\n\nexport type OnBlockParameter<\n  TChain extends Chain | undefined = Chain,\n  TIncludeTransactions extends boolean = false,\n  TBlockTag extends BlockTag = 'latest',\n> = GetBlockReturnType<TChain, TIncludeTransactions, TBlockTag>\n\nexport type OnBlock<\n  TChain extends Chain | undefined = Chain,\n  TIncludeTransactions extends boolean = false,\n  TBlockTag extends BlockTag = 'latest',\n> = (\n  block: OnBlockParameter<TChain, TIncludeTransactions, TBlockTag>,\n  prevBlock:\n    | OnBlockParameter<TChain, TIncludeTransactions, TBlockTag>\n    | undefined,\n) => void\n\ntype PollOptions<\n  TIncludeTransactions extends boolean = false,\n  TBlockTag extends BlockTag = 'latest',\n> = {\n  /** The block tag. Defaults to \"latest\". */\n  blockTag?: TBlockTag | BlockTag\n  /** Whether or not to emit the missed blocks to the callback. */\n  emitMissed?: boolean\n  /** Whether or not to emit the block to the callback when the subscription opens. */\n  emitOnBegin?: boolean\n  /** Whether or not to include transaction data in the response. */\n  includeTransactions?: TIncludeTransactions\n  /** Polling frequency (in ms). Defaults to the client's pollingInterval config. */\n  pollingInterval?: number\n}\n\nexport type WatchBlocksParameters<\n  TTransport extends Transport = Transport,\n  TChain extends Chain | undefined = Chain,\n  TIncludeTransactions extends boolean = false,\n  TBlockTag extends BlockTag = 'latest',\n> = {\n  /** The callback to call when a new block is received. */\n  onBlock: OnBlock<TChain, TIncludeTransactions, TBlockTag>\n  /** The callback to call when an error occurred when trying to get for a new block. */\n  onError?: (error: Error) => void\n} & (GetTransportConfig<TTransport>['type'] extends 'webSocket'\n  ?\n      | {\n          blockTag?: never\n          emitMissed?: never\n          emitOnBegin?: never\n          includeTransactions?: never\n          /** Whether or not the WebSocket Transport should poll the JSON-RPC, rather than using `eth_subscribe`. */\n          poll?: false\n          pollingInterval?: never\n        }\n      | (PollOptions<TIncludeTransactions, TBlockTag> & { poll?: true })\n  : PollOptions<TIncludeTransactions, TBlockTag> & { poll?: true })\n\nexport type WatchBlocksReturnType = () => void\n\nexport type WatchBlocksErrorType =\n  | StringifyErrorType\n  | PollErrorType\n  | ErrorType\n\n/**\n * Watches and returns information for incoming blocks.\n *\n * - Docs: https://viem.sh/docs/actions/public/watchBlocks.html\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/blocks/watching-blocks\n * - JSON-RPC Methods:\n *   - When `poll: true`, calls [`eth_getBlockByNumber`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getBlockByNumber) on a polling interval.\n *   - When `poll: false` & WebSocket Transport, uses a WebSocket subscription via [`eth_subscribe`](https://docs.alchemy.com/reference/eth-subscribe-polygon) and the `\"newHeads\"` event.\n *\n * @param client - Client to use\n * @param parameters - {@link WatchBlocksParameters}\n * @returns A function that can be invoked to stop watching for new block numbers. {@link WatchBlocksReturnType}\n *\n * @example\n * import { createPublicClient, watchBlocks, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n *   chain: mainnet,\n *   transport: http(),\n * })\n * const unwatch = watchBlocks(client, {\n *   onBlock: (block) => console.log(block),\n * })\n */\nexport function watchBlocks<\n  TTransport extends Transport,\n  TChain extends Chain | undefined,\n  TIncludeTransactions extends boolean = false,\n  TBlockTag extends BlockTag = 'latest',\n>(\n  client: Client<TTransport, TChain>,\n  {\n    blockTag = 'latest',\n    emitMissed = false,\n    emitOnBegin = false,\n    onBlock,\n    onError,\n    includeTransactions: includeTransactions_,\n    poll: poll_,\n    pollingInterval = client.pollingInterval,\n  }: WatchBlocksParameters<TTransport, TChain, TIncludeTransactions, TBlockTag>,\n): WatchBlocksReturnType {\n  const enablePolling =\n    typeof poll_ !== 'undefined' ? poll_ : client.transport.type !== 'webSocket'\n  const includeTransactions = includeTransactions_ ?? false\n\n  let prevBlock:\n    | GetBlockReturnType<TChain, false | TIncludeTransactions, 'latest'>\n    | undefined\n\n  const pollBlocks = () => {\n    const observerId = stringify([\n      'watchBlocks',\n      client.uid,\n      emitMissed,\n      emitOnBegin,\n      includeTransactions,\n      pollingInterval,\n    ])\n\n    return observe(observerId, { onBlock, onError }, (emit) =>\n      poll(\n        async () => {\n          try {\n            const block = await getAction(\n              client,\n              getBlock,\n              'getBlock',\n            )({\n              blockTag,\n              includeTransactions,\n            })\n            if (block.number && prevBlock?.number) {\n              // If the current block number is the same as the previous,\n              // we can skip.\n              if (block.number === prevBlock.number) return\n\n              // If we have missed out on some previous blocks, and the\n              // `emitMissed` flag is truthy, let's emit those blocks.\n              if (block.number - prevBlock.number > 1 && emitMissed) {\n                for (let i = prevBlock?.number + 1n; i < block.number; i++) {\n                  const block = (await getAction(\n                    client,\n                    getBlock,\n                    'getBlock',\n                  )({\n                    blockNumber: i,\n                    includeTransactions,\n                  })) as GetBlockReturnType<TChain>\n                  emit.onBlock(block as any, prevBlock as any)\n                  prevBlock = block\n                }\n              }\n            }\n\n            if (\n              // If no previous block exists, emit.\n              !prevBlock?.number ||\n              // If the block tag is \"pending\" with no block number, emit.\n              (blockTag === 'pending' && !block?.number) ||\n              // If the next block number is greater than the previous block number, emit.\n              // We don't want to emit blocks in the past.\n              (block.number && block.number > prevBlock.number)\n            ) {\n              emit.onBlock(block as any, prevBlock as any)\n              prevBlock = block as any\n            }\n          } catch (err) {\n            emit.onError?.(err as Error)\n          }\n        },\n        {\n          emitOnBegin,\n          interval: pollingInterval,\n        },\n      ),\n    )\n  }\n\n  const subscribeBlocks = () => {\n    let active = true\n    let unsubscribe = () => (active = false)\n    ;(async () => {\n      try {\n        const { unsubscribe: unsubscribe_ } = await client.transport.subscribe({\n          params: ['newHeads'],\n          onData(data: any) {\n            if (!active) return\n            const format =\n              client.chain?.formatters?.block?.format || formatBlock\n            const block = format(data.result)\n            onBlock(block, prevBlock as any)\n            prevBlock = block\n          },\n          onError(error: Error) {\n            onError?.(error)\n          },\n        })\n        unsubscribe = unsubscribe_\n        if (!active) unsubscribe()\n      } catch (err) {\n        onError?.(err as Error)\n      }\n    })()\n    return unsubscribe\n  }\n\n  return enablePolling ? pollBlocks() : subscribeBlocks()\n}\n","import type { Abi, AbiEvent, Address } from 'abitype'\n\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { Chain } from '../../types/chain.js'\nimport type {\n  MaybeAbiEventName,\n  MaybeExtractEventArgsFromAbi,\n} from '../../types/contract.js'\nimport type { Filter } from '../../types/filter.js'\nimport type { Log } from '../../types/log.js'\nimport type { LogTopic } from '../../types/misc.js'\nimport type { GetTransportConfig } from '../../types/transport.js'\nimport type { EncodeEventTopicsParameters } from '../../utils/index.js'\nimport { type ObserveErrorType, observe } from '../../utils/observe.js'\nimport { poll } from '../../utils/poll.js'\nimport { type StringifyErrorType, stringify } from '../../utils/stringify.js'\n\nimport {\n  DecodeLogDataMismatch,\n  DecodeLogTopicsMismatch,\n} from '../../errors/abi.js'\nimport { InvalidInputRpcError } from '../../errors/rpc.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport { getAction } from '../../utils/getAction.js'\nimport {\n  decodeEventLog,\n  encodeEventTopics,\n  formatLog,\n} from '../../utils/index.js'\nimport {\n  type CreateEventFilterParameters,\n  createEventFilter,\n} from './createEventFilter.js'\nimport { getBlockNumber } from './getBlockNumber.js'\nimport { getFilterChanges } from './getFilterChanges.js'\nimport { type GetLogsParameters, getLogs } from './getLogs.js'\nimport { uninstallFilter } from './uninstallFilter.js'\n\ntype PollOptions = {\n  /**\n   * Whether or not the transaction hashes should be batched on each invocation.\n   * @default true\n   */\n  batch?: boolean\n  /**\n   * Polling frequency (in ms). Defaults to Client's pollingInterval config.\n   * @default client.pollingInterval\n   */\n  pollingInterval?: number\n}\n\nexport type WatchEventOnLogsParameter<\n  TAbiEvent extends AbiEvent | undefined = undefined,\n  TAbiEvents extends\n    | readonly AbiEvent[]\n    | readonly unknown[]\n    | undefined = TAbiEvent extends AbiEvent ? [TAbiEvent] : undefined,\n  TStrict extends boolean | undefined = undefined,\n  TEventName extends string | undefined = MaybeAbiEventName<TAbiEvent>,\n> = Log<bigint, number, false, TAbiEvent, TStrict, TAbiEvents, TEventName>[]\nexport type WatchEventOnLogsFn<\n  TAbiEvent extends AbiEvent | undefined = undefined,\n  TAbiEvents extends\n    | readonly AbiEvent[]\n    | readonly unknown[]\n    | undefined = TAbiEvent extends AbiEvent ? [TAbiEvent] : undefined,\n  TStrict extends boolean | undefined = undefined,\n  _EventName extends string | undefined = MaybeAbiEventName<TAbiEvent>,\n> = (\n  logs: WatchEventOnLogsParameter<TAbiEvent, TAbiEvents, TStrict, _EventName>,\n) => void\n\nexport type WatchEventParameters<\n  TAbiEvent extends AbiEvent | undefined = undefined,\n  TAbiEvents extends\n    | readonly AbiEvent[]\n    | readonly unknown[]\n    | undefined = TAbiEvent extends AbiEvent ? [TAbiEvent] : undefined,\n  TStrict extends boolean | undefined = undefined,\n  _EventName extends string | undefined = MaybeAbiEventName<TAbiEvent>,\n> = {\n  /** The address of the contract. */\n  address?: Address | Address[]\n  /** The callback to call when an error occurred when trying to get for a new block. */\n  onError?: (error: Error) => void\n  /** The callback to call when new event logs are received. */\n  onLogs: WatchEventOnLogsFn<TAbiEvent, TAbiEvents, TStrict, _EventName>\n} & (GetTransportConfig<Transport>['type'] extends 'webSocket'\n  ?\n      | {\n          batch?: never\n          /**\n           * Whether or not the WebSocket Transport should poll the JSON-RPC, rather than using `eth_subscribe`.\n           * @default false\n           */\n          poll?: false\n          pollingInterval?: never\n        }\n      | (PollOptions & {\n          /**\n           * Whether or not the WebSocket Transport should poll the JSON-RPC, rather than using `eth_subscribe`.\n           * @default true\n           */\n          poll?: true\n        })\n  : PollOptions & {\n      poll?: true\n    }) &\n  (\n    | {\n        event: TAbiEvent\n        events?: never\n        args?: MaybeExtractEventArgsFromAbi<TAbiEvents, _EventName>\n        /**\n         * Whether or not the logs must match the indexed/non-indexed arguments on `event`.\n         * @default false\n         */\n        strict?: TStrict\n      }\n    | {\n        event?: never\n        events?: TAbiEvents\n        args?: never\n        /**\n         * Whether or not the logs must match the indexed/non-indexed arguments on `event`.\n         * @default false\n         */\n        strict?: TStrict\n      }\n    | {\n        event?: never\n        events?: never\n        args?: never\n        strict?: never\n      }\n  )\n\nexport type WatchEventReturnType = () => void\n\nexport type WatchEventErrorType =\n  | StringifyErrorType\n  | ObserveErrorType\n  | ErrorType\n\n/**\n * Watches and returns emitted [Event Logs](https://viem.sh/docs/glossary/terms.html#event-log).\n *\n * - Docs: https://viem.sh/docs/actions/public/watchEvent.html\n * - JSON-RPC Methods:\n *   - **RPC Provider supports `eth_newFilter`:**\n *     - Calls [`eth_newFilter`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_newfilter) to create a filter (called on initialize).\n *     - On a polling interval, it will call [`eth_getFilterChanges`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getfilterchanges).\n *   - **RPC Provider does not support `eth_newFilter`:**\n *     - Calls [`eth_getLogs`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getlogs) for each block between the polling interval.\n *\n * This Action will batch up all the Event Logs found within the [`pollingInterval`](https://viem.sh/docs/actions/public/watchEvent.html#pollinginterval-optional), and invoke them via [`onLogs`](https://viem.sh/docs/actions/public/watchEvent.html#onLogs).\n *\n * `watchEvent` will attempt to create an [Event Filter](https://viem.sh/docs/actions/public/createEventFilter.html) and listen to changes to the Filter per polling interval, however, if the RPC Provider does not support Filters (e.g. `eth_newFilter`), then `watchEvent` will fall back to using [`getLogs`](https://viem.sh/docs/actions/public/getLogs.html) instead.\n *\n * @param client - Client to use\n * @param parameters - {@link WatchEventParameters}\n * @returns A function that can be invoked to stop watching for new Event Logs. {@link WatchEventReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { watchEvent } from 'viem/public'\n *\n * const client = createPublicClient({\n *   chain: mainnet,\n *   transport: http(),\n * })\n * const unwatch = watchEvent(client, {\n *   onLogs: (logs) => console.log(logs),\n * })\n */\nexport function watchEvent<\n  TChain extends Chain | undefined,\n  const TAbiEvent extends AbiEvent | undefined = undefined,\n  const TAbiEvents extends\n    | readonly AbiEvent[]\n    | readonly unknown[]\n    | undefined = TAbiEvent extends AbiEvent ? [TAbiEvent] : undefined,\n  TStrict extends boolean | undefined = undefined,\n  _EventName extends string | undefined = undefined,\n>(\n  client: Client<Transport, TChain>,\n  {\n    address,\n    args,\n    batch = true,\n    event,\n    events,\n    onError,\n    onLogs,\n    poll: poll_,\n    pollingInterval = client.pollingInterval,\n    strict: strict_,\n  }: WatchEventParameters<TAbiEvent, TAbiEvents, TStrict>,\n): WatchEventReturnType {\n  const enablePolling =\n    typeof poll_ !== 'undefined' ? poll_ : client.transport.type !== 'webSocket'\n  const strict = strict_ ?? false\n\n  const pollEvent = () => {\n    const observerId = stringify([\n      'watchEvent',\n      address,\n      args,\n      batch,\n      client.uid,\n      event,\n      pollingInterval,\n    ])\n\n    return observe(observerId, { onLogs, onError }, (emit) => {\n      let previousBlockNumber: bigint\n      let filter: Filter<'event', TAbiEvents, _EventName, any>\n      let initialized = false\n\n      const unwatch = poll(\n        async () => {\n          if (!initialized) {\n            try {\n              filter = (await getAction(\n                client,\n                createEventFilter as any,\n                'createEventFilter',\n              )({\n                address,\n                args,\n                event: event!,\n                events,\n                strict,\n              } as unknown as CreateEventFilterParameters)) as unknown as Filter<\n                'event',\n                TAbiEvents,\n                _EventName\n              >\n            } catch {}\n            initialized = true\n            return\n          }\n\n          try {\n            let logs: Log[]\n            if (filter) {\n              logs = await getAction(\n                client,\n                getFilterChanges,\n                'getFilterChanges',\n              )({ filter })\n            } else {\n              // If the filter doesn't exist, we will fall back to use `getLogs`.\n              // The fall back exists because some RPC Providers do not support filters.\n\n              // Fetch the block number to use for `getLogs`.\n              const blockNumber = await getAction(\n                client,\n                getBlockNumber,\n                'getBlockNumber',\n              )({})\n\n              // If the block number has changed, we will need to fetch the logs.\n              // If the block number doesn't exist, we are yet to reach the first poll interval,\n              // so do not emit any logs.\n              if (previousBlockNumber && previousBlockNumber !== blockNumber) {\n                logs = await getAction(\n                  client,\n                  getLogs,\n                  'getLogs',\n                )({\n                  address,\n                  args,\n                  event: event!,\n                  events,\n                  fromBlock: previousBlockNumber + 1n,\n                  toBlock: blockNumber,\n                } as unknown as GetLogsParameters)\n              } else {\n                logs = []\n              }\n              previousBlockNumber = blockNumber\n            }\n\n            if (logs.length === 0) return\n            if (batch) emit.onLogs(logs as any)\n            else for (const log of logs) emit.onLogs([log] as any)\n          } catch (err) {\n            // If a filter has been set and gets uninstalled, providers will throw an InvalidInput error.\n            // Reinitalize the filter when this occurs\n            if (filter && err instanceof InvalidInputRpcError)\n              initialized = false\n            emit.onError?.(err as Error)\n          }\n        },\n        {\n          emitOnBegin: true,\n          interval: pollingInterval,\n        },\n      )\n\n      return async () => {\n        if (filter)\n          await getAction(\n            client,\n            uninstallFilter,\n            'uninstallFilter',\n          )({ filter })\n        unwatch()\n      }\n    })\n  }\n\n  const subscribeEvent = () => {\n    let active = true\n    let unsubscribe = () => (active = false)\n    ;(async () => {\n      try {\n        const events_ = events ?? (event ? [event] : undefined)\n        let topics: LogTopic[] = []\n        if (events_) {\n          topics = [\n            (events_ as AbiEvent[]).flatMap((event) =>\n              encodeEventTopics({\n                abi: [event],\n                eventName: (event as AbiEvent).name,\n                args,\n              } as EncodeEventTopicsParameters),\n            ),\n          ]\n          if (event) topics = topics[0] as LogTopic[]\n        }\n\n        const { unsubscribe: unsubscribe_ } = await client.transport.subscribe({\n          params: ['logs', { address, topics }],\n          onData(data: any) {\n            if (!active) return\n            const log = data.result\n            try {\n              const { eventName, args } = decodeEventLog({\n                abi: events_ as Abi,\n                data: log.data,\n                topics: log.topics as any,\n                strict,\n              })\n              const formatted = formatLog(log, {\n                args,\n                eventName: eventName as string,\n              })\n              onLogs([formatted] as any)\n            } catch (err) {\n              let eventName\n              let isUnnamed\n              if (\n                err instanceof DecodeLogDataMismatch ||\n                err instanceof DecodeLogTopicsMismatch\n              ) {\n                // If strict mode is on, and log data/topics do not match event definition, skip.\n                if (strict_) return\n                eventName = err.abiItem.name\n                isUnnamed = err.abiItem.inputs?.some(\n                  (x) => !('name' in x && x.name),\n                )\n              }\n\n              // Set args to empty if there is an error decoding (e.g. indexed/non-indexed params mismatch).\n              const formatted = formatLog(log, {\n                args: isUnnamed ? [] : {},\n                eventName,\n              })\n              onLogs([formatted] as any)\n            }\n          },\n          onError(error: Error) {\n            onError?.(error)\n          },\n        })\n        unsubscribe = unsubscribe_\n        if (!active) unsubscribe()\n      } catch (err) {\n        onError?.(err as Error)\n      }\n    })()\n    return unsubscribe\n  }\n\n  return enablePolling ? pollEvent() : subscribeEvent()\n}\n","import type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Filter } from '../../types/filter.js'\nimport type { Hash } from '../../types/misc.js'\nimport type { GetTransportConfig } from '../../types/transport.js'\nimport { getAction } from '../../utils/getAction.js'\nimport { type ObserveErrorType, observe } from '../../utils/observe.js'\nimport { poll } from '../../utils/poll.js'\nimport { type StringifyErrorType, stringify } from '../../utils/stringify.js'\n\nimport { createPendingTransactionFilter } from './createPendingTransactionFilter.js'\nimport { getFilterChanges } from './getFilterChanges.js'\nimport { uninstallFilter } from './uninstallFilter.js'\n\nexport type OnTransactionsParameter = Hash[]\nexport type OnTransactionsFn = (transactions: OnTransactionsParameter) => void\n\ntype PollOptions = {\n  /**\n   * Whether or not the transaction hashes should be batched on each invocation.\n   * @default true\n   */\n  batch?: boolean\n  /**\n   * Polling frequency (in ms). Defaults to Client's pollingInterval config.\n   * @default client.pollingInterval\n   */\n  pollingInterval?: number\n}\n\nexport type WatchPendingTransactionsParameters<\n  TTransport extends Transport = Transport,\n> = {\n  /** The callback to call when an error occurred when trying to get for a new block. */\n  onError?: (error: Error) => void\n  /** The callback to call when new transactions are received. */\n  onTransactions: OnTransactionsFn\n} & (GetTransportConfig<TTransport>['type'] extends 'webSocket'\n  ?\n      | {\n          batch?: never\n          /**\n           * Whether or not the WebSocket Transport should poll the JSON-RPC, rather than using `eth_subscribe`.\n           * @default false\n           */\n          poll?: false\n          pollingInterval?: never\n        }\n      | (PollOptions & {\n          /**\n           * Whether or not the WebSocket Transport should poll the JSON-RPC, rather than using `eth_subscribe`.\n           * @default true\n           */\n          poll?: true\n        })\n  : PollOptions & {\n      poll?: true\n    })\n\nexport type WatchPendingTransactionsReturnType = () => void\n\nexport type WatchPendingTransactionsErrorType =\n  | StringifyErrorType\n  | ObserveErrorType\n  | ErrorType\n\n/**\n * Watches and returns pending transaction hashes.\n *\n * - Docs: https://viem.sh/docs/actions/public/watchPendingTransactions.html\n * - JSON-RPC Methods:\n *   - When `poll: true`\n *     - Calls [`eth_newPendingTransactionFilter`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_newpendingtransactionfilter) to initialize the filter.\n *     - Calls [`eth_getFilterChanges`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getFilterChanges) on a polling interval.\n *   - When `poll: false` & WebSocket Transport, uses a WebSocket subscription via [`eth_subscribe`](https://docs.alchemy.com/reference/eth-subscribe-polygon) and the `\"newPendingTransactions\"` event.\n *\n * This Action will batch up all the pending transactions found within the [`pollingInterval`](https://viem.sh/docs/actions/public/watchPendingTransactions.html#pollinginterval-optional), and invoke them via [`onTransactions`](https://viem.sh/docs/actions/public/watchPendingTransactions.html#ontransactions).\n *\n * @param client - Client to use\n * @param parameters - {@link WatchPendingTransactionsParameters}\n * @returns A function that can be invoked to stop watching for new pending transaction hashes. {@link WatchPendingTransactionsReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { watchPendingTransactions } from 'viem/public'\n *\n * const client = createPublicClient({\n *   chain: mainnet,\n *   transport: http(),\n * })\n * const unwatch = await watchPendingTransactions(client, {\n *   onTransactions: (hashes) => console.log(hashes),\n * })\n */\nexport function watchPendingTransactions<\n  TTransport extends Transport,\n  TChain extends Chain | undefined,\n>(\n  client: Client<TTransport, TChain>,\n  {\n    batch = true,\n    onError,\n    onTransactions,\n    poll: poll_,\n    pollingInterval = client.pollingInterval,\n  }: WatchPendingTransactionsParameters<TTransport>,\n) {\n  const enablePolling =\n    typeof poll_ !== 'undefined' ? poll_ : client.transport.type !== 'webSocket'\n\n  const pollPendingTransactions = () => {\n    const observerId = stringify([\n      'watchPendingTransactions',\n      client.uid,\n      batch,\n      pollingInterval,\n    ])\n    return observe(observerId, { onTransactions, onError }, (emit) => {\n      let filter: Filter<'transaction'>\n\n      const unwatch = poll(\n        async () => {\n          try {\n            if (!filter) {\n              try {\n                filter = await getAction(\n                  client,\n                  createPendingTransactionFilter,\n                  'createPendingTransactionFilter',\n                )({})\n                return\n              } catch (err) {\n                unwatch()\n                throw err\n              }\n            }\n\n            const hashes = await getAction(\n              client,\n              getFilterChanges,\n              'getFilterChanges',\n            )({ filter })\n            if (hashes.length === 0) return\n            if (batch) emit.onTransactions(hashes)\n            else for (const hash of hashes) emit.onTransactions([hash])\n          } catch (err) {\n            emit.onError?.(err as Error)\n          }\n        },\n        {\n          emitOnBegin: true,\n          interval: pollingInterval,\n        },\n      )\n\n      return async () => {\n        if (filter)\n          await getAction(\n            client,\n            uninstallFilter,\n            'uninstallFilter',\n          )({ filter })\n        unwatch()\n      }\n    })\n  }\n\n  const subscribePendingTransactions = () => {\n    let active = true\n    let unsubscribe = () => (active = false)\n    ;(async () => {\n      try {\n        const { unsubscribe: unsubscribe_ } = await client.transport.subscribe({\n          params: ['newPendingTransactions'],\n          onData(data: any) {\n            if (!active) return\n            const transaction = data.result\n            onTransactions([transaction])\n          },\n          onError(error: Error) {\n            onError?.(error)\n          },\n        })\n        unsubscribe = unsubscribe_\n        if (!active) unsubscribe()\n      } catch (err) {\n        onError?.(err as Error)\n      }\n    })()\n    return unsubscribe\n  }\n\n  return enablePolling\n    ? pollPendingTransactions()\n    : subscribePendingTransactions()\n}\n","import type { ErrorType } from '../errors/utils.js'\nimport type { Chain } from '../types/chain.js'\nimport type { PublicRpcSchema } from '../types/eip1193.js'\nimport type { Prettify } from '../types/utils.js'\nimport {\n  type Client,\n  type ClientConfig,\n  type CreateClientErrorType,\n  createClient,\n} from './createClient.js'\nimport { type PublicActions, publicActions } from './decorators/public.js'\nimport type { Transport } from './transports/createTransport.js'\n\nexport type PublicClientConfig<\n  transport extends Transport = Transport,\n  chain extends Chain | undefined = Chain | undefined,\n> = Prettify<\n  Pick<\n    ClientConfig<transport, chain>,\n    | 'batch'\n    | 'cacheTime'\n    | 'chain'\n    | 'key'\n    | 'name'\n    | 'pollingInterval'\n    | 'transport'\n  >\n>\n\nexport type PublicClient<\n  transport extends Transport = Transport,\n  chain extends Chain | undefined = Chain | undefined,\n> = Prettify<\n  Client<\n    transport,\n    chain,\n    undefined,\n    PublicRpcSchema,\n    PublicActions<transport, chain>\n  >\n>\n\nexport type CreatePublicClientErrorType = CreateClientErrorType | ErrorType\n\n/**\n * Creates a Public Client with a given [Transport](https://viem.sh/docs/clients/intro.html) configured for a [Chain](https://viem.sh/docs/clients/chains.html).\n *\n * - Docs: https://viem.sh/docs/clients/public.html\n *\n * A Public Client is an interface to \"public\" [JSON-RPC API](https://ethereum.org/en/developers/docs/apis/json-rpc/) methods such as retrieving block numbers, transactions, reading from smart contracts, etc through [Public Actions](/docs/actions/public/introduction).\n *\n * @param config - {@link PublicClientConfig}\n * @returns A Public Client. {@link PublicClient}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createPublicClient({\n *   chain: mainnet,\n *   transport: http(),\n * })\n */\nexport function createPublicClient<\n  transport extends Transport,\n  chain extends Chain | undefined = undefined,\n>(\n  parameters: PublicClientConfig<transport, chain>,\n): PublicClient<transport, chain>\n\nexport function createPublicClient(\n  parameters: PublicClientConfig,\n): PublicClient {\n  const { key = 'public', name = 'Public Client' } = parameters\n  const client = createClient({\n    ...parameters,\n    key,\n    name,\n    type: 'publicClient',\n  })\n  return client.extend(publicActions)\n}\n","import type { Abi } from 'abitype'\n\nimport type { Account } from '../../accounts/types.js'\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { GetChain } from '../../types/chain.js'\nimport type { GetConstructorArgs } from '../../types/contract.js'\nimport type { Hex } from '../../types/misc.js'\nimport type { UnionOmit } from '../../types/utils.js'\nimport { encodeDeployData } from '../../utils/abi/encodeDeployData.js'\n\nimport type { ErrorType } from '../../errors/utils.js'\nimport {\n  type SendTransactionErrorType,\n  type SendTransactionParameters,\n  type SendTransactionReturnType,\n  sendTransaction,\n} from './sendTransaction.js'\n\nexport type DeployContractParameters<\n  TAbi extends Abi | readonly unknown[] = Abi,\n  TChain extends Chain | undefined = Chain | undefined,\n  TAccount extends Account | undefined = Account | undefined,\n  TChainOverride extends Chain | undefined = Chain | undefined,\n> = UnionOmit<\n  SendTransactionParameters<TChain, TAccount, TChainOverride>,\n  'accessList' | 'chain' | 'to' | 'data'\n> & {\n  abi: TAbi\n  bytecode: Hex\n} & GetChain<TChain, TChainOverride> &\n  GetConstructorArgs<TAbi>\n\nexport type DeployContractReturnType = SendTransactionReturnType\n\nexport type DeployContractErrorType = SendTransactionErrorType | ErrorType\n\n/**\n * Deploys a contract to the network, given bytecode and constructor arguments.\n *\n * - Docs: https://viem.sh/docs/contract/deployContract.html\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/contracts/deploying-contracts\n *\n * @param client - Client to use\n * @param parameters - {@link DeployContractParameters}\n * @returns The [Transaction](https://viem.sh/docs/glossary/terms.html#transaction) hash. {@link DeployContractReturnType}\n *\n * @example\n * import { createWalletClient, http } from 'viem'\n * import { privateKeyToAccount } from 'viem/accounts'\n * import { mainnet } from 'viem/chains'\n * import { deployContract } from 'viem/contract'\n *\n * const client = createWalletClient({\n *   account: privateKeyToAccount('0x…'),\n *   chain: mainnet,\n *   transport: http(),\n * })\n * const hash = await deployContract(client, {\n *   abi: [],\n *   account: '0x…,\n *   bytecode: '0x608060405260405161083e38038061083e833981016040819052610...',\n * })\n */\nexport function deployContract<\n  const TAbi extends Abi | readonly unknown[],\n  TChain extends Chain | undefined,\n  TAccount extends Account | undefined,\n  TChainOverride extends Chain | undefined = undefined,\n>(\n  walletClient: Client<Transport, TChain, TAccount>,\n  {\n    abi,\n    args,\n    bytecode,\n    ...request\n  }: DeployContractParameters<TAbi, TChain, TAccount, TChainOverride>,\n): Promise<DeployContractReturnType> {\n  const calldata = encodeDeployData({\n    abi,\n    args,\n    bytecode,\n  } as unknown as DeployContractParameters<\n    TAbi,\n    TChain,\n    TAccount,\n    TChainOverride\n  >)\n  return sendTransaction(walletClient, {\n    ...request,\n    data: calldata,\n  } as unknown as SendTransactionParameters<TChain, TAccount, TChainOverride>)\n}\n","import type { Address } from 'abitype'\n\nimport type { Account } from '../../accounts/types.js'\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport {\n  type ChecksumAddressErrorType,\n  checksumAddress,\n} from '../../utils/address/getAddress.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\n\nexport type GetAddressesReturnType = Address[]\n\nexport type GetAddressesErrorType =\n  | RequestErrorType\n  | ChecksumAddressErrorType\n  | ErrorType\n\n/**\n * Returns a list of account addresses owned by the wallet or client.\n *\n * - Docs: https://viem.sh/docs/actions/wallet/getAddresses.html\n * - JSON-RPC Methods: [`eth_accounts`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_accounts)\n *\n * @param client - Client to use\n * @returns List of account addresses owned by the wallet or client. {@link GetAddressesReturnType}\n *\n * @example\n * import { createWalletClient, custom } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getAddresses } from 'viem/wallet'\n *\n * const client = createWalletClient({\n *   chain: mainnet,\n *   transport: custom(window.ethereum),\n * })\n * const accounts = await getAddresses(client)\n */\nexport async function getAddresses<\n  TChain extends Chain | undefined,\n  TAccount extends Account | undefined = undefined,\n>(\n  client: Client<Transport, TChain, TAccount>,\n): Promise<GetAddressesReturnType> {\n  if (client.account?.type === 'local') return [client.account.address]\n  const addresses = await client.request({ method: 'eth_accounts' })\n  return addresses.map((address) => checksumAddress(address))\n}\n","import type { Account } from '../../accounts/types.js'\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { WalletPermission } from '../../types/eip1193.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\n\nexport type GetPermissionsReturnType = WalletPermission[]\n\nexport type GetPermissionsErrorType = RequestErrorType | ErrorType\n\n/**\n * Gets the wallets current permissions.\n *\n * - Docs: https://viem.sh/docs/actions/wallet/getPermissions.html\n * - JSON-RPC Methods: [`wallet_getPermissions`](https://eips.ethereum.org/EIPS/eip-2255)\n *\n * @param client - Client to use\n * @returns The wallet permissions. {@link GetPermissionsReturnType}\n *\n * @example\n * import { createWalletClient, custom } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getPermissions } from 'viem/wallet'\n *\n * const client = createWalletClient({\n *   chain: mainnet,\n *   transport: custom(window.ethereum),\n * })\n * const permissions = await getPermissions(client)\n */\nexport async function getPermissions<\n  TChain extends Chain | undefined,\n  TAccount extends Account | undefined = undefined,\n>(client: Client<Transport, TChain, TAccount>) {\n  const permissions = await client.request({ method: 'wallet_getPermissions' })\n  return permissions\n}\n","import type { Address } from 'abitype'\n\nimport type { Account } from '../../accounts/types.js'\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport { getAddress } from '../../utils/address/getAddress.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\n\nexport type RequestAddressesReturnType = Address[]\n\nexport type RequestAddressesErrorType = RequestErrorType | ErrorType\n\n/**\n * Requests a list of accounts managed by a wallet.\n *\n * - Docs: https://viem.sh/docs/actions/wallet/requestAddresses.html\n * - JSON-RPC Methods: [`eth_requestAccounts`](https://eips.ethereum.org/EIPS/eip-1102)\n *\n * Sends a request to the wallet, asking for permission to access the user's accounts. After the user accepts the request, it will return a list of accounts (addresses).\n *\n * This API can be useful for dapps that need to access the user's accounts in order to execute transactions or interact with smart contracts.\n *\n * @param client - Client to use\n * @returns List of accounts managed by a wallet {@link RequestAddressesReturnType}\n *\n * @example\n * import { createWalletClient, custom } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { requestAddresses } from 'viem/wallet'\n *\n * const client = createWalletClient({\n *   chain: mainnet,\n *   transport: custom(window.ethereum),\n * })\n * const accounts = await requestAddresses(client)\n */\nexport async function requestAddresses<\n  TChain extends Chain | undefined,\n  TAccount extends Account | undefined = undefined,\n>(\n  client: Client<Transport, TChain, TAccount>,\n): Promise<RequestAddressesReturnType> {\n  const addresses = await client.request({ method: 'eth_requestAccounts' })\n  return addresses.map((address) => getAddress(address))\n}\n","import type { Account } from '../../accounts/types.js'\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { WalletPermission } from '../../types/eip1193.js'\nimport type { Prettify } from '../../types/utils.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\n\nexport type RequestPermissionsParameters = Prettify<\n  {\n    eth_accounts: Record<string, any>\n  } & {\n    [key: string]: Record<string, any>\n  }\n>\nexport type RequestPermissionsReturnType = WalletPermission[]\n\nexport type RequestPermissionsErrorType = RequestErrorType | ErrorType\n\n/**\n * Requests permissions for a wallet.\n *\n * - Docs: https://viem.sh/docs/actions/wallet/requestPermissions.html\n * - JSON-RPC Methods: [`wallet_requestPermissions`](https://eips.ethereum.org/EIPS/eip-2255)\n *\n * @param client - Client to use\n * @param parameters - {@link RequestPermissionsParameters}\n * @returns The wallet permissions. {@link RequestPermissionsReturnType}\n *\n * @example\n * import { createWalletClient, custom } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { requestPermissions } from 'viem/wallet'\n *\n * const client = createWalletClient({\n *   chain: mainnet,\n *   transport: custom(window.ethereum),\n * })\n * const permissions = await requestPermissions(client, {\n *   eth_accounts: {}\n * })\n */\nexport async function requestPermissions<\n  TChain extends Chain | undefined,\n  TAccount extends Account | undefined = undefined,\n>(\n  client: Client<Transport, TChain, TAccount>,\n  permissions: RequestPermissionsParameters,\n) {\n  return client.request({\n    method: 'wallet_requestPermissions',\n    params: [permissions],\n  })\n}\n","import type { Account } from '../../accounts/types.js'\nimport {\n  type ParseAccountErrorType,\n  parseAccount,\n} from '../../accounts/utils/parseAccount.js'\nimport type { SignMessageErrorType as SignMessageErrorType_account } from '../../accounts/utils/signMessage.js'\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport { AccountNotFoundError } from '../../errors/account.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { GetAccountParameter } from '../../types/account.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Hex, SignableMessage } from '../../types/misc.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport {\n  type ToHexErrorType,\n  stringToHex,\n  toHex,\n} from '../../utils/encoding/toHex.js'\n\nexport type SignMessageParameters<\n  TAccount extends Account | undefined = Account | undefined,\n> = GetAccountParameter<TAccount> & {\n  message: SignableMessage\n}\n\nexport type SignMessageReturnType = Hex\n\nexport type SignMessageErrorType =\n  | ParseAccountErrorType\n  | RequestErrorType\n  | SignMessageErrorType_account\n  | ToHexErrorType\n  | ErrorType\n\n/**\n * Calculates an Ethereum-specific signature in [EIP-191 format](https://eips.ethereum.org/EIPS/eip-191): `keccak256(\"\\x19Ethereum Signed Message:\\n\" + len(message) + message))`.\n *\n * - Docs: https://viem.sh/docs/actions/wallet/signMessage.html\n * - JSON-RPC Methods:\n *   - JSON-RPC Accounts: [`personal_sign`](https://docs.metamask.io/guide/signing-data.html#personal-sign)\n *   - Local Accounts: Signs locally. No JSON-RPC request.\n *\n * With the calculated signature, you can:\n * - use [`verifyMessage`](https://viem.sh/docs/utilities/verifyMessage.html) to verify the signature,\n * - use [`recoverMessageAddress`](https://viem.sh/docs/utilities/recoverMessageAddress.html) to recover the signing address from a signature.\n *\n * @param client - Client to use\n * @param parameters - {@link SignMessageParameters}\n * @returns The signed message. {@link SignMessageReturnType}\n *\n * @example\n * import { createWalletClient, custom } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { signMessage } from 'viem/wallet'\n *\n * const client = createWalletClient({\n *   chain: mainnet,\n *   transport: custom(window.ethereum),\n * })\n * const signature = await signMessage(client, {\n *   account: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',\n *   message: 'hello world',\n * })\n *\n * @example\n * // Account Hoisting\n * import { createWalletClient, custom } from 'viem'\n * import { privateKeyToAccount } from 'viem/accounts'\n * import { mainnet } from 'viem/chains'\n * import { signMessage } from 'viem/wallet'\n *\n * const client = createWalletClient({\n *   account: privateKeyToAccount('0x…'),\n *   chain: mainnet,\n *   transport: custom(window.ethereum),\n * })\n * const signature = await signMessage(client, {\n *   message: 'hello world',\n * })\n */\nexport async function signMessage<\n  TChain extends Chain | undefined,\n  TAccount extends Account | undefined,\n>(\n  client: Client<Transport, TChain, TAccount>,\n  {\n    account: account_ = client.account,\n    message,\n  }: SignMessageParameters<TAccount>,\n): Promise<SignMessageReturnType> {\n  if (!account_)\n    throw new AccountNotFoundError({\n      docsPath: '/docs/actions/wallet/signMessage',\n    })\n  const account = parseAccount(account_)\n  if (account.type === 'local') return account.signMessage({ message })\n\n  const message_ = (() => {\n    if (typeof message === 'string') return stringToHex(message)\n    if (message.raw instanceof Uint8Array) return toHex(message.raw)\n    return message.raw\n  })()\n\n  return client.request({\n    method: 'personal_sign',\n    params: [message_, account.address],\n  })\n}\n","import type { Account } from '../../accounts/types.js'\nimport {\n  type ParseAccountErrorType,\n  parseAccount,\n} from '../../accounts/utils/parseAccount.js'\nimport type { SignTransactionErrorType as SignTransactionErrorType_account } from '../../accounts/utils/signTransaction.js'\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport { AccountNotFoundError } from '../../errors/account.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { GetAccountParameter } from '../../types/account.js'\nimport type { Chain, GetChain } from '../../types/chain.js'\nimport { type RpcTransactionRequest } from '../../types/rpc.js'\nimport type {\n  TransactionRequest,\n  TransactionSerializable,\n  TransactionSerialized,\n} from '../../types/transaction.js'\nimport type { UnionOmit } from '../../types/utils.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport {\n  type AssertCurrentChainErrorType,\n  assertCurrentChain,\n} from '../../utils/chain/assertCurrentChain.js'\nimport type { NumberToHexErrorType } from '../../utils/encoding/toHex.js'\nimport {\n  type FormattedTransactionRequest,\n  formatTransactionRequest,\n} from '../../utils/formatters/transactionRequest.js'\nimport { getAction } from '../../utils/getAction.js'\nimport { numberToHex } from '../../utils/index.js'\nimport {\n  type AssertRequestErrorType,\n  assertRequest,\n} from '../../utils/transaction/assertRequest.js'\nimport { type GetChainIdErrorType, getChainId } from '../public/getChainId.js'\n\nexport type SignTransactionParameters<\n  TChain extends Chain | undefined = Chain | undefined,\n  TAccount extends Account | undefined = Account | undefined,\n  TChainOverride extends Chain | undefined = Chain | undefined,\n> = UnionOmit<\n  FormattedTransactionRequest<\n    TChainOverride extends Chain ? TChainOverride : TChain\n  >,\n  'from'\n> &\n  GetAccountParameter<TAccount> &\n  GetChain<TChain, TChainOverride>\n\nexport type SignTransactionReturnType = TransactionSerialized\n\nexport type SignTransactionErrorType =\n  | ParseAccountErrorType\n  | AssertRequestErrorType\n  | GetChainIdErrorType\n  | AssertCurrentChainErrorType\n  | SignTransactionErrorType_account\n  | NumberToHexErrorType\n  | RequestErrorType\n  | ErrorType\n\n/**\n * Signs a transaction.\n *\n * - Docs: https://viem.sh/docs/actions/wallet/signTransaction.html\n * - JSON-RPC Methods:\n *   - JSON-RPC Accounts: [`eth_signTransaction`](https://ethereum.github.io/execution-apis/api-documentation/)\n *   - Local Accounts: Signs locally. No JSON-RPC request.\n *\n * @param args - {@link SignTransactionParameters}\n * @returns The signed serialized tranasction. {@link SignTransactionReturnType}\n *\n * @example\n * import { createWalletClient, custom } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { signTransaction } from 'viem/actions'\n *\n * const client = createWalletClient({\n *   chain: mainnet,\n *   transport: custom(window.ethereum),\n * })\n * const signature = await signTransaction(client, {\n *   account: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',\n *   to: '0x0000000000000000000000000000000000000000',\n *   value: 1n,\n * })\n *\n * @example\n * // Account Hoisting\n * import { createWalletClient, http } from 'viem'\n * import { privateKeyToAccount } from 'viem/accounts'\n * import { mainnet } from 'viem/chains'\n * import { signTransaction } from 'viem/actions'\n *\n * const client = createWalletClient({\n *   account: privateKeyToAccount('0x…'),\n *   chain: mainnet,\n *   transport: custom(window.ethereum),\n * })\n * const signature = await signTransaction(client, {\n *   to: '0x0000000000000000000000000000000000000000',\n *   value: 1n,\n * })\n */\nexport async function signTransaction<\n  TChain extends Chain | undefined,\n  TAccount extends Account | undefined,\n  TChainOverride extends Chain | undefined = undefined,\n>(\n  client: Client<Transport, TChain, TAccount>,\n  args: SignTransactionParameters<TChain, TAccount, TChainOverride>,\n): Promise<SignTransactionReturnType> {\n  const {\n    account: account_ = client.account,\n    chain = client.chain,\n    ...transaction\n  } = args\n\n  if (!account_)\n    throw new AccountNotFoundError({\n      docsPath: '/docs/actions/wallet/signTransaction',\n    })\n  const account = parseAccount(account_)\n\n  assertRequest({\n    account,\n    ...args,\n  })\n\n  const chainId = await getAction(client, getChainId, 'getChainId')({})\n  if (chain !== null)\n    assertCurrentChain({\n      currentChainId: chainId,\n      chain,\n    })\n\n  const formatters = chain?.formatters || client.chain?.formatters\n  const format =\n    formatters?.transactionRequest?.format || formatTransactionRequest\n\n  if (account.type === 'local')\n    return account.signTransaction(\n      {\n        ...transaction,\n        chainId,\n      } as unknown as TransactionSerializable,\n      { serializer: client.chain?.serializers?.transaction },\n    ) as Promise<SignTransactionReturnType>\n\n  return await client.request({\n    method: 'eth_signTransaction',\n    params: [\n      {\n        ...format(transaction as unknown as TransactionRequest),\n        chainId: numberToHex(chainId),\n        from: account.address,\n      } as unknown as RpcTransactionRequest,\n    ],\n  })\n}\n","import type { TypedData } from 'abitype'\n\nimport type { Account } from '../../accounts/types.js'\nimport {\n  type ParseAccountErrorType,\n  parseAccount,\n} from '../../accounts/utils/parseAccount.js'\nimport type { SignTypedDataErrorType as SignTypedDataErrorType_account } from '../../accounts/utils/signTypedData.js'\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport {\n  AccountNotFoundError,\n  type AccountNotFoundErrorType,\n} from '../../errors/account.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { GetAccountParameter } from '../../types/account.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Hex } from '../../types/misc.js'\nimport type { TypedDataDefinition } from '../../types/typedData.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport { type IsHexErrorType, isHex } from '../../utils/data/isHex.js'\nimport { type StringifyErrorType, stringify } from '../../utils/stringify.js'\nimport {\n  type GetTypesForEIP712DomainErrorType,\n  type ValidateTypedDataErrorType,\n  getTypesForEIP712Domain,\n  validateTypedData,\n} from '../../utils/typedData.js'\n\nexport type SignTypedDataParameters<\n  TTypedData extends TypedData | { [key: string]: unknown } = TypedData,\n  TPrimaryType extends string = string,\n  TAccount extends Account | undefined = undefined,\n> = GetAccountParameter<TAccount> &\n  TypedDataDefinition<TTypedData, TPrimaryType>\n\nexport type SignTypedDataReturnType = Hex\n\nexport type SignTypedDataErrorType =\n  | AccountNotFoundErrorType\n  | ParseAccountErrorType\n  | GetTypesForEIP712DomainErrorType\n  | ValidateTypedDataErrorType\n  | StringifyErrorType\n  | SignTypedDataErrorType_account\n  | IsHexErrorType\n  | RequestErrorType\n  | ErrorType\n\n/**\n * Signs typed data and calculates an Ethereum-specific signature in [https://eips.ethereum.org/EIPS/eip-712](https://eips.ethereum.org/EIPS/eip-712): `sign(keccak256(\"\\x19\\x01\" ‖ domainSeparator ‖ hashStruct(message)))`\n *\n * - Docs: https://viem.sh/docs/actions/wallet/signTypedData.html\n * - JSON-RPC Methods:\n *   - JSON-RPC Accounts: [`eth_signTypedData_v4`](https://docs.metamask.io/guide/signing-data.html#signtypeddata-v4)\n *   - Local Accounts: Signs locally. No JSON-RPC request.\n *\n * @param client - Client to use\n * @param parameters - {@link SignTypedDataParameters}\n * @returns The signed data. {@link SignTypedDataReturnType}\n *\n * @example\n * import { createWalletClient, custom } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { signTypedData } from 'viem/wallet'\n *\n * const client = createWalletClient({\n *   chain: mainnet,\n *   transport: custom(window.ethereum),\n * })\n * const signature = await signTypedData(client, {\n *   account: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',\n *   domain: {\n *     name: 'Ether Mail',\n *     version: '1',\n *     chainId: 1,\n *     verifyingContract: '0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC',\n *   },\n *   types: {\n *     Person: [\n *       { name: 'name', type: 'string' },\n *       { name: 'wallet', type: 'address' },\n *     ],\n *     Mail: [\n *       { name: 'from', type: 'Person' },\n *       { name: 'to', type: 'Person' },\n *       { name: 'contents', type: 'string' },\n *     ],\n *   },\n *   primaryType: 'Mail',\n *   message: {\n *     from: {\n *       name: 'Cow',\n *       wallet: '0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826',\n *     },\n *     to: {\n *       name: 'Bob',\n *       wallet: '0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB',\n *     },\n *     contents: 'Hello, Bob!',\n *   },\n * })\n *\n * @example\n * // Account Hoisting\n * import { createWalletClient, http } from 'viem'\n * import { privateKeyToAccount } from 'viem/accounts'\n * import { mainnet } from 'viem/chains'\n * import { signTypedData } from 'viem/wallet'\n *\n * const client = createWalletClient({\n *   account: privateKeyToAccount('0x…'),\n *   chain: mainnet,\n *   transport: http(),\n * })\n * const signature = await signTypedData(client, {\n *   domain: {\n *     name: 'Ether Mail',\n *     version: '1',\n *     chainId: 1,\n *     verifyingContract: '0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC',\n *   },\n *   types: {\n *     Person: [\n *       { name: 'name', type: 'string' },\n *       { name: 'wallet', type: 'address' },\n *     ],\n *     Mail: [\n *       { name: 'from', type: 'Person' },\n *       { name: 'to', type: 'Person' },\n *       { name: 'contents', type: 'string' },\n *     ],\n *   },\n *   primaryType: 'Mail',\n *   message: {\n *     from: {\n *       name: 'Cow',\n *       wallet: '0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826',\n *     },\n *     to: {\n *       name: 'Bob',\n *       wallet: '0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB',\n *     },\n *     contents: 'Hello, Bob!',\n *   },\n * })\n */\nexport async function signTypedData<\n  const TTypedData extends TypedData | { [key: string]: unknown },\n  TPrimaryType extends string,\n  TChain extends Chain | undefined,\n  TAccount extends Account | undefined,\n>(\n  client: Client<Transport, TChain, TAccount>,\n  {\n    account: account_ = client.account,\n    domain,\n    message,\n    primaryType,\n    types: types_,\n  }: SignTypedDataParameters<TTypedData, TPrimaryType, TAccount>,\n): Promise<SignTypedDataReturnType> {\n  if (!account_)\n    throw new AccountNotFoundError({\n      docsPath: '/docs/actions/wallet/signTypedData',\n    })\n  const account = parseAccount(account_)\n\n  const types = {\n    EIP712Domain: getTypesForEIP712Domain({ domain }),\n    ...(types_ as TTypedData),\n  }\n\n  // Need to do a runtime validation check on addresses, byte ranges, integer ranges, etc\n  // as we can't statically check this with TypeScript.\n  validateTypedData({\n    domain,\n    message,\n    primaryType,\n    types,\n  } as TypedDataDefinition)\n\n  if (account.type === 'local')\n    return account.signTypedData({\n      domain,\n      primaryType,\n      types,\n      message,\n    } as TypedDataDefinition)\n\n  const typedData = stringify(\n    { domain: domain ?? {}, primaryType, types, message },\n    (_, value) => (isHex(value) ? value.toLowerCase() : value),\n  )\n  return client.request({\n    method: 'eth_signTypedData_v4',\n    params: [account.address, typedData],\n  })\n}\n","import type { Account } from '../../accounts/types.js'\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport {\n  type NumberToHexErrorType,\n  numberToHex,\n} from '../../utils/encoding/toHex.js'\n\nexport type SwitchChainParameters = {\n  /** ID of Chain to switch to */\n  id: Chain['id']\n}\n\nexport type SwitchChainErrorType =\n  | NumberToHexErrorType\n  | RequestErrorType\n  | ErrorType\n\n/**\n * Switch the target chain in a wallet.\n *\n * - Docs: https://viem.sh/docs/actions/wallet/switchChain.html\n * - JSON-RPC Methods: [`eth_switchEthereumChain`](https://eips.ethereum.org/EIPS/eip-3326)\n *\n * @param client - Client to use\n * @param parameters - {@link SwitchChainParameters}\n *\n * @example\n * import { createWalletClient, custom } from 'viem'\n * import { mainnet, optimism } from 'viem/chains'\n * import { switchChain } from 'viem/wallet'\n *\n * const client = createWalletClient({\n *   chain: mainnet,\n *   transport: custom(window.ethereum),\n * })\n * await switchChain(client, { id: optimism.id })\n */\nexport async function switchChain<\n  TChain extends Chain | undefined,\n  TAccount extends Account | undefined = undefined,\n>(client: Client<Transport, TChain, TAccount>, { id }: SwitchChainParameters) {\n  await client.request({\n    method: 'wallet_switchEthereumChain',\n    params: [\n      {\n        chainId: numberToHex(id),\n      },\n    ],\n  })\n}\n","import type { Account } from '../../accounts/types.js'\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { WatchAssetParams } from '../../types/eip1193.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\n\nexport type WatchAssetParameters = WatchAssetParams\nexport type WatchAssetReturnType = boolean\nexport type WatchAssetErrorType = RequestErrorType | ErrorType\n\n/**\n * Adds an EVM chain to the wallet.\n *\n * - Docs: https://viem.sh/docs/actions/wallet/watchAsset.html\n * - JSON-RPC Methods: [`eth_switchEthereumChain`](https://eips.ethereum.org/EIPS/eip-747)\n *\n * @param client - Client to use\n * @param parameters - {@link WatchAssetParameters}\n * @returns Boolean indicating if the token was successfully added. {@link WatchAssetReturnType}\n *\n * @example\n * import { createWalletClient, custom } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { watchAsset } from 'viem/wallet'\n *\n * const client = createWalletClient({\n *   chain: mainnet,\n *   transport: custom(window.ethereum),\n * })\n * const success = await watchAsset(client, {\n *   type: 'ERC20',\n *   options: {\n *     address: '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2',\n *     decimals: 18,\n *     symbol: 'WETH',\n *   },\n * })\n */\nexport async function watchAsset<\n  TChain extends Chain | undefined,\n  TAccount extends Account | undefined = undefined,\n>(\n  client: Client<Transport, TChain, TAccount>,\n  params: WatchAssetParameters,\n): Promise<WatchAssetReturnType> {\n  const added = await client.request({\n    method: 'wallet_watchAsset',\n    params,\n  })\n  return added\n}\n","import type { Abi, TypedData } from 'abitype'\n\nimport type { Account } from '../../accounts/types.js'\nimport {\n  type GetChainIdReturnType,\n  getChainId,\n} from '../../actions/public/getChainId.js'\nimport {\n  type AddChainParameters,\n  addChain,\n} from '../../actions/wallet/addChain.js'\nimport {\n  type DeployContractParameters,\n  type DeployContractReturnType,\n  deployContract,\n} from '../../actions/wallet/deployContract.js'\nimport {\n  type GetAddressesReturnType,\n  getAddresses,\n} from '../../actions/wallet/getAddresses.js'\nimport {\n  type GetPermissionsReturnType,\n  getPermissions,\n} from '../../actions/wallet/getPermissions.js'\nimport {\n  type PrepareTransactionRequestParameters,\n  type PrepareTransactionRequestReturnType,\n  prepareTransactionRequest,\n} from '../../actions/wallet/prepareTransactionRequest.js'\nimport {\n  type RequestAddressesReturnType,\n  requestAddresses,\n} from '../../actions/wallet/requestAddresses.js'\nimport {\n  type RequestPermissionsParameters,\n  type RequestPermissionsReturnType,\n  requestPermissions,\n} from '../../actions/wallet/requestPermissions.js'\nimport {\n  type SendRawTransactionParameters,\n  type SendRawTransactionReturnType,\n  sendRawTransaction,\n} from '../../actions/wallet/sendRawTransaction.js'\nimport {\n  type SendTransactionParameters,\n  type SendTransactionReturnType,\n  sendTransaction,\n} from '../../actions/wallet/sendTransaction.js'\nimport {\n  type SignMessageParameters,\n  type SignMessageReturnType,\n  signMessage,\n} from '../../actions/wallet/signMessage.js'\nimport {\n  type SignTransactionParameters,\n  type SignTransactionReturnType,\n  signTransaction,\n} from '../../actions/wallet/signTransaction.js'\nimport {\n  type SignTypedDataParameters,\n  type SignTypedDataReturnType,\n  signTypedData,\n} from '../../actions/wallet/signTypedData.js'\nimport {\n  type SwitchChainParameters,\n  switchChain,\n} from '../../actions/wallet/switchChain.js'\nimport {\n  type WatchAssetParameters,\n  type WatchAssetReturnType,\n  watchAsset,\n} from '../../actions/wallet/watchAsset.js'\nimport {\n  type WriteContractParameters,\n  type WriteContractReturnType,\n  writeContract,\n} from '../../actions/wallet/writeContract.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Client } from '../createClient.js'\nimport type { Transport } from '../transports/createTransport.js'\n\nexport type WalletActions<\n  TChain extends Chain | undefined = Chain | undefined,\n  TAccount extends Account | undefined = Account | undefined,\n> = {\n  /**\n   * Adds an EVM chain to the wallet.\n   *\n   * - Docs: https://viem.sh/docs/actions/wallet/addChain.html\n   * - JSON-RPC Methods: [`eth_addEthereumChain`](https://eips.ethereum.org/EIPS/eip-3085)\n   *\n   * @param args - {@link AddChainParameters}\n   *\n   * @example\n   * import { createWalletClient, custom } from 'viem'\n   * import { optimism } from 'viem/chains'\n   *\n   * const client = createWalletClient({\n   *   transport: custom(window.ethereum),\n   * })\n   * await client.addChain({ chain: optimism })\n   */\n  addChain: (args: AddChainParameters) => Promise<void>\n  /**\n   * Deploys a contract to the network, given bytecode and constructor arguments.\n   *\n   * - Docs: https://viem.sh/docs/contract/deployContract.html\n   * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/contracts/deploying-contracts\n   *\n   * @param args - {@link DeployContractParameters}\n   * @returns The [Transaction](https://viem.sh/docs/glossary/terms.html#transaction) hash. {@link DeployContractReturnType}\n   *\n   * @example\n   * import { createWalletClient, http } from 'viem'\n   * import { privateKeyToAccount } from 'viem/accounts'\n   * import { mainnet } from 'viem/chains'\n   *\n   * const client = createWalletClient({\n   *   account: privateKeyToAccount('0x…'),\n   *   chain: mainnet,\n   *   transport: http(),\n   * })\n   * const hash = await client.deployContract({\n   *   abi: [],\n   *   account: '0x…,\n   *   bytecode: '0x608060405260405161083e38038061083e833981016040819052610...',\n   * })\n   */\n  deployContract: <\n    const TAbi extends Abi | readonly unknown[],\n    TChainOverride extends Chain | undefined = undefined,\n  >(\n    args: DeployContractParameters<TAbi, TChain, TAccount, TChainOverride>,\n  ) => Promise<DeployContractReturnType>\n  /**\n   * Returns a list of account addresses owned by the wallet or client.\n   *\n   * - Docs: https://viem.sh/docs/actions/wallet/getAddresses.html\n   * - JSON-RPC Methods: [`eth_accounts`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_accounts)\n   *\n   * @returns List of account addresses owned by the wallet or client. {@link GetAddressesReturnType}\n   *\n   * @example\n   * import { createWalletClient, custom } from 'viem'\n   * import { mainnet } from 'viem/chains'\n   *\n   * const client = createWalletClient({\n   *   chain: mainnet,\n   *   transport: custom(window.ethereum),\n   * })\n   * const accounts = await client.getAddresses()\n   */\n  getAddresses: () => Promise<GetAddressesReturnType>\n  /**\n   * Returns the chain ID associated with the current network.\n   *\n   * - Docs: https://viem.sh/docs/actions/public/getChainId.html\n   * - JSON-RPC Methods: [`eth_chainId`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_chainid)\n   *\n   * @returns The current chain ID. {@link GetChainIdReturnType}\n   *\n   * @example\n   * import { createWalletClient, http } from 'viem'\n   * import { mainnet } from 'viem/chains'\n   *\n   * const client = createWalletClient({\n   *   chain: mainnet,\n   *   transport: custom(window.ethereum),\n   * })\n   * const chainId = await client.getChainId()\n   * // 1\n   */\n  getChainId: () => Promise<GetChainIdReturnType>\n  /**\n   * Gets the wallets current permissions.\n   *\n   * - Docs: https://viem.sh/docs/actions/wallet/getPermissions.html\n   * - JSON-RPC Methods: [`wallet_getPermissions`](https://eips.ethereum.org/EIPS/eip-2255)\n   *\n   * @returns The wallet permissions. {@link GetPermissionsReturnType}\n   *\n   * @example\n   * import { createWalletClient, custom } from 'viem'\n   * import { mainnet } from 'viem/chains'\n   *\n   * const client = createWalletClient({\n   *   chain: mainnet,\n   *   transport: custom(window.ethereum),\n   * })\n   * const permissions = await client.getPermissions()\n   */\n  getPermissions: () => Promise<GetPermissionsReturnType>\n  /**\n   * Prepares a transaction request for signing.\n   *\n   * - Docs: https://viem.sh/docs/actions/wallet/prepareTransactionRequest.html\n   *\n   * @param args - {@link PrepareTransactionRequestParameters}\n   * @returns The transaction request. {@link PrepareTransactionRequestReturnType}\n   *\n   * @example\n   * import { createWalletClient, custom } from 'viem'\n   * import { mainnet } from 'viem/chains'\n   *\n   * const client = createWalletClient({\n   *   chain: mainnet,\n   *   transport: custom(window.ethereum),\n   * })\n   * const request = await client.prepareTransactionRequest({\n   *   account: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',\n   *   to: '0x0000000000000000000000000000000000000000',\n   *   value: 1n,\n   * })\n   *\n   * @example\n   * // Account Hoisting\n   * import { createWalletClient, http } from 'viem'\n   * import { privateKeyToAccount } from 'viem/accounts'\n   * import { mainnet } from 'viem/chains'\n   *\n   * const client = createWalletClient({\n   *   account: privateKeyToAccount('0x…'),\n   *   chain: mainnet,\n   *   transport: custom(window.ethereum),\n   * })\n   * const request = await client.prepareTransactionRequest({\n   *   to: '0x0000000000000000000000000000000000000000',\n   *   value: 1n,\n   * })\n   */\n  prepareTransactionRequest: <\n    TChainOverride extends Chain | undefined = undefined,\n  >(\n    args: PrepareTransactionRequestParameters<TChain, TAccount, TChainOverride>,\n  ) => Promise<PrepareTransactionRequestReturnType>\n  /**\n   * Requests a list of accounts managed by a wallet.\n   *\n   * - Docs: https://viem.sh/docs/actions/wallet/requestAddresses.html\n   * - JSON-RPC Methods: [`eth_requestAccounts`](https://eips.ethereum.org/EIPS/eip-1102)\n   *\n   * Sends a request to the wallet, asking for permission to access the user's accounts. After the user accepts the request, it will return a list of accounts (addresses).\n   *\n   * This API can be useful for dapps that need to access the user's accounts in order to execute transactions or interact with smart contracts.\n   *\n   * @returns List of accounts managed by a wallet {@link RequestAddressesReturnType}\n   *\n   * @example\n   * import { createWalletClient, custom } from 'viem'\n   * import { mainnet } from 'viem/chains'\n   *\n   * const client = createWalletClient({\n   *   chain: mainnet,\n   *   transport: custom(window.ethereum),\n   * })\n   * const accounts = await client.requestAddresses()\n   */\n  requestAddresses: () => Promise<RequestAddressesReturnType>\n  /**\n   * Requests permissions for a wallet.\n   *\n   * - Docs: https://viem.sh/docs/actions/wallet/requestPermissions.html\n   * - JSON-RPC Methods: [`wallet_requestPermissions`](https://eips.ethereum.org/EIPS/eip-2255)\n   *\n   * @param args - {@link RequestPermissionsParameters}\n   * @returns The wallet permissions. {@link RequestPermissionsReturnType}\n   *\n   * @example\n   * import { createWalletClient, custom } from 'viem'\n   * import { mainnet } from 'viem/chains'\n   *\n   * const client = createWalletClient({\n   *   chain: mainnet,\n   *   transport: custom(window.ethereum),\n   * })\n   * const permissions = await client.requestPermissions({\n   *   eth_accounts: {}\n   * })\n   */\n  requestPermissions: (\n    args: RequestPermissionsParameters,\n  ) => Promise<RequestPermissionsReturnType>\n  /**\n   * Sends a **signed** transaction to the network\n   *\n   * - Docs: https://viem.sh/docs/actions/wallet/sendRawTransaction.html\n   * - JSON-RPC Method: [`eth_sendRawTransaction`](https://ethereum.github.io/execution-apis/api-documentation/)\n   *\n   * @param client - Client to use\n   * @param parameters - {@link SendRawTransactionParameters}\n   * @returns The transaction hash. {@link SendRawTransactionReturnType}\n   *\n   * @example\n   * import { createWalletClient, custom } from 'viem'\n   * import { mainnet } from 'viem/chains'\n   * import { sendRawTransaction } from 'viem/wallet'\n   *\n   * const client = createWalletClient({\n   *   chain: mainnet,\n   *   transport: custom(window.ethereum),\n   * })\n   *\n   * const hash = await client.sendRawTransaction({\n   *   serializedTransaction: '0x02f850018203118080825208808080c080a04012522854168b27e5dc3d5839bab5e6b39e1a0ffd343901ce1622e3d64b48f1a04e00902ae0502c4728cbf12156290df99c3ed7de85b1dbfe20b5c36931733a33'\n   * })\n   */\n  sendRawTransaction: (\n    args: SendRawTransactionParameters,\n  ) => Promise<SendRawTransactionReturnType>\n  /**\n   * Creates, signs, and sends a new transaction to the network.\n   *\n   * - Docs: https://viem.sh/docs/actions/wallet/sendTransaction.html\n   * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/transactions/sending-transactions\n   * - JSON-RPC Methods:\n   *   - JSON-RPC Accounts: [`eth_sendTransaction`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_sendtransaction)\n   *   - Local Accounts: [`eth_sendRawTransaction`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_sendrawtransaction)\n   *\n   * @param args - {@link SendTransactionParameters}\n   * @returns The [Transaction](https://viem.sh/docs/glossary/terms.html#transaction) hash. {@link SendTransactionReturnType}\n   *\n   * @example\n   * import { createWalletClient, custom } from 'viem'\n   * import { mainnet } from 'viem/chains'\n   *\n   * const client = createWalletClient({\n   *   chain: mainnet,\n   *   transport: custom(window.ethereum),\n   * })\n   * const hash = await client.sendTransaction({\n   *   account: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',\n   *   to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',\n   *   value: 1000000000000000000n,\n   * })\n   *\n   * @example\n   * // Account Hoisting\n   * import { createWalletClient, http } from 'viem'\n   * import { privateKeyToAccount } from 'viem/accounts'\n   * import { mainnet } from 'viem/chains'\n   *\n   * const client = createWalletClient({\n   *   account: privateKeyToAccount('0x…'),\n   *   chain: mainnet,\n   *   transport: http(),\n   * })\n   * const hash = await client.sendTransaction({\n   *   to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',\n   *   value: 1000000000000000000n,\n   * })\n   */\n  sendTransaction: <TChainOverride extends Chain | undefined = undefined>(\n    args: SendTransactionParameters<TChain, TAccount, TChainOverride>,\n  ) => Promise<SendTransactionReturnType>\n  /**\n   * Calculates an Ethereum-specific signature in [EIP-191 format](https://eips.ethereum.org/EIPS/eip-191): `keccak256(\"\\x19Ethereum Signed Message:\\n\" + len(message) + message))`.\n   *\n   * - Docs: https://viem.sh/docs/actions/wallet/signMessage.html\n   * - JSON-RPC Methods:\n   *   - JSON-RPC Accounts: [`personal_sign`](https://docs.metamask.io/guide/signing-data.html#personal-sign)\n   *   - Local Accounts: Signs locally. No JSON-RPC request.\n   *\n   * With the calculated signature, you can:\n   * - use [`verifyMessage`](https://viem.sh/docs/utilities/verifyMessage.html) to verify the signature,\n   * - use [`recoverMessageAddress`](https://viem.sh/docs/utilities/recoverMessageAddress.html) to recover the signing address from a signature.\n   *\n   * @param args - {@link SignMessageParameters}\n   * @returns The signed message. {@link SignMessageReturnType}\n   *\n   * @example\n   * import { createWalletClient, custom } from 'viem'\n   * import { mainnet } from 'viem/chains'\n   *\n   * const client = createWalletClient({\n   *   chain: mainnet,\n   *   transport: custom(window.ethereum),\n   * })\n   * const signature = await client.signMessage({\n   *   account: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',\n   *   message: 'hello world',\n   * })\n   *\n   * @example\n   * // Account Hoisting\n   * import { createWalletClient, http } from 'viem'\n   * import { privateKeyToAccount } from 'viem/accounts'\n   * import { mainnet } from 'viem/chains'\n   *\n   * const client = createWalletClient({\n   *   account: privateKeyToAccount('0x…'),\n   *   chain: mainnet,\n   *   transport: http(),\n   * })\n   * const signature = await client.signMessage({\n   *   message: 'hello world',\n   * })\n   */\n  signMessage: (\n    args: SignMessageParameters<TAccount>,\n  ) => Promise<SignMessageReturnType>\n  /**\n   * Signs a transaction.\n   *\n   * - Docs: https://viem.sh/docs/actions/wallet/signTransaction.html\n   * - JSON-RPC Methods:\n   *   - JSON-RPC Accounts: [`eth_signTransaction`](https://ethereum.github.io/execution-apis/api-documentation/)\n   *   - Local Accounts: Signs locally. No JSON-RPC request.\n   *\n   * @param args - {@link SignTransactionParameters}\n   * @returns The signed message. {@link SignTransactionReturnType}\n   *\n   * @example\n   * import { createWalletClient, custom } from 'viem'\n   * import { mainnet } from 'viem/chains'\n   *\n   * const client = createWalletClient({\n   *   chain: mainnet,\n   *   transport: custom(window.ethereum),\n   * })\n   * const request = await client.prepareTransactionRequest({\n   *   account: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',\n   *   to: '0x0000000000000000000000000000000000000000',\n   *   value: 1n,\n   * })\n   * const signature = await client.signTransaction(request)\n   *\n   * @example\n   * // Account Hoisting\n   * import { createWalletClient, http } from 'viem'\n   * import { privateKeyToAccount } from 'viem/accounts'\n   * import { mainnet } from 'viem/chains'\n   *\n   * const client = createWalletClient({\n   *   account: privateKeyToAccount('0x…'),\n   *   chain: mainnet,\n   *   transport: custom(window.ethereum),\n   * })\n   * const request = await client.prepareTransactionRequest({\n   *   to: '0x0000000000000000000000000000000000000000',\n   *   value: 1n,\n   * })\n   * const signature = await client.signTransaction(request)\n   */\n  signTransaction: <TChainOverride extends Chain | undefined = undefined>(\n    args: SignTransactionParameters<TChain, TAccount, TChainOverride>,\n  ) => Promise<SignTransactionReturnType>\n  /**\n   * Signs typed data and calculates an Ethereum-specific signature in [EIP-191 format](https://eips.ethereum.org/EIPS/eip-191): `keccak256(\"\\x19Ethereum Signed Message:\\n\" + len(message) + message))`.\n   *\n   * - Docs: https://viem.sh/docs/actions/wallet/signTypedData.html\n   * - JSON-RPC Methods:\n   *   - JSON-RPC Accounts: [`eth_signTypedData_v4`](https://docs.metamask.io/guide/signing-data.html#signtypeddata-v4)\n   *   - Local Accounts: Signs locally. No JSON-RPC request.\n   *\n   * @param client - Client to use\n   * @param args - {@link SignTypedDataParameters}\n   * @returns The signed data. {@link SignTypedDataReturnType}\n   *\n   * @example\n   * import { createWalletClient, custom } from 'viem'\n   * import { mainnet } from 'viem/chains'\n   *\n   * const client = createWalletClient({\n   *   chain: mainnet,\n   *   transport: custom(window.ethereum),\n   * })\n   * const signature = await client.signTypedData({\n   *   account: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',\n   *   domain: {\n   *     name: 'Ether Mail',\n   *     version: '1',\n   *     chainId: 1,\n   *     verifyingContract: '0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC',\n   *   },\n   *   types: {\n   *     Person: [\n   *       { name: 'name', type: 'string' },\n   *       { name: 'wallet', type: 'address' },\n   *     ],\n   *     Mail: [\n   *       { name: 'from', type: 'Person' },\n   *       { name: 'to', type: 'Person' },\n   *       { name: 'contents', type: 'string' },\n   *     ],\n   *   },\n   *   primaryType: 'Mail',\n   *   message: {\n   *     from: {\n   *       name: 'Cow',\n   *       wallet: '0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826',\n   *     },\n   *     to: {\n   *       name: 'Bob',\n   *       wallet: '0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB',\n   *     },\n   *     contents: 'Hello, Bob!',\n   *   },\n   * })\n   *\n   * @example\n   * // Account Hoisting\n   * import { createWalletClient, http } from 'viem'\n   * import { privateKeyToAccount } from 'viem/accounts'\n   * import { mainnet } from 'viem/chains'\n   *\n   * const client = createWalletClient({\n   *   account: privateKeyToAccount('0x…'),\n   *   chain: mainnet,\n   *   transport: http(),\n   * })\n   * const signature = await client.signTypedData({\n   *   domain: {\n   *     name: 'Ether Mail',\n   *     version: '1',\n   *     chainId: 1,\n   *     verifyingContract: '0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC',\n   *   },\n   *   types: {\n   *     Person: [\n   *       { name: 'name', type: 'string' },\n   *       { name: 'wallet', type: 'address' },\n   *     ],\n   *     Mail: [\n   *       { name: 'from', type: 'Person' },\n   *       { name: 'to', type: 'Person' },\n   *       { name: 'contents', type: 'string' },\n   *     ],\n   *   },\n   *   primaryType: 'Mail',\n   *   message: {\n   *     from: {\n   *       name: 'Cow',\n   *       wallet: '0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826',\n   *     },\n   *     to: {\n   *       name: 'Bob',\n   *       wallet: '0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB',\n   *     },\n   *     contents: 'Hello, Bob!',\n   *   },\n   * })\n   */\n  signTypedData: <\n    const TTypedData extends TypedData | { [key: string]: unknown },\n    TPrimaryType extends string,\n  >(\n    args: SignTypedDataParameters<TTypedData, TPrimaryType, TAccount>,\n  ) => Promise<SignTypedDataReturnType>\n  /**\n   * Switch the target chain in a wallet.\n   *\n   * - Docs: https://viem.sh/docs/actions/wallet/switchChain.html\n   * - JSON-RPC Methods: [`eth_switchEthereumChain`](https://eips.ethereum.org/EIPS/eip-3326)\n   *\n   * @param args - {@link SwitchChainParameters}\n   *\n   * @example\n   * import { createWalletClient, custom } from 'viem'\n   * import { mainnet, optimism } from 'viem/chains'\n   *\n   * const client = createWalletClient({\n   *   chain: mainnet,\n   *   transport: custom(window.ethereum),\n   * })\n   * await client.switchChain({ id: optimism.id })\n   */\n  switchChain: (args: SwitchChainParameters) => Promise<void>\n  /**\n   * Adds an EVM chain to the wallet.\n   *\n   * - Docs: https://viem.sh/docs/actions/wallet/watchAsset.html\n   * - JSON-RPC Methods: [`eth_switchEthereumChain`](https://eips.ethereum.org/EIPS/eip-747)\n   *\n   * @param args - {@link WatchAssetParameters}\n   * @returns Boolean indicating if the token was successfully added. {@link WatchAssetReturnType}\n   *\n   * @example\n   * import { createWalletClient, custom } from 'viem'\n   * import { mainnet } from 'viem/chains'\n   *\n   * const client = createWalletClient({\n   *   chain: mainnet,\n   *   transport: custom(window.ethereum),\n   * })\n   * const success = await client.watchAsset({\n   *   type: 'ERC20',\n   *   options: {\n   *     address: '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2',\n   *     decimals: 18,\n   *     symbol: 'WETH',\n   *   },\n   * })\n   */\n  watchAsset: (args: WatchAssetParameters) => Promise<WatchAssetReturnType>\n  /**\n   * Executes a write function on a contract.\n   *\n   * - Docs: https://viem.sh/docs/contract/writeContract.html\n   * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/contracts/writing-to-contracts\n   *\n   * A \"write\" function on a Solidity contract modifies the state of the blockchain. These types of functions require gas to be executed, and hence a [Transaction](https://viem.sh/docs/glossary/terms.html) is needed to be broadcast in order to change the state.\n   *\n   * Internally, uses a [Wallet Client](https://viem.sh/docs/clients/wallet.html) to call the [`sendTransaction` action](https://viem.sh/docs/actions/wallet/sendTransaction.html) with [ABI-encoded `data`](https://viem.sh/docs/contract/encodeFunctionData.html).\n   *\n   * __Warning: The `write` internally sends a transaction – it does not validate if the contract write will succeed (the contract may throw an error). It is highly recommended to [simulate the contract write with `contract.simulate`](https://viem.sh/docs/contract/writeContract.html#usage) before you execute it.__\n   *\n   * @param args - {@link WriteContractParameters}\n   * @returns A [Transaction Hash](https://viem.sh/docs/glossary/terms.html#hash). {@link WriteContractReturnType}\n   *\n   * @example\n   * import { createWalletClient, custom, parseAbi } from 'viem'\n   * import { mainnet } from 'viem/chains'\n   *\n   * const client = createWalletClient({\n   *   chain: mainnet,\n   *   transport: custom(window.ethereum),\n   * })\n   * const hash = await client.writeContract({\n   *   address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\n   *   abi: parseAbi(['function mint(uint32 tokenId) nonpayable']),\n   *   functionName: 'mint',\n   *   args: [69420],\n   * })\n   *\n   * @example\n   * // With Validation\n   * import { createWalletClient, custom, parseAbi } from 'viem'\n   * import { mainnet } from 'viem/chains'\n   *\n   * const client = createWalletClient({\n   *   chain: mainnet,\n   *   transport: custom(window.ethereum),\n   * })\n   * const { request } = await client.simulateContract({\n   *   address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\n   *   abi: parseAbi(['function mint(uint32 tokenId) nonpayable']),\n   *   functionName: 'mint',\n   *   args: [69420],\n   * }\n   * const hash = await client.writeContract(request)\n   */\n  writeContract: <\n    const TAbi extends Abi | readonly unknown[],\n    TFunctionName extends string,\n    TChainOverride extends Chain | undefined = undefined,\n  >(\n    args: WriteContractParameters<\n      TAbi,\n      TFunctionName,\n      TChain,\n      TAccount,\n      TChainOverride\n    >,\n  ) => Promise<WriteContractReturnType>\n}\n\nexport function walletActions<\n  TTransport extends Transport,\n  TChain extends Chain | undefined = Chain | undefined,\n  TAccount extends Account | undefined = Account | undefined,\n>(\n  client: Client<TTransport, TChain, TAccount>,\n): WalletActions<TChain, TAccount> {\n  return {\n    addChain: (args) => addChain(client, args),\n    deployContract: (args) => deployContract(client, args),\n    getAddresses: () => getAddresses(client),\n    getChainId: () => getChainId(client),\n    getPermissions: () => getPermissions(client),\n    prepareTransactionRequest: (args) =>\n      prepareTransactionRequest(client as any, args as any),\n    requestAddresses: () => requestAddresses(client),\n    requestPermissions: (args) => requestPermissions(client, args),\n    sendRawTransaction: (args) => sendRawTransaction(client, args),\n    sendTransaction: (args) => sendTransaction(client, args),\n    signMessage: (args) => signMessage(client, args),\n    signTransaction: (args) => signTransaction(client, args),\n    signTypedData: (args) => signTypedData(client, args),\n    switchChain: (args) => switchChain(client, args),\n    watchAsset: (args) => watchAsset(client, args),\n    writeContract: (args) => writeContract(client, args),\n  }\n}\n","import type { Address } from 'abitype'\n\nimport type { Account } from '../accounts/types.js'\nimport type { ErrorType } from '../errors/utils.js'\nimport type { ParseAccount } from '../types/account.js'\nimport type { Chain } from '../types/chain.js'\nimport type { WalletRpcSchema } from '../types/eip1193.js'\nimport type { Prettify } from '../types/utils.js'\nimport {\n  type Client,\n  type ClientConfig,\n  type CreateClientErrorType,\n  createClient,\n} from './createClient.js'\nimport { type WalletActions, walletActions } from './decorators/wallet.js'\nimport type { Transport } from './transports/createTransport.js'\n\nexport type WalletClientConfig<\n  transport extends Transport = Transport,\n  chain extends Chain | undefined = Chain | undefined,\n  accountOrAddress extends Account | Address | undefined =\n    | Account\n    | Address\n    | undefined,\n> = Prettify<\n  Pick<\n    ClientConfig<transport, chain, accountOrAddress>,\n    | 'account'\n    | 'cacheTime'\n    | 'chain'\n    | 'key'\n    | 'name'\n    | 'pollingInterval'\n    | 'transport'\n  >\n>\n\nexport type WalletClient<\n  transport extends Transport = Transport,\n  chain extends Chain | undefined = Chain | undefined,\n  account extends Account | undefined = Account | undefined,\n> = Prettify<\n  Client<\n    transport,\n    chain,\n    account,\n    WalletRpcSchema,\n    WalletActions<chain, account>\n  >\n>\n\nexport type CreateWalletClientErrorType = CreateClientErrorType | ErrorType\n\n/**\n * Creates a Wallet Client with a given [Transport](https://viem.sh/docs/clients/intro.html) configured for a [Chain](https://viem.sh/docs/clients/chains.html).\n *\n * - Docs: https://viem.sh/docs/clients/wallet.html\n *\n * A Wallet Client is an interface to interact with [Ethereum Account(s)](https://ethereum.org/en/glossary/#account) and provides the ability to retrieve accounts, execute transactions, sign messages, etc. through [Wallet Actions](https://viem.sh/docs/actions/wallet/introduction.html).\n *\n * The Wallet Client supports signing over:\n * - [JSON-RPC Accounts](https://viem.sh/docs/clients/wallet.html#json-rpc-accounts) (e.g. Browser Extension Wallets, WalletConnect, etc).\n * - [Local Accounts](https://viem.sh/docs/clients/wallet.html#local-accounts-private-key-mnemonic-etc) (e.g. private key/mnemonic wallets).\n *\n * @param config - {@link WalletClientConfig}\n * @returns A Wallet Client. {@link WalletClient}\n *\n * @example\n * // JSON-RPC Account\n * import { createWalletClient, custom } from 'viem'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createWalletClient({\n *   chain: mainnet,\n *   transport: custom(window.ethereum),\n * })\n *\n * @example\n * // Local Account\n * import { createWalletClient, custom } from 'viem'\n * import { privateKeyToAccount } from 'viem/accounts'\n * import { mainnet } from 'viem/chains'\n *\n * const client = createWalletClient({\n *   account: privateKeyToAccount('0x…')\n *   chain: mainnet,\n *   transport: http(),\n * })\n */\nexport function createWalletClient<\n  transport extends Transport,\n  chain extends Chain | undefined = undefined,\n  accountOrAddress extends Account | Address | undefined = undefined,\n>(\n  parameters: WalletClientConfig<transport, chain, accountOrAddress>,\n): WalletClient<transport, chain, ParseAccount<accountOrAddress>>\n\nexport function createWalletClient(\n  parameters: WalletClientConfig,\n): WalletClient {\n  const { key = 'wallet', name = 'Wallet Client', transport } = parameters\n  const client = createClient({\n    ...parameters,\n    key,\n    name,\n    transport: (opts) => transport({ ...opts, retryCount: 0 }),\n    type: 'walletClient',\n  })\n  return client.extend(walletActions)\n}\n","import { secp256k1 } from '@noble/curves/secp256k1'\n\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Hex, Signature } from '../../types/misc.js'\nimport {\n  type HexToBigIntErrorType,\n  hexToBigInt,\n} from '../../utils/encoding/fromHex.js'\nimport { type ToHexErrorType, toHex } from '../../utils/encoding/toHex.js'\n\nexport type SignatureToHexErrorType =\n  | HexToBigIntErrorType\n  | ToHexErrorType\n  | ErrorType\n\n/**\n * @description Converts a signature into hex format.\n *\n * @param signature The signature to convert.\n * @returns The signature in hex format.\n *\n * @example\n * signatureToHex({\n *   r: '0x6e100a352ec6ad1b70802290e18aeed190704973570f3b8ed42cb9808e2ea6bf',\n *   s: '0x4a90a229a244495b41890987806fcbd2d5d23fc0dbe5f5256c2613c039d76db8',\n *   v: 28n\n * })\n * // \"0x6e100a352ec6ad1b70802290e18aeed190704973570f3b8ed42cb9808e2ea6bf4a90a229a244495b41890987806fcbd2d5d23fc0dbe5f5256c2613c039d76db81c\"\n */\nexport function signatureToHex({ r, s, v }: Signature): Hex {\n  return `0x${new secp256k1.Signature(\n    hexToBigInt(r),\n    hexToBigInt(s),\n  ).toCompactHex()}${toHex(v).slice(2)}`\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport { BaseError } from '../../index.js'\nimport type { ByteArray, Hex } from '../../types/misc.js'\nimport {\n  type CreateCursorErrorType,\n  type Cursor,\n  createCursor,\n} from '../cursor.js'\n\nimport { type HexToBytesErrorType, hexToBytes } from './toBytes.js'\nimport { type BytesToHexErrorType, bytesToHex } from './toHex.js'\n\nexport type RecursiveArray<T> = T | RecursiveArray<T>[]\n\ntype To = 'hex' | 'bytes'\n\ntype Encodable = {\n  length: number\n  encode(cursor: Cursor): void\n}\n\nexport type ToRlpReturnType<to extends To> =\n  | (to extends 'bytes' ? ByteArray : never)\n  | (to extends 'hex' ? Hex : never)\n\nexport type ToRlpErrorType =\n  | CreateCursorErrorType\n  | BytesToHexErrorType\n  | HexToBytesErrorType\n  | ErrorType\n\nexport function toRlp<to extends To = 'hex'>(\n  bytes: RecursiveArray<ByteArray> | RecursiveArray<Hex>,\n  to: to | To | undefined = 'hex',\n): ToRlpReturnType<to> {\n  const encodable = getEncodable(bytes)\n  const cursor = createCursor(new Uint8Array(encodable.length))\n  encodable.encode(cursor)\n\n  if (to === 'hex') return bytesToHex(cursor.bytes) as ToRlpReturnType<to>\n  return cursor.bytes as ToRlpReturnType<to>\n}\n\nexport type BytesToRlpErrorType = ToRlpErrorType | ErrorType\n\nexport function bytesToRlp<to extends To = 'bytes'>(\n  bytes: RecursiveArray<ByteArray>,\n  to: to | To | undefined = 'bytes',\n): ToRlpReturnType<to> {\n  return toRlp(bytes, to)\n}\n\nexport type HexToRlpErrorType = ToRlpErrorType | ErrorType\n\nexport function hexToRlp<to extends To = 'hex'>(\n  hex: RecursiveArray<Hex>,\n  to: to | To | undefined = 'hex',\n): ToRlpReturnType<to> {\n  return toRlp(hex, to)\n}\n\nfunction getEncodable(\n  bytes: RecursiveArray<ByteArray> | RecursiveArray<Hex>,\n): Encodable {\n  if (Array.isArray(bytes))\n    return getEncodableList(bytes.map((x) => getEncodable(x)))\n  return getEncodableBytes(bytes)\n}\n\nfunction getEncodableList(list: Encodable[]): Encodable {\n  const bodyLength = list.reduce((acc, x) => acc + x.length, 0)\n\n  const sizeOfBodyLength = getSizeOfLength(bodyLength)\n  const length = (() => {\n    if (bodyLength <= 55) return 1 + bodyLength\n    return 1 + sizeOfBodyLength + bodyLength\n  })()\n\n  return {\n    length,\n    encode(cursor: Cursor) {\n      if (bodyLength <= 55) {\n        cursor.pushByte(0xc0 + bodyLength)\n      } else {\n        cursor.pushByte(0xc0 + 55 + sizeOfBodyLength)\n        if (sizeOfBodyLength === 1) cursor.pushUint8(bodyLength)\n        else if (sizeOfBodyLength === 2) cursor.pushUint16(bodyLength)\n        else if (sizeOfBodyLength === 3) cursor.pushUint24(bodyLength)\n        else cursor.pushUint32(bodyLength)\n      }\n      for (const { encode } of list) {\n        encode(cursor)\n      }\n    },\n  }\n}\n\nfunction getEncodableBytes(bytesOrHex: ByteArray | Hex): Encodable {\n  const bytes =\n    typeof bytesOrHex === 'string' ? hexToBytes(bytesOrHex) : bytesOrHex\n\n  const sizeOfBytesLength = getSizeOfLength(bytes.length)\n  const length = (() => {\n    if (bytes.length === 1 && bytes[0] < 0x80) return 1\n    if (bytes.length <= 55) return 1 + bytes.length\n    return 1 + sizeOfBytesLength + bytes.length\n  })()\n\n  return {\n    length,\n    encode(cursor: Cursor) {\n      if (bytes.length === 1 && bytes[0] < 0x80) {\n        cursor.pushBytes(bytes)\n      } else if (bytes.length <= 55) {\n        cursor.pushByte(0x80 + bytes.length)\n        cursor.pushBytes(bytes)\n      } else {\n        cursor.pushByte(0x80 + 55 + sizeOfBytesLength)\n        if (sizeOfBytesLength === 1) cursor.pushUint8(bytes.length)\n        else if (sizeOfBytesLength === 2) cursor.pushUint16(bytes.length)\n        else if (sizeOfBytesLength === 3) cursor.pushUint24(bytes.length)\n        else cursor.pushUint32(bytes.length)\n        cursor.pushBytes(bytes)\n      }\n    },\n  }\n}\n\nfunction getSizeOfLength(length: number) {\n  if (length < 2 ** 8) return 1\n  if (length < 2 ** 16) return 2\n  if (length < 2 ** 24) return 3\n  if (length < 2 ** 32) return 4\n  throw new BaseError('Length is too large.')\n}\n","import { defineChain } from '../../utils/chain/defineChain.js'\n\nexport const mainnet = /*#__PURE__*/ defineChain({\n  id: 1,\n  network: 'homestead',\n  name: 'Ethereum',\n  nativeCurrency: { name: 'Ether', symbol: 'ETH', decimals: 18 },\n  rpcUrls: {\n    alchemy: {\n      http: ['https://eth-mainnet.g.alchemy.com/v2'],\n      webSocket: ['wss://eth-mainnet.g.alchemy.com/v2'],\n    },\n    infura: {\n      http: ['https://mainnet.infura.io/v3'],\n      webSocket: ['wss://mainnet.infura.io/ws/v3'],\n    },\n    default: {\n      http: ['https://cloudflare-eth.com'],\n    },\n    public: {\n      http: ['https://cloudflare-eth.com'],\n    },\n  },\n  blockExplorers: {\n    etherscan: {\n      name: 'Etherscan',\n      url: 'https://etherscan.io',\n    },\n    default: {\n      name: 'Etherscan',\n      url: 'https://etherscan.io',\n    },\n  },\n  contracts: {\n    ensRegistry: {\n      address: '0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e',\n    },\n    ensUniversalResolver: {\n      address: '0xc0497E381f536Be9ce14B0dD3817cBcAe57d2F62',\n      blockCreated: 16966585,\n    },\n    multicall3: {\n      address: '0xca11bde05977b3631167028862be2a173976ca11',\n      blockCreated: 14353601,\n    },\n  },\n})\n","import { Currencies, Currency } from \"../types\";\n\nexport const WETH: Currency = {\n  address: \"0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2\",\n  symbol: \"WETH\",\n  decimals: 18,\n};\n\nexport const DAI: Currency = {\n  address: \"0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2\",\n  symbol: \"DAI\",\n  decimals: 18,\n};\n\nexport const USDC: Currency = {\n  address: \"0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48\",\n  symbol: \"USDC\",\n  decimals: 6,\n};\n\nexport const BETH: Currency = {\n  address: \"0x0000000000A39bb272e79075ade125fd351887Ac\",\n  symbol: \"BETH\",\n  decimals: 18,\n};\n\nexport const UNKNOWN: Currency = {\n  address: \"0x\",\n  symbol: \"???\",\n  decimals: 18,\n};\n\nconst currencies: Currencies = {\n  \"0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2\": WETH,\n  \"0x6b175474e89094c44da98b954eedeac495271d0f\": DAI,\n  \"0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48\": USDC,\n};\n\nexport const currencyFromAddress = (address: `0x${string}`) =>\n  currencies[address.toLowerCase() as `0x${string}`] ?? UNKNOWN;\n\nimport { mainnet } from \"viem/chains\";\nimport { createPublicClient, http, parseAbi } from \"viem\";\n\nexport const getErc20Balance = async (\n  rpcUrl: `https://${string}`,\n  currency: Currency,\n  walletAddress: `0x${string}`,\n) => {\n  const client = createPublicClient({\n    chain: mainnet,\n    transport: http(rpcUrl),\n  });\n\n  const balance = await client.readContract({\n    address: currency.address,\n    abi: parseAbi([\"function balanceOf(address _address) public view returns (uint64)\"]),\n    functionName: \"balanceOf\",\n    args: [walletAddress],\n  });\n\n  return Number(balance) / 10 ** currency.decimals;\n};\n",null,null,null,null,null,null,null,null,null,"import { secp256k1 } from '@noble/curves/secp256k1'\n\nimport type { ErrorType } from '../errors/utils.js'\nimport type { Hex } from '../types/misc.js'\nimport { type ToHexErrorType, toHex } from '../utils/encoding/toHex.js'\n\nexport type GeneratePrivateKeyErrorType = ToHexErrorType | ErrorType\n\n/**\n * @description Generates a random private key.\n *\n * @returns A randomly generated private key.\n */\nexport function generatePrivateKey(): Hex {\n  return toHex(secp256k1.utils.randomPrivateKey())\n}\n","import { secp256k1 } from '@noble/curves/secp256k1'\n\nimport type { Hex } from '../types/misc.js'\nimport { type ToHexErrorType, toHex } from '../utils/encoding/toHex.js'\n\nimport type { ErrorType } from '../errors/utils.js'\nimport { type ToAccountErrorType, toAccount } from './toAccount.js'\nimport type { PrivateKeyAccount } from './types.js'\nimport {\n  type PublicKeyToAddressErrorType,\n  publicKeyToAddress,\n} from './utils/publicKeyToAddress.js'\nimport { type SignMessageErrorType, signMessage } from './utils/signMessage.js'\nimport {\n  type SignTransactionErrorType,\n  signTransaction,\n} from './utils/signTransaction.js'\nimport {\n  type SignTypedDataErrorType,\n  signTypedData,\n} from './utils/signTypedData.js'\n\nexport type PrivateKeyToAccountErrorType =\n  | ToAccountErrorType\n  | ToHexErrorType\n  | PublicKeyToAddressErrorType\n  | SignMessageErrorType\n  | SignTransactionErrorType\n  | SignTypedDataErrorType\n  | ErrorType\n\n/**\n * @description Creates an Account from a private key.\n *\n * @returns A Private Key Account.\n */\nexport function privateKeyToAccount(privateKey: Hex): PrivateKeyAccount {\n  const publicKey = toHex(secp256k1.getPublicKey(privateKey.slice(2), false))\n  const address = publicKeyToAddress(publicKey)\n\n  const account = toAccount({\n    address,\n    async signMessage({ message }) {\n      return signMessage({ message, privateKey })\n    },\n    async signTransaction(transaction, { serializer } = {}) {\n      return signTransaction({ privateKey, transaction, serializer })\n    },\n    async signTypedData(typedData) {\n      return signTypedData({ ...typedData, privateKey })\n    },\n  })\n\n  return {\n    ...account,\n    publicKey,\n    source: 'privateKey',\n  }\n}\n","import type { Address } from 'abitype'\n\nimport {\n  InvalidAddressError,\n  type InvalidAddressErrorType,\n} from '../errors/address.js'\nimport {\n  type IsAddressErrorType,\n  isAddress,\n} from '../utils/address/isAddress.js'\n\nimport type { ErrorType } from '../errors/utils.js'\nimport type {\n  AccountSource,\n  CustomSource,\n  JsonRpcAccount,\n  LocalAccount,\n} from './types.js'\n\ntype GetAccountReturnType<TAccountSource extends AccountSource> =\n  | (TAccountSource extends Address ? JsonRpcAccount : never)\n  | (TAccountSource extends CustomSource ? LocalAccount : never)\n\nexport type ToAccountErrorType =\n  | InvalidAddressErrorType\n  | IsAddressErrorType\n  | ErrorType\n\n/**\n * @description Creates an Account from a custom signing implementation.\n *\n * @returns A Local Account.\n */\nexport function toAccount<TAccountSource extends AccountSource>(\n  source: TAccountSource,\n): GetAccountReturnType<TAccountSource> {\n  if (typeof source === 'string') {\n    if (!isAddress(source)) throw new InvalidAddressError({ address: source })\n    return {\n      address: source,\n      type: 'json-rpc',\n    } as GetAccountReturnType<TAccountSource>\n  }\n\n  if (!isAddress(source.address))\n    throw new InvalidAddressError({ address: source.address })\n  return {\n    address: source.address,\n    signMessage: source.signMessage,\n    signTransaction: source.signTransaction,\n    signTypedData: source.signTypedData,\n    source: 'custom',\n    type: 'local',\n  } as GetAccountReturnType<TAccountSource>\n}\n","import { secp256k1 } from '@noble/curves/secp256k1'\n\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Hex, Signature } from '../../types/misc.js'\nimport { type ToHexErrorType, toHex } from '../../utils/encoding/toHex.js'\n\nexport type SignParameters = {\n  hash: Hex\n  privateKey: Hex\n}\n\nexport type SignReturnType = Signature\n\nexport type SignErrorType = ToHexErrorType | ErrorType\n\n/**\n * @description Signs a hash with a given private key.\n *\n * @param hash The hash to sign.\n * @param privateKey The private key to sign with.\n *\n * @returns The signature.\n */\nexport async function sign({\n  hash,\n  privateKey,\n}: SignParameters): Promise<SignReturnType> {\n  const { r, s, recovery } = secp256k1.sign(hash.slice(2), privateKey.slice(2))\n  return {\n    r: toHex(r),\n    s: toHex(s),\n    v: recovery ? 28n : 27n,\n  }\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { Hex, SignableMessage } from '../../types/misc.js'\nimport {\n  type HashMessageErrorType,\n  hashMessage,\n} from '../../utils/signature/hashMessage.js'\nimport {\n  type SignatureToHexErrorType,\n  signatureToHex,\n} from '../../utils/signature/signatureToHex.js'\n\nimport { type SignErrorType, sign } from './sign.js'\n\nexport type SignMessageParameters = {\n  /** The message to sign. */\n  message: SignableMessage\n  /** The private key to sign with. */\n  privateKey: Hex\n}\n\nexport type SignMessageReturnType = Hex\n\nexport type SignMessageErrorType =\n  | SignErrorType\n  | HashMessageErrorType\n  | SignatureToHexErrorType\n  | ErrorType\n\n/**\n * @description Calculates an Ethereum-specific signature in [EIP-191 format](https://eips.ethereum.org/EIPS/eip-191):\n * `keccak256(\"\\x19Ethereum Signed Message:\\n\" + len(message) + message))`.\n *\n * @returns The signature.\n */\nexport async function signMessage({\n  message,\n  privateKey,\n}: SignMessageParameters): Promise<SignMessageReturnType> {\n  const signature = await sign({ hash: hashMessage(message), privateKey })\n  return signatureToHex(signature)\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { Hex } from '../../types/misc.js'\nimport type {\n  TransactionSerializable,\n  TransactionSerialized,\n} from '../../types/transaction.js'\nimport {\n  type Keccak256ErrorType,\n  keccak256,\n} from '../../utils/hash/keccak256.js'\nimport type { GetTransactionType } from '../../utils/transaction/getTransactionType.js'\nimport {\n  type SerializeTransactionFn,\n  serializeTransaction,\n} from '../../utils/transaction/serializeTransaction.js'\n\nimport { type SignErrorType, sign } from './sign.js'\n\nexport type SignTransactionParameters<\n  TTransactionSerializable extends\n    TransactionSerializable = TransactionSerializable,\n> = {\n  privateKey: Hex\n  transaction: TTransactionSerializable\n  serializer?: SerializeTransactionFn<\n    TransactionSerializable & TTransactionSerializable\n  >\n}\n\nexport type SignTransactionReturnType<\n  TTransactionSerializable extends\n    TransactionSerializable = TransactionSerializable,\n> = TransactionSerialized<GetTransactionType<TTransactionSerializable>>\n\nexport type SignTransactionErrorType =\n  | Keccak256ErrorType\n  | SignErrorType\n  | ErrorType\n\nexport async function signTransaction<\n  TTransactionSerializable extends TransactionSerializable,\n>({\n  privateKey,\n  transaction,\n  serializer = serializeTransaction,\n}: SignTransactionParameters<TTransactionSerializable>): Promise<\n  SignTransactionReturnType<TTransactionSerializable>\n> {\n  const signature = await sign({\n    hash: keccak256(serializer(transaction)),\n    privateKey,\n  })\n  return serializer(\n    transaction,\n    signature,\n  ) as SignTransactionReturnType<TTransactionSerializable>\n}\n","import type { TypedData } from 'abitype'\n\nimport type { Hex } from '../../types/misc.js'\nimport type { TypedDataDefinition } from '../../types/typedData.js'\nimport {\n  type HashTypedDataErrorType,\n  type HashTypedDataParameters,\n  hashTypedData,\n} from '../../utils/signature/hashTypedData.js'\nimport {\n  type SignatureToHexErrorType,\n  signatureToHex,\n} from '../../utils/signature/signatureToHex.js'\n\nimport type { ErrorType } from '../../errors/utils.js'\nimport { type SignErrorType, sign } from './sign.js'\n\nexport type SignTypedDataParameters<\n  TTypedData extends TypedData | { [key: string]: unknown } = TypedData,\n  TPrimaryType extends string = string,\n> = TypedDataDefinition<TTypedData, TPrimaryType> & {\n  /** The private key to sign with. */\n  privateKey: Hex\n}\n\nexport type SignTypedDataReturnType = Hex\n\nexport type SignTypedDataErrorType =\n  | HashTypedDataErrorType\n  | SignErrorType\n  | SignatureToHexErrorType\n  | ErrorType\n\n/**\n * @description Signs typed data and calculates an Ethereum-specific signature in [EIP-191 format](https://eips.ethereum.org/EIPS/eip-191):\n * `keccak256(\"\\x19Ethereum Signed Message:\\n\" + len(message) + message))`.\n *\n * @returns The signature.\n */\nexport async function signTypedData<\n  const TTypedData extends TypedData | { [key: string]: unknown },\n  TPrimaryType extends string = string,\n>({\n  privateKey,\n  ...typedData\n}: SignTypedDataParameters<\n  TTypedData,\n  TPrimaryType\n>): Promise<SignTypedDataReturnType> {\n  const signature = await sign({\n    hash: hashTypedData(typedData as HashTypedDataParameters),\n    privateKey,\n  })\n  return signatureToHex(signature)\n}\n","import { generatePrivateKey, privateKeyToAccount } from \"viem/accounts\";\nimport axios, { AxiosInstance } from \"axios\";\nimport { PrivateKeyAccount } from \"viem\";\n\nimport { arcadeLoanMapper, arcadeOfferMapper } from \"./support/mappers\";\nimport {\n  Loan,\n  Offer,\n  LendingClientParameters,\n  LendingClientWithPromissoryNotes,\n  PromissoryNote,\n  Listing,\n  SingleItemOfferParams,\n  CollectionOfferParams,\n} from \"../types\";\nimport Offers from \"./api/offers\";\nimport Loans from \"./api/loans\";\n\nexport class ArcadeClient implements LendingClientWithPromissoryNotes {\n  private readonly account: PrivateKeyAccount;\n  private readonly http: AxiosInstance;\n\n  private offers: Offers;\n  private loans: Loans;\n\n  constructor(p: LendingClientParameters) {\n    this.account = privateKeyToAccount(p.privateKey ?? generatePrivateKey());\n\n    this.http = axios.create({\n      baseURL: \"https://api-v2.arcade.xyz/api/v2\",\n      headers: { \"x-api-key\": p.apiKey },\n    });\n    this.http.interceptors.request.use(function (config) {\n      config.headers[\"x-expires-at\"] = (Date.now() + 10 * 1000).toString();\n      return config;\n    });\n\n    this.offers = new Offers(this.account, this.http);\n    this.loans = new Loans(this.account, this.http);\n  }\n\n  public async getListings(): Promise<Listing[]> {\n    throw Error(\"Not implemented\");\n  }\n\n  public async getListingsForCollection(): Promise<Listing[]> {\n    throw Error(\"Not implemented\");\n  }\n\n  public async getLoans(): Promise<Loan[]> {\n    return await this.loans.getAll().then((res) => res.map(arcadeLoanMapper));\n  }\n\n  public async getLoansForCollection(address: `0x${string}`): Promise<Loan[]> {\n    console.log(address);\n    throw Error(\"Not implemented\");\n  }\n\n  public async getLoansForAccount(address: `0x${string}`): Promise<Loan[]> {\n    return await this.loans.get(address).then((res) => res.map(arcadeLoanMapper));\n  }\n\n  public async getMyLoans(): Promise<Loan[]> {\n    return await this.getLoansForAccount(this.account.address);\n  }\n\n  public async createSingleItemOffer(offerParams: SingleItemOfferParams): Promise<Offer> {\n    return await this.offers\n      .create(offerParams)\n      .then((res) => arcadeOfferMapper(res))\n      .catch((error) => {\n        throw Error(error); // TODO: error mapping\n      });\n  }\n\n  public async createCollectionOffer(offerParams: CollectionOfferParams): Promise<Offer> {\n    return await this.offers\n      .create(offerParams)\n      .then((res) => arcadeOfferMapper(res))\n      .catch((error) => {\n        throw Error(error); // TODO: error mapping\n      });\n  }\n\n  public async deleteOffer(offerId: string): Promise<void> {\n    await this.offers.delete(offerId);\n  }\n\n  public async getOffers(): Promise<Offer[]> {\n    throw Error(\"Not implemented\");\n  }\n\n  public async getOffersForAccount(address: `0x${string}`): Promise<Offer[]> {\n    return await this.offers.get(address).then((res) => res.map(arcadeOfferMapper));\n  }\n\n  public async getOffersForCollection(address: `0x${string}`): Promise<Offer[]> {\n    console.log(address);\n    throw Error(\"Not implemented\");\n  }\n\n  public async getMyOffers(): Promise<Offer[]> {\n    return await this.offers.get(this.account.address).then(async (res) => res.map(arcadeOfferMapper));\n  }\n\n  public async getPromissoryNote(loanId: number): Promise<PromissoryNote> {\n    return { address: \"0x349A026A43FFA8e2Ab4c4e59FCAa93F87Bd8DdeE\", id: loanId };\n  }\n}\n","export type Currency = { address: `0x${string}`; symbol: string; decimals: number };\nexport type Currencies = Record<`0x${string}`, Currency>;\n\nexport type CollectionDetails = { address: `0x${string}`; name: string; gondiCollectionId?: string };\nexport type Collections = Record<`0x${string}`, CollectionDetails>;\n\nexport interface LendingClient {\n  getListings: () => Promise<Listing[]>;\n  getListingsForCollection: (address: `0x${string}`) => Promise<Listing[]>;\n  getLoans: () => Promise<Loan[]>;\n  getLoansForAccount: (address: `0x${string}`) => Promise<Loan[]>;\n  getLoansForCollection: (address: `0x${string}`) => Promise<Loan[]>;\n  getMyLoans: () => Promise<Loan[]>;\n  createSingleItemOffer: (offerParams: SingleItemOfferParams) => Promise<Offer>;\n  createCollectionOffer: (offerParams: CollectionOfferParams) => Promise<Offer>;\n  getOffers: () => Promise<Offer[]>;\n  getOffersForAccount: (address: `0x${string}`) => Promise<Offer[]>;\n  getOffersForCollection: (address: `0x${string}`) => Promise<Offer[]>;\n  getMyOffers: () => Promise<Offer[]>;\n  deleteOffer: (offerId: string) => Promise<void>;\n}\n\nexport interface LendingClientBlur {\n  recallLoan: (collectionAddress: `0x${string}`, loanId: string, nftId: number) => Promise<void>;\n}\n\nexport interface LendingClientWithPromissoryNotes extends LendingClient {\n  getPromissoryNote: (loanId: number) => Promise<PromissoryNote>;\n}\n\nexport interface LendingClientParameters {\n  apiKey?: string;\n  privateKey?: `0x${string}`;\n  rpcUrl?: `https://${string}`;\n  testnet?: boolean;\n}\n\nexport enum LendingPlatform {\n  nftfi = \"nftfi\",\n  arcade = \"arcade\",\n  gondi = \"gondi\",\n  blur = \"blur\",\n}\n\nexport interface Listing {\n  id: string;\n}\n\nexport enum LoanStatus {\n  ongoing = \"ongoing\",\n  repaid = \"repaid\",\n  auctioned = \"auctioned\",\n  liquidated = \"liquidated\",\n  defaulted = \"defaulted\",\n}\n\nexport interface Collateral {\n  collectionAddress: `0x${string}`;\n  collectionName: string;\n  nftId: number;\n}\n\nexport interface Loan {\n  id: string;\n  platform: LendingPlatform;\n  borrower: `0x${string}`;\n  lender: `0x${string}`;\n  status: LoanStatus;\n  startDate: Date;\n  endDate: Date;\n  currency: Currency;\n  principal: number;\n  interestPayment: number;\n  durationInDays: number;\n  apr: number;\n  collateral: Collateral[];\n  valuation?: number;\n}\n\nexport enum OfferType {\n  collectionOffer = \"collectionOffer\",\n  singleItemOffer = \"singleItemOffer\",\n}\n\nexport interface Offer {\n  id: string;\n  platform: LendingPlatform;\n  lender: `0x${string}`;\n  offerDate: Date;\n  expiryDate: Date;\n  type: OfferType;\n  currency: Currency;\n  principal: number;\n  durationInDays: number;\n  apr: number;\n  collateral: {\n    collectionAddress: `0x${string}`;\n    collectionName: string;\n    nftId: string;\n  };\n}\n\nexport interface CollectionOfferParams {\n  collectionAddress: `0x${string}`;\n  currency: Currency;\n  principal: number;\n  apr: number;\n  durationInDays: number;\n  expiryInMinutes: number;\n  slug?: string;\n  lenderAddress?: `0x${string}`;\n  limit?: number;\n}\n\nexport interface SingleItemOfferParams extends CollectionOfferParams {\n  nftId: number;\n}\n\nexport interface PromissoryNote {\n  address: `0x${string}`;\n  id: number;\n}\n","import { Collections, CollectionDetails } from \"../types\";\n\nexport const defaultRegistry: Collections = {\n  \"0xbd3531da5cf5857e7cfaa92426877b022e612cf8\": {\n    address: \"0xbd3531da5cf5857e7cfaa92426877b022e612cf8\",\n    name: \"Pudgy Penguins\",\n  },\n  \"0x6efc003d3f3658383f06185503340c2cf27a57b6\": {\n    address: \"0x6efc003d3f3658383f06185503340c2cf27a57b6\",\n    name: \"YouTheRealMVP\",\n  },\n  \"0x60e4d786628fea6478f785a6d7e704777c86a7c6\": {\n    address: \"0x60e4d786628fea6478f785a6d7e704777c86a7c6\",\n    name: \"Mutant Ape Yacht Club\",\n  },\n  \"0xd1258db6ac08eb0e625b75b371c023da478e94a9\": {\n    address: \"0xd1258db6ac08eb0e625b75b371c023da478e94a9\",\n    name: \"DigiDaigaku\",\n  },\n  \"0x49cf6f5d44e70224e2e23fdcdd2c053f30ada28b\": {\n    address: \"0x49cf6f5d44e70224e2e23fdcdd2c053f30ada28b\",\n    name: \"CloneX\",\n  },\n  \"0x769272677fab02575e84945f03eca517acc544cc\": {\n    address: \"0x769272677fab02575e84945f03eca517acc544cc\",\n    name: \"The Captainz\",\n  },\n  \"0x054c122109b3c658ef2780c9ef6bd0b80818dab8\": {\n    address: \"0x054c122109b3c658ef2780c9ef6bd0b80818dab8\",\n    name: \"CryptoDickButts\",\n  },\n  \"0xbc4ca0eda7647a8ab7c2061c2e118a18a936f13d\": {\n    address: \"0xbc4ca0eda7647a8ab7c2061c2e118a18a936f13d\",\n    name: \"Bored Ape Yacht Club\",\n  },\n  \"0xba30e5f9bb24caa003e9f2f0497ad287fdf95623\": {\n    address: \"0xba30e5f9bb24caa003e9f2f0497ad287fdf95623\",\n    name: \"Bored Ape Kennel Club\",\n  },\n  \"0x34d85c9cdeb23fa97cb08333b511ac86e1c4e258\": {\n    address: \"0x34d85c9cdeb23fa97cb08333b511ac86e1c4e258\",\n    name: \"Otherdeed\",\n  },\n  \"0x394e3d3044fc89fcdd966d3cb35ac0b32b0cda91\": {\n    address: \"0x394e3d3044fc89fcdd966d3cb35ac0b32b0cda91\",\n    name: \"Renga\",\n  },\n  \"0xb852c6b5892256c264cc2c888ea462189154d8d7\": {\n    address: \"0xb852c6b5892256c264cc2c888ea462189154d8d7\",\n    name: \"RektGuy\",\n  },\n  \"0xed5af388653567af2f388e6224dc7c4b3241c544\": {\n    address: \"0xed5af388653567af2f388e6224dc7c4b3241c544\",\n    name: \"Azuki\",\n  },\n  \"0x5af0d9827e0c53e4799bb226655a1de152a425a5\": {\n    address: \"0x5af0d9827e0c53e4799bb226655a1de152a425a5\",\n    name: \"Milady\",\n  },\n  \"0xb7f7f6c52f2e2fdb1963eab30438024864c313f6\": {\n    address: \"0xb7f7f6c52f2e2fdb1963eab30438024864c313f6\",\n    name: \"Cryptopunks\",\n  },\n  \"0x000000000000003607fce1ac9e043a86675c5c2f\": {\n    address: \"0x000000000000003607fce1ac9e043a86675c5c2f\",\n    name: \"Cryptopunks\",\n  },\n  \"0x3bf2922f4520a8ba0c2efc3d2a1539678dad5e9d\": {\n    address: \"0x3bf2922f4520a8ba0c2efc3d2a1539678dad5e9d\",\n    name: \"0N1 Force\",\n  },\n  \"0x39ee2c7b3cb80254225884ca001f57118c8f21b6\": {\n    address: \"0x39ee2c7b3cb80254225884ca001f57118c8f21b6\",\n    name: \"Potatoz\",\n  },\n  \"0x7bd29408f11d2bfc23c34f18275bbf23bb716bc7\": {\n    address: \"0x7bd29408f11d2bfc23c34f18275bbf23bb716bc7\",\n    name: \"Meebits\",\n  },\n  \"0x8821bee2ba0df28761afff119d66390d594cd280\": {\n    address: \"0x8821bee2ba0df28761afff119d66390d594cd280\",\n    name: \"DeGods\",\n  },\n  \"0x23581767a106ae21c074b2276d25e5c3e136a68b\": {\n    address: \"0x23581767a106ae21c074b2276d25e5c3e136a68b\",\n    name: \"Moonbirds\",\n  },\n  \"0x8a90cab2b38dba80c64b7734e58ee1db38b8992e\": {\n    address: \"0x8a90cab2b38dba80c64b7734e58ee1db38b8992e\",\n    name: \"Doodles\",\n  },\n  \"0xd774557b647330c91bf44cfeab205095f7e6c367\": {\n    address: \"0xd774557b647330c91bf44cfeab205095f7e6c367\",\n    name: \"Nakamigos\",\n  },\n  \"0x46c9cfb32627b74f91e0b5ad575c247aec7e7847\": {\n    address: \"0x46c9cfb32627b74f91e0b5ad575c247aec7e7847\",\n    name: \"NFTfi Locked Bundle\",\n  },\n  \"0xd4e4078ca3495de5b1d4db434bebc5a986197782\": {\n    address: \"0xd4e4078ca3495de5b1d4db434bebc5a986197782\",\n    name: \"Autoglyphs\",\n  },\n  \"0x364c828ee171616a39897688a831c2499ad972ec\": {\n    address: \"0x364c828ee171616a39897688a831c2499ad972ec\",\n    name: \"Sappy Seals\",\n  },\n  \"0x036721e5a769cc48b3189efbb9cce4471e8a48b1\": {\n    address: \"0x036721e5a769cc48b3189efbb9cce4471e8a48b1\",\n    name: \"Checks - VV Originals\",\n  },\n  \"0xa7d8d9ef8d8ce8992df33d8b8cf4aebabd5bd270\": {\n    address: \"0xa7d8d9ef8d8ce8992df33d8b8cf4aebabd5bd270\",\n    name: \"Art Blocks\",\n  },\n};\n\nexport class CollectionRegistry {\n  private static collectionRegistry: Collections;\n\n  static initialize(initialRegistry: Collections) {\n    this.collectionRegistry = initialRegistry;\n  }\n\n  static getCollectionDetails(address: `0x${string}`): CollectionDetails {\n    return this.collectionRegistry[address.toLowerCase() as `0x${string}`] ?? { name: \"others\", address: address };\n  }\n\n  static addCollection(address: string, name: string): void {\n    this.collectionRegistry[address.toLowerCase() as `0x${string}`] = {\n      address: address.toLowerCase() as `0x${string}`,\n      name: name,\n    };\n  }\n}\n\nCollectionRegistry.initialize(defaultRegistry);\n","export const addDaysToDate = (date: Date, days: number): Date => {\n  const newDate = new Date(date.getTime());\n  newDate.setDate(newDate.getDate() + days);\n  return newDate;\n};\n\nexport const calculateDurationInDays = (durationSecs: number): number => {\n  return durationSecs / 3600 / 24;\n};\n","import { LendingPlatform, Loan, LoanStatus, Offer, OfferType } from \"../../types\";\nimport { currencyFromAddress } from \"../../support/currencies\";\nimport { ArcadeLoan, ArcadeOffer } from \"./types\";\nimport { CollectionRegistry } from \"../../support/CollectionRegistry\";\nimport { addDaysToDate, calculateDurationInDays } from \"../../helpers\";\n\nconst arcadeStatusMapper = (status: string): LoanStatus => {\n  switch (status) {\n    case \"Active\":\n      return LoanStatus.ongoing;\n    case \"Repaid\":\n      return LoanStatus.repaid;\n    default:\n      return LoanStatus.defaulted;\n  }\n};\n\nexport const arcadeLoanMapper = (arcadeLoan: ArcadeLoan): Loan => {\n  const currency = currencyFromAddress(arcadeLoan.payableCurrency);\n  const durationInDays = calculateDurationInDays(parseInt(arcadeLoan.durationSecs));\n  const principal = parseInt(arcadeLoan.principal) / 10 ** currency.decimals;\n  const apr = (parseInt(arcadeLoan.interestRate) / 1e18 / 10000) * (365 / durationInDays);\n  // console.log(arcadeLoan);\n  return {\n    id: arcadeLoan.loanId,\n    platform: LendingPlatform.arcade,\n    borrower: arcadeLoan.borrowerId.toLowerCase() as `0x${string}`,\n    lender: arcadeLoan.lenderId.toLowerCase() as `0x${string}`,\n    status: arcadeStatusMapper(arcadeLoan.state),\n    startDate: new Date(parseInt(arcadeLoan.startDate) * 1e3),\n    endDate: arcadeLoan.closedAt\n      ? new Date(arcadeLoan.closedAt * 1e3)\n      : addDaysToDate(new Date(parseInt(arcadeLoan.startDate) * 1e3), durationInDays),\n    currency: currency,\n    principal: parseInt(arcadeLoan.principal) / 10 ** currency.decimals,\n    interestPayment: (principal * apr * durationInDays) / 365,\n    durationInDays: durationInDays,\n    apr: apr,\n    collateral: arcadeLoan.collateral.map((collateral) => ({\n      collectionAddress: collateral.collectionAddress,\n      collectionName: CollectionRegistry.getCollectionDetails(collateral.collectionAddress).name,\n      nftId: parseInt(collateral.tokenId),\n    })),\n  };\n};\n\nexport const arcadeOfferMapper = (arcadeOffer: ArcadeOffer): Offer => {\n  const currency = currencyFromAddress(arcadeOffer.payableCurrency);\n  const durationInDays = calculateDurationInDays(arcadeOffer.durationSecs);\n  return {\n    id: arcadeOffer.id.toString(),\n    platform: LendingPlatform.arcade,\n    lender: arcadeOffer.creatorId,\n    offerDate: new Date(arcadeOffer.createdAt),\n    expiryDate: new Date(arcadeOffer.expiresAt),\n    type: arcadeOffer.collateralId === \"-1\" ? OfferType.collectionOffer : OfferType.singleItemOffer,\n    currency: currency,\n    principal: parseFloat(arcadeOffer.principal) / 10 ** currency.decimals,\n    durationInDays: durationInDays,\n    apr: (parseInt(arcadeOffer.interestRate) / 1e18 / 10000) * (365.25 / durationInDays),\n    collateral: {\n      collectionAddress: arcadeOffer.collateralAddress,\n      collectionName: CollectionRegistry.getCollectionDetails(arcadeOffer.collateralAddress).name,\n      nftId: arcadeOffer.collateralId,\n    },\n  };\n};\n","import { encodeAbiParameters, pad, PrivateKeyAccount } from \"viem\";\nimport { AxiosInstance } from \"axios\";\n\nimport { ArcadeOffer, ArcadeOfferParams, ItemsPayload } from \"../support/types\";\n\n// @ts-ignore\nBigInt.prototype[\"toJSON\"] = function () {\n  return this.toString();\n};\n\nconst typedLoanTermsItemsData = {\n  LoanTermsWithItems: [\n    { name: \"proratedInterestRate\", type: \"uint256\" },\n    { name: \"principal\", type: \"uint256\" },\n    { name: \"collateralAddress\", type: \"address\" },\n    { name: \"durationSecs\", type: \"uint96\" },\n    { name: \"items\", type: \"Predicate[]\" },\n    { name: \"payableCurrency\", type: \"address\" },\n    { name: \"deadline\", type: \"uint96\" },\n    { name: \"affiliateCode\", type: \"bytes32\" },\n    { name: \"nonce\", type: \"uint160\" },\n    { name: \"side\", type: \"uint8\" },\n  ],\n  Predicate: [\n    { name: \"data\", type: \"bytes\" },\n    { name: \"verifier\", type: \"address\" },\n  ],\n};\n\nexport default class Offers {\n  private account: PrivateKeyAccount;\n  private http: AxiosInstance;\n\n  private ARCADE_ITEMS_VERIFIER = \"0x1B6e58AaE43bFd2a435AA348F3328f3137DDA544\";\n  private ARCADE_ORIGINATION_CONTROLLER = \"0xB7BFcca7D7ff0f371867B770856FAc184B185878\";\n  private readonly domain = {\n    name: \"OriginationController\",\n    version: \"3\",\n    chainId: 1,\n    verifyingContract: this.ARCADE_ORIGINATION_CONTROLLER as `0x${string}`,\n  };\n\n  constructor(account: PrivateKeyAccount, http: AxiosInstance) {\n    this.account = account;\n    this.http = http;\n  }\n\n  async get(address: `0x${string}`): Promise<ArcadeOffer[]> {\n    return await this.http\n      .get(`/accounts/${address}/loanterms`)\n      .then((res) => res.data)\n      .catch((err) => console.log(err));\n  }\n\n  async create(offerParams: ArcadeOfferParams): Promise<ArcadeOffer> {\n    const { principal, currency, apr, durationInDays } = offerParams;\n    const nonce = this.getNonce();\n\n    const predicate = {\n      verifier: this.ARCADE_ITEMS_VERIFIER,\n      data: encodeAbiParameters([{ type: \"address\" }], [offerParams.collectionAddress]),\n    };\n\n    const loanTerms: ItemsPayload = {\n      durationSecs: durationInDays * 24 * 3600,\n      proratedInterestRate: BigInt(Math.floor(((apr * durationInDays) / 365.25) * 10000)) * BigInt(1e18),\n      principal: BigInt(Math.floor(principal * 10000)) * BigInt(1e14),\n      collateralAddress: offerParams.collectionAddress.toLowerCase(),\n      collateralId: offerParams.nftId === undefined ? \"-1\" : (offerParams.nftId?.toString() as string),\n      payableCurrency: currency.address,\n      deadline: this.getExpiry(offerParams.expiryInMinutes * 60),\n      affiliateCode: pad(\"0x0\"),\n      nonce: nonce,\n      side: 1,\n    };\n\n    const data = {\n      loanTerms: {\n        durationSecs: loanTerms.durationSecs,\n        payableCurrency: loanTerms.payableCurrency,\n        collateralAddress: loanTerms.collateralAddress,\n        collateralId: loanTerms.collateralId,\n        deadline: loanTerms.deadline.toString(),\n        principal: loanTerms.principal.toString(),\n        proratedInterestRate: loanTerms.proratedInterestRate.toString(),\n        affiliateCode: loanTerms.affiliateCode,\n      },\n      role: \"lender\",\n      signature: await this.account.signTypedData({\n        domain: this.domain,\n        types: typedLoanTermsItemsData,\n        primaryType: \"LoanTermsWithItems\",\n        message: {\n          ...loanTerms,\n          items: [predicate],\n        },\n      }),\n      nonce: nonce.toString(),\n      kind: offerParams.nftId === undefined ? \"collection\" : \"asset\",\n      collectionId: offerParams.collectionAddress.toLowerCase(),\n      itemPredicates: [predicate],\n    };\n\n    return await this.http.post(`/accounts/${this.account.address}/loanterms/`, data).then((res) => res.data);\n  }\n\n  async delete(offerId: string) {\n    await this.http.delete(`/accounts/${this.account.address}/loanterms/${offerId}`);\n  }\n\n  private getExpiry(offset: number) {\n    const currentTime = new Date();\n    const currentTimePlusOffset = new Date(currentTime.getTime() + offset * 1000); // Add offset\n    return BigInt(Math.floor(currentTimePlusOffset.getTime() / 1000)); // Convert to seconds\n  }\n\n  private getNonce(): bigint {\n    return BigInt(Date.now());\n  }\n}\n","import { PrivateKeyAccount } from \"viem\";\nimport { AxiosInstance } from \"axios\";\n\nimport { ArcadeLoan } from \"../support/types\";\n\nexport default class Loans {\n  private account: PrivateKeyAccount;\n  private http: AxiosInstance;\n\n  constructor(account: PrivateKeyAccount, http: AxiosInstance) {\n    this.account = account;\n    this.http = http;\n  }\n\n  public async get(address: `0x${string}`): Promise<ArcadeLoan[]> {\n    return await this.http.get(`/accounts/${address}/loans`).then((res) => res.data);\n  }\n\n  public async getAll(): Promise<ArcadeLoan[]> {\n    const allLoans: ArcadeLoan[] = [];\n    let cursor = 1000000000;\n\n    do {\n      const response = await fetch(`https://api-v2.arcade.xyz/api/v2/loans?cursor=${cursor}`);\n      const data = (await response.json()) as ArcadeLoan[];\n      cursor = data[data.length - 1].cursor;\n      allLoans.push(...data);\n    } while (cursor !== 1);\n\n    return allLoans;\n  }\n}\n","import { generatePrivateKey, privateKeyToAccount } from \"viem/accounts\";\nimport axios, { AxiosInstance } from \"axios\";\nimport { PrivateKeyAccount, PublicClient, createPublicClient, http, parseAbi } from \"viem\";\nimport { mainnet } from \"viem/chains\";\n\nimport { nftfiOfferMapper, nftfiLoanMapper, mapError } from \"./support/mappers\";\nimport {\n  Loan,\n  Offer,\n  LendingClient,\n  LendingClientParameters,\n  PromissoryNote,\n  Listing,\n  CollectionOfferParams,\n  SingleItemOfferParams,\n} from \"../types\";\nimport Offers from \"./api/offers\";\nimport Loans from \"./api/loans\";\n\nexport class NftfiClient implements LendingClient {\n  private readonly account: PrivateKeyAccount;\n  private readonly http: AxiosInstance;\n  private rpc: PublicClient;\n\n  private offers: Offers;\n  private loans: Loans;\n\n  constructor(p: LendingClientParameters) {\n    this.account = privateKeyToAccount(p.privateKey ?? generatePrivateKey());\n\n    this.http = axios.create({\n      baseURL: \"https://sdk-api.nftfi.com\",\n      headers: { \"X-API-Key\": p.apiKey },\n    });\n    this.rpc = createPublicClient({\n      chain: mainnet,\n      transport: http(p.rpcUrl),\n    });\n\n    this.offers = new Offers(this.account, this.http);\n    this.loans = new Loans(this.account, this.http);\n  }\n\n  public async getListings(): Promise<Listing[]> {\n    throw Error(\"Not implemented\");\n  }\n\n  public async getListingsForCollection(): Promise<Listing[]> {\n    throw Error(\"Not implemented\");\n  }\n\n  public async getLoans(): Promise<Loan[]> {\n    return await this.loans.getAll().then((res) => res.map((o) => nftfiLoanMapper(o)));\n  }\n\n  public async getLoansForCollection(address: `0x${string}`): Promise<Loan[]> {\n    console.log(address);\n    throw Error(\"Not implemented\");\n  }\n\n  public async getLoansForAccount(address: `0x${string}`): Promise<Loan[]> {\n    return await this.loans.get(address).then((res) => res.map((o) => nftfiLoanMapper(o, address)));\n  }\n\n  public async getMyLoans(): Promise<Loan[]> {\n    return await this.getLoansForAccount(this.account.address);\n  }\n\n  public async createSingleItemOffer(offerParams: SingleItemOfferParams): Promise<Offer> {\n    console.log(offerParams);\n    throw Error(\"Not implemented\");\n  }\n\n  public async createCollectionOffer(offerParams: CollectionOfferParams): Promise<Offer> {\n    const { principal, currency, apr, durationInDays } = offerParams;\n    const payload = {\n      terms: {\n        principal: BigInt(Math.round(principal * 10 ** currency.decimals)),\n        repayment: BigInt(Math.round(principal * (1 + apr * (durationInDays / 365)) * 10 ** currency.decimals)),\n        duration: 24 * 3600 * durationInDays,\n        currency: currency.address,\n        expiry: { seconds: 60 * offerParams.expiryInMinutes },\n      },\n      nft: { address: offerParams.collectionAddress },\n      nftfi: { contract: { name: \"v2-3.loan.fixed.collection\" } },\n    };\n\n    return await this.offers\n      .create(payload)\n      .then((res) => nftfiOfferMapper(res))\n      .catch((error) => {\n        throw mapError(error);\n      });\n  }\n\n  public async deleteOffer(offerId: string): Promise<void> {\n    await this.offers.delete(offerId);\n  }\n\n  public async getOffers(): Promise<Offer[]> {\n    throw Error(\"Not implemented\");\n  }\n\n  public async getOffersForAccount(address: `0x${string}`): Promise<Offer[]> {\n    return await this.offers.get(address).then((res) => res.map(nftfiOfferMapper));\n  }\n\n  public async getOffersForCollection(address: `0x${string}`): Promise<Offer[]> {\n    console.log(address);\n    throw Error(\"Not implemented\");\n  }\n\n  public async getMyOffers(): Promise<Offer[]> {\n    return await this.offers.get(this.account.address).then((res) => res.map(nftfiOfferMapper));\n  }\n\n  public async getPromissoryNote(loanId: number): Promise<PromissoryNote> {\n    const contractAddress = \"0x329E090aCE410aC8D86f1f0c2a13486884E7072a\";\n    const response = await this.rpc.readContract({\n      address: contractAddress,\n      abi: parseAbi([\"function getLoanData(uint32 _loanId) public view returns (address, uint64, uint8)\"]),\n      functionName: \"getLoanData\",\n      args: [loanId],\n    });\n\n    return {\n      address: response[0],\n      id: Number(response[1]),\n    };\n  }\n}\n","export class AccountUnderfunded extends Error {\n  constructor() {\n    super(\"\");\n    this.name = this.constructor.name;\n  }\n}\n\nexport class UnsufficientAllowance extends Error {\n  constructor() {\n    super(\"\");\n    this.name = this.constructor.name;\n  }\n}\n\nexport class CollectionNotSupported extends Error {\n  constructor() {\n    super(\"\");\n    this.name = this.constructor.name;\n  }\n}\n","import { Offer, LendingPlatform, Loan, LoanStatus, OfferType } from \"../../types\";\nimport { currencyFromAddress } from \"../../support/currencies\";\nimport { NFTfiLoan, NFTfiOffer } from \"./types\";\nimport { addDaysToDate, calculateDurationInDays } from \"../../helpers\";\nimport { CollectionRegistry } from \"../../support/CollectionRegistry\";\nimport { AccountUnderfunded, UnsufficientAllowance } from \"../../errors\";\n\nconst nftfiStatusMapper = (status: string): LoanStatus => {\n  switch (status) {\n    case \"active\":\n      return LoanStatus.ongoing;\n    case \"escrow\":\n      return LoanStatus.ongoing;\n    case \"repaid\":\n      return LoanStatus.repaid;\n    case \"foreclosed\":\n      return LoanStatus.liquidated;\n    case \"liquidated\":\n      return LoanStatus.liquidated;\n    case \"defaulted\":\n      return LoanStatus.defaulted;\n    default:\n      throw new Error(`Loan status ${status} is not supported!`);\n  }\n};\n\nexport const nftfiLoanMapper = (nftfiLoan: NFTfiLoan, lender?: `0x${string}`): Loan => {\n  const currency = currencyFromAddress(nftfiLoan.terms.loan.currency);\n  const durationInDays = calculateDurationInDays(nftfiLoan.terms.loan.duration);\n  return {\n    id: nftfiLoan.id.toString(),\n    platform: LendingPlatform.nftfi,\n    borrower: nftfiLoan.borrower.address,\n    lender: (lender?.toLowerCase() ?? nftfiLoan.lender.address) as `0x${string}`,\n    status: nftfiStatusMapper(nftfiLoan.status),\n    startDate: new Date(nftfiLoan.date.started),\n    endDate: nftfiLoan.date.repaid\n      ? new Date(nftfiLoan.date.repaid)\n      : addDaysToDate(new Date(nftfiLoan.date.started), durationInDays),\n    currency: currency,\n    principal: parseFloat(nftfiLoan.terms.loan.principal.toString()) / 10 ** currency.decimals,\n    interestPayment:\n      parseFloat(nftfiLoan.terms.loan.repayment.toString()) / 10 ** currency.decimals -\n      parseFloat(nftfiLoan.terms.loan.principal.toString()) / 10 ** currency.decimals,\n    durationInDays: durationInDays,\n    apr:\n      (parseFloat(nftfiLoan.terms.loan.repayment.toString()) / parseFloat(nftfiLoan.terms.loan.principal.toString()) -\n        1) *\n      (365 / durationInDays),\n    collateral: [\n      {\n        collectionAddress: nftfiLoan.nft.address,\n        collectionName: CollectionRegistry.getCollectionDetails(nftfiLoan.nft.address).name,\n        nftId: parseInt(nftfiLoan.nft.id),\n      },\n    ],\n  };\n};\n\nexport const nftfiOfferMapper = (nftfiOffer: NFTfiOffer): Offer => {\n  const currency = currencyFromAddress(nftfiOffer.terms.loan.currency);\n  const durationInDays = calculateDurationInDays(nftfiOffer.terms.loan.duration);\n  return {\n    id: nftfiOffer.id,\n    platform: LendingPlatform.nftfi,\n    lender: nftfiOffer.lender.address.toLowerCase() as `0x${string}`,\n    offerDate: new Date(nftfiOffer.date.offered),\n    expiryDate: addDaysToDate(new Date(nftfiOffer.terms.loan.expiry * 1e3), durationInDays),\n    type: nftfiOffer.nft.id === \"0\" ? OfferType.collectionOffer : OfferType.singleItemOffer,\n    currency: currency,\n    principal: parseFloat(nftfiOffer.terms.loan.principal.toString()) / 10 ** currency.decimals,\n    durationInDays: durationInDays,\n    apr:\n      (parseFloat(nftfiOffer.terms.loan.repayment.toString()) / parseFloat(nftfiOffer.terms.loan.principal.toString()) -\n        1) *\n      (365.25 / durationInDays),\n    collateral: {\n      collectionAddress: nftfiOffer.nft.address,\n      collectionName: CollectionRegistry.getCollectionDetails(nftfiOffer.nft.address).name,\n      nftId: nftfiOffer.nft.id,\n    },\n  };\n};\n\nexport const mapError = (error: any) => {\n  const errorMessage = JSON.stringify(error.response.data.errors);\n  switch (errorMessage) {\n    case `{\"terms.loan.principal\":[\"principal is greater than available funds in lender account\"]}`:\n      return new AccountUnderfunded();\n    case `{\"terms.loan.principal\":[\"principal is greater than approved allowance on lender account\"]}`:\n      return new UnsufficientAllowance();\n    default:\n      return Error(errorMessage);\n  }\n};\n","import { encodePacked, keccak256, PrivateKeyAccount } from \"viem\";\nimport { generatePrivateKey } from \"viem/accounts\";\nimport { AxiosInstance } from \"axios\";\nimport { mainnet } from \"viem/chains\";\n\nimport { NFTfiOffer, NFTfiOfferParams, NFTfiPaginatedOffers } from \"../support/types\";\n\n// @ts-ignore\nBigInt.prototype[\"toJSON\"] = function () {\n  return this.toString();\n};\n\nexport default class Offers {\n  private account: PrivateKeyAccount;\n  private http: AxiosInstance;\n\n  constructor(account: PrivateKeyAccount, http: AxiosInstance) {\n    this.account = account;\n    this.http = http;\n  }\n\n  async get(address: `0x${string}`) {\n    const res: NFTfiPaginatedOffers = await this.http\n      .get(`/v0.1/offers`, {\n        params: { lenderAddress: address.toLowerCase() },\n      })\n      .then((res) => res.data);\n\n    return res.results;\n  }\n\n  async create(params: NFTfiOfferParams) {\n    const contractName = params.nftfi.contract.name;\n\n    switch (contractName) {\n      case \"v2-3.loan.fixed.collection\": {\n        let payload = await this.constructV2_3FixedCollectionOffer(params);\n\n        const res: { result: NFTfiOffer } = await this.http.post(\"/v0.2/offers\", payload).then((res) => res.data);\n        return res.result;\n      }\n      default: {\n        throw new Error(`${contractName} not supported`);\n      }\n    }\n  }\n\n  async delete(offerId: string) {\n    await this.http.delete(`/v0.2/offers/${offerId}`);\n  }\n\n  private async constructV2_3FixedCollectionOffer(options: NFTfiOfferParams) {\n    let offer = {\n      nft: {\n        id: 0, // offer is for whole collection\n        address: options.nft.address,\n      },\n      lender: {\n        address: this.account.address,\n        nonce: BigInt(generatePrivateKey()).toString(),\n      },\n      referrer: {\n        address: \"0x0000000000000000000000000000000000000000\" as `0x${string}`,\n      },\n      terms: {\n        loan: {\n          duration: Number(options.terms.duration),\n          repayment: ((options.terms.repayment / BigInt(1e4)) * BigInt(1e4)).toString(),\n          principal: ((options.terms.principal / BigInt(1e4)) * BigInt(1e4)).toString(),\n          currency: options.terms.currency,\n          expiry: Number(this.getExpiry(options.terms.expiry.seconds)),\n          interest: { prorated: false, bps: 0 },\n        },\n      },\n      nftfi: {\n        contract: { name: options.nftfi.contract.name },\n        fee: { bps: \"500\" },\n      },\n\n      signature: \"\",\n    };\n\n    const packed = encodePacked(\n      [\n        \"address\",\n        \"uint256\",\n        \"uint256\",\n        \"address\",\n        \"uint256\",\n        \"address\",\n        \"uint32\",\n        \"uint16\",\n        \"address\",\n        \"uint256\",\n        \"uint256\",\n        \"address\",\n        \"uint256\",\n      ],\n      [\n        offer.terms.loan.currency,\n        BigInt(offer.terms.loan.principal),\n        BigInt(offer.terms.loan.repayment),\n        offer.nft.address,\n        BigInt(offer.nft.id),\n        offer.referrer.address,\n        offer.terms.loan.duration,\n        Number(offer.nftfi.fee.bps),\n        this.account.address,\n        BigInt(offer.lender.nonce),\n        BigInt(offer.terms.loan.expiry),\n        \"0xD0C6e59B50C32530C627107F50Acc71958C4341F\",\n        BigInt(mainnet.id),\n      ],\n    );\n    offer.signature = await this.account.signMessage({\n      message: { raw: keccak256(packed) },\n    });\n    return offer;\n  }\n\n  private getExpiry(seconds: number) {\n    const currentTimestampSecs = Math.floor(Date.now() / 1000);\n    const secondsIntoTheFuture = seconds || 24 * 60 * 60; // 24 hours\n    return BigInt(currentTimestampSecs + secondsIntoTheFuture);\n  }\n}\n","import { PrivateKeyAccount } from \"viem\";\nimport { AxiosInstance } from \"axios\";\n\nimport { NFTFfiLoanCounterparty, NFTFfiLoanStatus, NFTfiLoan } from \"../support/types\";\n\nexport default class Loans {\n  private account: PrivateKeyAccount;\n  private http: AxiosInstance;\n\n  constructor(account: PrivateKeyAccount, http: AxiosInstance) {\n    this.account = account;\n    this.http = http;\n  }\n\n  public async get(\n    address: `0x${string}`,\n    counterparty: NFTFfiLoanCounterparty = NFTFfiLoanCounterparty.Lender,\n    status?: NFTFfiLoanStatus,\n  ) {\n    const res: { results: NFTfiLoan[] } = await this.http\n      .get(\"/v0.1/loans\", {\n        params: {\n          accountAddress: address,\n          counterparty: counterparty,\n          status: status,\n        },\n      })\n      .then((res) => res.data);\n\n    return res.results;\n  }\n\n  public async getAll() {\n    const limit = 100;\n    let allLoans: NFTfiLoan[] = [];\n\n    for (const status of [\"active\", \"repaid\", \"liquidated\", \"defaulted\"]) {\n      let page = 1;\n      let totalPages = 1;\n      while (page <= totalPages) {\n        const data = (\n          await this.http.get(\"/v0.2/loans\", {\n            params: { status: status, page: page, limit: limit },\n          })\n        ).data;\n\n        allLoans = allLoans.concat(data.results);\n\n        if (page === 1) {\n          // Calculate total pages only once using total count from the first page\n          const totalLoans = data.pagination.total;\n          totalPages = Math.ceil(totalLoans / limit);\n        }\n\n        page++;\n      }\n    }\n\n    console.log(`Fetched ${allLoans.length} loans.`);\n    return allLoans;\n  }\n}\n","import { Gondi } from \"gondi\";\nimport { gondiConfig, testChain } from \"./config\";\nimport axios, { AxiosInstance } from \"axios\";\nimport { generatePrivateKey, privateKeyToAccount } from \"viem/accounts\";\nimport { PrivateKeyAccount, createWalletClient, http } from \"viem\";\nimport { mainnet } from \"viem/chains\";\nimport {\n  Loan,\n  Offer,\n  LendingClientParameters,\n  PromissoryNote,\n  LendingClientWithPromissoryNotes,\n  Listing,\n  SingleItemOfferParams,\n  CollectionOfferParams,\n} from \"../types\";\nimport Loans from \"./api/loans\";\nimport Offers from \"./api/offers\";\nimport { gondiLoanMapper, gondiOfferMapper, mapError } from \"./support/mappers\";\nimport { CollectionNotSupported } from \"../errors\";\n\nconst nowPlusOffset = (offset: number) => {\n  const currentTime = new Date();\n  const currentTimePlusOffset = new Date(currentTime.getTime() + offset * 60 * 1000); // Add offset\n  return Math.floor(currentTimePlusOffset.getTime() / 1000); // Convert to seconds\n};\n\nexport interface LendingClientParametersGondi extends LendingClientParameters {\n  originationFeeInPercentage?: number;\n}\n\nexport class GondiClient implements LendingClientWithPromissoryNotes {\n  private http: AxiosInstance;\n  private readonly account: PrivateKeyAccount;\n  private loans: Loans;\n  private offers: Offers;\n  private client: Gondi;\n  private originationFeeInPercentage: number;\n\n  constructor(p: LendingClientParametersGondi) {\n    this.account = privateKeyToAccount(p.privateKey ?? generatePrivateKey());\n    this.http = axios.create({\n      baseURL: gondiConfig.baseUrl,\n    });\n\n    const wallet = createWalletClient({\n      account: privateKeyToAccount(p.privateKey ?? generatePrivateKey()),\n      transport: p.testnet ? http(gondiConfig.rpcTestnet) : http(),\n      chain: p.testnet ? testChain : mainnet,\n    });\n    this.client = new Gondi({ wallet });\n\n    this.originationFeeInPercentage = p.originationFeeInPercentage ?? 0;\n\n    this.loans = new Loans(this.http);\n    this.offers = new Offers(this.http, this.client);\n  }\n\n  public async _getCollectionId(collectionAddress: `0x${string}`, slug?: string): Promise<any> {\n    let collectionId: number;\n    if (slug) {\n      collectionId = await this.client.collectionId({\n        slug: slug,\n      });\n    } else {\n      collectionId = (\n        await this.client.collectionId({\n          contractAddress: collectionAddress,\n        })\n      )[0];\n    }\n\n    if (collectionId === undefined) {\n      throw new CollectionNotSupported();\n    }\n    return collectionId;\n  }\n\n  public async getListings(): Promise<Listing[]> {\n    throw Error(\"Not implemented\");\n  }\n\n  public async getListingsForCollection(): Promise<Listing[]> {\n    throw Error(\"Not implemented\");\n  }\n\n  public async getLoans(): Promise<Loan[]> {\n    return await this.loans.get([], false).then((res) => res.map(gondiLoanMapper));\n  }\n\n  public async getLoansForCollection(address: `0x${string}`): Promise<Loan[]> {\n    console.log(address);\n    throw Error(\"Not implemented\");\n  }\n\n  public async getLoansForAccount(address: `0x${string}`): Promise<Loan[]> {\n    return await this.loans.get([address], true).then((res) => res.map(gondiLoanMapper));\n  }\n\n  public async getMyLoans(): Promise<Loan[]> {\n    return await this.getLoansForAccount(this.account.address);\n  }\n\n  public async createSingleItemOffer(offerParams: SingleItemOfferParams): Promise<Offer> {\n    console.log(offerParams);\n    throw Error(\"Not implemented\");\n  }\n\n  public async createCollectionOffer(offerParams: CollectionOfferParams): Promise<Offer> {\n    const payload = {\n      collectionId: await this._getCollectionId(offerParams.collectionAddress, offerParams.slug),\n      principalAddress: offerParams.currency.address,\n      principalAmount: BigInt(offerParams.principal * 1e18),\n      capacity: BigInt(offerParams.principal * 1e18),\n      fee: BigInt(\n        Math.round(\n          ((offerParams.principal * this.originationFeeInPercentage * offerParams.apr * offerParams.durationInDays) /\n            365) *\n            1e18,\n        ),\n      ), // Origination fee\n      aprBps: BigInt(Math.round(offerParams.apr * (1 - this.originationFeeInPercentage) * 10000)),\n      expirationTime: BigInt(nowPlusOffset(offerParams.expiryInMinutes)),\n      duration: BigInt(Math.round(offerParams.durationInDays * 24 * 3600)),\n      requiresLiquidation: false, // Sets the collateral to be liquidated on default.\n      lenderAddress: offerParams.lenderAddress ?? this.account.address,\n      // borrowerAddress: null, // Optional: allow only this borrower to accept the offer.\n    };\n    return await this.offers\n      .createCollectionOffer(payload)\n      .then((res) => gondiOfferMapper(res))\n      .catch((error) => {\n        throw mapError(error);\n      });\n  }\n\n  public async deleteOffer(offerId: string): Promise<void> {\n    console.log(offerId);\n    throw new Error(\"Not implemented!\");\n  }\n\n  public async getOffers(): Promise<Offer[]> {\n    throw Error(\"Not implemented\");\n  }\n\n  public async getOffersForAccount(address: `0x${string}`): Promise<Offer[]> {\n    console.log(address);\n    throw new Error(\"Not implemented!\");\n  }\n\n  public async getOffersForCollection(address: `0x${string}`): Promise<Offer[]> {\n    console.log(address);\n    throw Error(\"Not implemented\");\n  }\n\n  public async getMyOffers(): Promise<Offer[]> {\n    throw new Error(\"Not implemented!\");\n  }\n\n  public async getPromissoryNote(loanId: number): Promise<PromissoryNote> {\n    console.log(loanId);\n    throw Error(\"Not implemented\");\n  }\n}\n","import { defineChain, Chain } from \"viem\";\n\nexport const gondiConfig = {\n  baseUrl: \"https://api.gondi.xyz/lending/\",\n  rpcTestnet: \"https://dev.floridast.xyz/rpc\",\n};\n\nexport const testChain: Chain = defineChain({\n  id: 31337,\n  name: \"GondiChain\",\n  network: \"GondiChain\",\n  nativeCurrency: {\n    decimals: 18,\n    name: \"Ether\",\n    symbol: \"ETH\",\n  },\n  rpcUrls: {\n    default: {\n      http: [gondiConfig.rpcTestnet],\n      webSocket: [gondiConfig.rpcTestnet],\n    },\n    public: {\n      http: [gondiConfig.rpcTestnet],\n      webSocket: [gondiConfig.rpcTestnet],\n    },\n  },\n  blockExplorers: {\n    default: { name: \"Explorer\", url: \"https://explorer.zora.energy\" },\n  },\n  contracts: {},\n});\n","import { AxiosInstance } from \"axios\";\nimport { GondiLoan } from \"../support/types\";\n\ninterface LoanEdge {\n  node: GondiLoan;\n}\n\ninterface PageInfo {\n  endCursor: string | null;\n  hasNextPage: boolean;\n}\n\ninterface SourceData {\n  totalCount: number;\n  pageInfo: PageInfo;\n  edges: LoanEdge[];\n}\n\nexport default class Loans {\n  private http: AxiosInstance;\n\n  constructor(http: AxiosInstance) {\n    this.http = http;\n  }\n\n  public async getSources(\n    addresses: `0x${string}`[] = [],\n    after: string | null = \"\",\n    includeRefinancedLoans: boolean = true,\n  ): Promise<SourceData> {\n    const payload = {\n      operationName: \"ListSources\",\n      variables: {\n        lenders: addresses,\n        statuses: [\n          \"LOAN_INITIATED\",\n          \"LOAN_DEFAULTED\",\n          \"LOAN_SENT_TO_AUCTION\",\n          \"LOAN_AUCTIONED\",\n          \"LOAN_FORECLOSED\",\n          \"LOAN_REPAID\",\n        ],\n        sortBy: { field: \"START_TIME\", order: \"DESC\" },\n        includeLost: includeRefinancedLoans,\n        first: 20,\n        terms: {},\n        currencyAddress: null,\n        after: after === \"\" ? undefined : after,\n      },\n      query:\n        \"query ListSources($lenders: [String!] = [], $statuses: [LoanStatusType!] = [], $sortBy: [SourceSortInput!] = [], $terms: TermsFilter, $includeLost: Boolean = false, $currencyAddress: Address, $first: Int = 24, $after: String) {\\n  sources: listSources(\\n    statuses: $statuses\\n    lenders: $lenders\\n    sortBy: $sortBy\\n    terms: $terms\\n    includeLost: $includeLost\\n    currencyAddress: $currencyAddress\\n    first: $first\\n    after: $after\\n  ) {\\n    totalCount\\n    pageInfo {\\n      endCursor\\n      hasNextPage\\n      __typename\\n    }\\n    edges {\\n      node {\\n        ... on LostSource {\\n          id\\n          originationFee\\n          principalAmount\\n          lenderAddress\\n          accruedInterest\\n          aprBps\\n          startTime\\n          duration\\n          loan {\\n            principalAmount\\n            principalAddress\\n            status\\n            currency {\\n              symbol\\n              decimals\\n              address\\n              __typename\\n            }\\n            nft {\\n              ...MinimalNft\\n              __typename\\n            }\\n            __typename\\n          }\\n          __typename\\n        }\\n        ... on Source {\\n          id\\n          loanId\\n          originationFee\\n          principalAmount\\n          lenderAddress\\n          accruedInterest\\n          aprBps\\n          startTime\\n          loan {\\n            status\\n            startTime\\n            duration\\n            principalAmount\\n            principalAddress\\n            address\\n            borrowerAddress\\n            loanId\\n            id\\n            timestamp\\n            txHash\\n            indexInBlock\\n            auction {\\n              id\\n              endTime\\n              status\\n              originator\\n              triggerFee\\n              settler\\n              duration\\n              startTime\\n              highestBid {\\n                amount\\n                bidder\\n                timestamp\\n                __typename\\n              }\\n              __typename\\n            }\\n            sources {\\n              accruedInterest\\n              aprBps\\n              id\\n              lenderAddress\\n              loanId\\n              originationFee\\n              principalAmount\\n              startTime\\n              __typename\\n            }\\n            currency {\\n              symbol\\n              decimals\\n              address\\n              __typename\\n            }\\n            repaidActivity {\\n              totalInterest\\n              timestamp\\n              __typename\\n            }\\n            nft {\\n              ...MinimalNft\\n              __typename\\n            }\\n            __typename\\n          }\\n          __typename\\n        }\\n        __typename\\n      }\\n      __typename\\n    }\\n    __typename\\n  }\\n}\\n\\nfragment MinimalNft on NFT {\\n  id\\n  name\\n  tokenId\\n  nftId\\n  owner\\n  image {\\n    data\\n    cacheUrl\\n    contentTypeMime\\n    accessTypeName\\n    __typename\\n  }\\n  collection {\\n    id\\n    slug\\n    name\\n    nftsCount\\n    contractData {\\n      contractAddress\\n      __typename\\n    }\\n    __typename\\n  }\\n  wrapsNfts {\\n    id\\n    name\\n    tokenId\\n    nftId\\n    owner\\n    image {\\n      data\\n      cacheUrl\\n      contentTypeMime\\n      accessTypeName\\n      __typename\\n    }\\n    collection {\\n      id\\n      slug\\n      name\\n      nftsCount\\n      contractData {\\n        contractAddress\\n        __typename\\n      }\\n      __typename\\n    }\\n    __typename\\n  }\\n  __typename\\n}\",\n    };\n    return (await this.http.post(\"graphql?operation=ListSources\", payload)).data.data.sources;\n  }\n\n  public async get(addresses: `0x${string}`[], includeRefinancedLoans: boolean): Promise<GondiLoan[]> {\n    let after: string | null = \"\";\n    let hasNextPage: boolean = false;\n    let loans: LoanEdge[] = [];\n    do {\n      const sources = await this.getSources(addresses, after, includeRefinancedLoans);\n      loans = loans.concat(sources.edges);\n      after = sources.pageInfo.endCursor;\n      hasNextPage = sources.pageInfo.hasNextPage;\n    } while (hasNextPage);\n\n    return loans.map((edge) => edge.node);\n  }\n}\n","import { Gondi } from \"gondi\";\nimport { AxiosInstance } from \"axios\";\nimport { CollectionOfferInput } from \"gondi/dist/src/model\";\nimport { GondiOffer } from \"../support/types\";\n\nexport default class Offers {\n  private http: AxiosInstance;\n  private client: Gondi;\n\n  constructor(http: AxiosInstance, client: Gondi) {\n    this.http = http;\n    this.client = client;\n  }\n\n  async createCollectionOffer(offerParams: CollectionOfferInput): Promise<GondiOffer> {\n    return this.client.makeCollectionOffer(offerParams);\n  }\n}\n","import { LendingPlatform, Loan, LoanStatus, Offer, OfferType } from \"../../types\";\nimport { currencyFromAddress } from \"../../support/currencies\";\nimport { GondiLoan, GondiOffer } from \"./types\";\nimport { CollectionRegistry } from \"../../support/CollectionRegistry\";\nimport { addDaysToDate, calculateDurationInDays } from \"../../helpers\";\n\nconst gondiStatusMapper = (status: string, sourceType: string): LoanStatus => {\n  if (sourceType === \"LostSource\") {\n    return LoanStatus.repaid;\n  } else {\n    if (status === \"loan_initiated\") {\n      return LoanStatus.ongoing;\n    } else if (status === \"loan_repaid\") {\n      return LoanStatus.repaid;\n    } else if ([\"loan_sent_to_auction\", \"loan_defaulted\"]) {\n      return LoanStatus.defaulted;\n    } else {\n      return LoanStatus.liquidated;\n    }\n  }\n};\n\nexport const gondiLoanMapper = (gondiLoan: GondiLoan): Loan => {\n  const currency = currencyFromAddress(gondiLoan.loan.currency.address);\n  const durationInDays = calculateDurationInDays(parseInt(gondiLoan.duration ?? gondiLoan.loan.duration));\n  const principal = parseInt(gondiLoan.principalAmount) / 10 ** currency.decimals;\n  const apr = parseInt(gondiLoan.aprBps) / 10000;\n  return {\n    id: gondiLoan.id,\n    platform: LendingPlatform.gondi,\n    borrower: (gondiLoan.loan.borrowerAddress ?? gondiLoan.loan.nft.owner).toLowerCase() as `0x${string}`,\n    lender: gondiLoan.lenderAddress.toLowerCase() as `0x${string}`,\n    status: gondiStatusMapper(gondiLoan.loan.status, gondiLoan.__typename),\n    startDate: new Date(gondiLoan.startTime),\n    endDate: gondiLoan.loan.repaidActivity\n      ? new Date(gondiLoan.loan.repaidActivity.timestamp)\n      : addDaysToDate(new Date(gondiLoan.startTime), durationInDays),\n    currency: currency,\n    principal: parseInt(gondiLoan.principalAmount) / 10 ** currency.decimals,\n    interestPayment: (principal * apr * durationInDays) / 365,\n    durationInDays: durationInDays,\n    apr: parseInt(gondiLoan.aprBps) / 10000,\n    collateral: [\n      {\n        collectionAddress: gondiLoan.loan.nft.collection.contractData.contractAddress.toLowerCase() as `0x${string}`,\n        collectionName: CollectionRegistry.getCollectionDetails(\n          gondiLoan.loan.nft.collection.contractData.contractAddress.toLowerCase() as `0x${string}`,\n        ).name,\n        nftId: parseInt(gondiLoan.loan.nft.tokenId),\n      },\n    ],\n  };\n};\n\nexport const gondiOfferMapper = (gondiOffer: GondiOffer): Offer => {\n  const currency = currencyFromAddress(gondiOffer.principalAddress);\n  const durationInDays = Number(gondiOffer.duration) / 24 / 3600;\n  return {\n    id: gondiOffer.id.toString(),\n    platform: LendingPlatform.gondi,\n    lender: gondiOffer.lenderAddress,\n    offerDate: new Date(),\n    expiryDate: new Date(Number(gondiOffer.expirationTime) * 1e3),\n    type: gondiOffer.nftCollateralTokenId === 0n ? OfferType.collectionOffer : OfferType.singleItemOffer,\n    currency: currency,\n    principal: Number(gondiOffer.principalAmount) / 10 ** currency.decimals,\n    durationInDays: durationInDays,\n    apr: Number(gondiOffer.aprBps) / 10000,\n    collateral: {\n      collectionAddress: gondiOffer.nftCollateralAddress,\n      collectionName: CollectionRegistry.getCollectionDetails(gondiOffer.nftCollateralAddress).name,\n      nftId: Number(gondiOffer.nftCollateralTokenId).toString(),\n    },\n  };\n};\n\nexport const mapError = (error: any) => {\n  const errorMessage = JSON.stringify(error.response.data.errors);\n  switch (errorMessage) {\n    // case `Field 'collectionId' of required type 'Int!' was not provided.`:\n    //   return new CollectionNotSupported();\n    default:\n      return Error(errorMessage);\n  }\n};\n","import { generatePrivateKey } from \"viem/accounts\";\n\nexport const config = {\n  defaultRpc: \"https://eth.llamarpc.com\" as `https://${string}`,\n  defaultPrivateKey: generatePrivateKey(),\n  blur: {\n    baseUrlHome: \"https://blur.io/\",\n    baseUrlAuth: \"https://core-api.prod.blur.io/auth\",\n    baseUrlBlend: \"https://core-api.prod.blur.io/v1/blend\",\n    baseUrlPortfolio: \"https://core-api.prod.blur.io/v1/portfolio\",\n  },\n};\n","import puppeteer from \"puppeteer-extra\";\nimport StealthPlugin from \"puppeteer-extra-plugin-stealth\";\nimport { Page, Browser } from \"puppeteer\";\nimport { PrivateKeyAccount, createWalletClient, WalletClient, http } from \"viem\";\nimport { mainnet } from \"viem/chains\";\nimport { privateKeyToAccount } from \"viem/accounts\";\nimport { BlurLoan, BlurOffer } from \"./support/types\";\nimport { LendingPlatform, Offer, OfferType } from \"../types\";\nimport { BETH } from \"../support/currencies\";\nimport { config } from \"../config\";\n\npuppeteer.use(StealthPlugin());\n\nexport class GhostApi {\n  private client: WalletClient;\n  private account: PrivateKeyAccount;\n  private browser: Browser | null;\n  private page: Page | null;\n  private initialised: boolean;\n\n  constructor(privateKey: `0x${string}`, rpcUrl: `https://${string}` = config.defaultRpc) {\n    this.account = privateKeyToAccount(privateKey);\n    this.client = createWalletClient({\n      account: this.account,\n      chain: mainnet,\n      transport: http(rpcUrl),\n    });\n    this.browser = null;\n    this.page = null;\n    this.initialised = false;\n  }\n\n  public async initialise() {\n    if (this.initialised) {\n      return;\n    }\n    this.browser = await puppeteer.launch({\n      headless: \"new\",\n      args: [\n        \"--no-sandbox\",\n        \"--disable-setuid-sandbox\",\n        \"--disable-dev-shm-usage\",\n        \"--disable-accelerated-2d-canvas\",\n        \"--no-first-run\",\n        \"--no-zygote\",\n        \"--disable-gpu\",\n      ],\n    });\n    this.page = await this.browser.newPage();\n    await this.page.goto(config.blur.baseUrlHome);\n    const challenge: any = await this.challenge();\n    const signedMessage = await this.account.signMessage({ message: challenge.message });\n    const authToken: any = await this.login(challenge, signedMessage);\n    this.createCookie(authToken);\n    this.initialised = true;\n  }\n\n  private getPage(): Page {\n    return this.page as Page;\n  }\n\n  private async get(url: string): Promise<any> {\n    return await this.getPage().evaluate(\n      async (url, options) => {\n        const response = await fetch(url, options);\n        return response.json();\n      },\n      url,\n      {\n        method: \"GET\",\n        credentials: \"include\",\n      } as RequestInit,\n    );\n  }\n\n  private async post(url: string, payload: {}): Promise<any> {\n    const response = (await this.getPage().evaluate(\n      async (url, options) => {\n        const response = await fetch(url, options);\n        return response.json();\n      },\n      url,\n      {\n        method: \"POST\",\n        headers: { \"Content-Type\": \"application/json\" },\n        body: JSON.stringify(payload),\n        credentials: \"include\",\n      } as RequestInit,\n    )) as any;\n\n    if (response.statusCode && response.statusCode !== 200) {\n      throw Error(response.message);\n    }\n\n    return response;\n  }\n\n  private async challenge() {\n    return await this.post(`${config.blur.baseUrlAuth}/challenge`, { walletAddress: this.account.address });\n  }\n\n  private async login(challenge: {}, signedMessage: `0x${string}`) {\n    return await this.post(`${config.blur.baseUrlAuth}/login`, { ...challenge, signature: signedMessage });\n  }\n\n  private async createCookie(authToken: { accessToken: string }) {\n    return await this.post(`${config.blur.baseUrlAuth}/cookie`, { authToken: authToken.accessToken });\n  }\n\n  public async getLiens(address: `0x${string}`): Promise<BlurLoan[]> {\n    await this.initialise();\n    const liens = await this.get(`${config.blur.baseUrlPortfolio}/${address.toLowerCase()}/liens`);\n    return liens.liens;\n  }\n\n  public async getLoanOffers(accountAddress: `0x${string}`, collectionAddress?: `0x${string}`): Promise<BlurOffer[]> {\n    await this.initialise();\n    const loans = await this.get(\n      `${config.blur.baseUrlPortfolio}/${accountAddress.toLowerCase()}/loan-offers?contractAddress=${collectionAddress}`,\n    );\n\n    return loans.loanOffers;\n  }\n\n  public async postLoanOffer(\n    collectionAddress: `0x${string}`,\n    principal: number,\n    limit: number,\n    apr: number,\n    expiryInMinutes: number,\n  ): Promise<Offer> {\n    await this.initialise();\n\n    // Format the query\n    const format = await this.post(`${config.blur.baseUrlBlend}/loan-offer/format`, {\n      contractAddress: collectionAddress.toLowerCase(),\n      orders: [\n        {\n          contractAddress: collectionAddress.toLowerCase(),\n          expirationTime: new Date(new Date().getTime() + expiryInMinutes * 60 * 1000).toISOString(),\n          maxAmount: principal.toString(),\n          rate: apr * 10000,\n          totalAmount: limit.toString(),\n        },\n      ],\n      userAddress: this.account.address.toLowerCase(),\n    });\n\n    // Signing\n    const signData = format.signatures[0].signData;\n    signData.value.minAmount = BigInt(signData.value.minAmount.hex);\n    signData.value.maxAmount = BigInt(signData.value.maxAmount.hex);\n    signData.value.totalAmount = BigInt(signData.value.totalAmount.hex);\n    signData.value.salt = BigInt(signData.value.salt.hex);\n    signData.value.auctionDuration = BigInt(signData.value.auctionDuration.hex);\n    signData.value.expirationTime = BigInt(signData.value.expirationTime.hex);\n\n    const signature = await this.account.signTypedData({\n      domain: signData.domain,\n      types: signData.types,\n      primaryType: \"LoanOffer\",\n      message: signData.value,\n    });\n\n    // Submit the offer\n    const response = await this.post(`${config.blur.baseUrlBlend}/loan-offer/submit`, {\n      contractAddress: collectionAddress.toLowerCase(),\n      orders: [\n        {\n          contractAddress: collectionAddress.toLowerCase(),\n          expirationTime: new Date(new Date().getTime() + expiryInMinutes * 60 * 1000).toISOString(),\n          maxAmount: principal.toString(),\n          rate: apr * 10000,\n          totalAmount: limit.toString(),\n          signature: signature,\n          marketplaceData: format.signatures[0].marketplaceData,\n        },\n      ],\n      userAddress: this.account.address.toLowerCase(),\n    });\n\n    return {\n      id: response.hashes[0],\n      platform: LendingPlatform.blur,\n      lender: this.account.address,\n      offerDate: new Date(),\n      expiryDate: new Date(new Date().getTime() + expiryInMinutes * 60 * 1000),\n      type: OfferType.collectionOffer,\n      currency: BETH,\n      principal: principal,\n      durationInDays: 0,\n      apr: apr,\n      collateral: {\n        collectionAddress: collectionAddress,\n        collectionName: \"\",\n        nftId: \"\",\n      },\n    };\n  }\n\n  public async recallLoan(collectionAddress: `0x${string}`, loanId: string, nftId: string) {\n    await this.initialise();\n\n    // Fetching the tx data\n    const payload = {\n      userAddress: this.account.address.toLowerCase(),\n      contractAddress: collectionAddress.toLowerCase(),\n      lienRequests: [\n        {\n          lienId: loanId,\n          tokenId: nftId,\n        },\n      ],\n    };\n    const format = await this.post(`${config.blur.baseUrlBlend}/loan-offer/end`, payload);\n\n    // Sending the transaction\n    const tx = format.data.actions[0].txnData;\n    await this.client.sendTransaction(tx);\n    // const signedTx = await this.client.signTransaction(tx);\n    // await this.client.sendRawTransaction({ serializedTransaction: signedTx });\n  }\n}\n","import { BETH, WETH } from \"../..\";\nimport { BlurLoan, BlurOffer } from \"./types\";\nimport { Loan, LendingPlatform, LoanStatus, Offer, OfferType } from \"../../types\";\nimport { CollectionRegistry } from \"../../support/CollectionRegistry\";\n\nexport const blurLoanMapper = (blurLoan: BlurLoan): Loan => {\n  const durationInDays = (new Date().getTime() - new Date(blurLoan.lien.createdAt).getTime()) / (1000 * 3600 * 24);\n\n  return {\n    id: blurLoan.lien.lienId,\n    platform: LendingPlatform.blur,\n    borrower: blurLoan.lien.borrower.address,\n    lender: blurLoan.lien.lender.address,\n    status: blurLoan.lien.repaidAt\n      ? LoanStatus.repaid\n      : blurLoan.lien.auctionStartedAt\n        ? LoanStatus.auctioned\n        : LoanStatus.ongoing,\n    startDate: new Date(blurLoan.lien.createdAt),\n    endDate: new Date(),\n    currency: WETH,\n    principal: parseFloat(blurLoan.lien.principal.amount),\n    interestPayment:\n      (((durationInDays / 365) * parseFloat(blurLoan.lien.interestRateBips)) / 10000) *\n      parseFloat(blurLoan.lien.principal.amount),\n    durationInDays: durationInDays,\n    apr: parseFloat(blurLoan.lien.interestRateBips) / 10000,\n    collateral: [\n      {\n        collectionAddress: blurLoan.lien.contractAddress,\n        collectionName: CollectionRegistry.getCollectionDetails(blurLoan.lien.contractAddress).name,\n        nftId: parseInt(blurLoan.nft.tokenId),\n      },\n    ],\n  };\n};\n\nexport const blurOfferMapper = (blurOffer: BlurOffer, lender: `0x${string}`): Offer => {\n  return {\n    id: blurOffer.hash,\n    platform: LendingPlatform.blur,\n    lender: lender,\n    offerDate: new Date(blurOffer.createdAt),\n    expiryDate: new Date(blurOffer.expiresOn),\n    type: OfferType.collectionOffer,\n    currency: BETH,\n    principal: Number(blurOffer.maxAmount),\n    durationInDays: 0,\n    apr: Number(blurOffer.interestRate),\n    collateral: {\n      collectionAddress: blurOffer.contractAddress,\n      collectionName: CollectionRegistry.getCollectionDetails(blurOffer.contractAddress).name,\n      nftId: \"0\",\n    },\n  };\n};\n","import {\n  Loan,\n  Offer,\n  LendingClientParameters,\n  Listing,\n  SingleItemOfferParams,\n  CollectionOfferParams,\n  LendingClientBlur,\n} from \"../types\";\nimport { config } from \"../config\";\nimport { GhostApi } from \"./GhostApi\";\nimport { blurLoanMapper, blurOfferMapper } from \"./support/mappers\";\n\nexport class BlurClient implements LendingClientBlur {\n  private api: GhostApi;\n\n  constructor(p: LendingClientParameters) {\n    this.api = new GhostApi(p.privateKey ?? config.defaultPrivateKey, p.rpcUrl ?? config.defaultRpc);\n  }\n\n  public async getListings(): Promise<Listing[]> {\n    throw Error(\"Not implemented\");\n  }\n\n  public async getListingsForCollection(): Promise<Listing[]> {\n    throw Error(\"Not implemented\");\n  }\n\n  public async getLoans(): Promise<Loan[]> {\n    throw Error(\"Not implemented\");\n  }\n\n  public async getLoansForCollection(address: `0x${string}`): Promise<Loan[]> {\n    console.log(address);\n    throw Error(\"Not implemented\");\n  }\n\n  public async getLoansForAccount(address: `0x${string}`): Promise<Loan[]> {\n    return await this.api.getLiens(address).then((res) => res.map(blurLoanMapper));\n  }\n\n  public async getMyLoans(): Promise<Loan[]> {\n    throw Error(\"Not implemented\");\n  }\n\n  public async createSingleItemOffer(offerParams: SingleItemOfferParams): Promise<Offer> {\n    console.log(offerParams);\n    throw Error(\"Not implemented\");\n  }\n\n  public async createCollectionOffer(offerParams: CollectionOfferParams): Promise<Offer> {\n    return await this.api.postLoanOffer(\n      offerParams.collectionAddress,\n      offerParams.principal,\n      offerParams.limit ?? offerParams.principal,\n      offerParams.apr,\n      offerParams.expiryInMinutes,\n    );\n  }\n\n  public async deleteOffer(offerId: string): Promise<void> {\n    console.log(offerId);\n    throw new Error(\"Not implemented!\");\n  }\n\n  public async getOffers(): Promise<Offer[]> {\n    throw Error(\"Not implemented\");\n  }\n\n  public async getOffersForAccount(address: `0x${string}`): Promise<Offer[]> {\n    return await this.api.getLoanOffers(address).then((res) => res.map((x) => blurOfferMapper(x, address)));\n  }\n\n  public async getOffersForCollection(address: `0x${string}`): Promise<Offer[]> {\n    console.log(address);\n    throw Error(\"Not implemented\");\n  }\n\n  public async getMyOffers(): Promise<Offer[]> {\n    throw new Error(\"Not implemented!\");\n  }\n\n  public async recallLoan(collectionAddress: `0x${string}`, loanId: string, nftId: number): Promise<void> {\n    await this.api.recallLoan(collectionAddress, loanId, nftId.toString());\n  }\n}\n","import axios, { AxiosInstance } from \"axios\";\n\nexport class DeepNftValueClient {\n  private readonly apiKey: string;\n  private axiosInstance: AxiosInstance;\n\n  constructor(apiKey: string = \"6d3b85e2e7d3679c55dedc0f2b21ef2a72018061\") {\n    this.apiKey = apiKey;\n    this.axiosInstance = axios.create({\n      baseURL: \"https://api.deepnftvalue.com/v2\",\n      headers: {\n        Authorization: `Token ${this.apiKey}`,\n        accept: \"application/json\",\n      },\n    });\n  }\n\n  public async getValuation(collectionAddress: `0x${string}`, tokenId: number, chainId: number = 1): Promise<number> {\n    try {\n      // Mapping certains addresses\n      let collectionAddress2: `0x${string}`;\n      if (collectionAddress.toLowerCase() === \"0xb7f7f6c52f2e2fdb1963eab30438024864c313f6\") {\n        // Wrapped cryptopunks to cryptopunks\n        collectionAddress2 = \"0xb47e3cd837dDF8e4c57F05d70Ab865de6e193BBB\";\n      } else {\n        collectionAddress2 = collectionAddress;\n      }\n\n      const response = await this.axiosInstance.get(`/valuations`, {\n        params: {\n          contract: collectionAddress2,\n          chain_id: chainId,\n          token_ids: tokenId.toString(),\n        },\n      });\n\n      if (response.data.results[0] !== undefined) {\n        return parseFloat(response.data.results[0].price);\n      } else {\n        return 0;\n      }\n    } catch (error) {\n      return 0;\n    }\n  }\n}\n","import axios, { AxiosInstance } from \"axios\";\n\ntype CollectionsAnswer = {\n  collections: {\n    name: string;\n    floorAsk: { price: { amount: { native: number; usd: number } } };\n    topBid: { price: { amount: { native: number; usd: number } } };\n  }[];\n};\n\ntype Quotes = { bid: { eth: number; usd: number }; ask: { eth: number; usd: number } };\n\nexport class ReservoirClient {\n  private readonly apiKey: string;\n  private axiosInstance: AxiosInstance;\n\n  constructor(apiKey: string = \"demo-api-key\") {\n    this.apiKey = apiKey;\n    this.axiosInstance = axios.create({\n      baseURL: \"https://api.reservoir.tools\",\n      headers: {\n        \"X-Api-Key\": this.apiKey,\n        Accept: \"*/*\",\n      },\n    });\n  }\n\n  public async getQuotes(collectionAddress: `0x${string}`): Promise<Quotes> {\n    // In case it's an address within the cryptopunks universe\n    if (\n      [\n        \"0xb47e3cd837dDF8e4c57F05d70Ab865de6e193BBB\",\n        \"0xb7F7F6C52F2e2fdb1963Eab30438024864c313F6\",\n        \"0x000000000000003607fce1aC9e043a86675C5C2F\",\n      ].includes(collectionAddress)\n    ) {\n      return await this.getQuotesForPunks();\n    }\n\n    // Otherwise\n    const response: CollectionsAnswer = await this.axiosInstance\n      .get(`/collections/v7`, {\n        params: { id: collectionAddress },\n      })\n      .then((response) => response.data);\n\n    const bidPrice = response.collections[0].topBid.price || response.collections[0].floorAsk.price;\n    const askPrice = response.collections[0].floorAsk.price || response.collections[0].topBid.price;\n\n    return {\n      bid: {\n        eth: bidPrice.amount.native,\n        usd: bidPrice.amount.usd,\n      },\n      ask: {\n        eth: askPrice.amount.native,\n        usd: askPrice.amount.usd,\n      },\n    };\n  }\n\n  public async getQuotesBySlug(slug: string): Promise<Quotes> {\n    const response: CollectionsAnswer = await this.axiosInstance\n      .get(`/collections/v7`, {\n        params: { slug: slug },\n      })\n      .then((response) => response.data);\n\n    const bidPrice = response.collections[0].topBid.price || response.collections[0].floorAsk.price;\n    const askPrice = response.collections[0].floorAsk.price || response.collections[0].topBid.price;\n\n    return {\n      bid: {\n        eth: bidPrice.amount.native,\n        usd: bidPrice.amount.usd,\n      },\n      ask: {\n        eth: askPrice.amount.native,\n        usd: askPrice.amount.usd,\n      },\n    };\n  }\n\n  public async getQuotesForPunks(): Promise<Quotes> {\n    const response: CollectionsAnswer = await this.axiosInstance\n      .get(`/collections/v7`, {\n        params: {\n          contract: [\n            \"0xb47e3cd837dDF8e4c57F05d70Ab865de6e193BBB\",\n            \"0xb7F7F6C52F2e2fdb1963Eab30438024864c313F6\",\n            \"0x000000000000003607fce1aC9e043a86675C5C2F\",\n          ],\n        },\n      })\n      .then((response) => response.data);\n\n    let bidPriceNative = 0;\n    let bidPriceUsd = 0;\n    let askPriceNative = 999999999;\n    let askPriceUsd = 999999999;\n    for (let i = 0; i < 3; i++) {\n      if (response.collections[i].topBid.price) {\n        bidPriceNative = Math.max(response.collections[i].topBid.price.amount.native, bidPriceNative);\n        bidPriceUsd = Math.max(response.collections[i].topBid.price.amount.usd, bidPriceUsd);\n      }\n      if (response.collections[i].floorAsk.price) {\n        askPriceNative = Math.min(response.collections[i].floorAsk.price.amount.native, askPriceNative);\n        askPriceUsd = Math.min(response.collections[i].floorAsk.price.amount.usd, askPriceUsd);\n      }\n    }\n\n    return {\n      bid: {\n        eth: bidPriceNative,\n        usd: bidPriceUsd,\n      },\n      ask: {\n        eth: askPriceNative,\n        usd: askPriceUsd,\n      },\n    };\n  }\n\n  public async getCollectionActivity(collection: string, attributes: string, continuation: string) {\n    const url = `/collections/activity/v6`;\n    const response = await this.axiosInstance.get(url, {\n      params: {\n        collection,\n        attributes,\n        continuation,\n      },\n    });\n\n    return response.data;\n  }\n}\n","import { DeepNftValueClient } from \"../deepnftvalue/DeepNftValueClient\";\nimport { LendingClient, Loan, Offer, CollectionOfferParams } from \"../types\";\n\nexport class PortfolioClient {\n  private readonly clients: LendingClient[];\n  private readonly addresses: `0x${string}`[];\n  private readonly pricer: DeepNftValueClient;\n\n  constructor(clients: LendingClient[], addresses: `0x${string}`[]) {\n    this.clients = clients;\n    this.addresses = addresses;\n    this.pricer = new DeepNftValueClient();\n  }\n\n  public async createCollectionOffer(offerParams: CollectionOfferParams, logs: boolean = true) {\n    const promises = [];\n    for (const client of this.clients) {\n      promises.push(\n        client\n          .createCollectionOffer(offerParams)\n          .then(() => (logs ? console.log(`${client.constructor.name} ✓`) : null))\n          .catch((error) => (logs ? console.error(`${client.constructor.name} ${error}`) : null)),\n      );\n    }\n    await Promise.all(promises);\n  }\n\n  public async getMyLoans(): Promise<Loan[]> {\n    let loans: Loan[] = [];\n    for (const client of this.clients) {\n      for (const address of this.addresses) {\n        loans = loans.concat(await client.getLoansForAccount(address));\n      }\n    }\n\n    return loans;\n  }\n\n  public async priceMyLoans(loans: Loan[]): Promise<Loan[]> {\n    for (const loan of loans) {\n      if (loan.status === \"ongoing\" || loan.status === \"auctioned\") {\n        const collateralPrice = await this.pricer.getValuation(\n          loan.collateral[0].collectionAddress,\n          loan.collateral[0].nftId,\n        );\n        if (collateralPrice === 0) {\n          loan.valuation = loan.principal;\n        } else {\n          loan.valuation = Math.min(loan.principal, collateralPrice);\n        }\n      } else {\n        loan.valuation = 0;\n      }\n    }\n\n    return loans;\n  }\n\n  public async getMyOffers(): Promise<Offer[]> {\n    throw Error(\"Not implemented\");\n  }\n}\n","import { PortfolioClient } from \"..\";\nimport { Currency } from \"../types\";\nimport { CollectionRegistry } from \"./CollectionRegistry\";\n\ntype LoanTerm = { currency: Currency; principal: number; durationInDays: number; apr: number };\ntype CollectionOffers = Record<`0x${string}`, LoanTerm[]>;\n\nexport class Loaner {\n  private readonly portfolioClient: PortfolioClient;\n  private collectionOffers: CollectionOffers;\n\n  constructor(portfolioClient: PortfolioClient) {\n    this.portfolioClient = portfolioClient;\n    this.collectionOffers = {};\n  }\n\n  public updateCollectionOffers(collectionAddress: `0x${string}`, loanTerms: LoanTerm[]) {\n    this.collectionOffers[collectionAddress] = loanTerms;\n  }\n\n  public async publishCollectionOffers(expiryInMinutes: number = 10, logs: boolean = true) {\n    for (const [collectionAddress, loanTerms] of Object.entries(this.collectionOffers)) {\n      const collectionName = CollectionRegistry.getCollectionDetails(collectionAddress as `0x${string}`).name;\n      for (const loanTerm of loanTerms) {\n        if (logs) {\n          console.log(\n            `publishing collection offer on ${collectionName}: principal=${\n              loanTerm.principal\n            } ${loanTerm.currency.symbol.toLowerCase()} | duration=${loanTerm.durationInDays} days | apr=${\n              loanTerm.apr * 100\n            }%`,\n          );\n        }\n        await this.portfolioClient.createCollectionOffer(\n          {\n            collectionAddress: collectionAddress as `0x${string}`,\n            currency: loanTerm.currency,\n            principal: loanTerm.principal,\n            apr: loanTerm.apr,\n            durationInDays: loanTerm.durationInDays,\n            expiryInMinutes: expiryInMinutes,\n          },\n          logs,\n        );\n      }\n    }\n  }\n}\n"]}