@axonfi/plugin-elizaos 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../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/exports/index.ts","../../../node_modules/viem/utils/abi/formatAbiItem.ts","../../../node_modules/viem/utils/data/isHex.ts","../../../node_modules/viem/utils/data/size.ts","../../../node_modules/viem/errors/version.ts","../../../node_modules/viem/errors/base.ts","../../../node_modules/viem/errors/abi.ts","../../../node_modules/viem/errors/data.ts","../../../node_modules/viem/utils/data/pad.ts","../../../node_modules/viem/errors/encoding.ts","../../../node_modules/viem/utils/data/trim.ts","../../../node_modules/viem/utils/encoding/fromHex.ts","../../../node_modules/viem/utils/encoding/toHex.ts","../../../node_modules/viem/utils/encoding/toBytes.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/hashSignature.ts","../../../node_modules/viem/utils/hash/normalizeSignature.ts","../../../node_modules/viem/utils/hash/toSignature.ts","../../../node_modules/viem/utils/hash/toSignatureHash.ts","../../../node_modules/viem/utils/hash/toEventSelector.ts","../../../node_modules/viem/errors/address.ts","../../../node_modules/viem/utils/lru.ts","../../../node_modules/viem/utils/address/getAddress.ts","../../../node_modules/viem/utils/address/isAddress.ts","../../../node_modules/viem/utils/data/concat.ts","../../../node_modules/viem/utils/data/slice.ts","../../../node_modules/viem/utils/regex.ts","../../../node_modules/viem/utils/abi/encodeAbiParameters.ts","../../../node_modules/viem/utils/hash/toFunctionSelector.ts","../../../node_modules/viem/utils/abi/getAbiItem.ts","../../../node_modules/viem/accounts/utils/parseAccount.ts","../../../node_modules/viem/utils/abi/prepareEncodeFunctionData.ts","../../../node_modules/viem/utils/abi/encodeFunctionData.ts","../../../node_modules/viem/constants/solidity.ts","../../../node_modules/viem/errors/cursor.ts","../../../node_modules/viem/utils/cursor.ts","../../../node_modules/viem/utils/encoding/fromBytes.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/constants/unit.ts","../../../node_modules/viem/utils/unit/formatUnits.ts","../../../node_modules/viem/utils/unit/formatEther.ts","../../../node_modules/viem/utils/unit/formatGwei.ts","../../../node_modules/viem/errors/stateOverride.ts","../../../node_modules/viem/errors/transaction.ts","../../../node_modules/viem/errors/utils.ts","../../../node_modules/viem/errors/contract.ts","../../../node_modules/viem/errors/request.ts","../../../node_modules/viem/errors/rpc.ts","../../../node_modules/@noble/hashes/src/_md.ts","../../../node_modules/@noble/hashes/src/sha2.ts","../../../node_modules/@noble/hashes/src/hmac.ts","../../../node_modules/viem/node_modules/@noble/curves/src/abstract/utils.ts","../../../node_modules/viem/node_modules/@noble/curves/src/abstract/modular.ts","../../../node_modules/viem/node_modules/@noble/curves/src/abstract/curve.ts","../../../node_modules/viem/node_modules/@noble/curves/src/abstract/weierstrass.ts","../../../node_modules/viem/node_modules/@noble/curves/src/_shortw_utils.ts","../../../node_modules/viem/node_modules/@noble/curves/src/abstract/hash-to-curve.ts","../../../node_modules/viem/node_modules/@noble/curves/src/secp256k1.ts","../../../node_modules/viem/errors/node.ts","../../../node_modules/viem/utils/errors/getNodeError.ts","../../../node_modules/viem/utils/formatters/extract.ts","../../../node_modules/viem/utils/formatters/formatter.ts","../../../node_modules/viem/utils/formatters/transactionRequest.ts","../../../node_modules/viem/utils/stateOverride.ts","../../../node_modules/viem/constants/number.ts","../../../node_modules/viem/utils/transaction/assertRequest.ts","../../../node_modules/viem/utils/address/isAddressEqual.ts","../../../node_modules/viem/errors/chain.ts","../../../node_modules/viem/utils/abi/encodeDeployData.ts","../../../node_modules/viem/utils/promise/withResolvers.ts","../../../node_modules/viem/utils/promise/createBatchScheduler.ts","../../../node_modules/viem/utils/getAction.ts","../../../node_modules/viem/utils/errors/getContractError.ts","../../../node_modules/viem/actions/public/estimateGas.ts","../../../node_modules/viem/accounts/utils/publicKeyToAddress.ts","../../../node_modules/viem/utils/signature/recoverPublicKey.ts","../../../node_modules/viem/utils/signature/recoverAddress.ts","../../../node_modules/viem/utils/authorization/hashAuthorization.ts","../../../node_modules/viem/utils/encoding/toRlp.ts","../../../node_modules/viem/utils/authorization/recoverAuthorizationAddress.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/utils/formatters/block.ts","../../../node_modules/viem/utils/formatters/transaction.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/blob/blobsToCommitments.ts","../../../node_modules/viem/utils/blob/blobsToProofs.ts","../../../node_modules/viem/utils/blob/commitmentToVersionedHash.ts","../../../node_modules/@noble/hashes/src/sha256.ts","../../../node_modules/viem/utils/hash/sha256.ts","../../../node_modules/viem/utils/blob/commitmentsToVersionedHashes.ts","../../../node_modules/viem/constants/blob.ts","../../../node_modules/viem/constants/kzg.ts","../../../node_modules/viem/errors/blob.ts","../../../node_modules/viem/utils/blob/toBlobs.ts","../../../node_modules/viem/utils/blob/toBlobSidecars.ts","../../../node_modules/viem/utils/transaction/getTransactionType.ts","../../../node_modules/viem/actions/public/fillTransaction.ts","../../../node_modules/viem/utils/errors/getTransactionError.ts","../../../node_modules/viem/actions/public/getChainId.ts","../../../node_modules/viem/utils/formatters/log.ts","../../../node_modules/viem/utils/observe.ts","../../../node_modules/viem/utils/wait.ts","../../../node_modules/viem/utils/poll.ts","../../../node_modules/viem/utils/promise/withCache.ts","../../../node_modules/viem/actions/public/getBlockNumber.ts","../../../node_modules/viem/actions/wallet/writeContract.ts","../../../node_modules/viem/errors/account.ts","../../../node_modules/viem/actions/wallet/sendTransaction.ts","../../../node_modules/viem/utils/chain/assertCurrentChain.ts","../../../node_modules/viem/actions/wallet/sendRawTransaction.ts","../../../node_modules/viem/actions/wallet/waitForCallsStatus.ts","../../../node_modules/viem/errors/calls.ts","../../../node_modules/viem/utils/promise/withRetry.ts","../../../node_modules/viem/actions/wallet/getCallsStatus.ts","../../../node_modules/viem/utils/formatters/transactionReceipt.ts","../../../node_modules/viem/actions/wallet/sendCalls.ts","../../../node_modules/viem/clients/createClient.ts","../../../node_modules/viem/utils/uid.ts","../../../node_modules/viem/utils/authorization/serializeAuthorizationList.ts","../../../node_modules/viem/utils/transaction/serializeTransaction.ts","../../../node_modules/viem/utils/transaction/assertTransaction.ts","../../../node_modules/viem/utils/transaction/serializeAccessList.ts","../../../node_modules/viem/utils/buildRequest.ts","../../../node_modules/viem/utils/promise/withDedupe.ts","../../../node_modules/viem/utils/chain/defineChain.ts","../../../node_modules/viem/utils/index.ts","../../../node_modules/viem/utils/rpc/http.ts","../../../node_modules/viem/utils/promise/withTimeout.ts","../../../node_modules/viem/utils/rpc/id.ts","../../../node_modules/viem/utils/signature/hashMessage.ts","../../../node_modules/viem/constants/strings.ts","../../../node_modules/viem/utils/signature/toPrefixedMessage.ts","../../../node_modules/viem/utils/signature/hashTypedData.ts","../../../node_modules/viem/utils/typedData.ts","../../../node_modules/viem/errors/typedData.ts","../../../node_modules/viem/errors/unit.ts","../../../node_modules/viem/utils/unit/parseUnits.ts","../../../node_modules/viem/actions/public/getTransaction.ts","../../../node_modules/viem/actions/public/getTransactionReceipt.ts","../../../node_modules/viem/utils/signature/serializeSignature.ts","../../../node_modules/viem/actions/public/waitForTransactionReceipt.ts","../../../node_modules/viem/actions/public/watchBlockNumber.ts","../../../node_modules/viem/actions/wallet/sendRawTransactionSync.ts","../../../node_modules/viem/actions/wallet/addChain.ts","../../../node_modules/viem/actions/wallet/deployContract.ts","../../../node_modules/viem/actions/wallet/getAddresses.ts","../../../node_modules/viem/actions/wallet/getCapabilities.ts","../../../node_modules/viem/actions/wallet/getPermissions.ts","../../../node_modules/viem/actions/wallet/prepareAuthorization.ts","../../../node_modules/viem/actions/wallet/requestAddresses.ts","../../../node_modules/viem/actions/wallet/requestPermissions.ts","../../../node_modules/viem/actions/wallet/sendCallsSync.ts","../../../node_modules/viem/actions/wallet/sendTransactionSync.ts","../../../node_modules/viem/actions/wallet/showCallsStatus.ts","../../../node_modules/viem/actions/wallet/signAuthorization.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/actions/wallet/writeContractSync.ts","../../../node_modules/viem/clients/decorators/wallet.ts","../../../node_modules/viem/clients/createWalletClient.ts","../../../node_modules/viem/clients/transports/createTransport.ts","../../../node_modules/viem/clients/transports/http.ts","../../../node_modules/viem/errors/transport.ts","../../../node_modules/viem/index.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/signAuthorization.ts","../../../node_modules/viem/accounts/utils/signMessage.ts","../../../node_modules/viem/accounts/utils/signTransaction.ts","../../../node_modules/viem/accounts/utils/signTypedData.ts","../../../node_modules/viem/op-stack/contracts.ts","../../../node_modules/viem/op-stack/formatters.ts","../../../node_modules/viem/op-stack/serializers.ts","../../../node_modules/viem/op-stack/chainConfig.ts","../../../node_modules/viem/chains/definitions/arbitrum.ts","../../../node_modules/viem/chains/definitions/arbitrumSepolia.ts","../../../node_modules/viem/chains/definitions/base.ts","../../../node_modules/viem/chains/definitions/baseSepolia.ts","../../sdk-ts/src/constants.ts","../../sdk-ts/src/signer.ts","../../sdk-ts/src/vault.ts","../../sdk-ts/src/tokens.ts","../../sdk-ts/src/amounts.ts","../../sdk-ts/src/utils.ts","../../sdk-ts/src/client.ts","../src/service.ts","../src/actions/sendPayment.ts","../src/actions/swapTokens.ts","../src/actions/executeProtocol.ts","../src/actions/checkBalance.ts","../src/providers/vaultContext.ts","../src/index.ts"],"names":["formatAbiItem","init_formatAbiItem","docsPath","size","index","encoder","crypto","toBytes","pad","hash","cacheKey","concatBytes","init_regex","length","init_cursor","data","consumed","value","init_utils","isLE","_32n","buffer","isBytes","abytes","num","hexToNumber","_0n","bytesToHex","hexes","hexToBytes","utf8ToBytes","_1n","gen","_2n","bitLen","base","wbits","_3n","_4n","Point","endo","a","modN","randomBytes","sign","isHex","tv5","c1","c2","createHasher","formatted","init_stateOverride","wait","args","split","err","secp256k1","yParityOrV","recoveryBit","cause","formatAuthorizationList","sha256","version","format","prepareTransactionRequest","getChainId","chainId","gas","nonce","type","e","error","getBlock","block","listeners","cleanup","poll","writeContract","shouldRetry","receipts","status","statusCode","result","key","blobs","commitments","proofs","v","promiseCache","uid","body","response","struct","transport","supportsWalletNamespace","formatters","signAuthorization","signMessage","signTransaction","signTypedData","serializeTransaction","sourceId","keccak256","stringToBytes","entry","__require"],"mappings":";;;;;;;;;;;;;;;;;;;;AAEM,SAAU,SAAA,CAAgB,OAAe,MAAA,EAAc;AAC3D,EAAA,MAAM,KAAA,GAAQ,KAAA,CAAM,IAAA,CAAK,MAAM,CAAA;AAC/B,EAAA,OAAO,KAAA,EAAO,MAAA;AAChB;AALA,IAAA,UAAA,GAAA,KAAA,CAAA;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uC;AAAA,IACxD;AAAA,EACF;AACF;;;ACrDO,IAAM,UAAA,GAAqB;AAAA,EAChC,IAAA,EAAM,aAAA;AAAA,EACN,WAAA,EACE,kJAAA;AAAA,EACF,QAAA,EAAU,CAAC,WAAkB,CAAA;AAAA,EAC7B,OAAA,EAAS,CAAC,iBAAA,EAAmB,gBAAA,EAAkB,uBAAuB,kBAAkB,CAAA;AAAA,EACxF,SAAA,EAAW,CAAC,oBAAoB;AAClC;AAEA,IAAO,aAAA,GAAQ","file":"index.js","sourcesContent":["// 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<type>(regex: RegExp, string: string) {\n const match = regex.exec(string)\n return match?.groups as type | 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 abiParameter - 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 abiParameter extends AbiParameter | AbiEventParameter,\n> = abiParameter 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 [key in keyof components]: FormatAbiParameter<\n {\n type: components[key]['type']\n } & (IsNarrowable<components[key]['name'], string> extends true\n ? { name: components[key]['name'] }\n : unknown) &\n (components[key] extends { components: readonly AbiParameter[] }\n ? { components: components[key]['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 : `${abiParameter['type']}${abiParameter extends { indexed: true }\n ? ' indexed'\n : ''}${abiParameter['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 abiParameter extends AbiParameter | AbiEventParameter,\n>(abiParameter: abiParameter): FormatAbiParameter<abiParameter> {\n type Result = FormatAbiParameter<abiParameter>\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 abiParameters - 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 abiParameters extends readonly [\n AbiParameter | AbiEventParameter,\n ...(readonly (AbiParameter | AbiEventParameter)[]),\n ],\n> = Join<\n {\n [key in keyof abiParameters]: FormatAbiParameter<abiParameters[key]>\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 abiParameters extends readonly [\n AbiParameter | AbiEventParameter,\n ...(readonly (AbiParameter | AbiEventParameter)[]),\n ],\n>(abiParameters: abiParameters): FormatAbiParameters<abiParameters> {\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<abiParameters>\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 abiItem - ABI item\n * @returns Human-readable ABI item\n */\nexport type FormatAbiItem<abiItem extends Abi[number]> =\n Abi[number] extends abiItem\n ? string\n :\n | (abiItem extends AbiFunction\n ? AbiFunction extends abiItem\n ? string\n : `function ${AssertName<abiItem['name']>}(${FormatAbiParameters<\n abiItem['inputs']\n >})${abiItem['stateMutability'] extends Exclude<\n AbiStateMutability,\n 'nonpayable'\n >\n ? ` ${abiItem['stateMutability']}`\n : ''}${abiItem['outputs']['length'] extends 0\n ? ''\n : ` returns (${FormatAbiParameters<abiItem['outputs']>})`}`\n : never)\n | (abiItem extends AbiEvent\n ? AbiEvent extends abiItem\n ? string\n : `event ${AssertName<abiItem['name']>}(${FormatAbiParameters<\n abiItem['inputs']\n >})`\n : never)\n | (abiItem extends AbiError\n ? AbiError extends abiItem\n ? string\n : `error ${AssertName<abiItem['name']>}(${FormatAbiParameters<\n abiItem['inputs']\n >})`\n : never)\n | (abiItem extends AbiConstructor\n ? AbiConstructor extends abiItem\n ? string\n : `constructor(${FormatAbiParameters<\n abiItem['inputs']\n >})${abiItem['stateMutability'] extends 'payable'\n ? ' payable'\n : ''}`\n : never)\n | (abiItem extends AbiFallback\n ? AbiFallback extends abiItem\n ? string\n : `fallback() external${abiItem['stateMutability'] extends 'payable'\n ? ' payable'\n : ''}`\n : never)\n | (abiItem extends AbiReceive\n ? AbiReceive extends abiItem\n ? string\n : 'receive() external payable'\n : never)\n\ntype FormatAbiParameters<\n abiParameters extends readonly (AbiParameter | AbiEventParameter)[],\n> = abiParameters['length'] extends 0\n ? ''\n : FormatAbiParameters_<\n abiParameters extends readonly [\n AbiParameter | AbiEventParameter,\n ...(readonly (AbiParameter | AbiEventParameter)[]),\n ]\n ? abiParameters\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 abiItem extends Abi[number]>(\n abiItem: abiItem,\n): FormatAbiItem<abiItem> {\n type Result = FormatAbiItem<abiItem>\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 if (abiItem.type === 'event')\n return `event ${abiItem.name}(${formatAbiParameters(\n abiItem.inputs as Params,\n )})`\n if (abiItem.type === 'error')\n return `error ${abiItem.name}(${formatAbiParameters(\n abiItem.inputs as Params,\n )})`\n if (abiItem.type === 'constructor')\n return `constructor(${formatAbiParameters(abiItem.inputs as Params)})${\n abiItem.stateMutability === 'payable' ? ' payable' : ''\n }`\n if (abiItem.type === 'fallback')\n return `fallback() external${\n abiItem.stateMutability === 'payable' ? ' payable' : ''\n }` as Result\n return 'receive() external payable' as Result\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\n// biome-ignore lint/performance/noBarrelFile: <explanation>\nexport { BaseError } from '../errors.js'\n\nexport type { Narrow } from '../narrow.js'\nexport { narrow } from '../narrow.js'\n\nexport type {\n Register,\n DefaultRegister,\n ResolvedRegister,\n} from '../register.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 | undefined } = {},\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 | undefined } = {},\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 { 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 | undefined } = {},\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","export const version = '2.46.2'\n","import { version } from './version.js'\n\ntype ErrorConfig = {\n getDocsUrl?: ((args: BaseErrorParameters) => string | undefined) | undefined\n version?: string | undefined\n}\n\nlet errorConfig: ErrorConfig = {\n getDocsUrl: ({\n docsBaseUrl,\n docsPath = '',\n docsSlug,\n }: BaseErrorParameters) =>\n docsPath\n ? `${docsBaseUrl ?? 'https://viem.sh'}${docsPath}${\n docsSlug ? `#${docsSlug}` : ''\n }`\n : undefined,\n version: `viem@${version}`,\n}\n\nexport function setErrorConfig(config: ErrorConfig) {\n errorConfig = config\n}\n\ntype BaseErrorParameters = {\n cause?: BaseError | Error | undefined\n details?: string | undefined\n docsBaseUrl?: string | undefined\n docsPath?: string | undefined\n docsSlug?: string | undefined\n metaMessages?: string[] | undefined\n name?: string | undefined\n}\n\nexport type BaseErrorType = BaseError & { name: 'BaseError' }\nexport class BaseError extends Error {\n details: string\n docsPath?: string | undefined\n metaMessages?: string[] | undefined\n shortMessage: string\n version: string\n\n override name = 'BaseError'\n\n constructor(shortMessage: string, args: BaseErrorParameters = {}) {\n const details = (() => {\n if (args.cause instanceof BaseError) return args.cause.details\n if (args.cause?.message) return args.cause.message\n return args.details!\n })()\n const docsPath = (() => {\n if (args.cause instanceof BaseError)\n return args.cause.docsPath || args.docsPath\n return args.docsPath\n })()\n const docsUrl = errorConfig.getDocsUrl?.({ ...args, docsPath })\n\n const message = [\n shortMessage || 'An error occurred.',\n '',\n ...(args.metaMessages ? [...args.metaMessages, ''] : []),\n ...(docsUrl ? [`Docs: ${docsUrl}`] : []),\n ...(details ? [`Details: ${details}`] : []),\n ...(errorConfig.version ? [`Version: ${errorConfig.version}`] : []),\n ].join('\\n')\n\n super(message, args.cause ? { cause: args.cause } : undefined)\n\n this.details = details\n this.docsPath = docsPath\n this.metaMessages = args.metaMessages\n this.name = args.name ?? this.name\n this.shortMessage = shortMessage\n this.version = version\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(\n err: unknown,\n fn?: ((err: unknown) => boolean) | undefined,\n): unknown {\n if (fn?.(err)) return err\n if (\n err &&\n typeof err === 'object' &&\n 'cause' in err &&\n err.cause !== undefined\n )\n return walk(err.cause, fn)\n return fn ? null : err\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 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 name: 'AbiConstructorNotFoundError',\n },\n )\n }\n}\n\nexport type AbiConstructorParamsNotFoundErrorType =\n AbiConstructorParamsNotFoundError & {\n name: 'AbiConstructorParamsNotFoundError'\n }\n\nexport class AbiConstructorParamsNotFoundError extends BaseError {\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 name: 'AbiConstructorParamsNotFoundError',\n },\n )\n }\n}\n\nexport type AbiDecodingDataSizeInvalidErrorType =\n AbiDecodingDataSizeInvalidError & {\n name: 'AbiDecodingDataSizeInvalidError'\n }\nexport class AbiDecodingDataSizeInvalidError extends BaseError {\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 {\n metaMessages: [`Data: ${data} (${size} bytes)`],\n name: 'AbiDecodingDataSizeInvalidError',\n },\n )\n }\n}\n\nexport type AbiDecodingDataSizeTooSmallErrorType =\n AbiDecodingDataSizeTooSmallError & {\n name: 'AbiDecodingDataSizeTooSmallError'\n }\nexport class AbiDecodingDataSizeTooSmallError extends BaseError {\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 name: 'AbiDecodingDataSizeTooSmallError',\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 constructor() {\n super('Cannot decode zero data (\"0x\") with ABI parameters.', {\n name: 'AbiDecodingZeroDataError',\n })\n }\n}\n\nexport type AbiEncodingArrayLengthMismatchErrorType =\n AbiEncodingArrayLengthMismatchError & {\n name: 'AbiEncodingArrayLengthMismatchError'\n }\nexport class AbiEncodingArrayLengthMismatchError extends BaseError {\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 { name: 'AbiEncodingArrayLengthMismatchError' },\n )\n }\n}\n\nexport type AbiEncodingBytesSizeMismatchErrorType =\n AbiEncodingBytesSizeMismatchError & {\n name: 'AbiEncodingBytesSizeMismatchError'\n }\nexport class AbiEncodingBytesSizeMismatchError extends BaseError {\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 { name: 'AbiEncodingBytesSizeMismatchError' },\n )\n }\n}\n\nexport type AbiEncodingLengthMismatchErrorType =\n AbiEncodingLengthMismatchError & {\n name: 'AbiEncodingLengthMismatchError'\n }\nexport class AbiEncodingLengthMismatchError extends BaseError {\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 { name: 'AbiEncodingLengthMismatchError' },\n )\n }\n}\n\nexport type AbiErrorInputsNotFoundErrorType = AbiErrorInputsNotFoundError & {\n name: 'AbiErrorInputsNotFoundError'\n}\nexport class AbiErrorInputsNotFoundError extends BaseError {\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 name: 'AbiErrorInputsNotFoundError',\n },\n )\n }\n}\n\nexport type AbiErrorNotFoundErrorType = AbiErrorNotFoundError & {\n name: 'AbiErrorNotFoundError'\n}\nexport class AbiErrorNotFoundError extends BaseError {\n constructor(\n errorName?: string | undefined,\n { docsPath }: { docsPath?: string | undefined } = {},\n ) {\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 name: 'AbiErrorNotFoundError',\n },\n )\n }\n}\n\nexport type AbiErrorSignatureNotFoundErrorType =\n AbiErrorSignatureNotFoundError & {\n name: 'AbiErrorSignatureNotFoundError'\n }\nexport class AbiErrorSignatureNotFoundError extends BaseError {\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://4byte.sourcify.dev/?q=${signature}.`,\n ].join('\\n'),\n {\n docsPath,\n name: 'AbiErrorSignatureNotFoundError',\n },\n )\n this.signature = signature\n }\n}\n\nexport type AbiEventSignatureEmptyTopicsErrorType =\n AbiEventSignatureEmptyTopicsError & {\n name: 'AbiEventSignatureEmptyTopicsError'\n }\nexport class AbiEventSignatureEmptyTopicsError extends BaseError {\n constructor({ docsPath }: { docsPath: string }) {\n super('Cannot extract event signature from empty topics.', {\n docsPath,\n name: 'AbiEventSignatureEmptyTopicsError',\n })\n }\n}\n\nexport type AbiEventSignatureNotFoundErrorType =\n AbiEventSignatureNotFoundError & {\n name: 'AbiEventSignatureNotFoundError'\n }\nexport class AbiEventSignatureNotFoundError extends BaseError {\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://4byte.sourcify.dev/?q=${signature}.`,\n ].join('\\n'),\n {\n docsPath,\n name: 'AbiEventSignatureNotFoundError',\n },\n )\n }\n}\n\nexport type AbiEventNotFoundErrorType = AbiEventNotFoundError & {\n name: 'AbiEventNotFoundError'\n}\nexport class AbiEventNotFoundError extends BaseError {\n constructor(\n eventName?: string | undefined,\n { docsPath }: { docsPath?: string | undefined } = {},\n ) {\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 name: 'AbiEventNotFoundError',\n },\n )\n }\n}\n\nexport type AbiFunctionNotFoundErrorType = AbiFunctionNotFoundError & {\n name: 'AbiFunctionNotFoundError'\n}\nexport class AbiFunctionNotFoundError extends BaseError {\n constructor(\n functionName?: string | undefined,\n { docsPath }: { docsPath?: string | undefined } = {},\n ) {\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 name: 'AbiFunctionNotFoundError',\n },\n )\n }\n}\n\nexport type AbiFunctionOutputsNotFoundErrorType =\n AbiFunctionOutputsNotFoundError & {\n name: 'AbiFunctionOutputsNotFoundError'\n }\nexport class AbiFunctionOutputsNotFoundError extends BaseError {\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 name: 'AbiFunctionOutputsNotFoundError',\n },\n )\n }\n}\n\nexport type AbiFunctionSignatureNotFoundErrorType =\n AbiFunctionSignatureNotFoundError & {\n name: 'AbiFunctionSignatureNotFoundError'\n }\nexport class AbiFunctionSignatureNotFoundError extends BaseError {\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://4byte.sourcify.dev/?q=${signature}.`,\n ].join('\\n'),\n {\n docsPath,\n name: 'AbiFunctionSignatureNotFoundError',\n },\n )\n }\n}\n\nexport type AbiItemAmbiguityErrorType = AbiItemAmbiguityError & {\n name: 'AbiItemAmbiguityError'\n}\nexport class AbiItemAmbiguityError extends BaseError {\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 name: 'AbiItemAmbiguityError',\n })\n }\n}\n\nexport type BytesSizeMismatchErrorType = BytesSizeMismatchError & {\n name: 'BytesSizeMismatchError'\n}\nexport class BytesSizeMismatchError extends BaseError {\n constructor({\n expectedSize,\n givenSize,\n }: { expectedSize: number; givenSize: number }) {\n super(`Expected bytes${expectedSize}, got bytes${givenSize}.`, {\n name: 'BytesSizeMismatchError',\n })\n }\n}\n\nexport type DecodeLogDataMismatchErrorType = DecodeLogDataMismatch & {\n name: 'DecodeLogDataMismatch'\n}\nexport class DecodeLogDataMismatch extends BaseError {\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 name: 'DecodeLogDataMismatch',\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 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 { name: 'DecodeLogTopicsMismatch' },\n )\n\n this.abiItem = abiItem\n }\n}\n\nexport type InvalidAbiEncodingTypeErrorType = InvalidAbiEncodingTypeError & {\n name: 'InvalidAbiEncodingTypeError'\n}\nexport class InvalidAbiEncodingTypeError extends BaseError {\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, name: 'InvalidAbiEncodingType' },\n )\n }\n}\n\nexport type InvalidAbiDecodingTypeErrorType = InvalidAbiDecodingTypeError & {\n name: 'InvalidAbiDecodingTypeError'\n}\nexport class InvalidAbiDecodingTypeError extends BaseError {\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, name: 'InvalidAbiDecodingType' },\n )\n }\n}\n\nexport type InvalidArrayErrorType = InvalidArrayError & {\n name: 'InvalidArrayError'\n}\nexport class InvalidArrayError extends BaseError {\n constructor(value: unknown) {\n super([`Value \"${value}\" is not a valid array.`].join('\\n'), {\n name: 'InvalidArrayError',\n })\n }\n}\n\nexport type InvalidDefinitionTypeErrorType = InvalidDefinitionTypeError & {\n name: 'InvalidDefinitionTypeError'\n}\nexport class InvalidDefinitionTypeError extends BaseError {\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 { name: 'InvalidDefinitionTypeError' },\n )\n }\n}\n\nexport type UnsupportedPackedAbiTypeErrorType = UnsupportedPackedAbiType & {\n name: 'UnsupportedPackedAbiType'\n}\nexport class UnsupportedPackedAbiType extends BaseError {\n constructor(type: unknown) {\n super(`Type \"${type}\" is not supported for packed encoding.`, {\n name: 'UnsupportedPackedAbiType',\n })\n }\n}\n","import { BaseError } from './base.js'\n\nexport type SliceOffsetOutOfBoundsErrorType = SliceOffsetOutOfBoundsError & {\n name: 'SliceOffsetOutOfBoundsError'\n}\nexport class SliceOffsetOutOfBoundsError extends BaseError {\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 { name: 'SliceOffsetOutOfBoundsError' },\n )\n }\n}\n\nexport type SizeExceedsPaddingSizeErrorType = SizeExceedsPaddingSizeError & {\n name: 'SizeExceedsPaddingSizeError'\n}\nexport class SizeExceedsPaddingSizeError extends BaseError {\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 { name: 'SizeExceedsPaddingSizeError' },\n )\n }\n}\n\nexport type InvalidBytesLengthErrorType = InvalidBytesLengthError & {\n name: 'InvalidBytesLengthError'\n}\nexport class InvalidBytesLengthError extends BaseError {\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()} is expected to be ${targetSize} ${type} long, but is ${size} ${type} long.`,\n { name: 'InvalidBytesLengthError' },\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' | undefined\n size?: number | null | undefined\n}\nexport type PadReturnType<value extends ByteArray | Hex> = value extends Hex\n ? Hex\n : ByteArray\n\nexport type PadErrorType = PadHexErrorType | PadBytesErrorType | ErrorType\n\nexport function pad<value extends ByteArray | Hex>(\n hexOrBytes: value,\n { dir, size = 32 }: PadOptions = {},\n): PadReturnType<value> {\n if (typeof hexOrBytes === 'string')\n return padHex(hexOrBytes, { dir, size }) as PadReturnType<value>\n return padBytes(hexOrBytes, { dir, size }) as PadReturnType<value>\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 type { ByteArray, Hex } from '../types/misc.js'\n\nimport { BaseError } from './base.js'\n\nexport type IntegerOutOfRangeErrorType = IntegerOutOfRangeError & {\n name: 'IntegerOutOfRangeError'\n}\nexport class IntegerOutOfRangeError extends BaseError {\n constructor({\n max,\n min,\n signed,\n size,\n value,\n }: {\n max?: string | undefined\n min: string\n signed?: boolean | undefined\n size?: number | undefined\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 { name: 'IntegerOutOfRangeError' },\n )\n }\n}\n\nexport type InvalidBytesBooleanErrorType = InvalidBytesBooleanError & {\n name: 'InvalidBytesBooleanError'\n}\nexport class InvalidBytesBooleanError extends BaseError {\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 name: 'InvalidBytesBooleanError',\n },\n )\n }\n}\n\nexport type InvalidHexBooleanErrorType = InvalidHexBooleanError & {\n name: 'InvalidHexBooleanError'\n}\nexport class InvalidHexBooleanError extends BaseError {\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 { name: 'InvalidHexBooleanError' },\n )\n }\n}\n\nexport type InvalidHexValueErrorType = InvalidHexValueError & {\n name: 'InvalidHexValueError'\n}\nexport class InvalidHexValueError extends BaseError {\n constructor(value: Hex) {\n super(\n `Hex value \"${value}\" is an odd length (${value.length}). It must be an even length.`,\n { name: 'InvalidHexValueError' },\n )\n }\n}\n\nexport type SizeOverflowErrorType = SizeOverflowError & {\n name: 'SizeOverflowError'\n}\nexport class SizeOverflowError extends BaseError {\n constructor({ givenSize, maxSize }: { givenSize: number; maxSize: number }) {\n super(\n `Size cannot exceed ${maxSize} bytes. Given size: ${givenSize} bytes.`,\n { name: 'SizeOverflowError' },\n )\n }\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray, Hex } from '../../types/misc.js'\n\ntype TrimOptions = {\n dir?: 'left' | 'right' | undefined\n}\nexport type TrimReturnType<value extends ByteArray | Hex> = value extends Hex\n ? Hex\n : ByteArray\n\nexport type TrimErrorType = ErrorType\n\nexport function trim<value extends ByteArray | Hex>(\n hexOrBytes: value,\n { dir = 'left' }: TrimOptions = {},\n): TrimReturnType<value> {\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<value>\n }\n return data as TrimReturnType<value>\n}\n","import {\n IntegerOutOfRangeError,\n type IntegerOutOfRangeErrorType,\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 to extends 'string' | 'bigint' | 'number' | 'bytes' | 'boolean',\n> =\n | to\n | {\n /** Size (in bytes) of the hex value. */\n size?: number | undefined\n /** Type to convert to. */\n to: to\n }\n\nexport type FromHexReturnType<to> = to extends 'string'\n ? string\n : to extends 'bigint'\n ? bigint\n : to extends 'number'\n ? number\n : to extends 'bytes'\n ? ByteArray\n : to 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\n * - Example: https://viem.sh/docs/utilities/fromHex#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 to extends 'string' | 'bigint' | 'number' | 'bytes' | 'boolean',\n>(hex: Hex, toOrOpts: FromHexParameters<to>): FromHexReturnType<to> {\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<to>\n if (to === 'bigint') return hexToBigInt(hex, opts) as FromHexReturnType<to>\n if (to === 'string') return hexToString(hex, opts) as FromHexReturnType<to>\n if (to === 'boolean') return hexToBool(hex, opts) as FromHexReturnType<to>\n return hexToBytes(hex, opts) as FromHexReturnType<to>\n}\n\nexport type HexToBigIntOpts = {\n /** Whether or not the number of a signed representation. */\n signed?: boolean | undefined\n /** Size (in bytes) of the hex value. */\n size?: number | undefined\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#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 | undefined\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#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 =\n | HexToBigIntErrorType\n | IntegerOutOfRangeErrorType\n | ErrorType\n\n/**\n * Decodes a hex string into a number.\n *\n * - Docs: https://viem.sh/docs/utilities/fromHex#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 const value = hexToBigInt(hex, opts)\n const number = Number(value)\n if (!Number.isSafeInteger(number))\n throw new IntegerOutOfRangeError({\n max: `${Number.MAX_SAFE_INTEGER}`,\n min: `${Number.MIN_SAFE_INTEGER}`,\n signed: opts.signed,\n size: opts.size,\n value: `${value}n`,\n })\n return number\n}\n\nexport type HexToStringOpts = {\n /** Size (in bytes) of the hex value. */\n size?: number | undefined\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#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 {\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 | undefined\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\n * - Example: https://viem.sh/docs/utilities/toHex#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 | undefined\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#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 | undefined\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#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 | undefined\n /** The size (in bytes) of the output hex value. */\n size: number\n }\n | {\n signed?: undefined\n /** The size (in bytes) of the output hex value. */\n size?: number | undefined\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#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: bigint | number | undefined\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${(\n signed && value < 0 ? (1n << BigInt(size * 8)) + BigInt(value) : 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 | undefined\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#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 | undefined\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\n * - Example: https://viem.sh/docs/utilities/toBytes#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 | undefined\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#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 | undefined\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#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#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(\n value: bigint | number,\n opts?: NumberToHexOpts | undefined,\n) {\n const hex = numberToHex(value, opts)\n return hexToBytes(hex)\n}\n\nexport type StringToBytesOpts = {\n /** Size of the output bytes. */\n size?: number | undefined\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#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","/**\n * Internal helpers for u64. BigUint64Array is too slow as per 2025, so we implement it using Uint32Array.\n * @todo re-check https://issues.chromium.org/issues/42212588\n * @module\n */\nconst U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);\nconst _32n = /* @__PURE__ */ BigInt(32);\n\nfunction fromBig(\n n: bigint,\n le = false\n): {\n h: number;\n l: number;\n} {\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): Uint32Array[] {\n const len = lst.length;\n let Ah = new Uint32Array(len);\n let Al = new Uint32Array(len);\n for (let i = 0; i < len; 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 => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0);\n// for Shift in [0, 32)\nconst shrSH = (h: number, _l: number, s: number): number => h >>> s;\nconst shrSL = (h: number, l: number, s: number): number => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in [1, 32)\nconst rotrSH = (h: number, l: number, s: number): number => (h >>> s) | (l << (32 - s));\nconst rotrSL = (h: number, l: number, s: number): 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): number => (h << (64 - s)) | (l >>> (s - 32));\nconst rotrBL = (h: number, l: number, s: number): number => (h >>> (s - 32)) | (l << (64 - s));\n// Right rotate for shift===32 (just swaps l&h)\nconst rotr32H = (_h: number, l: number): number => l;\nconst rotr32L = (h: number, _l: number): number => h;\n// Left rotate for Shift in [1, 32)\nconst rotlSH = (h: number, l: number, s: number): number => (h << s) | (l >>> (32 - s));\nconst rotlSL = (h: number, l: number, s: number): 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): number => (l << (s - 32)) | (h >>> (64 - s));\nconst rotlBL = (h: number, l: number, s: number): 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(\n Ah: number,\n Al: number,\n Bh: number,\n Bl: number\n): {\n h: number;\n l: number;\n} {\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): number => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);\nconst add3H = (low: number, Ah: number, Bh: number, Ch: number): number =>\n (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;\nconst add4L = (Al: number, Bl: number, Cl: number, Dl: number): number =>\n (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);\nconst add4H = (low: number, Ah: number, Bh: number, Ch: number, Dh: number): number =>\n (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;\nconst add5L = (Al: number, Bl: number, Cl: number, Dl: number, El: number): 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): number =>\n (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;\n\n// prettier-ignore\nexport {\n add, add3H, add3L, add4H, add4L, add5H, add5L, fromBig, rotlBH, rotlBL, rotlSH, rotlSL, rotr32H, rotr32L, rotrBH, rotrBL, rotrSH, rotrSL, shrSH, shrSL, split, toBig\n};\n// prettier-ignore\nconst u64: { fromBig: typeof fromBig; split: typeof split; toBig: (h: number, l: number) => bigint; shrSH: (h: number, _l: number, s: number) => number; shrSL: (h: number, l: number, s: number) => number; rotrSH: (h: number, l: number, s: number) => number; rotrSL: (h: number, l: number, s: number) => number; rotrBH: (h: number, l: number, s: number) => number; rotrBL: (h: number, l: number, s: number) => number; rotr32H: (_h: number, l: number) => number; rotr32L: (h: number, _l: number) => number; rotlSH: (h: number, l: number, s: number) => number; rotlSL: (h: number, l: number, s: number) => number; rotlBH: (h: number, l: number, s: number) => number; rotlBL: (h: number, l: number, s: number) => number; add: typeof add; add3L: (Al: number, Bl: number, Cl: number) => number; add3H: (low: number, Ah: number, Bh: number, Ch: number) => number; add4L: (Al: number, Bl: number, Cl: number, Dl: number) => number; add4H: (low: number, Ah: number, Bh: number, Ch: number, Dh: number) => number; add5H: (low: number, Ah: number, Bh: number, Ch: number, Dh: number, Eh: number) => number; add5L: (Al: number, Bl: number, Cl: number, Dl: number, El: number) => number; } = {\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","/**\n * Internal webcrypto alias.\n * We prefer WebCrypto aka globalThis.crypto, which exists in node.js 16+.\n * Falls back to Node.js built-in crypto for Node.js <=v14.\n * See utils.ts for details.\n * @module\n */\n// @ts-ignore\nimport * as nc from 'node:crypto';\nexport const crypto: any =\n nc && typeof nc === 'object' && 'webcrypto' in nc\n ? (nc.webcrypto as any)\n : nc && typeof nc === 'object' && 'randomBytes' in nc\n ? nc\n : undefined;\n","/**\n * Utilities for hex, bytes, CSPRNG.\n * @module\n */\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 (2025-04-30), we can just drop the import.\nimport { crypto } from '@noble/hashes/crypto';\n\n/** Checks if something is Uint8Array. Be careful: nodejs Buffer will return true. */\nexport function isBytes(a: unknown): a is Uint8Array {\n return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');\n}\n\n/** Asserts something is positive integer. */\nexport function anumber(n: number): void {\n if (!Number.isSafeInteger(n) || n < 0) throw new Error('positive integer expected, got ' + n);\n}\n\n/** Asserts something is Uint8Array. */\nexport function abytes(b: Uint8Array | undefined, ...lengths: number[]): void {\n if (!isBytes(b)) throw new Error('Uint8Array expected');\n if (lengths.length > 0 && !lengths.includes(b.length))\n throw new Error('Uint8Array expected of length ' + lengths + ', got length=' + b.length);\n}\n\n/** Asserts something is hash */\nexport function ahash(h: IHash): void {\n if (typeof h !== 'function' || typeof h.create !== 'function')\n throw new Error('Hash should be wrapped by utils.createHasher');\n anumber(h.outputLen);\n anumber(h.blockLen);\n}\n\n/** Asserts a hash instance has not been destroyed / finished */\nexport function aexists(instance: any, checkFinished = true): void {\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}\n\n/** Asserts output is properly-sized byte array */\nexport function aoutput(out: any, instance: any): void {\n abytes(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\n/** Generic type encompassing 8/16/32-byte arrays - but not 64-byte. */\n// prettier-ignore\nexport type TypedArray = Int8Array | Uint8ClampedArray | Uint8Array |\n Uint16Array | Int16Array | Uint32Array | Int32Array;\n\n/** Cast u8 / u16 / u32 to u8. */\nexport function u8(arr: TypedArray): Uint8Array {\n return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n\n/** Cast u8 / u16 / u32 to u32. */\nexport function u32(arr: TypedArray): Uint32Array {\n return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n}\n\n/** Zeroize a byte array. Warning: JS provides no guarantees. */\nexport function clean(...arrays: TypedArray[]): void {\n for (let i = 0; i < arrays.length; i++) {\n arrays[i].fill(0);\n }\n}\n\n/** Create DataView of an array for easy byte-level manipulation. */\nexport function createView(arr: TypedArray): DataView {\n return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n\n/** The rotate right (circular right shift) operation for uint32 */\nexport function rotr(word: number, shift: number): number {\n return (word << (32 - shift)) | (word >>> shift);\n}\n\n/** The rotate left (circular left shift) operation for uint32 */\nexport function rotl(word: number, shift: number): number {\n return (word << shift) | ((word >>> (32 - shift)) >>> 0);\n}\n\n/** Is current platform little-endian? Most are. Big-Endian platform: IBM */\nexport const isLE: boolean = /* @__PURE__ */ (() =>\n new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();\n\n/** The byte swap operation for uint32 */\nexport function byteSwap(word: number): number {\n return (\n ((word << 24) & 0xff000000) |\n ((word << 8) & 0xff0000) |\n ((word >>> 8) & 0xff00) |\n ((word >>> 24) & 0xff)\n );\n}\n/** Conditionally byte swap if on a big-endian platform */\nexport const swap8IfBE: (n: number) => number = isLE\n ? (n: number) => n\n : (n: number) => byteSwap(n);\n\n/** @deprecated */\nexport const byteSwapIfBE: typeof swap8IfBE = swap8IfBE;\n/** In place byte swap for Uint32Array */\nexport function byteSwap32(arr: Uint32Array): Uint32Array {\n for (let i = 0; i < arr.length; i++) {\n arr[i] = byteSwap(arr[i]);\n }\n return arr;\n}\n\nexport const swap32IfBE: (u: Uint32Array) => Uint32Array = isLE\n ? (u: Uint32Array) => u\n : byteSwap32;\n\n// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex\nconst hasHexBuiltin: boolean = /* @__PURE__ */ (() =>\n // @ts-ignore\n typeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')();\n\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) =>\n i.toString(16).padStart(2, '0')\n);\n\n/**\n * Convert byte array to hex string. Uses built-in function, when available.\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes: Uint8Array): string {\n abytes(bytes);\n // @ts-ignore\n if (hasHexBuiltin) return bytes.toHex();\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// We use optimized technique to convert hex string to byte array\nconst asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 } as const;\nfunction asciiToBase16(ch: number): number | undefined {\n if (ch >= asciis._0 && ch <= asciis._9) return ch - asciis._0; // '2' => 50-48\n if (ch >= asciis.A && ch <= asciis.F) return ch - (asciis.A - 10); // 'B' => 66-(65-10)\n if (ch >= asciis.a && ch <= asciis.f) return ch - (asciis.a - 10); // 'b' => 98-(97-10)\n return;\n}\n\n/**\n * Convert hex string to byte array. Uses built-in function, when available.\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 // @ts-ignore\n if (hasHexBuiltin) return Uint8Array.fromHex(hex);\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2) throw new Error('hex string expected, got unpadded hex of length ' + hl);\n const array = new Uint8Array(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n const n1 = asciiToBase16(hex.charCodeAt(hi));\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1));\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new Error('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n }\n array[ai] = n1 * 16 + n2; // multiply first octet, e.g. 'a3' => 10*16+3 => 160 + 3 => 163\n }\n return array;\n}\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.\n */\nexport const nextTick = async (): Promise<void> => {};\n\n/** Returns control to thread each 'tick' ms to avoid blocking. */\nexport async function asyncLoop(\n iters: number,\n tick: number,\n cb: (i: number) => void\n): Promise<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, but ts doesn't see them: https://github.com/microsoft/TypeScript/issues/31535\ndeclare const TextEncoder: any;\ndeclare const TextDecoder: any;\n\n/**\n * Converts string to bytes using UTF8 encoding.\n * @example utf8ToBytes('abc') // Uint8Array.from([97, 98, 99])\n */\nexport function utf8ToBytes(str: string): Uint8Array {\n if (typeof str !== 'string') throw new Error('string expected');\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n\n/**\n * Converts bytes to string using UTF8 encoding.\n * @example bytesToUtf8(Uint8Array.from([97, 98, 99])) // 'abc'\n */\nexport function bytesToUtf8(bytes: Uint8Array): string {\n return new TextDecoder().decode(bytes);\n}\n\n/** Accepted input of hash functions. Strings are converted to byte arrays. */\nexport type Input = string | Uint8Array;\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 abytes(data);\n return data;\n}\n\n/** KDFs can accept string or Uint8Array for user convenience. */\nexport type KDFInput = string | Uint8Array;\n/**\n * Helper for KDFs: consumes uint8array or string.\n * When string is passed, does utf8 decoding, using TextDecoder.\n */\nexport function kdfInputToBytes(data: KDFInput): Uint8Array {\n if (typeof data === 'string') data = utf8ToBytes(data);\n abytes(data);\n return data;\n}\n\n/** Copies several Uint8Arrays into one. */\nexport function concatBytes(...arrays: Uint8Array[]): Uint8Array {\n let sum = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n abytes(a);\n sum += a.length;\n }\n const res = new Uint8Array(sum);\n for (let i = 0, pad = 0; i < arrays.length; i++) {\n const a = arrays[i];\n res.set(a, pad);\n pad += a.length;\n }\n return res;\n}\n\ntype EmptyObj = {};\nexport function checkOpts<T1 extends EmptyObj, T2 extends EmptyObj>(\n defaults: T1,\n opts?: T2\n): T1 & T2 {\n if (opts !== undefined && {}.toString.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\n/** Hash interface. */\nexport type IHash = {\n (data: Uint8Array): Uint8Array;\n blockLen: number;\n outputLen: number;\n create: any;\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 abstract clone(): T;\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\n/** Hash function */\nexport type CHash = ReturnType<typeof createHasher>;\n/** Hash function with output */\nexport type CHashO = ReturnType<typeof createOptHasher>;\n/** XOF with output */\nexport type CHashXO = ReturnType<typeof createXOFer>;\n\n/** Wraps hash function, creating an interface on top of it */\nexport function createHasher<T extends Hash<T>>(\n hashCons: () => Hash<T>\n): {\n (msg: Input): Uint8Array;\n outputLen: number;\n blockLen: number;\n create(): Hash<T>;\n} {\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 createOptHasher<H extends Hash<H>, T extends Object>(\n hashCons: (opts?: T) => Hash<H>\n): {\n (msg: Input, opts?: T): Uint8Array;\n outputLen: number;\n blockLen: number;\n create(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 createXOFer<H extends HashXOF<H>, T extends Object>(\n hashCons: (opts?: T) => HashXOF<H>\n): {\n (msg: Input, opts?: T): Uint8Array;\n outputLen: number;\n blockLen: number;\n create(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}\nexport const wrapConstructor: typeof createHasher = createHasher;\nexport const wrapConstructorWithOpts: typeof createOptHasher = createOptHasher;\nexport const wrapXOFConstructorWithOpts: typeof createXOFer = createXOFer;\n\n/** Cryptographically secure PRNG. Uses internal OS-level `crypto.getRandomValues`. */\nexport function randomBytes(bytesLength = 32): Uint8Array {\n if (crypto && typeof crypto.getRandomValues === 'function') {\n return crypto.getRandomValues(new Uint8Array(bytesLength));\n }\n // Legacy Node.js compatibility\n if (crypto && typeof crypto.randomBytes === 'function') {\n return Uint8Array.from(crypto.randomBytes(bytesLength));\n }\n throw new Error('crypto.getRandomValues must be defined');\n}\n","/**\n * SHA3 (keccak) hash function, based on a new \"Sponge function\" design.\n * Different from older hashes, the internal state is bigger than output size.\n *\n * Check out [FIPS-202](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.202.pdf),\n * [Website](https://keccak.team/keccak.html),\n * [the differences between SHA-3 and Keccak](https://crypto.stackexchange.com/questions/15727/what-are-the-key-differences-between-the-draft-sha-3-standard-and-the-keccak-sub).\n *\n * Check out `sha3-addons` module for cSHAKE, k12, and others.\n * @module\n */\nimport { rotlBH, rotlBL, rotlSH, rotlSL, split } from './_u64.ts';\n// prettier-ignore\nimport {\n abytes, aexists, anumber, aoutput,\n clean, createHasher, createXOFer, Hash,\n swap32IfBE,\n toBytes, u32,\n type CHash, type CHashXO, type HashXOF, type Input\n} from './utils.ts';\n\n// No __PURE__ annotations in sha3 header:\n// EVERYTHING is in fact used on every export.\n// Various per round constants calculations\nconst _0n = BigInt(0);\nconst _1n = BigInt(1);\nconst _2n = BigInt(2);\nconst _7n = BigInt(7);\nconst _256n = BigInt(256);\nconst _0x71n = BigInt(0x71);\nconst SHA3_PI: number[] = [];\nconst SHA3_ROTL: number[] = [];\nconst _SHA3_IOTA: bigint[] = [];\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 IOTAS = split(_SHA3_IOTA, true);\nconst SHA3_IOTA_H = IOTAS[0];\nconst SHA3_IOTA_L = IOTAS[1];\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/** `keccakf1600` internal function, additionally allows to adjust round count. */\nexport function keccakP(s: Uint32Array, rounds: number = 24): void {\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 clean(B);\n}\n\n/** Keccak sponge function. */\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\n public blockLen: number;\n public suffix: number;\n public outputLen: number;\n protected enableXOF = false;\n protected rounds: number;\n\n // NOTE: we accept arguments in bytes instead of bits here.\n constructor(\n blockLen: number,\n suffix: number,\n outputLen: number,\n enableXOF = false,\n rounds: number = 24\n ) {\n super();\n this.blockLen = blockLen;\n this.suffix = suffix;\n this.outputLen = outputLen;\n this.enableXOF = enableXOF;\n this.rounds = rounds;\n // Can be passed from user as dkLen\n anumber(outputLen);\n // 1600 = 5x5 matrix of 64bit. 1600 bits === 200 bytes\n // 0 < blockLen < 200\n if (!(0 < blockLen && blockLen < 200))\n throw new Error('only keccak-f1600 function is supported');\n this.state = new Uint8Array(200);\n this.state32 = u32(this.state);\n }\n clone(): Keccak {\n return this._cloneInto();\n }\n protected keccak(): void {\n swap32IfBE(this.state32);\n keccakP(this.state32, this.rounds);\n swap32IfBE(this.state32);\n this.posOut = 0;\n this.pos = 0;\n }\n update(data: Input): this {\n aexists(this);\n data = toBytes(data);\n abytes(data);\n const { blockLen, state } = this;\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(): void {\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 aexists(this, false);\n abytes(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 anumber(bytes);\n return this.xofInto(new Uint8Array(bytes));\n }\n digestInto(out: Uint8Array): Uint8Array {\n aoutput(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(): Uint8Array {\n return this.digestInto(new Uint8Array(this.outputLen));\n }\n destroy(): void {\n this.destroyed = true;\n clean(this.state);\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 createHasher(() => new Keccak(blockLen, suffix, outputLen));\n\n/** SHA3-224 hash function. */\nexport const sha3_224: CHash = /* @__PURE__ */ (() => gen(0x06, 144, 224 / 8))();\n/** SHA3-256 hash function. Different from keccak-256. */\nexport const sha3_256: CHash = /* @__PURE__ */ (() => gen(0x06, 136, 256 / 8))();\n/** SHA3-384 hash function. */\nexport const sha3_384: CHash = /* @__PURE__ */ (() => gen(0x06, 104, 384 / 8))();\n/** SHA3-512 hash function. */\nexport const sha3_512: CHash = /* @__PURE__ */ (() => gen(0x06, 72, 512 / 8))();\n\n/** keccak-224 hash function. */\nexport const keccak_224: CHash = /* @__PURE__ */ (() => gen(0x01, 144, 224 / 8))();\n/** keccak-256 hash function. Different from SHA3-256. */\nexport const keccak_256: CHash = /* @__PURE__ */ (() => gen(0x01, 136, 256 / 8))();\n/** keccak-384 hash function. */\nexport const keccak_384: CHash = /* @__PURE__ */ (() => gen(0x01, 104, 384 / 8))();\n/** keccak-512 hash function. */\nexport const keccak_512: CHash = /* @__PURE__ */ (() => gen(0x01, 72, 512 / 8))();\n\nexport type ShakeOpts = { dkLen?: number };\n\nconst genShake = (suffix: number, blockLen: number, outputLen: number) =>\n createXOFer<HashXOF<Keccak>, ShakeOpts>(\n (opts: ShakeOpts = {}) =>\n new Keccak(blockLen, suffix, opts.dkLen === undefined ? outputLen : opts.dkLen, true)\n );\n\n/** SHAKE128 XOF with 128-bit security. */\nexport const shake128: CHashXO = /* @__PURE__ */ (() => genShake(0x1f, 168, 128 / 8))();\n/** SHAKE256 XOF with 256-bit security. */\nexport const shake256: CHashXO = /* @__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<to extends To> =\n | (to extends 'bytes' ? ByteArray : never)\n | (to extends 'hex' ? Hex : never)\n\nexport type Keccak256ErrorType =\n | IsHexErrorType\n | ToBytesErrorType\n | ToHexErrorType\n | ErrorType\n\nexport function keccak256<to extends To = 'hex'>(\n value: Hex | ByteArray,\n to_?: to | undefined,\n): Keccak256Hash<to> {\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<to>\n return toHex(bytes) as Keccak256Hash<to>\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport { type ToBytesErrorType, toBytes } from '../encoding/toBytes.js'\nimport { type Keccak256ErrorType, keccak256 } from './keccak256.js'\n\nconst hash = (value: string) => keccak256(toBytes(value))\n\nexport type HashSignatureErrorType =\n | Keccak256ErrorType\n | ToBytesErrorType\n | ErrorType\n\nexport function hashSignature(sig: string) {\n return hash(sig)\n}\n","import { BaseError } from '../../errors/base.js'\nimport type { ErrorType } from '../../errors/utils.js'\n\ntype NormalizeSignatureParameters = string\ntype 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 AbiEvent, 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 ToSignatureErrorType = NormalizeSignatureErrorType | ErrorType\n\n/**\n * Returns the signature for a given function or event definition.\n *\n * @example\n * const signature = toSignature('function ownerOf(uint256 tokenId)')\n * // 'ownerOf(uint256)'\n *\n * @example\n * const signature_3 = toSignature({\n * name: 'ownerOf',\n * type: 'function',\n * inputs: [{ name: 'tokenId', type: 'uint256' }],\n * outputs: [],\n * stateMutability: 'view',\n * })\n * // 'ownerOf(uint256)'\n */\nexport const toSignature = (def: string | AbiFunction | AbiEvent) => {\n const def_ = (() => {\n if (typeof def === 'string') return def\n return formatAbiItem(def)\n })()\n return normalizeSignature(def_)\n}\n","import type { AbiEvent, AbiFunction } from 'abitype'\n\nimport type { ErrorType } from '../../errors/utils.js'\nimport { type HashSignatureErrorType, hashSignature } from './hashSignature.js'\nimport { type ToSignatureErrorType, toSignature } from './toSignature.js'\n\nexport type ToSignatureHashErrorType =\n | HashSignatureErrorType\n | ToSignatureErrorType\n | ErrorType\n\n/**\n * Returns the hash (of the function/event signature) for a given event or function definition.\n */\nexport function toSignatureHash(fn: string | AbiFunction | AbiEvent) {\n return hashSignature(toSignature(fn))\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport {\n type ToSignatureHashErrorType,\n toSignatureHash,\n} from './toSignatureHash.js'\n\nexport type ToEventSelectorErrorType = ToSignatureHashErrorType | ErrorType\n\n/**\n * Returns the event selector for a given event definition.\n *\n * @example\n * const selector = toEventSelector('Transfer(address indexed from, address indexed to, uint256 amount)')\n * // 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef\n */\nexport const toEventSelector = toSignatureHash\n","import { BaseError } from './base.js'\n\nexport type InvalidAddressErrorType = InvalidAddressError & {\n name: 'InvalidAddressError'\n}\nexport class InvalidAddressError extends BaseError {\n constructor({ address }: { address: string }) {\n super(`Address \"${address}\" is invalid.`, {\n metaMessages: [\n '- Address must be a hex value of 20 bytes (40 hex characters).',\n '- Address must match its checksum counterpart.',\n ],\n name: 'InvalidAddressError',\n })\n }\n}\n","/**\n * Map with a LRU (Least recently used) policy.\n *\n * @link https://en.wikipedia.org/wiki/Cache_replacement_policies#LRU\n */\nexport class LruMap<value = unknown> extends Map<string, value> {\n maxSize: number\n\n constructor(size: number) {\n super()\n this.maxSize = size\n }\n\n override get(key: string) {\n const value = super.get(key)\n\n if (super.has(key) && value !== undefined) {\n this.delete(key)\n super.set(key, value)\n }\n\n return value\n }\n\n override set(key: string, value: value) {\n super.set(key, value)\n if (this.maxSize && this.size > this.maxSize) {\n const firstKey = this.keys().next().value\n if (firstKey) this.delete(firstKey)\n }\n return this\n }\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 { LruMap } from '../lru.js'\nimport { type IsAddressErrorType, isAddress } from './isAddress.js'\n\nconst checksumAddressCache = /*#__PURE__*/ new LruMap<Address>(8192)\n\nexport type ChecksumAddressErrorType =\n | Keccak256ErrorType\n | StringToBytesErrorType\n | ErrorType\n\nexport function checksumAddress(\n address_: Address,\n /**\n * Warning: EIP-1191 checksum addresses are generally not backwards compatible with the\n * wider Ethereum ecosystem, meaning it will break when validated against an application/tool\n * that relies on EIP-55 checksum encoding (checksum without chainId).\n *\n * It is highly recommended to not use this feature unless you\n * know what you are doing.\n *\n * See more: https://github.com/ethereum/EIPs/issues/1121\n */\n chainId?: number | undefined,\n): Address {\n if (checksumAddressCache.has(`${address_}.${chainId}`))\n return checksumAddressCache.get(`${address_}.${chainId}`)!\n\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 const result = `0x${address.join('')}` as const\n checksumAddressCache.set(`${address_}.${chainId}`, result)\n return result\n}\n\nexport type GetAddressErrorType =\n | ChecksumAddressErrorType\n | IsAddressErrorType\n | ErrorType\n\nexport function getAddress(\n address: string,\n /**\n * Warning: EIP-1191 checksum addresses are generally not backwards compatible with the\n * wider Ethereum ecosystem, meaning it will break when validated against an application/tool\n * that relies on EIP-55 checksum encoding (checksum without chainId).\n *\n * It is highly recommended to not use this feature unless you\n * know what you are doing.\n *\n * See more: https://github.com/ethereum/EIPs/issues/1121\n */\n chainId?: number,\n): Address {\n if (!isAddress(address, { strict: false }))\n throw new InvalidAddressError({ address })\n return checksumAddress(address, chainId)\n}\n","import type { Address } from 'abitype'\nimport type { ErrorType } from '../../errors/utils.js'\nimport { LruMap } from '../lru.js'\nimport { checksumAddress } from './getAddress.js'\n\nconst addressRegex = /^0x[a-fA-F0-9]{40}$/\n\n/** @internal */\nexport const isAddressCache = /*#__PURE__*/ new LruMap<boolean>(8192)\n\nexport type IsAddressOptions = {\n /**\n * Enables strict mode. Whether or not to compare the address against its checksum.\n *\n * @default true\n */\n strict?: boolean | undefined\n}\n\nexport type IsAddressErrorType = ErrorType\n\nexport function isAddress(\n address: string,\n options?: IsAddressOptions | undefined,\n): address is Address {\n const { strict = true } = options ?? {}\n const cacheKey = `${address}.${strict}`\n\n if (isAddressCache.has(cacheKey)) return isAddressCache.get(cacheKey)!\n\n const result = (() => {\n if (!addressRegex.test(address)) return false\n if (address.toLowerCase() === address) return true\n if (strict) return checksumAddress(address as Address) === address\n return true\n })()\n isAddressCache.set(cacheKey, result)\n return result\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray, Hex } from '../../types/misc.js'\n\nexport type ConcatReturnType<value extends Hex | ByteArray> = value extends Hex\n ? Hex\n : ByteArray\n\nexport type ConcatErrorType =\n | ConcatBytesErrorType\n | ConcatHexErrorType\n | ErrorType\n\nexport function concat<value extends Hex | ByteArray>(\n values: readonly value[],\n): ConcatReturnType<value> {\n if (typeof values[0] === 'string')\n return concatHex(values as readonly Hex[]) as ConcatReturnType<value>\n return concatBytes(values as readonly ByteArray[]) as ConcatReturnType<value>\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","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<value extends ByteArray | Hex> = value 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<value extends ByteArray | Hex>(\n value: value,\n start?: number | undefined,\n end?: number | undefined,\n { strict }: { strict?: boolean | undefined } = {},\n): SliceReturnType<value> {\n if (isHex(value, { strict: false }))\n return sliceHex(value as Hex, start, end, {\n strict,\n }) as SliceReturnType<value>\n return sliceBytes(value as ByteArray, start, end, {\n strict,\n }) as SliceReturnType<value>\n}\n\nexport type AssertStartOffsetErrorType =\n | SliceOffsetOutOfBoundsErrorType\n | SizeErrorType\n | ErrorType\n\nfunction assertStartOffset(value: Hex | ByteArray, start?: number | undefined) {\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(\n value: Hex | ByteArray,\n start?: number | undefined,\n end?: number | undefined,\n) {\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 | undefined,\n end?: number | undefined,\n { strict }: { strict?: boolean | undefined } = {},\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 | undefined,\n end?: number | undefined,\n { strict }: { strict?: boolean | undefined } = {},\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","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 AbiParameter,\n AbiParameterKind,\n AbiParametersToPrimitiveTypes,\n AbiParameterToPrimitiveType,\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 { BaseError } from '../../errors/base.js'\nimport { IntegerOutOfRangeError } from '../../errors/encoding.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 boolToHex,\n type NumberToHexErrorType,\n numberToHex,\n type StringToHexErrorType,\n stringToHex,\n} from '../encoding/toHex.js'\nimport { integerRegex } from '../regex.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 *\n * - Docs: https://viem.sh/docs/abi/encodeAbiParameters#encodeabiparameters\n *\n * Generates ABI encoded data using the [ABI specification](https://docs.soliditylang.org/en/latest/abi-spec), given a set of ABI parameters (inputs/outputs) and their corresponding values.\n *\n * @param params - a set of ABI Parameters (params), that can be in the shape of the inputs or outputs attribute of an ABI Item.\n * @param values - a set of values (values) that correspond to the given params.\n * @example\n * ```typescript\n * import { encodeAbiParameters } from 'viem'\n *\n * const encodedData = encodeAbiParameters(\n * [\n * { name: 'x', type: 'string' },\n * { name: 'y', type: 'uint' },\n * { name: 'z', type: 'bool' }\n * ],\n * ['wagmi', 420n, true]\n * )\n * ```\n *\n * You can also pass in Human Readable parameters with the parseAbiParameters utility.\n *\n * @example\n * ```typescript\n * import { encodeAbiParameters, parseAbiParameters } from 'viem'\n *\n * const encodedData = encodeAbiParameters(\n * parseAbiParameters('string x, uint y, bool z'),\n * ['wagmi', 420n, true]\n * )\n * ```\n */\nexport function encodeAbiParameters<\n const params extends readonly AbiParameter[] | readonly unknown[],\n>(\n params: params,\n values: params extends readonly AbiParameter[]\n ? AbiParametersToPrimitiveTypes<params, AbiParameterKind, true>\n : never,\n): EncodeAbiParametersReturnType {\n if (params.length !== values.length)\n throw new AbiEncodingLengthMismatchError({\n expectedLength: params.length as number,\n givenLength: values.length as any,\n })\n // Prepare the parameters to determine dynamic types to encode.\n const preparedParams = prepareParams({\n params: params as readonly AbiParameter[],\n values: values as any,\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\ntype PrepareParamsErrorType = PrepareParamErrorType | ErrorType\n\nfunction prepareParams<const params extends readonly AbiParameter[]>({\n params,\n values,\n}: {\n params: params\n values: AbiParametersToPrimitiveTypes<params>\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\ntype PrepareParamErrorType =\n | EncodeAddressErrorType\n | EncodeArrayErrorType\n | EncodeBytesErrorType\n | EncodeBoolErrorType\n | EncodeNumberErrorType\n | EncodeStringErrorType\n | EncodeTupleErrorType\n | GetArrayComponentsErrorType\n | InvalidAbiEncodingTypeErrorType\n | ErrorType\n\nfunction prepareParam<const param extends AbiParameter>({\n param,\n value,\n}: {\n param: param\n value: AbiParameterToPrimitiveType<param>\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 const [, , size = '256'] = integerRegex.exec(param.type) ?? []\n return encodeNumber(value as unknown as number, {\n signed,\n size: Number(size),\n })\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\ntype EncodeParamsErrorType = NumberToHexErrorType | SizeErrorType | 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\ntype 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\ntype EncodeArrayErrorType =\n | AbiEncodingArrayLengthMismatchErrorType\n | ConcatErrorType\n | EncodeParamsErrorType\n | InvalidArrayErrorType\n | NumberToHexErrorType\n // TODO: Add back once circular type reference is resolved\n // | PrepareParamErrorType\n | ErrorType\n\nfunction encodeArray<const param extends AbiParameter>(\n value: AbiParameterToPrimitiveType<param>,\n {\n length,\n param,\n }: {\n length: number | null\n param: param\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\ntype EncodeBytesErrorType =\n | AbiEncodingBytesSizeMismatchErrorType\n | ConcatErrorType\n | PadHexErrorType\n | NumberToHexErrorType\n | SizeErrorType\n | ErrorType\n\nfunction encodeBytes<const param extends AbiParameter>(\n value: Hex,\n { param }: { param: param },\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 !== Number.parseInt(paramSize, 10))\n throw new AbiEncodingBytesSizeMismatchError({\n expectedSize: Number.parseInt(paramSize, 10),\n value,\n })\n return { dynamic: false, encoded: padHex(value, { dir: 'right' }) }\n}\n\ntype EncodeBoolErrorType = PadHexErrorType | BoolToHexErrorType | ErrorType\n\nfunction encodeBool(value: boolean): PreparedParam {\n if (typeof value !== 'boolean')\n throw new BaseError(\n `Invalid boolean value: \"${value}\" (type: ${typeof value}). Expected: \\`true\\` or \\`false\\`.`,\n )\n return { dynamic: false, encoded: padHex(boolToHex(value)) }\n}\n\ntype EncodeNumberErrorType = NumberToHexErrorType | ErrorType\n\nfunction encodeNumber(\n value: number,\n { signed, size = 256 }: { signed: boolean; size?: number | undefined },\n): PreparedParam {\n if (typeof size === 'number') {\n const max = 2n ** (BigInt(size) - (signed ? 1n : 0n)) - 1n\n const min = signed ? -max - 1n : 0n\n if (value > max || value < min)\n throw new IntegerOutOfRangeError({\n max: max.toString(),\n min: min.toString(),\n signed,\n size: size / 8,\n value: value.toString(),\n })\n }\n return {\n dynamic: false,\n encoded: numberToHex(value, {\n size: 32,\n signed,\n }),\n }\n}\n\ntype 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\ntype EncodeTupleErrorType =\n | ConcatErrorType\n | EncodeParamsErrorType\n // TODO: Add back once circular type reference is resolved\n // | PrepareParamErrorType\n | ErrorType\n\nfunction encodeTuple<\n const param extends AbiParameter & { components: readonly AbiParameter[] },\n>(\n value: AbiParameterToPrimitiveType<param>,\n { param }: { param: param },\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\ntype 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 {\n type ToSignatureHashErrorType,\n toSignatureHash,\n} from './toSignatureHash.js'\n\nexport type ToFunctionSelectorErrorType =\n | ToSignatureHashErrorType\n | SliceErrorType\n | ErrorType\n\n/**\n * Returns the function selector for a given function definition.\n *\n * @example\n * const selector = toFunctionSelector('function ownerOf(uint256 tokenId)')\n * // 0x6352211e\n */\nexport const toFunctionSelector = (fn: string | AbiFunction) =>\n slice(toSignatureHash(fn), 0, 4)\n","import type { Abi, AbiParameter, Address } from 'abitype'\n\nimport {\n AbiItemAmbiguityError,\n type AbiItemAmbiguityErrorType,\n} from '../../errors/abi.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type {\n AbiItem,\n AbiItemArgs,\n AbiItemName,\n ExtractAbiItemForArgs,\n Widen,\n} from '../../types/contract.js'\nimport type { Hex } from '../../types/misc.js'\nimport type { UnionEvaluate } from '../../types/utils.js'\nimport { type IsHexErrorType, isHex } from '../../utils/data/isHex.js'\nimport { type IsAddressErrorType, isAddress } from '../address/isAddress.js'\nimport { toEventSelector } from '../hash/toEventSelector.js'\nimport {\n type ToFunctionSelectorErrorType,\n toFunctionSelector,\n} from '../hash/toFunctionSelector.js'\n\nexport type GetAbiItemParameters<\n abi extends Abi | readonly unknown[] = Abi,\n name extends AbiItemName<abi> = AbiItemName<abi>,\n args extends AbiItemArgs<abi, name> | undefined = AbiItemArgs<abi, name>,\n ///\n allArgs = AbiItemArgs<abi, name>,\n allNames = AbiItemName<abi>,\n> = {\n abi: abi\n name:\n | allNames // show all options\n | (name extends allNames ? name : never) // infer value\n | Hex // function selector\n} & UnionEvaluate<\n readonly [] extends allArgs\n ? {\n args?:\n | allArgs // show all options\n // infer value, widen inferred value of `args` conditionally to match `allArgs`\n | (abi extends Abi\n ? args extends allArgs\n ? Widen<args>\n : never\n : never)\n | undefined\n }\n : {\n args?:\n | allArgs // show all options\n | (Widen<args> & (args extends allArgs ? unknown : never)) // infer value, widen inferred value of `args` match `allArgs` (e.g. avoid union `args: readonly [123n] | readonly [bigint]`)\n | undefined\n }\n>\n\nexport type GetAbiItemErrorType =\n | IsArgOfTypeErrorType\n | IsHexErrorType\n | ToFunctionSelectorErrorType\n | AbiItemAmbiguityErrorType\n | ErrorType\n\nexport type GetAbiItemReturnType<\n abi extends Abi | readonly unknown[] = Abi,\n name extends AbiItemName<abi> = AbiItemName<abi>,\n args extends AbiItemArgs<abi, name> | undefined = AbiItemArgs<abi, name>,\n> = abi extends Abi\n ? Abi extends abi\n ? AbiItem | undefined\n : ExtractAbiItemForArgs<\n abi,\n name,\n args extends AbiItemArgs<abi, name> ? args : AbiItemArgs<abi, name>\n >\n : AbiItem | undefined\n\nexport function getAbiItem<\n const abi extends Abi | readonly unknown[],\n name extends AbiItemName<abi>,\n const args extends AbiItemArgs<abi, name> | undefined = undefined,\n>(\n parameters: GetAbiItemParameters<abi, name, args>,\n): GetAbiItemReturnType<abi, name, args> {\n const { abi, args = [], name } = parameters as unknown as GetAbiItemParameters\n\n const isSelector = isHex(name, { strict: false })\n const abiItems = (abi as Abi).filter((abiItem) => {\n if (isSelector) {\n if (abiItem.type === 'function')\n return toFunctionSelector(abiItem) === name\n if (abiItem.type === 'event') return toEventSelector(abiItem) === name\n return false\n }\n return 'name' in abiItem && abiItem.name === name\n })\n\n if (abiItems.length === 0)\n return undefined as GetAbiItemReturnType<abi, name, args>\n if (abiItems.length === 1)\n return abiItems[0] as GetAbiItemReturnType<abi, name, args>\n\n let matchedAbiItem: AbiItem | 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)\n return abiItem as GetAbiItemReturnType<abi, name, args>\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.every((arg, index) => {\n const abiParameter = 'inputs' in abiItem && abiItem.inputs![index]\n if (!abiParameter) return false\n return isArgOfType(arg, 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<abi, name, args>\n return abiItems[0] as GetAbiItemReturnType<abi, name, args>\n}\n\ntype IsArgOfTypeErrorType = IsAddressErrorType | ErrorType\n\n/** @internal */\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, { strict: false })\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 (\n argType === 'object' &&\n isArgOfType(\n Object.values(arg as unknown[] | Record<string, unknown>)[\n index\n ],\n component as AbiParameter,\n )\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\n/** @internal */\nexport function getAmbiguousTypes(\n sourceParameters: readonly AbiParameter[],\n targetParameters: readonly AbiParameter[],\n args: AbiItemArgs,\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, { strict: false })\n if (types.includes('address') && types.includes('bytes'))\n return isAddress(args[parameterIndex] as Address, { strict: false })\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<accountOrAddress extends Address | Account>(\n account: accountOrAddress,\n): accountOrAddress extends Address ? Account : accountOrAddress {\n if (typeof account === 'string')\n return { address: account, type: 'json-rpc' } as any\n return account as any\n}\n","import type {\n Abi,\n AbiStateMutability,\n ExtractAbiFunction,\n ExtractAbiFunctions,\n} from 'abitype'\n\nimport {\n AbiFunctionNotFoundError,\n type AbiFunctionNotFoundErrorType,\n} from '../../errors/abi.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type {\n ContractFunctionArgs,\n ContractFunctionName,\n} from '../../types/contract.js'\nimport type { Hex } from '../../types/misc.js'\nimport type { IsNarrowable, UnionEvaluate } from '../../types/utils.js'\nimport type { ConcatHexErrorType } from '../data/concat.js'\nimport {\n type ToFunctionSelectorErrorType,\n toFunctionSelector,\n} from '../hash/toFunctionSelector.js'\nimport { type FormatAbiItemErrorType, formatAbiItem } from './formatAbiItem.js'\nimport { type GetAbiItemErrorType, getAbiItem } from './getAbiItem.js'\n\nconst docsPath = '/docs/contract/encodeFunctionData'\n\nexport type PrepareEncodeFunctionDataParameters<\n abi extends Abi | readonly unknown[] = Abi,\n functionName extends\n | ContractFunctionName<abi>\n | undefined = ContractFunctionName<abi>,\n ///\n hasFunctions = abi extends Abi\n ? Abi extends abi\n ? true\n : [ExtractAbiFunctions<abi>] extends [never]\n ? false\n : true\n : true,\n allArgs = ContractFunctionArgs<\n abi,\n AbiStateMutability,\n functionName extends ContractFunctionName<abi>\n ? functionName\n : ContractFunctionName<abi>\n >,\n allFunctionNames = ContractFunctionName<abi>,\n> = {\n abi: abi\n} & UnionEvaluate<\n IsNarrowable<abi, Abi> extends true\n ? abi['length'] extends 1\n ? { functionName?: functionName | allFunctionNames | Hex | undefined }\n : { functionName: functionName | allFunctionNames | Hex }\n : { functionName?: functionName | allFunctionNames | Hex | undefined }\n> &\n UnionEvaluate<{ args?: allArgs | undefined }> &\n (hasFunctions extends true ? unknown : never)\n\nexport type PrepareEncodeFunctionDataReturnType<\n abi extends Abi | readonly unknown[] = Abi,\n functionName extends\n | ContractFunctionName<abi>\n | undefined = ContractFunctionName<abi>,\n> = {\n abi: abi extends Abi\n ? functionName extends ContractFunctionName<abi>\n ? [ExtractAbiFunction<abi, functionName>]\n : abi\n : Abi\n functionName: Hex\n}\n\nexport type PrepareEncodeFunctionDataErrorType =\n | AbiFunctionNotFoundErrorType\n | ConcatHexErrorType\n | FormatAbiItemErrorType\n | GetAbiItemErrorType\n | ToFunctionSelectorErrorType\n | ErrorType\n\nexport function prepareEncodeFunctionData<\n const abi extends Abi | readonly unknown[],\n functionName extends ContractFunctionName<abi> | undefined = undefined,\n>(\n parameters: PrepareEncodeFunctionDataParameters<abi, functionName>,\n): PrepareEncodeFunctionDataReturnType<abi, functionName> {\n const { abi, args, functionName } =\n parameters as PrepareEncodeFunctionDataParameters\n\n let abiItem = abi[0]\n if (functionName) {\n const item = getAbiItem({\n abi,\n args,\n name: functionName,\n })\n if (!item) throw new AbiFunctionNotFoundError(functionName, { docsPath })\n abiItem = item\n }\n\n if (abiItem.type !== 'function')\n throw new AbiFunctionNotFoundError(undefined, { docsPath })\n\n return {\n abi: [abiItem],\n functionName: toFunctionSelector(formatAbiItem(abiItem)),\n } as unknown as PrepareEncodeFunctionDataReturnType<abi, functionName>\n}\n","import type { Abi, AbiStateMutability, ExtractAbiFunctions } from 'abitype'\n\nimport type { AbiFunctionNotFoundErrorType } from '../../errors/abi.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type {\n ContractFunctionArgs,\n ContractFunctionName,\n} from '../../types/contract.js'\nimport type { Hex } from '../../types/misc.js'\nimport type { IsNarrowable, UnionEvaluate } from '../../types/utils.js'\nimport { type ConcatHexErrorType, concatHex } from '../data/concat.js'\nimport type { ToFunctionSelectorErrorType } from '../hash/toFunctionSelector.js'\nimport {\n type EncodeAbiParametersErrorType,\n encodeAbiParameters,\n} from './encodeAbiParameters.js'\nimport type { FormatAbiItemErrorType } from './formatAbiItem.js'\nimport type { GetAbiItemErrorType } from './getAbiItem.js'\nimport { prepareEncodeFunctionData } from './prepareEncodeFunctionData.js'\n\nexport type EncodeFunctionDataParameters<\n abi extends Abi | readonly unknown[] = Abi,\n functionName extends\n | ContractFunctionName<abi>\n | Hex\n | undefined = ContractFunctionName<abi>,\n ///\n hasFunctions = abi extends Abi\n ? Abi extends abi\n ? true\n : [ExtractAbiFunctions<abi>] extends [never]\n ? false\n : true\n : true,\n allArgs = ContractFunctionArgs<\n abi,\n AbiStateMutability,\n functionName extends ContractFunctionName<abi>\n ? functionName\n : ContractFunctionName<abi>\n >,\n allFunctionNames = ContractFunctionName<abi>,\n> = {\n abi: abi\n} & UnionEvaluate<\n IsNarrowable<abi, Abi> extends true\n ? abi['length'] extends 1\n ? { functionName?: functionName | allFunctionNames | Hex | undefined }\n : { functionName: functionName | allFunctionNames | Hex }\n : { functionName?: functionName | allFunctionNames | Hex | undefined }\n> &\n UnionEvaluate<\n readonly [] extends allArgs\n ? { args?: allArgs | undefined }\n : { args: allArgs }\n > &\n (hasFunctions extends true ? unknown : never)\n\nexport type EncodeFunctionDataReturnType = Hex\n\nexport type EncodeFunctionDataErrorType =\n | AbiFunctionNotFoundErrorType\n | ConcatHexErrorType\n | EncodeAbiParametersErrorType\n | FormatAbiItemErrorType\n | GetAbiItemErrorType\n | ToFunctionSelectorErrorType\n | ErrorType\n\nexport function encodeFunctionData<\n const abi extends Abi | readonly unknown[],\n functionName extends ContractFunctionName<abi> | undefined = undefined,\n>(\n parameters: EncodeFunctionDataParameters<abi, functionName>,\n): EncodeFunctionDataReturnType {\n const { args } = parameters as EncodeFunctionDataParameters\n\n const { abi, functionName } = (() => {\n if (\n parameters.abi.length === 1 &&\n parameters.functionName?.startsWith('0x')\n )\n return parameters as { abi: Abi; functionName: Hex }\n return prepareEncodeFunctionData(parameters)\n })()\n\n const abiItem = abi[0]\n const signature = functionName\n\n const data =\n 'inputs' in abiItem && abiItem.inputs\n ? encodeAbiParameters(abiItem.inputs, args ?? [])\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: 'Arithmetic 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 { BaseError } from './base.js'\n\nexport type NegativeOffsetErrorType = NegativeOffsetError & {\n name: 'NegativeOffsetError'\n}\nexport class NegativeOffsetError extends BaseError {\n constructor({ offset }: { offset: number }) {\n super(`Offset \\`${offset}\\` cannot be negative.`, {\n name: 'NegativeOffsetError',\n })\n }\n}\n\nexport type PositionOutOfBoundsErrorType = PositionOutOfBoundsError & {\n name: 'PositionOutOfBoundsError'\n}\nexport class PositionOutOfBoundsError extends BaseError {\n constructor({ length, position }: { length: number; position: number }) {\n super(\n `Position \\`${position}\\` is out of bounds (\\`0 < position < ${length}\\`).`,\n { name: 'PositionOutOfBoundsError' },\n )\n }\n}\n\nexport type RecursiveReadLimitExceededErrorType =\n RecursiveReadLimitExceededError & {\n name: 'RecursiveReadLimitExceededError'\n }\nexport class RecursiveReadLimitExceededError extends BaseError {\n constructor({ count, limit }: { count: number; limit: number }) {\n super(\n `Recursive read limit of \\`${limit}\\` exceeded (recursive read count: \\`${count}\\`).`,\n { name: 'RecursiveReadLimitExceededError' },\n )\n }\n}\n","import {\n NegativeOffsetError,\n type NegativeOffsetErrorType,\n PositionOutOfBoundsError,\n type PositionOutOfBoundsErrorType,\n RecursiveReadLimitExceededError,\n type RecursiveReadLimitExceededErrorType,\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 positionReadCount: Map<number, number>\n recursiveReadCount: number\n recursiveReadLimit: number\n remaining: number\n assertReadLimit(position?: number): void\n assertPosition(position: number): void\n decrementPosition(offset: number): void\n getReadCount(position?: number): number\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, size?: number): ByteArray\n readUint8(): number\n readUint16(): number\n readUint24(): number\n readUint32(): number\n setPosition(position: number): () => void\n _touch(): void\n}\n\ntype CursorErrorType =\n | CursorAssertPositionErrorType\n | CursorDecrementPositionErrorType\n | CursorIncrementPositionErrorType\n | ErrorType\n\ntype CursorAssertPositionErrorType = PositionOutOfBoundsErrorType | ErrorType\n\ntype CursorDecrementPositionErrorType = NegativeOffsetErrorType | ErrorType\n\ntype CursorIncrementPositionErrorType = NegativeOffsetErrorType | ErrorType\n\ntype StaticCursorErrorType =\n | NegativeOffsetErrorType\n | RecursiveReadLimitExceededErrorType\n\nconst staticCursor: Cursor = {\n bytes: new Uint8Array(),\n dataView: new DataView(new ArrayBuffer(0)),\n position: 0,\n positionReadCount: new Map(),\n recursiveReadCount: 0,\n recursiveReadLimit: Number.POSITIVE_INFINITY,\n assertReadLimit() {\n if (this.recursiveReadCount >= this.recursiveReadLimit)\n throw new RecursiveReadLimitExceededError({\n count: this.recursiveReadCount + 1,\n limit: this.recursiveReadLimit,\n })\n },\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 getReadCount(position) {\n return this.positionReadCount.get(position || this.position) || 0\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 this.assertReadLimit()\n this._touch()\n const value = this.inspectByte()\n this.position++\n return value\n },\n readBytes(length, size) {\n this.assertReadLimit()\n this._touch()\n const value = this.inspectBytes(length)\n this.position += size ?? length\n return value\n },\n readUint8() {\n this.assertReadLimit()\n this._touch()\n const value = this.inspectUint8()\n this.position += 1\n return value\n },\n readUint16() {\n this.assertReadLimit()\n this._touch()\n const value = this.inspectUint16()\n this.position += 2\n return value\n },\n readUint24() {\n this.assertReadLimit()\n this._touch()\n const value = this.inspectUint24()\n this.position += 3\n return value\n },\n readUint32() {\n this.assertReadLimit()\n this._touch()\n const value = this.inspectUint32()\n this.position += 4\n return value\n },\n get remaining() {\n return this.bytes.length - this.position\n },\n setPosition(position) {\n const oldPosition = this.position\n this.assertPosition(position)\n this.position = position\n return () => (this.position = oldPosition)\n },\n _touch() {\n if (this.recursiveReadLimit === Number.POSITIVE_INFINITY) return\n const count = this.getReadCount()\n this.positionReadCount.set(this.position, count + 1)\n if (count > 0) this.recursiveReadCount++\n },\n}\n\ntype CursorConfig = { recursiveReadLimit?: number | undefined }\n\nexport type CreateCursorErrorType =\n | CursorErrorType\n | StaticCursorErrorType\n | ErrorType\n\nexport function createCursor(\n bytes: ByteArray,\n { recursiveReadLimit = 8_192 }: CursorConfig = {},\n): Cursor {\n const cursor: Cursor = Object.create(staticCursor)\n cursor.bytes = bytes\n cursor.dataView = new DataView(\n bytes.buffer ?? bytes,\n bytes.byteOffset,\n bytes.byteLength,\n )\n cursor.positionReadCount = new Map()\n cursor.recursiveReadLimit = recursiveReadLimit\n return cursor\n}\n","import { InvalidBytesBooleanError } from '../../errors/encoding.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray, Hex } from '../../types/misc.js'\nimport { type TrimErrorType, trim } from '../data/trim.js'\n\nimport {\n type AssertSizeErrorType,\n assertSize,\n type HexToBigIntErrorType,\n type HexToNumberErrorType,\n hexToBigInt,\n hexToNumber,\n} from './fromHex.js'\nimport { type BytesToHexErrorType, bytesToHex } from './toHex.js'\n\nexport type FromBytesParameters<\n to extends 'string' | 'hex' | 'bigint' | 'number' | 'boolean',\n> =\n | to\n | {\n /** Size of the bytes. */\n size?: number | undefined\n /** Type to convert to. */\n to: to\n }\n\nexport type FromBytesReturnType<to> = to extends 'string'\n ? string\n : to extends 'hex'\n ? Hex\n : to extends 'bigint'\n ? bigint\n : to extends 'number'\n ? number\n : to extends 'boolean'\n ? boolean\n : never\n\nexport type FromBytesErrorType =\n | BytesToHexErrorType\n | BytesToBigIntErrorType\n | BytesToBoolErrorType\n | BytesToNumberErrorType\n | BytesToStringErrorType\n | ErrorType\n\n/**\n * Decodes a byte array into a UTF-8 string, hex value, number, bigint or boolean.\n *\n * - Docs: https://viem.sh/docs/utilities/fromBytes\n * - Example: https://viem.sh/docs/utilities/fromBytes#usage\n *\n * @param bytes Byte array to decode.\n * @param toOrOpts Type to convert to or options.\n * @returns Decoded value.\n *\n * @example\n * import { fromBytes } from 'viem'\n * const data = fromBytes(new Uint8Array([1, 164]), 'number')\n * // 420\n *\n * @example\n * import { fromBytes } from 'viem'\n * const data = fromBytes(\n * new Uint8Array([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33]),\n * 'string'\n * )\n * // 'Hello world'\n */\nexport function fromBytes<\n to extends 'string' | 'hex' | 'bigint' | 'number' | 'boolean',\n>(\n bytes: ByteArray,\n toOrOpts: FromBytesParameters<to>,\n): FromBytesReturnType<to> {\n const opts = typeof toOrOpts === 'string' ? { to: toOrOpts } : toOrOpts\n const to = opts.to\n\n if (to === 'number')\n return bytesToNumber(bytes, opts) as FromBytesReturnType<to>\n if (to === 'bigint')\n return bytesToBigInt(bytes, opts) as FromBytesReturnType<to>\n if (to === 'boolean')\n return bytesToBool(bytes, opts) as FromBytesReturnType<to>\n if (to === 'string')\n return bytesToString(bytes, opts) as FromBytesReturnType<to>\n return bytesToHex(bytes, opts) as FromBytesReturnType<to>\n}\n\nexport type BytesToBigIntOpts = {\n /** Whether or not the number of a signed representation. */\n signed?: boolean | undefined\n /** Size of the bytes. */\n size?: number | undefined\n}\n\nexport type BytesToBigIntErrorType =\n | BytesToHexErrorType\n | HexToBigIntErrorType\n | ErrorType\n\n/**\n * Decodes a byte array into a bigint.\n *\n * - Docs: https://viem.sh/docs/utilities/fromBytes#bytestobigint\n *\n * @param bytes Byte array to decode.\n * @param opts Options.\n * @returns BigInt value.\n *\n * @example\n * import { bytesToBigInt } from 'viem'\n * const data = bytesToBigInt(new Uint8Array([1, 164]))\n * // 420n\n */\nexport function bytesToBigInt(\n bytes: ByteArray,\n opts: BytesToBigIntOpts = {},\n): bigint {\n if (typeof opts.size !== 'undefined') assertSize(bytes, { size: opts.size })\n const hex = bytesToHex(bytes, opts)\n return hexToBigInt(hex, opts)\n}\n\nexport type BytesToBoolOpts = {\n /** Size of the bytes. */\n size?: number | undefined\n}\n\nexport type BytesToBoolErrorType =\n | AssertSizeErrorType\n | TrimErrorType\n | ErrorType\n\n/**\n * Decodes a byte array into a boolean.\n *\n * - Docs: https://viem.sh/docs/utilities/fromBytes#bytestobool\n *\n * @param bytes Byte array to decode.\n * @param opts Options.\n * @returns Boolean value.\n *\n * @example\n * import { bytesToBool } from 'viem'\n * const data = bytesToBool(new Uint8Array([1]))\n * // true\n */\nexport function bytesToBool(\n bytes_: ByteArray,\n opts: BytesToBoolOpts = {},\n): boolean {\n let bytes = bytes_\n if (typeof opts.size !== 'undefined') {\n assertSize(bytes, { size: opts.size })\n bytes = trim(bytes)\n }\n if (bytes.length > 1 || bytes[0] > 1)\n throw new InvalidBytesBooleanError(bytes)\n return Boolean(bytes[0])\n}\n\nexport type BytesToNumberOpts = BytesToBigIntOpts\n\nexport type BytesToNumberErrorType =\n | BytesToHexErrorType\n | HexToNumberErrorType\n | ErrorType\n\n/**\n * Decodes a byte array into a number.\n *\n * - Docs: https://viem.sh/docs/utilities/fromBytes#bytestonumber\n *\n * @param bytes Byte array to decode.\n * @param opts Options.\n * @returns Number value.\n *\n * @example\n * import { bytesToNumber } from 'viem'\n * const data = bytesToNumber(new Uint8Array([1, 164]))\n * // 420\n */\nexport function bytesToNumber(\n bytes: ByteArray,\n opts: BytesToNumberOpts = {},\n): number {\n if (typeof opts.size !== 'undefined') assertSize(bytes, { size: opts.size })\n const hex = bytesToHex(bytes, opts)\n return hexToNumber(hex, opts)\n}\n\nexport type BytesToStringOpts = {\n /** Size of the bytes. */\n size?: number | undefined\n}\n\nexport type BytesToStringErrorType =\n | AssertSizeErrorType\n | TrimErrorType\n | ErrorType\n\n/**\n * Decodes a byte array into a UTF-8 string.\n *\n * - Docs: https://viem.sh/docs/utilities/fromBytes#bytestostring\n *\n * @param bytes Byte array to decode.\n * @param opts Options.\n * @returns String value.\n *\n * @example\n * import { bytesToString } from 'viem'\n * const data = bytesToString(new Uint8Array([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33]))\n * // 'Hello world'\n */\nexport function bytesToString(\n bytes_: ByteArray,\n opts: BytesToStringOpts = {},\n): string {\n let bytes = bytes_\n if (typeof opts.size !== 'undefined') {\n assertSize(bytes, { size: opts.size })\n bytes = trim(bytes, { dir: 'right' })\n }\n return new TextDecoder().decode(bytes)\n}\n","import type {\n AbiParameter,\n AbiParameterKind,\n AbiParametersToPrimitiveTypes,\n} from 'abitype'\nimport {\n AbiDecodingDataSizeTooSmallError,\n AbiDecodingZeroDataError,\n InvalidAbiDecodingTypeError,\n type InvalidAbiDecodingTypeErrorType,\n} from '../../errors/abi.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray, Hex } from '../../types/misc.js'\nimport {\n type ChecksumAddressErrorType,\n checksumAddress,\n} from '../address/getAddress.js'\nimport {\n type CreateCursorErrorType,\n type Cursor,\n createCursor,\n} from '../cursor.js'\nimport { type SizeErrorType, size } from '../data/size.js'\nimport { type SliceBytesErrorType, sliceBytes } from '../data/slice.js'\nimport { type TrimErrorType, trim } from '../data/trim.js'\nimport {\n type BytesToBigIntErrorType,\n type BytesToBoolErrorType,\n type BytesToNumberErrorType,\n type BytesToStringErrorType,\n bytesToBigInt,\n bytesToBool,\n bytesToNumber,\n bytesToString,\n} from '../encoding/fromBytes.js'\nimport { type HexToBytesErrorType, hexToBytes } from '../encoding/toBytes.js'\nimport { type BytesToHexErrorType, bytesToHex } from '../encoding/toHex.js'\nimport { getArrayComponents } from './encodeAbiParameters.js'\n\nexport type DecodeAbiParametersReturnType<\n params extends readonly AbiParameter[] = readonly AbiParameter[],\n> = AbiParametersToPrimitiveTypes<\n params extends readonly AbiParameter[] ? params : AbiParameter[],\n AbiParameterKind,\n true\n>\n\nexport type DecodeAbiParametersErrorType =\n | HexToBytesErrorType\n | BytesToHexErrorType\n | DecodeParameterErrorType\n | SizeErrorType\n | CreateCursorErrorType\n | ErrorType\n\nexport function decodeAbiParameters<\n const params extends readonly AbiParameter[],\n>(\n params: params,\n data: ByteArray | Hex,\n): DecodeAbiParametersReturnType<params> {\n const bytes = typeof data === 'string' ? hexToBytes(data) : data\n const cursor = createCursor(bytes)\n\n if (size(bytes) === 0 && params.length > 0)\n throw new AbiDecodingZeroDataError()\n if (size(data) && size(data) < 32)\n throw new AbiDecodingDataSizeTooSmallError({\n data: typeof data === 'string' ? data : bytesToHex(data),\n params: params as readonly AbiParameter[],\n size: size(data),\n })\n\n let consumed = 0\n const values = []\n for (let i = 0; i < params.length; ++i) {\n const param = params[i]\n cursor.setPosition(consumed)\n const [data, consumed_] = decodeParameter(cursor, param, {\n staticPosition: 0,\n })\n consumed += consumed_\n values.push(data)\n }\n return values as never\n}\n\ntype DecodeParameterErrorType =\n | DecodeArrayErrorType\n | DecodeTupleErrorType\n | DecodeAddressErrorType\n | DecodeBoolErrorType\n | DecodeBytesErrorType\n | DecodeNumberErrorType\n | DecodeStringErrorType\n | InvalidAbiDecodingTypeErrorType\n\nfunction decodeParameter(\n cursor: Cursor,\n param: AbiParameter,\n { staticPosition }: { staticPosition: number },\n) {\n const arrayComponents = getArrayComponents(param.type)\n if (arrayComponents) {\n const [length, type] = arrayComponents\n return decodeArray(cursor, { ...param, type }, { length, staticPosition })\n }\n if (param.type === 'tuple')\n return decodeTuple(cursor, param as TupleAbiParameter, { staticPosition })\n\n if (param.type === 'address') return decodeAddress(cursor)\n if (param.type === 'bool') return decodeBool(cursor)\n if (param.type.startsWith('bytes'))\n return decodeBytes(cursor, param, { staticPosition })\n if (param.type.startsWith('uint') || param.type.startsWith('int'))\n return decodeNumber(cursor, param)\n if (param.type === 'string') return decodeString(cursor, { staticPosition })\n throw new InvalidAbiDecodingTypeError(param.type, {\n docsPath: '/docs/contract/decodeAbiParameters',\n })\n}\n\n////////////////////////////////////////////////////////////////////\n// Type Decoders\n\nconst sizeOfLength = 32\nconst sizeOfOffset = 32\n\ntype DecodeAddressErrorType =\n | ChecksumAddressErrorType\n | BytesToHexErrorType\n | SliceBytesErrorType\n | ErrorType\n\nfunction decodeAddress(cursor: Cursor) {\n const value = cursor.readBytes(32)\n return [checksumAddress(bytesToHex(sliceBytes(value, -20))), 32]\n}\n\ntype DecodeArrayErrorType = BytesToNumberErrorType | ErrorType\n\nfunction decodeArray(\n cursor: Cursor,\n param: AbiParameter,\n { length, staticPosition }: { length: number | null; staticPosition: number },\n) {\n // If the length of the array is not known in advance (dynamic array),\n // this means we will need to wonder off to the pointer and decode.\n if (!length) {\n // Dealing with a dynamic type, so get the offset of the array data.\n const offset = bytesToNumber(cursor.readBytes(sizeOfOffset))\n\n // Start is the static position of current slot + offset.\n const start = staticPosition + offset\n const startOfData = start + sizeOfLength\n\n // Get the length of the array from the offset.\n cursor.setPosition(start)\n const length = bytesToNumber(cursor.readBytes(sizeOfLength))\n\n // Check if the array has any dynamic children.\n const dynamicChild = hasDynamicChild(param)\n\n let consumed = 0\n const value: unknown[] = []\n for (let i = 0; i < length; ++i) {\n // If any of the children is dynamic, then all elements will be offset pointer, thus size of one slot (32 bytes).\n // Otherwise, elements will be the size of their encoding (consumed bytes).\n cursor.setPosition(startOfData + (dynamicChild ? i * 32 : consumed))\n const [data, consumed_] = decodeParameter(cursor, param, {\n staticPosition: startOfData,\n })\n consumed += consumed_\n value.push(data)\n }\n\n // As we have gone wondering, restore to the original position + next slot.\n cursor.setPosition(staticPosition + 32)\n return [value, 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 // Dealing with dynamic types, so get the offset of the array data.\n const offset = bytesToNumber(cursor.readBytes(sizeOfOffset))\n\n // Start is the static position of current slot + offset.\n const start = staticPosition + offset\n\n const value: unknown[] = []\n for (let i = 0; i < length; ++i) {\n // Move cursor along to the next slot (next offset pointer).\n cursor.setPosition(start + i * 32)\n const [data] = decodeParameter(cursor, param, {\n staticPosition: start,\n })\n value.push(data)\n }\n\n // As we have gone wondering, restore to the original position + next slot.\n cursor.setPosition(staticPosition + 32)\n return [value, 32]\n }\n\n // If the length of the array is known in advance and the array is deeply static,\n // then we can just decode each element in sequence.\n let consumed = 0\n const value: unknown[] = []\n for (let i = 0; i < length; ++i) {\n const [data, consumed_] = decodeParameter(cursor, param, {\n staticPosition: staticPosition + consumed,\n })\n consumed += consumed_\n value.push(data)\n }\n return [value, consumed]\n}\n\ntype DecodeBoolErrorType = BytesToBoolErrorType | ErrorType\n\nfunction decodeBool(cursor: Cursor) {\n return [bytesToBool(cursor.readBytes(32), { size: 32 }), 32]\n}\n\ntype DecodeBytesErrorType =\n | BytesToNumberErrorType\n | BytesToHexErrorType\n | ErrorType\n\nfunction decodeBytes(\n cursor: Cursor,\n param: AbiParameter,\n { staticPosition }: { staticPosition: number },\n) {\n const [_, size] = param.type.split('bytes')\n if (!size) {\n // Dealing with dynamic types, so get the offset of the bytes data.\n const offset = bytesToNumber(cursor.readBytes(32))\n\n // Set position of the cursor to start of bytes data.\n cursor.setPosition(staticPosition + offset)\n\n const length = bytesToNumber(cursor.readBytes(32))\n\n // If there is no length, we have zero data.\n if (length === 0) {\n // As we have gone wondering, restore to the original position + next slot.\n cursor.setPosition(staticPosition + 32)\n return ['0x', 32]\n }\n\n const data = cursor.readBytes(length)\n\n // As we have gone wondering, restore to the original position + next slot.\n cursor.setPosition(staticPosition + 32)\n return [bytesToHex(data), 32]\n }\n\n const value = bytesToHex(cursor.readBytes(Number.parseInt(size, 10), 32))\n return [value, 32]\n}\n\ntype DecodeNumberErrorType =\n | BytesToNumberErrorType\n | BytesToBigIntErrorType\n | ErrorType\n\nfunction decodeNumber(cursor: Cursor, param: AbiParameter) {\n const signed = param.type.startsWith('int')\n const size = Number.parseInt(param.type.split('int')[1] || '256', 10)\n const value = cursor.readBytes(32)\n return [\n size > 48\n ? bytesToBigInt(value, { signed })\n : bytesToNumber(value, { signed }),\n 32,\n ]\n}\n\ntype TupleAbiParameter = AbiParameter & { components: readonly AbiParameter[] }\n\ntype DecodeTupleErrorType = BytesToNumberErrorType | ErrorType\n\nfunction decodeTuple(\n cursor: Cursor,\n param: TupleAbiParameter,\n { staticPosition }: { staticPosition: number },\n) {\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 // Dealing with dynamic types, so get the offset of the tuple data.\n const offset = bytesToNumber(cursor.readBytes(sizeOfOffset))\n\n // Start is the static position of referencing slot + offset.\n const start = staticPosition + offset\n\n for (let i = 0; i < param.components.length; ++i) {\n const component = param.components[i]\n cursor.setPosition(start + consumed)\n const [data, consumed_] = decodeParameter(cursor, component, {\n staticPosition: start,\n })\n consumed += consumed_\n value[hasUnnamedChild ? i : component?.name!] = data\n }\n\n // As we have gone wondering, restore to the original position + next slot.\n cursor.setPosition(staticPosition + 32)\n return [value, 32]\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 [data, consumed_] = decodeParameter(cursor, component, {\n staticPosition,\n })\n value[hasUnnamedChild ? i : component?.name!] = data\n consumed += consumed_\n }\n return [value, consumed]\n}\n\ntype DecodeStringErrorType =\n | BytesToNumberErrorType\n | BytesToStringErrorType\n | TrimErrorType\n | ErrorType\n\nfunction decodeString(\n cursor: Cursor,\n { staticPosition }: { staticPosition: number },\n) {\n // Get offset to start of string data.\n const offset = bytesToNumber(cursor.readBytes(32))\n\n // Start is the static position of current slot + offset.\n const start = staticPosition + offset\n cursor.setPosition(start)\n\n const length = bytesToNumber(cursor.readBytes(32))\n\n // If there is no length, we have zero data (empty string).\n if (length === 0) {\n cursor.setPosition(staticPosition + 32)\n return ['', 32]\n }\n\n const data = cursor.readBytes(length, 32)\n const value = bytesToString(trim(data))\n\n // As we have gone wondering, restore to the original position + next slot.\n cursor.setPosition(staticPosition + 32)\n\n return [value, 32]\n}\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 } 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 { ErrorType } from '../../errors/utils.js'\nimport type {\n AbiItem,\n ContractErrorArgs,\n ContractErrorName,\n} from '../../types/contract.js'\nimport type { Hex } from '../../types/misc.js'\nimport type { IsNarrowable, UnionEvaluate } from '../../types/utils.js'\nimport { slice } from '../data/slice.js'\nimport {\n type ToFunctionSelectorErrorType,\n toFunctionSelector,\n} from '../hash/toFunctionSelector.js'\nimport {\n type DecodeAbiParametersErrorType,\n decodeAbiParameters,\n} from './decodeAbiParameters.js'\nimport { type FormatAbiItemErrorType, formatAbiItem } from './formatAbiItem.js'\n\nexport type DecodeErrorResultParameters<\n abi extends Abi | readonly unknown[] = Abi,\n> = { abi?: abi | undefined; data: Hex }\n\nexport type DecodeErrorResultReturnType<\n abi extends Abi | readonly unknown[] = Abi,\n ///\n allErrorNames extends ContractErrorName<abi> = ContractErrorName<abi>,\n> = IsNarrowable<abi, Abi> extends true\n ? UnionEvaluate<\n {\n [errorName in allErrorNames]: {\n abiItem: abi extends Abi\n ? Abi extends abi\n ? AbiItem\n : ExtractAbiError<abi, errorName>\n : AbiItem\n args: ContractErrorArgs<abi, errorName>\n errorName: errorName\n }\n }[allErrorNames]\n >\n : {\n abiItem: AbiItem\n args: readonly unknown[] | undefined\n errorName: string\n }\n\nexport type DecodeErrorResultErrorType =\n | AbiDecodingZeroDataErrorType\n | AbiErrorSignatureNotFoundErrorType\n | DecodeAbiParametersErrorType\n | FormatAbiItemErrorType\n | ToFunctionSelectorErrorType\n | ErrorType\n\nexport function decodeErrorResult<const abi extends Abi | readonly unknown[]>(\n parameters: DecodeErrorResultParameters<abi>,\n): DecodeErrorResultReturnType<abi> {\n const { abi, data } = parameters as DecodeErrorResultParameters\n\n const signature = slice(data, 0, 4)\n if (signature === '0x') throw new AbiDecodingZeroDataError()\n\n const abi_ = [...(abi || []), solidityError, solidityPanic]\n const abiItem = abi_.find(\n (x) =>\n x.type === 'error' && signature === toFunctionSelector(formatAbiItem(x)),\n )\n if (!abiItem)\n throw new AbiErrorSignatureNotFoundError(signature, {\n docsPath: '/docs/contract/decodeErrorResult',\n })\n return {\n abiItem,\n args:\n 'inputs' in abiItem && abiItem.inputs && abiItem.inputs.length > 0\n ? decodeAbiParameters(abiItem.inputs, slice(data, 4))\n : undefined,\n errorName: (abiItem as { name: string }).name,\n } as DecodeErrorResultReturnType<abi>\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 | undefined\n includeName?: boolean | undefined\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","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\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 { 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\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 { 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\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 type { StateMapping, StateOverride } from '../types/stateOverride.js'\nimport { BaseError } from './base.js'\n\nexport type AccountStateConflictErrorType = AccountStateConflictError & {\n name: 'AccountStateConflictError'\n}\n\nexport class AccountStateConflictError extends BaseError {\n constructor({ address }: { address: string }) {\n super(`State for account \"${address}\" is set multiple times.`, {\n name: 'AccountStateConflictError',\n })\n }\n}\n\nexport type StateAssignmentConflictErrorType = StateAssignmentConflictError & {\n name: 'StateAssignmentConflictError'\n}\n\nexport class StateAssignmentConflictError extends BaseError {\n constructor() {\n super('state and stateDiff are set on the same account.', {\n name: 'StateAssignmentConflictError',\n })\n }\n}\n\n/** @internal */\nexport function prettyStateMapping(stateMapping: StateMapping) {\n return stateMapping.reduce((pretty, { slot, value }) => {\n return `${pretty} ${slot}: ${value}\\n`\n }, '')\n}\n\nexport function prettyStateOverride(stateOverride: StateOverride) {\n return stateOverride\n .reduce((pretty, { address, ...state }) => {\n let val = `${pretty} ${address}:\\n`\n if (state.nonce) val += ` nonce: ${state.nonce}\\n`\n if (state.balance) val += ` balance: ${state.balance}\\n`\n if (state.code) val += ` code: ${state.code}\\n`\n if (state.state) {\n val += ' state:\\n'\n val += prettyStateMapping(state.state)\n }\n if (state.stateDiff) {\n val += ' stateDiff:\\n'\n val += prettyStateMapping(state.stateDiff)\n }\n return val\n }, ' State Override:\\n')\n .slice(0, -1)\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 {\n TransactionReceipt,\n TransactionType,\n} 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 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 { name: 'FeeConflictError' },\n )\n }\n}\n\nexport type InvalidLegacyVErrorType = InvalidLegacyVError & {\n name: 'InvalidLegacyVError'\n}\nexport class InvalidLegacyVError extends BaseError {\n constructor({ v }: { v: bigint }) {\n super(`Invalid \\`v\\` value \"${v}\". Expected 27 or 28.`, {\n name: 'InvalidLegacyVError',\n })\n }\n}\n\nexport type InvalidSerializableTransactionErrorType =\n InvalidSerializableTransactionError & {\n name: 'InvalidSerializableTransactionError'\n }\nexport class InvalidSerializableTransactionError extends BaseError {\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 '- an EIP-4844 Transaction with `blobs`, `blobVersionedHashes`, `sidecars`, or',\n '- an EIP-7702 Transaction with `authorizationList`, or',\n '- a Legacy Transaction with `gasPrice`',\n ],\n name: 'InvalidSerializableTransactionError',\n })\n }\n}\n\nexport type InvalidSerializedTransactionTypeErrorType =\n InvalidSerializedTransactionTypeError & {\n name: 'InvalidSerializedTransactionTypeError'\n }\nexport class InvalidSerializedTransactionTypeError extends BaseError {\n serializedType: Hex\n\n constructor({ serializedType }: { serializedType: Hex }) {\n super(`Serialized transaction type \"${serializedType}\" is invalid.`, {\n name: 'InvalidSerializedTransactionType',\n })\n\n this.serializedType = serializedType\n }\n}\n\nexport type InvalidSerializedTransactionErrorType =\n InvalidSerializedTransactionError & {\n name: 'InvalidSerializedTransactionError'\n }\nexport class InvalidSerializedTransactionError extends BaseError {\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 name: 'InvalidSerializedTransactionError',\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 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 { name: 'InvalidStorageKeySizeError' },\n )\n }\n}\n\nexport type TransactionExecutionErrorType = TransactionExecutionError & {\n name: 'TransactionExecutionError'\n}\nexport class TransactionExecutionError extends BaseError {\n override cause: BaseError\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 | null\n chain?: Chain | undefined\n docsPath?: string | undefined\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 name: 'TransactionExecutionError',\n })\n this.cause = cause\n }\n}\n\nexport type TransactionNotFoundErrorType = TransactionNotFoundError & {\n name: 'TransactionNotFoundError'\n}\nexport class TransactionNotFoundError extends BaseError {\n constructor({\n blockHash,\n blockNumber,\n blockTag,\n hash,\n index,\n }: {\n blockHash?: Hash | undefined\n blockNumber?: bigint | undefined\n blockTag?: BlockTag | undefined\n hash?: Hash | undefined\n index?: number | undefined\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 name: 'TransactionNotFoundError',\n })\n }\n}\n\nexport type TransactionReceiptNotFoundErrorType =\n TransactionReceiptNotFoundError & {\n name: 'TransactionReceiptNotFoundError'\n }\nexport class TransactionReceiptNotFoundError extends BaseError {\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 name: 'TransactionReceiptNotFoundError',\n },\n )\n }\n}\n\nexport type TransactionReceiptRevertedErrorType =\n TransactionReceiptRevertedError & {\n name: 'TransactionReceiptRevertedError'\n }\nexport class TransactionReceiptRevertedError extends BaseError {\n receipt: TransactionReceipt\n\n constructor({ receipt }: { receipt: TransactionReceipt }) {\n super(`Transaction with hash \"${receipt.transactionHash}\" reverted.`, {\n metaMessages: [\n 'The receipt marked the transaction as \"reverted\". This could mean that the function on the contract you are trying to call threw an error.',\n ' ',\n 'You can attempt to extract the revert reason by:',\n '- calling the `simulateContract` or `simulateCalls` Action with the `abi` and `functionName` of the contract',\n '- using the `call` Action with raw `data`',\n ],\n name: 'TransactionReceiptRevertedError',\n })\n\n this.receipt = receipt\n }\n}\n\nexport type WaitForTransactionReceiptTimeoutErrorType =\n WaitForTransactionReceiptTimeoutError & {\n name: 'WaitForTransactionReceiptTimeoutError'\n }\nexport class WaitForTransactionReceiptTimeoutError extends BaseError {\n constructor({ hash }: { hash: Hash }) {\n super(\n `Timed out while waiting for transaction with hash \"${hash}\" to be confirmed.`,\n { name: 'WaitForTransactionReceiptTimeoutError' },\n )\n }\n}\n","import type { Address } from 'abitype'\n\nexport type ErrorType<name extends string = 'Error'> = Error & { name: name }\n\nexport const getContractAddress = (address: Address) => address\nexport const getUrl = (url: string) => url\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 { prettyStateOverride } from './stateOverride.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 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 stateOverride,\n }: CallParameters & {\n chain?: Chain | undefined\n docsPath?: string | undefined\n },\n ) {\n const account = account_ ? parseAccount(account_) : undefined\n let 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 if (stateOverride) {\n prettyArgs += `\\n${prettyStateOverride(stateOverride)}`\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 name: 'CallExecutionError',\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[] | undefined\n override cause: BaseError\n contractAddress?: Address | undefined\n formattedArgs?: string | undefined\n functionName: string\n sender?: Address | undefined\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 | undefined\n contractAddress?: Address | undefined\n docsPath?: string | undefined\n functionName: string\n sender?: Address | undefined\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 prettyArgs && 'Contract Call:',\n prettyArgs,\n ].filter(Boolean) as string[],\n name: 'ContractFunctionExecutionError',\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 data?: DecodeErrorResultReturnType | undefined\n raw?: Hex | undefined\n reason?: string | undefined\n signature?: Hex | undefined\n\n constructor({\n abi,\n data,\n functionName,\n message,\n }: {\n abi: Abi\n data?: Hex | undefined\n functionName: string\n message?: string | undefined\n }) {\n let cause: Error | undefined\n let decodedData: DecodeErrorResultReturnType | undefined\n let metaMessages: string[] | undefined\n let reason: string | undefined\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://4byte.sourcify.dev/?q=${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 name: 'ContractFunctionRevertedError',\n },\n )\n\n this.data = decodedData\n this.raw = data\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 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 name: 'ContractFunctionZeroDataError',\n })\n }\n}\n\nexport type CounterfactualDeploymentFailedErrorType =\n CounterfactualDeploymentFailedError & {\n name: 'CounterfactualDeploymentFailedError'\n }\nexport class CounterfactualDeploymentFailedError extends BaseError {\n constructor({ factory }: { factory?: Address | undefined }) {\n super(\n `Deployment for counterfactual contract call failed${\n factory ? ` for factory \"${factory}\".` : ''\n }`,\n {\n metaMessages: [\n 'Please ensure:',\n '- The `factory` is a valid contract deployment factory (ie. Create2 Factory, ERC-4337 Factory, etc).',\n '- The `factoryData` is a valid encoded function call for contract deployment function on the factory.',\n ],\n name: 'CounterfactualDeploymentFailedError',\n },\n )\n }\n}\n\nexport type RawContractErrorType = RawContractError & {\n name: 'RawContractError'\n}\nexport class RawContractError extends BaseError {\n code = 3\n\n data?: Hex | { data?: Hex | undefined } | undefined\n\n constructor({\n data,\n message,\n }: {\n data?: Hex | { data?: Hex | undefined } | undefined\n message?: string | undefined\n }) {\n super(message || '', { name: 'RawContractError' })\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 body?: { [x: string]: unknown } | { [y: string]: unknown }[] | undefined\n headers?: Headers | undefined\n status?: number | undefined\n url: string\n\n constructor({\n body,\n cause,\n details,\n headers,\n status,\n url,\n }: {\n body?: { [x: string]: unknown } | { [y: string]: unknown }[] | undefined\n cause?: Error | undefined\n details?: string | undefined\n headers?: Headers | undefined\n status?: number | undefined\n url: string\n }) {\n super('HTTP request failed.', {\n cause,\n details,\n metaMessages: [\n status && `Status: ${status}`,\n `URL: ${getUrl(url)}`,\n body && `Request body: ${stringify(body)}`,\n ].filter(Boolean) as string[],\n name: 'HttpRequestError',\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 url: string\n constructor({\n body,\n cause,\n details,\n url,\n }: {\n body?: { [key: string]: unknown } | undefined\n cause?: Error | undefined\n details?: string | undefined\n url: string\n }) {\n super('WebSocket request failed.', {\n cause,\n details,\n metaMessages: [\n `URL: ${getUrl(url)}`,\n body && `Request body: ${stringify(body)}`,\n ].filter(Boolean) as string[],\n name: 'WebSocketRequestError',\n })\n this.url = url\n }\n}\n\nexport type RpcRequestErrorType = RpcRequestError & {\n name: 'RpcRequestError'\n}\nexport class RpcRequestError extends BaseError {\n code: number\n data?: unknown\n url: string\n constructor({\n body,\n error,\n url,\n }: {\n body: { [x: string]: unknown } | { [y: string]: unknown }[]\n error: { code: number; data?: unknown; 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 name: 'RpcRequestError',\n })\n this.code = error.code\n this.data = error.data\n this.url = url\n }\n}\n\nexport type SocketClosedErrorType = SocketClosedError & {\n name: 'SocketClosedError'\n}\nexport class SocketClosedError extends BaseError {\n url: string | undefined\n constructor({\n url,\n }: {\n url?: string | undefined\n } = {}) {\n super('The socket has been closed.', {\n metaMessages: [url && `URL: ${getUrl(url)}`].filter(Boolean) as string[],\n name: 'SocketClosedError',\n })\n this.url = url\n }\n}\n\nexport type TimeoutErrorType = TimeoutError & {\n name: 'TimeoutError'\n}\nexport class TimeoutError extends BaseError {\n url: string\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 name: 'TimeoutError',\n })\n this.url = url\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<code extends number = RpcErrorCode> = {\n code?: code | (number & {}) | undefined\n docsPath?: string | undefined\n metaMessages?: string[] | undefined\n name?: string | undefined\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<code_ extends number = RpcErrorCode> extends BaseError {\n code: code_ | (number & {})\n\n constructor(\n cause: Error,\n {\n code,\n docsPath,\n metaMessages,\n name,\n shortMessage,\n }: RpcErrorOptions<code_>,\n ) {\n super(shortMessage, {\n cause,\n docsPath,\n metaMessages:\n metaMessages || (cause as { metaMessages?: string[] })?.metaMessages,\n name: name || 'RpcError',\n })\n this.name = name || cause.name\n this.code = (\n cause instanceof RpcRequestError ? cause.code : (code ?? unknownErrorCode)\n ) as code_\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 | 5700 // Unsupported non-optional capability\n | 5710 // Unsupported chain id\n | 5720 // Duplicate ID\n | 5730 // Unknown bundle id\n | 5740 // Bundle too large\n | 5750 // Atomic-ready wallet rejected upgrade\n | 5760 // Atomicity not supported\n | 7000 // WalletConnect Session Settlement Failed\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 data?: T | undefined\n\n constructor(\n cause: Error,\n options: Prettify<\n RpcErrorOptions<ProviderRpcErrorCode> & {\n data?: T | undefined\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 static code = -32700 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: ParseRpcError.code,\n name: 'ParseRpcError',\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 static code = -32600 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: InvalidRequestRpcError.code,\n name: 'InvalidRequestRpcError',\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 static code = -32601 as const\n\n constructor(cause: Error, { method }: { method?: string } = {}) {\n super(cause, {\n code: MethodNotFoundRpcError.code,\n name: 'MethodNotFoundRpcError',\n shortMessage: `The method${method ? ` \"${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 static code = -32602 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: InvalidParamsRpcError.code,\n name: 'InvalidParamsRpcError',\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 static code = -32603 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: InternalRpcError.code,\n name: 'InternalRpcError',\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 static code = -32000 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: InvalidInputRpcError.code,\n name: 'InvalidInputRpcError',\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 name: 'ResourceNotFoundRpcError',\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 static code = -32002 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: ResourceUnavailableRpcError.code,\n name: 'ResourceUnavailableRpcError',\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 static code = -32003 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: TransactionRejectedRpcError.code,\n name: 'TransactionRejectedRpcError',\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 static code = -32004 as const\n\n constructor(cause: Error, { method }: { method?: string } = {}) {\n super(cause, {\n code: MethodNotSupportedRpcError.code,\n name: 'MethodNotSupportedRpcError',\n shortMessage: `Method${method ? ` \"${method}\"` : ''} is not supported.`,\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 static code = -32005 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: LimitExceededRpcError.code,\n name: 'LimitExceededRpcError',\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 static code = -32006 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: JsonRpcVersionUnsupportedError.code,\n name: 'JsonRpcVersionUnsupportedError',\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 static code = 4001 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: UserRejectedRequestError.code,\n name: 'UserRejectedRequestError',\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 static code = 4100 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: UnauthorizedProviderError.code,\n name: 'UnauthorizedProviderError',\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 static code = 4200 as const\n\n constructor(cause: Error, { method }: { method?: string } = {}) {\n super(cause, {\n code: UnsupportedProviderMethodError.code,\n name: 'UnsupportedProviderMethodError',\n shortMessage: `The Provider does not support the requested method${method ? ` \" ${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 static code = 4900 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: ProviderDisconnectedError.code,\n name: 'ProviderDisconnectedError',\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 static code = 4901 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: ChainDisconnectedError.code,\n name: 'ChainDisconnectedError',\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 static code = 4902 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: SwitchChainError.code,\n name: 'SwitchChainError',\n shortMessage: 'An error occurred when attempting to switch chain.',\n })\n }\n}\n\n/**\n * Subclass for an \"Unsupported non-optional capability\" EIP-5792 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-5792#error-codes\n */\nexport type UnsupportedNonOptionalCapabilityErrorType =\n UnsupportedNonOptionalCapabilityError & {\n code: 5700\n name: 'UnsupportedNonOptionalCapabilityError'\n }\nexport class UnsupportedNonOptionalCapabilityError extends ProviderRpcError {\n static code = 5700 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: UnsupportedNonOptionalCapabilityError.code,\n name: 'UnsupportedNonOptionalCapabilityError',\n shortMessage:\n 'This Wallet does not support a capability that was not marked as optional.',\n })\n }\n}\n\n/**\n * Subclass for an \"Unsupported chain id\" EIP-5792 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-5792#error-codes\n */\nexport type UnsupportedChainIdErrorType = UnsupportedChainIdError & {\n code: 5710\n name: 'UnsupportedChainIdError'\n}\nexport class UnsupportedChainIdError extends ProviderRpcError {\n static code = 5710 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: UnsupportedChainIdError.code,\n name: 'UnsupportedChainIdError',\n shortMessage: 'This Wallet does not support the requested chain ID.',\n })\n }\n}\n\n/**\n * Subclass for an \"Duplicate ID\" EIP-5792 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-5792#error-codes\n */\nexport type DuplicateIdErrorType = DuplicateIdError & {\n code: 5720\n name: 'DuplicateIdError'\n}\nexport class DuplicateIdError extends ProviderRpcError {\n static code = 5720 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: DuplicateIdError.code,\n name: 'DuplicateIdError',\n shortMessage: 'There is already a bundle submitted with this ID.',\n })\n }\n}\n\n/**\n * Subclass for an \"Unknown bundle ID\" EIP-5792 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-5792#error-codes\n */\nexport type UnknownBundleIdErrorType = UnknownBundleIdError & {\n code: 5730\n name: 'UnknownBundleIdError'\n}\nexport class UnknownBundleIdError extends ProviderRpcError {\n static code = 5730 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: UnknownBundleIdError.code,\n name: 'UnknownBundleIdError',\n shortMessage: 'This bundle id is unknown / has not been submitted',\n })\n }\n}\n\n/**\n * Subclass for an \"Bundle too large\" EIP-5792 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-5792#error-codes\n */\nexport type BundleTooLargeErrorType = BundleTooLargeError & {\n code: 5740\n name: 'BundleTooLargeError'\n}\nexport class BundleTooLargeError extends ProviderRpcError {\n static code = 5740 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: BundleTooLargeError.code,\n name: 'BundleTooLargeError',\n shortMessage: 'The call bundle is too large for the Wallet to process.',\n })\n }\n}\n\n/**\n * Subclass for an \"Atomic-ready wallet rejected upgrade\" EIP-5792 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-5792#error-codes\n */\nexport type AtomicReadyWalletRejectedUpgradeErrorType =\n AtomicReadyWalletRejectedUpgradeError & {\n code: 5750\n name: 'AtomicReadyWalletRejectedUpgradeError'\n }\nexport class AtomicReadyWalletRejectedUpgradeError extends ProviderRpcError {\n static code = 5750 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: AtomicReadyWalletRejectedUpgradeError.code,\n name: 'AtomicReadyWalletRejectedUpgradeError',\n shortMessage:\n 'The Wallet can support atomicity after an upgrade, but the user rejected the upgrade.',\n })\n }\n}\n\n/**\n * Subclass for an \"Atomicity not supported\" EIP-5792 error.\n *\n * EIP https://eips.ethereum.org/EIPS/eip-5792#error-codes\n */\nexport type AtomicityNotSupportedErrorType = AtomicityNotSupportedError & {\n code: 5760\n name: 'AtomicityNotSupportedError'\n}\nexport class AtomicityNotSupportedError extends ProviderRpcError {\n static code = 5760 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: AtomicityNotSupportedError.code,\n name: 'AtomicityNotSupportedError',\n shortMessage:\n 'The wallet does not support atomic execution but the request requires it.',\n })\n }\n}\n\n/**\n * Subclass for a \"Session Settlement Failed\" WalletConnect error.\n *\n * WalletConnect https://docs.walletconnect.com/2.0/specs/clients/sign/error-codes\n */\nexport type WalletConnectSessionSettlementErrorType =\n WalletConnectSessionSettlementError & {\n code: 7000\n name: 'WalletConnectSessionSettlementError'\n }\nexport class WalletConnectSessionSettlementError extends ProviderRpcError {\n static code = 7000 as const\n\n constructor(cause: Error) {\n super(cause, {\n code: WalletConnectSessionSettlementError.code,\n name: 'WalletConnectSessionSettlementError',\n shortMessage: 'WalletConnect session settlement failed.',\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 constructor(cause: Error) {\n super(cause, {\n name: 'UnknownRpcError',\n shortMessage: 'An unknown RPC error occurred.',\n })\n }\n}\n","/**\n * Internal Merkle-Damgard hash utils.\n * @module\n */\nimport { type Input, Hash, abytes, aexists, aoutput, clean, createView, toBytes } from './utils.ts';\n\n/** Polyfill for Safari 14. https://caniuse.com/mdn-javascript_builtins_dataview_setbiguint64 */\nexport function setBigUint64(\n view: DataView,\n byteOffset: number,\n value: bigint,\n isLE: boolean\n): 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/** Choice: a ? b : c */\nexport function Chi(a: number, b: number, c: number): number {\n return (a & b) ^ (~a & c);\n}\n\n/** Majority function, true if any two inputs is true. */\nexport function Maj(a: number, b: number, c: number): number {\n return (a & b) ^ (a & c) ^ (b & c);\n}\n\n/**\n * Merkle-Damgard hash construction base class.\n * Could be used to create MD5, RIPEMD, SHA1, SHA2.\n */\nexport abstract class HashMD<T extends HashMD<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\n readonly blockLen: number;\n readonly outputLen: number;\n readonly padOffset: number;\n readonly isLE: boolean;\n\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(blockLen: number, outputLen: number, padOffset: number, isLE: boolean) {\n super();\n this.blockLen = blockLen;\n this.outputLen = outputLen;\n this.padOffset = padOffset;\n this.isLE = isLE;\n this.buffer = new Uint8Array(blockLen);\n this.view = createView(this.buffer);\n }\n update(data: Input): this {\n aexists(this);\n data = toBytes(data);\n abytes(data);\n const { view, buffer, blockLen } = this;\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): void {\n aexists(this);\n aoutput(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 clean(this.buffer.subarray(pos));\n // we have less than padOffset left in buffer, so we cannot put length in\n // 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(): Uint8Array {\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.destroyed = destroyed;\n to.finished = finished;\n to.length = length;\n to.pos = pos;\n if (length % blockLen) to.buffer.set(buffer);\n return to;\n }\n clone(): T {\n return this._cloneInto();\n }\n}\n\n/**\n * Initial SHA-2 state: fractional parts of square roots of first 16 primes 2..53.\n * Check out `test/misc/sha2-gen-iv.js` for recomputation guide.\n */\n\n/** Initial SHA256 state. Bits 0..32 of frac part of sqrt of primes 2..19 */\nexport const SHA256_IV: Uint32Array = /* @__PURE__ */ Uint32Array.from([\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,\n]);\n\n/** Initial SHA224 state. Bits 32..64 of frac part of sqrt of primes 23..53 */\nexport const SHA224_IV: Uint32Array = /* @__PURE__ */ Uint32Array.from([\n 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4,\n]);\n\n/** Initial SHA384 state. Bits 0..64 of frac part of sqrt of primes 23..53 */\nexport const SHA384_IV: Uint32Array = /* @__PURE__ */ Uint32Array.from([\n 0xcbbb9d5d, 0xc1059ed8, 0x629a292a, 0x367cd507, 0x9159015a, 0x3070dd17, 0x152fecd8, 0xf70e5939,\n 0x67332667, 0xffc00b31, 0x8eb44a87, 0x68581511, 0xdb0c2e0d, 0x64f98fa7, 0x47b5481d, 0xbefa4fa4,\n]);\n\n/** Initial SHA512 state. Bits 0..64 of frac part of sqrt of primes 2..19 */\nexport const SHA512_IV: Uint32Array = /* @__PURE__ */ Uint32Array.from([\n 0x6a09e667, 0xf3bcc908, 0xbb67ae85, 0x84caa73b, 0x3c6ef372, 0xfe94f82b, 0xa54ff53a, 0x5f1d36f1,\n 0x510e527f, 0xade682d1, 0x9b05688c, 0x2b3e6c1f, 0x1f83d9ab, 0xfb41bd6b, 0x5be0cd19, 0x137e2179,\n]);\n","/**\n * SHA2 hash function. A.k.a. sha256, sha384, sha512, sha512_224, sha512_256.\n * SHA256 is the fastest hash implementable in JS, even faster than Blake3.\n * Check out [RFC 4634](https://datatracker.ietf.org/doc/html/rfc4634) and\n * [FIPS 180-4](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf).\n * @module\n */\nimport { Chi, HashMD, Maj, SHA224_IV, SHA256_IV, SHA384_IV, SHA512_IV } from './_md.ts';\nimport * as u64 from './_u64.ts';\nimport { type CHash, clean, createHasher, rotr } from './utils.ts';\n\n/**\n * Round constants:\n * First 32 bits of fractional parts of the cube roots of the first 64 primes 2..311)\n */\n// prettier-ignore\nconst SHA256_K = /* @__PURE__ */ Uint32Array.from([\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/** Reusable temporary buffer. \"W\" comes straight from spec. */\nconst SHA256_W = /* @__PURE__ */ new Uint32Array(64);\nexport class SHA256 extends HashMD<SHA256> {\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n protected A: number = SHA256_IV[0] | 0;\n protected B: number = SHA256_IV[1] | 0;\n protected C: number = SHA256_IV[2] | 0;\n protected D: number = SHA256_IV[3] | 0;\n protected E: number = SHA256_IV[4] | 0;\n protected F: number = SHA256_IV[5] | 0;\n protected G: number = SHA256_IV[6] | 0;\n protected H: number = SHA256_IV[7] | 0;\n\n constructor(outputLen: number = 32) {\n super(64, outputLen, 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 ): void {\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(): void {\n clean(SHA256_W);\n }\n destroy(): void {\n this.set(0, 0, 0, 0, 0, 0, 0, 0);\n clean(this.buffer);\n }\n}\n\nexport class SHA224 extends SHA256 {\n protected A: number = SHA224_IV[0] | 0;\n protected B: number = SHA224_IV[1] | 0;\n protected C: number = SHA224_IV[2] | 0;\n protected D: number = SHA224_IV[3] | 0;\n protected E: number = SHA224_IV[4] | 0;\n protected F: number = SHA224_IV[5] | 0;\n protected G: number = SHA224_IV[6] | 0;\n protected H: number = SHA224_IV[7] | 0;\n constructor() {\n super(28);\n }\n}\n\n// SHA2-512 is slower than sha256 in js because u64 operations are slow.\n\n// Round contants\n// First 32 bits of the fractional parts of the cube roots of the first 80 primes 2..409\n// prettier-ignore\nconst K512 = /* @__PURE__ */ (() => u64.split([\n '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc',\n '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118',\n '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2',\n '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694',\n '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65',\n '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5',\n '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4',\n '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70',\n '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df',\n '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b',\n '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30',\n '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8',\n '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8',\n '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3',\n '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec',\n '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b',\n '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178',\n '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b',\n '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c',\n '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817'\n].map(n => BigInt(n))))();\nconst SHA512_Kh = /* @__PURE__ */ (() => K512[0])();\nconst SHA512_Kl = /* @__PURE__ */ (() => K512[1])();\n\n// Reusable temporary buffers\nconst SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);\nconst SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);\n\nexport class SHA512 extends HashMD<SHA512> {\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n // h -- high 32 bits, l -- low 32 bits\n protected Ah: number = SHA512_IV[0] | 0;\n protected Al: number = SHA512_IV[1] | 0;\n protected Bh: number = SHA512_IV[2] | 0;\n protected Bl: number = SHA512_IV[3] | 0;\n protected Ch: number = SHA512_IV[4] | 0;\n protected Cl: number = SHA512_IV[5] | 0;\n protected Dh: number = SHA512_IV[6] | 0;\n protected Dl: number = SHA512_IV[7] | 0;\n protected Eh: number = SHA512_IV[8] | 0;\n protected El: number = SHA512_IV[9] | 0;\n protected Fh: number = SHA512_IV[10] | 0;\n protected Fl: number = SHA512_IV[11] | 0;\n protected Gh: number = SHA512_IV[12] | 0;\n protected Gl: number = SHA512_IV[13] | 0;\n protected Hh: number = SHA512_IV[14] | 0;\n protected Hl: number = SHA512_IV[15] | 0;\n\n constructor(outputLen: number = 64) {\n super(128, outputLen, 16, false);\n }\n // prettier-ignore\n protected get(): [\n number, number, number, number, number, number, number, number,\n number, number, number, number, number, number, number, number\n ] {\n const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];\n }\n // prettier-ignore\n protected set(\n Ah: number, Al: number, Bh: number, Bl: number, Ch: number, Cl: number, Dh: number, Dl: number,\n Eh: number, El: number, Fh: number, Fl: number, Gh: number, Gl: number, Hh: number, Hl: number\n ): void {\n this.Ah = Ah | 0;\n this.Al = Al | 0;\n this.Bh = Bh | 0;\n this.Bl = Bl | 0;\n this.Ch = Ch | 0;\n this.Cl = Cl | 0;\n this.Dh = Dh | 0;\n this.Dl = Dl | 0;\n this.Eh = Eh | 0;\n this.El = El | 0;\n this.Fh = Fh | 0;\n this.Fl = Fl | 0;\n this.Gh = Gh | 0;\n this.Gl = Gl | 0;\n this.Hh = Hh | 0;\n this.Hl = Hl | 0;\n }\n protected process(view: DataView, offset: number): void {\n // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4) {\n SHA512_W_H[i] = view.getUint32(offset);\n SHA512_W_L[i] = view.getUint32((offset += 4));\n }\n for (let i = 16; i < 80; i++) {\n // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7)\n const W15h = SHA512_W_H[i - 15] | 0;\n const W15l = SHA512_W_L[i - 15] | 0;\n const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7);\n const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7);\n // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6)\n const W2h = SHA512_W_H[i - 2] | 0;\n const W2l = SHA512_W_L[i - 2] | 0;\n const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6);\n const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6);\n // SHA256_W[i] = s0 + s1 + SHA256_W[i - 7] + SHA256_W[i - 16];\n const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);\n const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);\n SHA512_W_H[i] = SUMh | 0;\n SHA512_W_L[i] = SUMl | 0;\n }\n let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n // Compression function main loop, 80 rounds\n for (let i = 0; i < 80; i++) {\n // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41)\n const sigma1h = u64.rotrSH(Eh, El, 14) ^ u64.rotrSH(Eh, El, 18) ^ u64.rotrBH(Eh, El, 41);\n const sigma1l = u64.rotrSL(Eh, El, 14) ^ u64.rotrSL(Eh, El, 18) ^ u64.rotrBL(Eh, El, 41);\n //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const CHIh = (Eh & Fh) ^ (~Eh & Gh);\n const CHIl = (El & Fl) ^ (~El & Gl);\n // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i]\n // prettier-ignore\n const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);\n const T1h = u64.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);\n const T1l = T1ll | 0;\n // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39)\n const sigma0h = u64.rotrSH(Ah, Al, 28) ^ u64.rotrBH(Ah, Al, 34) ^ u64.rotrBH(Ah, Al, 39);\n const sigma0l = u64.rotrSL(Ah, Al, 28) ^ u64.rotrBL(Ah, Al, 34) ^ u64.rotrBL(Ah, Al, 39);\n const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch);\n const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl);\n Hh = Gh | 0;\n Hl = Gl | 0;\n Gh = Fh | 0;\n Gl = Fl | 0;\n Fh = Eh | 0;\n Fl = El | 0;\n ({ h: Eh, l: El } = u64.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));\n Dh = Ch | 0;\n Dl = Cl | 0;\n Ch = Bh | 0;\n Cl = Bl | 0;\n Bh = Ah | 0;\n Bl = Al | 0;\n const All = u64.add3L(T1l, sigma0l, MAJl);\n Ah = u64.add3H(All, T1h, sigma0h, MAJh);\n Al = All | 0;\n }\n // Add the compressed chunk to the current hash value\n ({ h: Ah, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));\n ({ h: Bh, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));\n ({ h: Ch, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));\n ({ h: Dh, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));\n ({ h: Eh, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));\n ({ h: Fh, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));\n ({ h: Gh, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));\n ({ h: Hh, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));\n this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);\n }\n protected roundClean(): void {\n clean(SHA512_W_H, SHA512_W_L);\n }\n destroy(): void {\n clean(this.buffer);\n this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);\n }\n}\n\nexport class SHA384 extends SHA512 {\n protected Ah: number = SHA384_IV[0] | 0;\n protected Al: number = SHA384_IV[1] | 0;\n protected Bh: number = SHA384_IV[2] | 0;\n protected Bl: number = SHA384_IV[3] | 0;\n protected Ch: number = SHA384_IV[4] | 0;\n protected Cl: number = SHA384_IV[5] | 0;\n protected Dh: number = SHA384_IV[6] | 0;\n protected Dl: number = SHA384_IV[7] | 0;\n protected Eh: number = SHA384_IV[8] | 0;\n protected El: number = SHA384_IV[9] | 0;\n protected Fh: number = SHA384_IV[10] | 0;\n protected Fl: number = SHA384_IV[11] | 0;\n protected Gh: number = SHA384_IV[12] | 0;\n protected Gl: number = SHA384_IV[13] | 0;\n protected Hh: number = SHA384_IV[14] | 0;\n protected Hl: number = SHA384_IV[15] | 0;\n\n constructor() {\n super(48);\n }\n}\n\n/**\n * Truncated SHA512/256 and SHA512/224.\n * SHA512_IV is XORed with 0xa5a5a5a5a5a5a5a5, then used as \"intermediary\" IV of SHA512/t.\n * Then t hashes string to produce result IV.\n * See `test/misc/sha2-gen-iv.js`.\n */\n\n/** SHA512/224 IV */\nconst T224_IV = /* @__PURE__ */ Uint32Array.from([\n 0x8c3d37c8, 0x19544da2, 0x73e19966, 0x89dcd4d6, 0x1dfab7ae, 0x32ff9c82, 0x679dd514, 0x582f9fcf,\n 0x0f6d2b69, 0x7bd44da8, 0x77e36f73, 0x04c48942, 0x3f9d85a8, 0x6a1d36c8, 0x1112e6ad, 0x91d692a1,\n]);\n\n/** SHA512/256 IV */\nconst T256_IV = /* @__PURE__ */ Uint32Array.from([\n 0x22312194, 0xfc2bf72c, 0x9f555fa3, 0xc84c64c2, 0x2393b86b, 0x6f53b151, 0x96387719, 0x5940eabd,\n 0x96283ee2, 0xa88effe3, 0xbe5e1e25, 0x53863992, 0x2b0199fc, 0x2c85b8aa, 0x0eb72ddc, 0x81c52ca2,\n]);\n\nexport class SHA512_224 extends SHA512 {\n protected Ah: number = T224_IV[0] | 0;\n protected Al: number = T224_IV[1] | 0;\n protected Bh: number = T224_IV[2] | 0;\n protected Bl: number = T224_IV[3] | 0;\n protected Ch: number = T224_IV[4] | 0;\n protected Cl: number = T224_IV[5] | 0;\n protected Dh: number = T224_IV[6] | 0;\n protected Dl: number = T224_IV[7] | 0;\n protected Eh: number = T224_IV[8] | 0;\n protected El: number = T224_IV[9] | 0;\n protected Fh: number = T224_IV[10] | 0;\n protected Fl: number = T224_IV[11] | 0;\n protected Gh: number = T224_IV[12] | 0;\n protected Gl: number = T224_IV[13] | 0;\n protected Hh: number = T224_IV[14] | 0;\n protected Hl: number = T224_IV[15] | 0;\n\n constructor() {\n super(28);\n }\n}\n\nexport class SHA512_256 extends SHA512 {\n protected Ah: number = T256_IV[0] | 0;\n protected Al: number = T256_IV[1] | 0;\n protected Bh: number = T256_IV[2] | 0;\n protected Bl: number = T256_IV[3] | 0;\n protected Ch: number = T256_IV[4] | 0;\n protected Cl: number = T256_IV[5] | 0;\n protected Dh: number = T256_IV[6] | 0;\n protected Dl: number = T256_IV[7] | 0;\n protected Eh: number = T256_IV[8] | 0;\n protected El: number = T256_IV[9] | 0;\n protected Fh: number = T256_IV[10] | 0;\n protected Fl: number = T256_IV[11] | 0;\n protected Gh: number = T256_IV[12] | 0;\n protected Gl: number = T256_IV[13] | 0;\n protected Hh: number = T256_IV[14] | 0;\n protected Hl: number = T256_IV[15] | 0;\n\n constructor() {\n super(32);\n }\n}\n\n/**\n * SHA2-256 hash function from RFC 4634.\n *\n * It is the fastest JS hash, even faster than Blake3.\n * To break sha256 using birthday attack, attackers need to try 2^128 hashes.\n * BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.\n */\nexport const sha256: CHash = /* @__PURE__ */ createHasher(() => new SHA256());\n/** SHA2-224 hash function from RFC 4634 */\nexport const sha224: CHash = /* @__PURE__ */ createHasher(() => new SHA224());\n\n/** SHA2-512 hash function from RFC 4634. */\nexport const sha512: CHash = /* @__PURE__ */ createHasher(() => new SHA512());\n/** SHA2-384 hash function from RFC 4634. */\nexport const sha384: CHash = /* @__PURE__ */ createHasher(() => new SHA384());\n\n/**\n * SHA2-512/256 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on [truncated SHA512](https://eprint.iacr.org/2010/548.pdf).\n */\nexport const sha512_256: CHash = /* @__PURE__ */ createHasher(() => new SHA512_256());\n/**\n * SHA2-512/224 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on [truncated SHA512](https://eprint.iacr.org/2010/548.pdf).\n */\nexport const sha512_224: CHash = /* @__PURE__ */ createHasher(() => new SHA512_224());\n","/**\n * HMAC: RFC2104 message authentication code.\n * @module\n */\nimport { abytes, aexists, ahash, clean, Hash, toBytes, type CHash, type Input } from './utils.ts';\n\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 ahash(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 clean(pad);\n }\n update(buf: Input): this {\n aexists(this);\n this.iHash.update(buf);\n return this;\n }\n digestInto(out: Uint8Array): void {\n aexists(this);\n abytes(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(): Uint8Array {\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 clone(): HMAC<T> {\n return this._cloneInto();\n }\n destroy(): void {\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 * @example\n * import { hmac } from '@noble/hashes/hmac';\n * import { sha256 } from '@noble/hashes/sha2';\n * const mac1 = hmac(sha256, 'key', 'message');\n */\nexport const hmac: {\n (hash: CHash, key: Input, message: Input): Uint8Array;\n create(hash: CHash, key: Input): HMAC<any>;\n} = (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","/**\n * Hex, bytes and number utilities.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n\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 = /* @__PURE__ */ BigInt(0);\nconst _1n = /* @__PURE__ */ BigInt(1);\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\nexport function isBytes(a: unknown): a is Uint8Array {\n return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');\n}\n\nexport function abytes(item: unknown): void {\n if (!isBytes(item)) throw new Error('Uint8Array expected');\n}\n\nexport function abool(title: string, value: boolean): void {\n if (typeof value !== 'boolean') throw new Error(title + ' boolean expected, got ' + value);\n}\n\n// Used in weierstrass, der\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 return hex === '' ? _0n : BigInt('0x' + hex); // Big Endian\n}\n\n// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex\nconst hasHexBuiltin: boolean =\n // @ts-ignore\n typeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function';\n\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) =>\n i.toString(16).padStart(2, '0')\n);\n\n/**\n * Convert byte array to hex string. Uses built-in function, when available.\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes: Uint8Array): string {\n abytes(bytes);\n // @ts-ignore\n if (hasHexBuiltin) return bytes.toHex();\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// We use optimized technique to convert hex string to byte array\nconst asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 } as const;\nfunction asciiToBase16(ch: number): number | undefined {\n if (ch >= asciis._0 && ch <= asciis._9) return ch - asciis._0; // '2' => 50-48\n if (ch >= asciis.A && ch <= asciis.F) return ch - (asciis.A - 10); // 'B' => 66-(65-10)\n if (ch >= asciis.a && ch <= asciis.f) return ch - (asciis.a - 10); // 'b' => 98-(97-10)\n return;\n}\n\n/**\n * Convert hex string to byte array. Uses built-in function, when available.\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 // @ts-ignore\n if (hasHexBuiltin) return Uint8Array.fromHex(hex);\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2) throw new Error('hex string expected, got unpadded hex of length ' + hl);\n const array = new Uint8Array(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n const n1 = asciiToBase16(hex.charCodeAt(hi));\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1));\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new Error('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n }\n array[ai] = n1 * 16 + n2; // multiply first octet, e.g. 'a3' => 10*16+3 => 160 + 3 => 163\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 abytes(bytes);\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 hex string or Uint8Array, cause: ' + e);\n }\n } else if (isBytes(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 + ' of length ' + expectedLength + ' expected, got ' + len);\n return res;\n}\n\n/**\n * Copies several Uint8Arrays into one.\n */\nexport function concatBytes(...arrays: Uint8Array[]): Uint8Array {\n let sum = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n abytes(a);\n sum += a.length;\n }\n const res = new Uint8Array(sum);\n for (let i = 0, pad = 0; i < arrays.length; i++) {\n const a = arrays[i];\n res.set(a, pad);\n pad += a.length;\n }\n return res;\n}\n\n// Compares 2 u8a-s in kinda constant time\nexport function equalBytes(a: Uint8Array, b: Uint8Array): boolean {\n if (a.length !== b.length) return false;\n let diff = 0;\n for (let i = 0; i < a.length; i++) diff |= a[i] ^ b[i];\n return diff === 0;\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('string expected');\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n\n// Is positive bigint\nconst isPosBig = (n: bigint) => typeof n === 'bigint' && _0n <= n;\n\nexport function inRange(n: bigint, min: bigint, max: bigint): boolean {\n return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;\n}\n\n/**\n * Asserts min <= n < max. NOTE: It's < max and not <= max.\n * @example\n * aInRange('x', x, 1n, 256n); // would assume x is in (1n..255n)\n */\nexport function aInRange(title: string, n: bigint, min: bigint, max: bigint): void {\n // Why min <= n < max and not a (min < n < max) OR b (min <= n <= max)?\n // consider P=256n, min=0n, max=P\n // - a for min=0 would require -1: `inRange('x', x, -1n, P)`\n // - b would commonly require subtraction: `inRange('x', x, 0n, P - 1n)`\n // - our way is the cleanest: `inRange('x', x, 0n, P)\n if (!inRange(n, min, max))\n throw new Error('expected valid ' + title + ': ' + min + ' <= n < ' + max + ', got ' + n);\n}\n\n// Bit operations\n\n/**\n * Calculates amount of bits in a bigint.\n * Same as `n.toString(2).length`\n * TODO: merge with nLength in modular\n */\nexport function bitLen(n: bigint): number {\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): bigint {\n return (n >> BigInt(pos)) & _1n;\n}\n\n/**\n * Sets single bit at position.\n */\nexport function bitSet(n: bigint, pos: number, value: boolean): bigint {\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): bigint => (_1n << BigInt(n)) - _1n;\n\n// DRBG\n\nconst u8n = (len: number) => new Uint8Array(len); // creates Uint8Array\nconst u8fr = (arr: ArrayLike<number>) => 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(0)) => {\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): boolean => typeof val === 'bigint',\n function: (val: any): boolean => typeof val === 'function',\n boolean: (val: any): boolean => typeof val === 'boolean',\n string: (val: any): boolean => typeof val === 'string',\n stringOrUint8Array: (val: any): boolean => typeof val === 'string' || isBytes(val),\n isSafeInteger: (val: any): boolean => Number.isSafeInteger(val),\n array: (val: any): boolean => Array.isArray(val),\n field: (val: any, object: any): any => (object as any).Fp.isValid(val),\n hash: (val: any): boolean => 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): T {\n const checkField = (fieldName: keyof T, type: Validator, isOptional: boolean) => {\n const checkVal = validatorFns[type];\n if (typeof checkVal !== 'function') throw new Error('invalid validator 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 'param ' + String(fieldName) + ' is invalid. Expected ' + type + ', got ' + val\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\n/**\n * throws not implemented error\n */\nexport const notImplemented = (): never => {\n throw new Error('not implemented');\n};\n\n/**\n * Memoizes (caches) computation result.\n * Uses WeakMap: the value is going auto-cleaned by GC after last reference is removed.\n */\nexport function memoized<T extends object, R, O extends any[]>(\n fn: (arg: T, ...args: O) => R\n): (arg: T, ...args: O) => R {\n const map = new WeakMap<T, R>();\n return (arg: T, ...args: O): R => {\n const val = map.get(arg);\n if (val !== undefined) return val;\n const computed = fn(arg, ...args);\n map.set(arg, computed);\n return computed;\n };\n}\n","/**\n * Utils for modular division and finite fields.\n * A finite field over 11 is integer number operations `mod 11`.\n * There is no division: it is replaced by modular multiplicative inverse.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { anumber } from '@noble/hashes/utils';\nimport {\n bitMask,\n bytesToNumberBE,\n bytesToNumberLE,\n ensureBytes,\n numberToBytesBE,\n numberToBytesLE,\n validateObject,\n} from './utils.ts';\n\n// prettier-ignore\nconst _0n = BigInt(0), _1n = BigInt(1), _2n = /* @__PURE__ */ BigInt(2), _3n = /* @__PURE__ */ BigInt(3);\n// prettier-ignore\nconst _4n = /* @__PURE__ */ BigInt(4), _5n = /* @__PURE__ */ BigInt(5), _8n = /* @__PURE__ */ BigInt(8);\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 * TODO: remove.\n * @example\n * pow(2n, 6n, 11n) // 64n % 11n == 9n\n */\nexport function pow(num: bigint, power: bigint, modulo: bigint): bigint {\n return FpPow(Field(modulo), num, power);\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/**\n * Inverses number over modulo.\n * Implemented using [Euclidean GCD](https://brilliant.org/wiki/extended-euclidean-algorithm/).\n */\nexport function invert(number: bigint, modulo: bigint): bigint {\n if (number === _0n) throw new Error('invert: expected non-zero number');\n if (modulo <= _0n) throw new Error('invert: expected positive modulus, got ' + modulo);\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// Not all roots are possible! Example which will throw:\n// const NUM =\n// n = 72057594037927816n;\n// Fp = Field(BigInt('0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab'));\nfunction sqrt3mod4<T>(Fp: IField<T>, n: T) {\n const p1div4 = (Fp.ORDER + _1n) / _4n;\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\nfunction sqrt5mod8<T>(Fp: IField<T>, n: T) {\n const p5div8 = (Fp.ORDER - _5n) / _8n;\n const n2 = Fp.mul(n, _2n);\n const v = Fp.pow(n2, p5div8);\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// TODO: Commented-out for now. Provide test vectors.\n// Tonelli is too slow for extension fields Fp2.\n// That means we can't use sqrt (c1, c2...) even for initialization constants.\n// if (P % _16n === _9n) return sqrt9mod16;\n// // prettier-ignore\n// function sqrt9mod16<T>(Fp: IField<T>, n: T, p7div16?: bigint) {\n// if (p7div16 === undefined) p7div16 = (Fp.ORDER + BigInt(7)) / _16n;\n// const c1 = Fp.sqrt(Fp.neg(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.neg(c1)); // 3. c3 = sqrt(-c1) in F, i.e., (c3^2) == -c1 in F\n// const c4 = p7div16; // 4. c4 = (q + 7) / 16 # Integer arithmetic\n// let tv1 = Fp.pow(n, 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.eql(Fp.sqr(tv2), n); // 5. e1 = (tv2^2) == x\n// const e2 = Fp.eql(Fp.sqr(tv3), n); // 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.eql(Fp.sqr(tv2), n); // 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 * 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 * @param P field order\n * @returns function that takes field Fp (created from P) and number n\n */\nexport function tonelliShanks(P: bigint): <T>(Fp: IField<T>, n: T) => T {\n // Initialization (precomputation).\n if (P < BigInt(3)) throw new Error('sqrt is not defined for small field');\n // Factor P - 1 = Q * 2^S, where Q is odd\n let Q = P - _1n;\n let S = 0;\n while (Q % _2n === _0n) {\n Q /= _2n;\n S++;\n }\n\n // Find the first quadratic non-residue Z >= 2\n let Z = _2n;\n const _Fp = Field(P);\n while (FpLegendre(_Fp, Z) === 1) {\n // Basic primality test for P. After x iterations, chance of\n // not finding quadratic non-residue is 2^x, so 2^1000.\n if (Z++ > 1000) throw new Error('Cannot find square root: probably non-prime P');\n }\n // Fast-path; usually done before Z, but we do \"primality test\".\n if (S === 1) return sqrt3mod4;\n\n // Slow-path\n // TODO: test on Fp2 and others\n let cc = _Fp.pow(Z, Q); // c = z^Q\n const Q1div2 = (Q + _1n) / _2n;\n return function tonelliSlow<T>(Fp: IField<T>, n: T): T {\n if (Fp.is0(n)) return n;\n // Check if n is a quadratic residue using Legendre symbol\n if (FpLegendre(Fp, n) !== 1) throw new Error('Cannot find square root');\n\n // Initialize variables for the main loop\n let M = S;\n let c = Fp.mul(Fp.ONE, cc); // c = z^Q, move cc from field _Fp into field Fp\n let t = Fp.pow(n, Q); // t = n^Q, first guess at the fudge factor\n let R = Fp.pow(n, Q1div2); // R = n^((Q+1)/2), first guess at the square root\n\n // Main loop\n // while t != 1\n while (!Fp.eql(t, Fp.ONE)) {\n if (Fp.is0(t)) return Fp.ZERO; // if t=0 return R=0\n let i = 1;\n\n // Find the smallest i >= 1 such that t^(2^i) ≡ 1 (mod P)\n let t_tmp = Fp.sqr(t); // t^(2^1)\n while (!Fp.eql(t_tmp, Fp.ONE)) {\n i++;\n t_tmp = Fp.sqr(t_tmp); // t^(2^2)...\n if (i === M) throw new Error('Cannot find square root');\n }\n\n // Calculate the exponent for b: 2^(M - i - 1)\n const exponent = _1n << BigInt(M - i - 1); // bigint is important\n const b = Fp.pow(c, exponent); // b = 2^(M - i - 1)\n\n // Update variables\n M = i;\n c = Fp.sqr(b); // c = b^2\n t = Fp.mul(t, c); // t = (t * b^2)\n R = Fp.mul(R, b); // R = R*b\n }\n return R;\n };\n}\n\n/**\n * Square root for a finite field. Will try optimized versions first:\n *\n * 1. P ≡ 3 (mod 4)\n * 2. P ≡ 5 (mod 8)\n * 3. Tonelli-Shanks algorithm\n *\n * 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 */\nexport function FpSqrt(P: bigint): <T>(Fp: IField<T>, n: T) => T {\n // P ≡ 3 (mod 4) => √n = n^((P+1)/4)\n if (P % _4n === _3n) return sqrt3mod4;\n // P ≡ 5 (mod 8) => Atkin algorithm, page 10 of https://eprint.iacr.org/2012/685.pdf\n if (P % _8n === _5n) return sqrt5mod8;\n // P ≡ 9 (mod 16) not implemented, see above\n // 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): boolean =>\n (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 isLE: boolean;\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 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>): 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>(Fp: IField<T>, num: T, power: bigint): T {\n if (power < _0n) throw new Error('invalid exponent, negatives unsupported');\n if (power === _0n) return Fp.ONE;\n if (power === _1n) return num;\n let p = Fp.ONE;\n let d = num;\n while (power > _0n) {\n if (power & _1n) p = Fp.mul(p, d);\n d = Fp.sqr(d);\n power >>= _1n;\n }\n return p;\n}\n\n/**\n * Efficiently invert an array of Field elements.\n * Exception-free. Will return `undefined` for 0 elements.\n * @param passZero map 0 to 0 (instead of undefined)\n */\nexport function FpInvertBatch<T>(Fp: IField<T>, nums: T[], passZero = false): T[] {\n const inverted = new Array(nums.length).fill(passZero ? Fp.ZERO : undefined);\n // Walk from first to last, multiply them by each other MOD p\n const multipliedAcc = nums.reduce((acc, num, i) => {\n if (Fp.is0(num)) return acc;\n inverted[i] = acc;\n return Fp.mul(acc, num);\n }, Fp.ONE);\n // Invert last element\n const invertedAcc = Fp.inv(multipliedAcc);\n // Walk from last to first, multiply them by inverted each other MOD p\n nums.reduceRight((acc, num, i) => {\n if (Fp.is0(num)) return acc;\n inverted[i] = Fp.mul(acc, inverted[i]);\n return Fp.mul(acc, num);\n }, invertedAcc);\n return inverted;\n}\n\n// TODO: remove\nexport function FpDiv<T>(Fp: IField<T>, lhs: T, rhs: T | bigint): T {\n return Fp.mul(lhs, typeof rhs === 'bigint' ? invert(rhs, Fp.ORDER) : Fp.inv(rhs));\n}\n\n/**\n * Legendre symbol.\n * Legendre constant is used to calculate Legendre symbol (a | p)\n * which denotes the value of a^((p-1)/2) (mod p).\n *\n * * (a | p) ≡ 1 if a is a square (mod p), quadratic residue\n * * (a | p) ≡ -1 if a is not a square (mod p), quadratic non residue\n * * (a | p) ≡ 0 if a ≡ 0 (mod p)\n */\nexport function FpLegendre<T>(Fp: IField<T>, n: T): -1 | 0 | 1 {\n // We can use 3rd argument as optional cache of this value\n // but seems unneeded for now. The operation is very fast.\n const p1mod2 = (Fp.ORDER - _1n) / _2n;\n const powered = Fp.pow(n, p1mod2);\n const yes = Fp.eql(powered, Fp.ONE);\n const zero = Fp.eql(powered, Fp.ZERO);\n const no = Fp.eql(powered, Fp.neg(Fp.ONE));\n if (!yes && !zero && !no) throw new Error('invalid Legendre symbol result');\n return yes ? 1 : zero ? 0 : -1;\n}\n\n// This function returns True whenever the value x is a square in the field F.\nexport function FpIsSquare<T>(Fp: IField<T>, n: T): boolean {\n const l = FpLegendre(Fp, n);\n return l === 1;\n}\n\n// CURVE.n lengths\nexport function nLength(\n n: bigint,\n nBitLength?: number\n): {\n nBitLength: number;\n nByteLength: number;\n} {\n // Bit size, byte size of CURVE.n\n if (nBitLength !== undefined) anumber(nBitLength);\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.\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 * Fragile: always run a benchmark on a change.\n * Security note: operations don't check 'isValid' for all elements for performance reasons,\n * it is caller responsibility to check this.\n * This is low-level code, please make sure you know what you're doing.\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('invalid field: expected ORDER > 0, got ' + ORDER);\n const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, bitLen);\n if (BYTES > 2048) throw new Error('invalid field: expected ORDER of <= 2048 bytes');\n let sqrtP: ReturnType<typeof FpSqrt>; // cached sqrtP\n const f: Readonly<FpField> = Object.freeze({\n ORDER,\n isLE,\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:\n redef.sqrt ||\n ((n) => {\n if (!sqrtP) sqrtP = FpSqrt(ORDER);\n return sqrtP(f, n);\n }),\n toBytes: (num) => (isLE ? numberToBytesLE(num, BYTES) : numberToBytesBE(num, BYTES)),\n fromBytes: (bytes) => {\n if (bytes.length !== BYTES)\n throw new Error('Field.fromBytes: expected ' + BYTES + ' bytes, got ' + bytes.length);\n return isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);\n },\n // TODO: we don't need it here, move out to separate fn\n invertBatch: (lst) => FpInvertBatch(f, lst),\n // We can't move this out because Fp6, Fp12 implement it\n // and it's unclear what to return in there.\n cmov: (a, b, c) => (c ? b : a),\n } as FpField);\n return Object.freeze(f);\n}\n\nexport function FpSqrtOdd<T>(Fp: IField<T>, elm: T): 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): 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(\n 'hashToPrivateScalar: expected ' + minLen + '-1024 bytes of input, got ' + hashLen\n );\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 ? bytesToNumberLE(key) : bytesToNumberBE(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","/**\n * Methods for elliptic curve multiplication by scalars.\n * Contains wNAF, pippenger\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { type IField, nLength, validateField } from './modular.ts';\nimport { bitLen, bitMask, validateObject } from './utils.ts';\n\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\nfunction constTimeNegate<T extends Group<T>>(condition: boolean, item: T): T {\n const neg = item.negate();\n return condition ? neg : item;\n}\n\nfunction validateW(W: number, bits: number) {\n if (!Number.isSafeInteger(W) || W <= 0 || W > bits)\n throw new Error('invalid window size, expected [1..' + bits + '], got W=' + W);\n}\n\n/** Internal wNAF opts for specific W and scalarBits */\nexport type WOpts = {\n windows: number;\n windowSize: number;\n mask: bigint;\n maxNumber: number;\n shiftBy: bigint;\n};\n\nfunction calcWOpts(W: number, scalarBits: number): WOpts {\n validateW(W, scalarBits);\n const windows = Math.ceil(scalarBits / W) + 1; // W=8 33. Not 32, because we skip zero\n const windowSize = 2 ** (W - 1); // W=8 128. Not 256, because we skip zero\n const maxNumber = 2 ** W; // W=8 256\n const mask = bitMask(W); // W=8 255 == mask 0b11111111\n const shiftBy = BigInt(W); // W=8 8\n return { windows, windowSize, mask, maxNumber, shiftBy };\n}\n\nfunction calcOffsets(n: bigint, window: number, wOpts: WOpts) {\n const { windowSize, mask, maxNumber, shiftBy } = wOpts;\n let wbits = Number(n & mask); // extract W bits.\n let nextN = n >> shiftBy; // shift number by W bits.\n\n // What actually happens here:\n // const highestBit = Number(mask ^ (mask >> 1n));\n // let wbits2 = wbits - 1; // skip zero\n // if (wbits2 & highestBit) { wbits2 ^= Number(mask); // (~);\n\n // split if bits > max: +224 => 256-32\n if (wbits > windowSize) {\n // we skip zero, which means instead of `>= size-1`, we do `> size`\n wbits -= maxNumber; // -32, can be maxNumber - wbits, but then we need to set isNeg here.\n nextN += _1n; // +256 (carry)\n }\n const offsetStart = window * windowSize;\n const offset = offsetStart + Math.abs(wbits) - 1; // -1 because we skip zero\n const isZero = wbits === 0; // is current window slice a 0?\n const isNeg = wbits < 0; // is current window slice negative?\n const isNegF = window % 2 !== 0; // fake random statement for noise\n const offsetF = offsetStart; // fake offset for noise\n return { nextN, offset, isZero, isNeg, isNegF, offsetF };\n}\n\nfunction validateMSMPoints(points: any[], c: any) {\n if (!Array.isArray(points)) throw new Error('array expected');\n points.forEach((p, i) => {\n if (!(p instanceof c)) throw new Error('invalid point at index ' + i);\n });\n}\nfunction validateMSMScalars(scalars: any[], field: any) {\n if (!Array.isArray(scalars)) throw new Error('array of scalars expected');\n scalars.forEach((s, i) => {\n if (!field.isValid(s)) throw new Error('invalid scalar at index ' + i);\n });\n}\n\n// Since points in different groups cannot be equal (different object constructor),\n// we can have single place to store precomputes.\n// Allows to make points frozen / immutable.\nconst pointPrecomputes = new WeakMap<any, any[]>();\nconst pointWindowSizes = new WeakMap<any, number>();\n\nfunction getW(P: any): number {\n return pointWindowSizes.get(P) || 1;\n}\n\nexport type IWNAF<T extends Group<T>> = {\n constTimeNegate: <T extends Group<T>>(condition: boolean, item: T) => T;\n hasPrecomputes(elm: T): boolean;\n unsafeLadder(elm: T, n: bigint, p?: T): T;\n precomputeWindow(elm: T, W: number): Group<T>[];\n getPrecomputes(W: number, P: T, transform: Mapper<T>): T[];\n wNAF(W: number, precomputes: T[], n: bigint): { p: T; f: T };\n wNAFUnsafe(W: number, precomputes: T[], n: bigint, acc?: T): T;\n wNAFCached(P: T, n: bigint, transform: Mapper<T>): { p: T; f: T };\n wNAFCachedUnsafe(P: T, n: bigint, transform: Mapper<T>, prev?: T): T;\n setWindowSize(P: T, W: number): void;\n};\n\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 *\n * @todo Research returning 2d JS array of windows, instead of a single window.\n * This would allow windows to be in different memory locations\n */\nexport function wNAF<T extends Group<T>>(c: GroupConstructor<T>, bits: number): IWNAF<T> {\n return {\n constTimeNegate,\n\n hasPrecomputes(elm: T) {\n return getW(elm) !== 1;\n },\n\n // non-const time multiplication ladder\n unsafeLadder(elm: T, n: bigint, 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 * @param elm Point instance\n * @param W window size\n * @returns precomputed point tables flattened to a single array\n */\n precomputeWindow(elm: T, W: number): Group<T>[] {\n const { windows, windowSize } = calcWOpts(W, bits);\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 // i=1, bc we skip 0\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 // Smaller version:\n // https://github.com/paulmillr/noble-secp256k1/blob/47cb1669b6e506ad66b35fe7d76132ae97465da2/index.ts#L502-L541\n // TODO: check the scalar is less than group order?\n // wNAF behavior is undefined otherwise. But have to carefully remove\n // other checks before wNAF. ORDER == bits here.\n // Accumulators\n let p = c.ZERO;\n let f = c.BASE;\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 const wo = calcWOpts(W, bits);\n for (let window = 0; window < wo.windows; window++) {\n // (n === _0n) is handled and not early-exited. isEven and offsetF are used for noise\n const { nextN, offset, isZero, isNeg, isNegF, offsetF } = calcOffsets(n, window, wo);\n n = nextN;\n if (isZero) {\n // bits are 0: add garbage to fake point\n // Important part for const-time getPublicKey: add random \"noise\" point to f.\n f = f.add(constTimeNegate(isNegF, precomputes[offsetF]));\n } else {\n // bits are 1: add to result point\n p = p.add(constTimeNegate(isNeg, precomputes[offset]));\n }\n }\n // Return both real and fake points: JIT won't eliminate f.\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 /**\n * Implements ec unsafe (non const-time) 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 * @param acc accumulator point to add result of multiplication\n * @returns point\n */\n wNAFUnsafe(W: number, precomputes: T[], n: bigint, acc: T = c.ZERO): T {\n const wo = calcWOpts(W, bits);\n for (let window = 0; window < wo.windows; window++) {\n if (n === _0n) break; // Early-exit, skip 0 value\n const { nextN, offset, isZero, isNeg } = calcOffsets(n, window, wo);\n n = nextN;\n if (isZero) {\n // Window bits are 0: skip processing.\n // Move to next window.\n continue;\n } else {\n const item = precomputes[offset];\n acc = acc.add(isNeg ? item.negate() : item); // Re-using acc allows to save adds in MSM\n }\n }\n return acc;\n },\n\n getPrecomputes(W: number, P: T, transform: Mapper<T>): T[] {\n // Calculate precomputes on a first run, reuse them after\n let comp = pointPrecomputes.get(P);\n if (!comp) {\n comp = this.precomputeWindow(P, W) as T[];\n if (W !== 1) pointPrecomputes.set(P, transform(comp));\n }\n return comp;\n },\n\n wNAFCached(P: T, n: bigint, transform: Mapper<T>): { p: T; f: T } {\n const W = getW(P);\n return this.wNAF(W, this.getPrecomputes(W, P, transform), n);\n },\n\n wNAFCachedUnsafe(P: T, n: bigint, transform: Mapper<T>, prev?: T): T {\n const W = getW(P);\n if (W === 1) return this.unsafeLadder(P, n, prev); // For W=1 ladder is ~x2 faster\n return this.wNAFUnsafe(W, this.getPrecomputes(W, P, transform), n, prev);\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\n setWindowSize(P: T, W: number) {\n validateW(W, bits);\n pointWindowSizes.set(P, W);\n pointPrecomputes.delete(P);\n },\n };\n}\n\n/**\n * Pippenger algorithm for multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).\n * 30x faster vs naive addition on L=4096, 10x faster than precomputes.\n * For N=254bit, L=1, it does: 1024 ADD + 254 DBL. For L=5: 1536 ADD + 254 DBL.\n * Algorithmically constant-time (for same L), even when 1 point + scalar, or when scalar = 0.\n * @param c Curve Point constructor\n * @param fieldN field over CURVE.N - important that it's not over CURVE.P\n * @param points array of L curve points\n * @param scalars array of L scalars (aka private keys / bigints)\n */\nexport function pippenger<T extends Group<T>>(\n c: GroupConstructor<T>,\n fieldN: IField<bigint>,\n points: T[],\n scalars: bigint[]\n): T {\n // If we split scalars by some window (let's say 8 bits), every chunk will only\n // take 256 buckets even if there are 4096 scalars, also re-uses double.\n // TODO:\n // - https://eprint.iacr.org/2024/750.pdf\n // - https://tches.iacr.org/index.php/TCHES/article/view/10287\n // 0 is accepted in scalars\n validateMSMPoints(points, c);\n validateMSMScalars(scalars, fieldN);\n const plength = points.length;\n const slength = scalars.length;\n if (plength !== slength) throw new Error('arrays of points and scalars must have equal length');\n // if (plength === 0) throw new Error('array must be of length >= 2');\n const zero = c.ZERO;\n const wbits = bitLen(BigInt(plength));\n let windowSize = 1; // bits\n if (wbits > 12) windowSize = wbits - 3;\n else if (wbits > 4) windowSize = wbits - 2;\n else if (wbits > 0) windowSize = 2;\n const MASK = bitMask(windowSize);\n const buckets = new Array(Number(MASK) + 1).fill(zero); // +1 for zero array\n const lastBits = Math.floor((fieldN.BITS - 1) / windowSize) * windowSize;\n let sum = zero;\n for (let i = lastBits; i >= 0; i -= windowSize) {\n buckets.fill(zero);\n for (let j = 0; j < slength; j++) {\n const scalar = scalars[j];\n const wbits = Number((scalar >> BigInt(i)) & MASK);\n buckets[wbits] = buckets[wbits].add(points[j]);\n }\n let resI = zero; // not using this will do small speed-up, but will lose ct\n // Skip first bucket, because it is zero\n for (let j = buckets.length - 1, sumI = zero; j > 0; j--) {\n sumI = sumI.add(buckets[j]);\n resI = resI.add(sumI);\n }\n sum = sum.add(resI);\n if (i !== 0) for (let j = 0; j < windowSize; j++) sum = sum.double();\n }\n return sum as T;\n}\n/**\n * Precomputed multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).\n * @param c Curve Point constructor\n * @param fieldN field over CURVE.N - important that it's not over CURVE.P\n * @param points array of L curve points\n * @returns function which multiplies points with scaars\n */\nexport function precomputeMSMUnsafe<T extends Group<T>>(\n c: GroupConstructor<T>,\n fieldN: IField<bigint>,\n points: T[],\n windowSize: number\n): (scalars: bigint[]) => T {\n /**\n * Performance Analysis of Window-based Precomputation\n *\n * Base Case (256-bit scalar, 8-bit window):\n * - Standard precomputation requires:\n * - 31 additions per scalar × 256 scalars = 7,936 ops\n * - Plus 255 summary additions = 8,191 total ops\n * Note: Summary additions can be optimized via accumulator\n *\n * Chunked Precomputation Analysis:\n * - Using 32 chunks requires:\n * - 255 additions per chunk\n * - 256 doublings\n * - Total: (255 × 32) + 256 = 8,416 ops\n *\n * Memory Usage Comparison:\n * Window Size | Standard Points | Chunked Points\n * ------------|-----------------|---------------\n * 4-bit | 520 | 15\n * 8-bit | 4,224 | 255\n * 10-bit | 13,824 | 1,023\n * 16-bit | 557,056 | 65,535\n *\n * Key Advantages:\n * 1. Enables larger window sizes due to reduced memory overhead\n * 2. More efficient for smaller scalar counts:\n * - 16 chunks: (16 × 255) + 256 = 4,336 ops\n * - ~2x faster than standard 8,191 ops\n *\n * Limitations:\n * - Not suitable for plain precomputes (requires 256 constant doublings)\n * - Performance degrades with larger scalar counts:\n * - Optimal for ~256 scalars\n * - Less efficient for 4096+ scalars (Pippenger preferred)\n */\n validateW(windowSize, fieldN.BITS);\n validateMSMPoints(points, c);\n const zero = c.ZERO;\n const tableSize = 2 ** windowSize - 1; // table size (without zero)\n const chunks = Math.ceil(fieldN.BITS / windowSize); // chunks of item\n const MASK = bitMask(windowSize);\n const tables = points.map((p: T) => {\n const res = [];\n for (let i = 0, acc = p; i < tableSize; i++) {\n res.push(acc);\n acc = acc.add(p);\n }\n return res;\n });\n return (scalars: bigint[]): T => {\n validateMSMScalars(scalars, fieldN);\n if (scalars.length > points.length)\n throw new Error('array of scalars must be smaller than array of points');\n let res = zero;\n for (let i = 0; i < chunks; i++) {\n // No need to double if accumulator is still zero.\n if (res !== zero) for (let j = 0; j < windowSize; j++) res = res.double();\n const shiftBy = BigInt(chunks * windowSize - (i + 1) * windowSize);\n for (let j = 0; j < scalars.length; j++) {\n const n = scalars[j];\n const curr = Number((n >> shiftBy) & MASK);\n if (!curr) continue; // skip zero scalars chunks\n res = res.add(tables[j][curr - 1]);\n }\n }\n return res;\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).\n */\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>(\n curve: BasicCurve<FP> & T\n): Readonly<\n {\n readonly nBitLength: number;\n readonly nByteLength: number;\n } & BasicCurve<FP> &\n T & {\n p: bigint;\n }\n> {\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","/**\n * Short Weierstrass curve methods. The formula is: y² = x³ + ax + b.\n *\n * ### Parameters\n *\n * To initialize a weierstrass curve, one needs to pass following params:\n *\n * * a: formula param\n * * b: formula param\n * * Fp: finite field of prime characteristic P; may be complex (Fp2). Arithmetics is done in field\n * * n: order of prime subgroup a.k.a total amount of valid curve points\n * * Gx: Base point (x, y) aka generator point. Gx = x coordinate\n * * Gy: ...y coordinate\n * * h: cofactor, usually 1. h*n = curve group order (n is only subgroup order)\n * * lowS: whether to enable (default) or disable \"low-s\" non-malleable signatures\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\n * of nominative types in TypeScript and interfaces only check for shape, so it's hard to create\n * 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 * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// prettier-ignore\nimport {\n pippenger, validateBasic, wNAF,\n type AffinePoint, type BasicCurve, type Group, type GroupConstructor\n} from './curve.ts';\n// prettier-ignore\nimport {\n Field,\n FpInvertBatch,\n getMinHashLength, invert, mapHashToField, mod, validateField,\n type IField\n} from './modular.ts';\n// prettier-ignore\nimport {\n aInRange, abool,\n bitMask,\n bytesToHex, bytesToNumberBE, concatBytes, createHmacDrbg, ensureBytes, hexToBytes,\n inRange, isBytes, memoized, numberToBytesBE, numberToHexUnpadded, validateObject,\n type CHash, type Hex, type PrivKey\n} from './utils.ts';\n\nexport type { AffinePoint };\ntype HmacFnSync = (key: Uint8Array, ...messages: Uint8Array[]) => Uint8Array;\n/**\n * When Weierstrass curve has `a=0`, it becomes Koblitz curve.\n * Koblitz curves allow using **efficiently-computable GLV 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 *\n * Endomorphism consists of beta, lambda and splitScalar:\n *\n * 1. GLV endomorphism ψ transforms a point: `P = (x, y) ↦ ψ(P) = (β·x mod p, y)`\n * 2. GLV scalar decomposition transforms a scalar: `k ≡ k₁ + k₂·λ (mod n)`\n * 3. Then these are combined: `k·P = k₁·P + k₂·ψ(P)`\n * 4. Two 128-bit point-by-scalar multiplications + one point addition is faster than\n * one 256-bit multiplication.\n *\n * where\n * * beta: β ∈ Fₚ with β³ = 1, β ≠ 1\n * * lambda: λ ∈ Fₙ with λ³ = 1, λ ≠ 1\n * * splitScalar decomposes k ↦ k₁, k₂, by using reduced basis vectors.\n * Gauss lattice reduction calculates them from initial basis vectors `(n, 0), (-λ, 0)`\n *\n * Check out `test/misc/endomorphism.js` and\n * [gist](https://gist.github.com/paulmillr/eb670806793e84df628a7c434a873066).\n */\nexport type 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;\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\nexport type Entropy = Hex | boolean;\nexport type SignOpts = { lowS?: boolean; extraEntropy?: Entropy; prehash?: boolean };\nexport type VerOpts = { lowS?: boolean; prehash?: boolean; format?: 'compact' | 'der' | undefined };\n\nfunction validateSigVerOpts(opts: SignOpts | VerOpts) {\n if (opts.lowS !== undefined) abool('lowS', opts.lowS);\n if (opts.prehash !== undefined) abool('prehash', opts.prehash);\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 toAffine(iz?: T): AffinePoint<T>;\n toHex(isCompressed?: boolean): string;\n toRawBytes(isCompressed?: boolean): Uint8Array;\n\n assertValidity(): void;\n hasEvenY(): boolean;\n multiplyUnsafe(scalar: bigint): ProjPointType<T>;\n multiplyAndAddUnsafe(Q: ProjPointType<T>, a: bigint, b: bigint): ProjPointType<T> | undefined;\n isTorsionFree(): boolean;\n clearCofactor(): ProjPointType<T>;\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 msm(points: ProjPointType<T>[], scalars: bigint[]): 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\nexport type CurvePointsTypeWithLength<T> = Readonly<\n CurvePointsType<T> & { nByteLength: number; nBitLength: number }\n>;\n\nfunction validatePointOpts<T>(curve: CurvePointsType<T>): CurvePointsTypeWithLength<T> {\n const opts = validateBasic(curve);\n validateObject(\n opts,\n {\n a: 'field',\n b: 'field',\n },\n {\n allowInfinityPoint: 'boolean',\n allowedPrivateKeyLengths: 'array',\n clearCofactor: 'function',\n fromBytes: 'function',\n isTorsionFree: 'function',\n toBytes: 'function',\n wrapPrivateKey: 'boolean',\n }\n );\n const { endo, Fp, a } = opts;\n if (endo) {\n if (!Fp.eql(a, Fp.ZERO)) {\n throw new Error('invalid endo: CURVE.a must be 0');\n }\n if (\n typeof endo !== 'object' ||\n typeof endo.beta !== 'bigint' ||\n typeof endo.splitScalar !== 'function'\n ) {\n throw new Error('invalid endo: expected \"beta\": bigint and \"splitScalar\": function');\n }\n }\n return Object.freeze({ ...opts } as const);\n}\n\nexport type CurvePointsRes<T> = {\n CURVE: ReturnType<typeof validatePointOpts<T>>;\n ProjectivePoint: ProjConstructor<T>;\n normPrivateKeyToScalar: (key: PrivKey) => bigint;\n weierstrassEquation: (x: T) => T;\n isWithinCurveOrder: (num: bigint) => boolean;\n};\n\nexport class DERErr extends Error {\n constructor(m = '') {\n super(m);\n }\n}\nexport type IDER = {\n // asn.1 DER encoding utils\n Err: typeof DERErr;\n // Basic building block is TLV (Tag-Length-Value)\n _tlv: {\n encode: (tag: number, data: string) => string;\n // v - value, l - left bytes (unparsed)\n decode(tag: number, data: Uint8Array): { v: Uint8Array; l: Uint8Array };\n };\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 _int: {\n encode(num: bigint): string;\n decode(data: Uint8Array): bigint;\n };\n toSig(hex: string | Uint8Array): { r: bigint; s: bigint };\n hexFromSig(sig: { r: bigint; s: bigint }): string;\n};\n/**\n * ASN.1 DER encoding utilities. ASN is very complex & fragile. Format:\n *\n * [0x30 (SEQUENCE), bytelength, 0x02 (INTEGER), intLength, R, 0x02 (INTEGER), intLength, S]\n *\n * Docs: https://letsencrypt.org/docs/a-warm-welcome-to-asn1-and-der/, https://luca.ntop.org/Teaching/Appunti/asn1.html\n */\nexport const DER: IDER = {\n // asn.1 DER encoding utils\n Err: DERErr,\n // Basic building block is TLV (Tag-Length-Value)\n _tlv: {\n encode: (tag: number, data: string): string => {\n const { Err: E } = DER;\n if (tag < 0 || tag > 256) throw new E('tlv.encode: wrong tag');\n if (data.length & 1) throw new E('tlv.encode: unpadded data');\n const dataLen = data.length / 2;\n const len = numberToHexUnpadded(dataLen);\n if ((len.length / 2) & 0b1000_0000) throw new E('tlv.encode: long form length too big');\n // length of length with long form flag\n const lenLen = dataLen > 127 ? numberToHexUnpadded((len.length / 2) | 0b1000_0000) : '';\n const t = numberToHexUnpadded(tag);\n return t + lenLen + len + data;\n },\n // v - value, l - left bytes (unparsed)\n decode(tag: number, data: Uint8Array): { v: Uint8Array; l: Uint8Array } {\n const { Err: E } = DER;\n let pos = 0;\n if (tag < 0 || tag > 256) throw new E('tlv.encode: wrong tag');\n if (data.length < 2 || data[pos++] !== tag) throw new E('tlv.decode: wrong tlv');\n const first = data[pos++];\n const isLong = !!(first & 0b1000_0000); // First bit of first length byte is flag for short/long form\n let length = 0;\n if (!isLong) length = first;\n else {\n // Long form: [longFlag(1bit), lengthLength(7bit), length (BE)]\n const lenLen = first & 0b0111_1111;\n if (!lenLen) throw new E('tlv.decode(long): indefinite length not supported');\n if (lenLen > 4) throw new E('tlv.decode(long): byte length is too big'); // this will overflow u32 in js\n const lengthBytes = data.subarray(pos, pos + lenLen);\n if (lengthBytes.length !== lenLen) throw new E('tlv.decode: length bytes not complete');\n if (lengthBytes[0] === 0) throw new E('tlv.decode(long): zero leftmost byte');\n for (const b of lengthBytes) length = (length << 8) | b;\n pos += lenLen;\n if (length < 128) throw new E('tlv.decode(long): not minimal encoding');\n }\n const v = data.subarray(pos, pos + length);\n if (v.length !== length) throw new E('tlv.decode: wrong value length');\n return { v, l: data.subarray(pos + length) };\n },\n },\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 _int: {\n encode(num: bigint): string {\n const { Err: E } = DER;\n if (num < _0n) throw new E('integer: negative integers are not allowed');\n let hex = numberToHexUnpadded(num);\n // Pad with zero byte if negative flag is present\n if (Number.parseInt(hex[0], 16) & 0b1000) hex = '00' + hex;\n if (hex.length & 1) throw new E('unexpected DER parsing assertion: unpadded hex');\n return hex;\n },\n decode(data: Uint8Array): bigint {\n const { Err: E } = DER;\n if (data[0] & 0b1000_0000) throw new E('invalid signature integer: negative');\n if (data[0] === 0x00 && !(data[1] & 0b1000_0000))\n throw new E('invalid signature integer: unnecessary leading zero');\n return bytesToNumberBE(data);\n },\n },\n toSig(hex: string | Uint8Array): { r: bigint; s: bigint } {\n // parse DER signature\n const { Err: E, _int: int, _tlv: tlv } = DER;\n const data = ensureBytes('signature', hex);\n const { v: seqBytes, l: seqLeftBytes } = tlv.decode(0x30, data);\n if (seqLeftBytes.length) throw new E('invalid signature: left bytes after parsing');\n const { v: rBytes, l: rLeftBytes } = tlv.decode(0x02, seqBytes);\n const { v: sBytes, l: sLeftBytes } = tlv.decode(0x02, rLeftBytes);\n if (sLeftBytes.length) throw new E('invalid signature: left bytes after parsing');\n return { r: int.decode(rBytes), s: int.decode(sBytes) };\n },\n hexFromSig(sig: { r: bigint; s: bigint }): string {\n const { _tlv: tlv, _int: int } = DER;\n const rs = tlv.encode(0x02, int.encode(sig.r));\n const ss = tlv.encode(0x02, int.encode(sig.s));\n const seq = rs + ss;\n return tlv.encode(0x30, seq);\n },\n};\n\nfunction numToSizedHex(num: bigint, size: number): string {\n return bytesToHex(numberToBytesBE(num, size));\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>): CurvePointsRes<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 const Fn = Field(CURVE.n, CURVE.nBitLength);\n\n const toBytes =\n CURVE.toBytes ||\n ((_c: ProjConstructor<T>, point: ProjPointType<T>, _isCompressed: boolean) => {\n const a = point.toAffine();\n return 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. Takes x, returns y².\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); // x² * x\n return Fp.add(Fp.add(x3, Fp.mul(x, a)), b); // x³ + a * x + b\n }\n\n function isValidXY(x: T, y: T): boolean {\n const left = Fp.sqr(y); // y²\n const right = weierstrassEquation(x); // x³ + ax + b\n return Fp.eql(left, right);\n }\n\n // Validate whether the passed curve params are valid.\n // Test 1: equation y² = x³ + ax + b should work for generator point.\n if (!isValidXY(CURVE.Gx, CURVE.Gy)) throw new Error('bad curve params: generator point');\n\n // Test 2: discriminant Δ part should be non-zero: 4a³ + 27b² != 0.\n // Guarantees curve is genus-1, smooth (non-singular).\n const _4a3 = Fp.mul(Fp.pow(CURVE.a, _3n), _4n);\n const _27b2 = Fp.mul(Fp.sqr(CURVE.b), BigInt(27));\n if (Fp.is0(Fp.add(_4a3, _27b2))) throw new Error('bad curve params: a or b');\n\n // Valid group elements reside in range 1..n-1\n function isWithinCurveOrder(num: bigint): boolean {\n return inRange(num, _1n, 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: N } = CURVE;\n if (lengths && typeof key !== 'bigint') {\n if (isBytes(key)) key = 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))\n throw new Error('invalid private key');\n key = key.padStart(nByteLength * 2, '0');\n }\n let num: bigint;\n try {\n num =\n typeof key === 'bigint'\n ? key\n : bytesToNumberBE(ensureBytes('private key', key, nByteLength));\n } catch (error) {\n throw new Error(\n 'invalid private key, expected hex or ' + nByteLength + ' bytes, got ' + typeof key\n );\n }\n if (wrapPrivateKey) num = mod(num, N); // disabled by default, enabled for BLS\n aInRange('private key', num, _1n, N); // num in range [1..N-1]\n return num;\n }\n\n function aprjpoint(other: unknown) {\n if (!(other instanceof Point)) throw new Error('ProjectivePoint expected');\n }\n\n // Memoized toAffine / validity check. They are heavy. Points are immutable.\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 const toAffineMemo = memoized((p: Point, iz?: T): AffinePoint<T> => {\n const { px: x, py: y, pz: z } = p;\n // Fast-path for normalized points\n if (Fp.eql(z, Fp.ONE)) return { x, y };\n const is0 = p.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 // NOTE: on exception this will crash 'cached' and no value will be set.\n // Otherwise true will be return\n const assertValidMemo = memoized((p: Point) => {\n if (p.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 invalid representation of ZERO.\n if (CURVE.allowInfinityPoint && !Fp.is0(p.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 } = p.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 if (!isValidXY(x, y)) throw new Error('bad point: equation left != right');\n if (!p.isTorsionFree()) throw new Error('bad point: not in prime-order subgroup');\n return true;\n });\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 // base / generator point\n static readonly BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);\n // zero / infinity / identity point\n static readonly ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO); // 0, 1, 0\n readonly px: T;\n readonly py: T;\n readonly pz: T;\n\n constructor(px: T, py: T, pz: T) {\n if (px == null || !Fp.isValid(px)) throw new Error('x required');\n if (py == null || !Fp.isValid(py) || Fp.is0(py)) throw new Error('y required');\n if (pz == null || !Fp.isValid(pz)) throw new Error('z required');\n this.px = px;\n this.py = py;\n this.pz = pz;\n Object.freeze(this);\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 = FpInvertBatch(\n Fp,\n points.map((p) => p.pz)\n );\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 // Multiscalar Multiplication\n static msm(points: Point[], scalars: bigint[]): Point {\n return pippenger(Point, Fn, points, scalars);\n }\n\n // \"Private method\", don't use it directly\n _setWindowSize(windowSize: number) {\n wnaf.setWindowSize(this, windowSize);\n }\n\n // A point on curve is valid if it conforms to equation.\n assertValidity(): void {\n assertValidMemo(this);\n }\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 aprjpoint(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 aprjpoint(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 is0() {\n return this.equals(Point.ZERO);\n }\n\n private wNAF(n: bigint): { p: Point; f: Point } {\n return wnaf.wNAFCached(this, n, Point.normalizeZ);\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(sc: bigint): Point {\n const { endo, n: N } = CURVE;\n aInRange('scalar', sc, _0n, N);\n const I = Point.ZERO;\n if (sc === _0n) return I;\n if (this.is0() || sc === _1n) return this;\n\n // Case a: no endomorphism. Case b: has precomputes.\n if (!endo || wnaf.hasPrecomputes(this))\n return wnaf.wNAFCachedUnsafe(this, sc, Point.normalizeZ);\n\n // Case c: endomorphism\n /** See docs for {@link EndomorphismOpts} */\n let { k1neg, k1, k2neg, k2 } = endo.splitScalar(sc);\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 const { endo, n: N } = CURVE;\n aInRange('scalar', scalar, _1n, N);\n let point: Point, fake: Point; // Fake point is used to const-time mult\n /** See docs for {@link EndomorphismOpts} */\n if (endo) {\n const { k1neg, k1, k2neg, k2 } = endo.splitScalar(scalar);\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(scalar);\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 return toAffineMemo(this, iz);\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 abool('isCompressed', isCompressed);\n this.assertValidity();\n return toBytes(Point, this, isCompressed);\n }\n\n toHex(isCompressed = true): string {\n abool('isCompressed', isCompressed);\n return bytesToHex(this.toRawBytes(isCompressed));\n }\n }\n const { endo, nBitLength } = CURVE;\n const wnaf = wNAF(Point, endo ? Math.ceil(nBitLength / 2) : nBitLength);\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 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(\n curve: CurveType\n): Readonly<CurveType & { nByteLength: number; nBitLength: number }> {\n const opts = validateBasic(curve);\n 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\n/**\n * Creates short weierstrass curve and ECDSA signature methods for it.\n * @example\n * import { Field } from '@noble/curves/abstract/modular';\n * // Before that, define BigInt-s: a, b, p, n, Gx, Gy\n * const curve = weierstrass({ a, b, Fp: Field(p), n, Gx, Gy, h: 1n })\n */\nexport function weierstrass(curveDef: CurveType): CurveFn {\n const CURVE = validateOpts(curveDef) as ReturnType<typeof validateOpts>;\n const { Fp, n: CURVE_ORDER, nByteLength, nBitLength } = 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 modN(a: bigint) {\n return mod(a, CURVE_ORDER);\n }\n function invN(a: bigint) {\n return 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 = concatBytes;\n abool('isCompressed', isCompressed);\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 = bytesToNumberBE(tail);\n if (!inRange(x, _1n, Fp.ORDER)) throw new Error('Point is not on curve');\n const y2 = weierstrassEquation(x); // y² = x³ + ax + b\n let y: bigint;\n try {\n y = Fp.sqrt(y2); // y = y² ^ (p+1)/4\n } catch (sqrtError) {\n const suffix = sqrtError instanceof Error ? ': ' + sqrtError.message : '';\n throw new Error('Point is not on curve' + suffix);\n }\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 const cl = compressedLen;\n const ul = uncompressedLen;\n throw new Error(\n 'invalid Point, expected length of ' + cl + ', or uncompressed ' + ul + ', got ' + len\n );\n }\n },\n });\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) => 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 readonly r: bigint;\n readonly s: bigint;\n readonly recovery?: number;\n constructor(r: bigint, s: bigint, recovery?: number) {\n aInRange('r', r, _1n, CURVE_ORDER); // r in [1..N]\n aInRange('s', s, _1n, CURVE_ORDER); // s in [1..N]\n this.r = r;\n this.s = s;\n if (recovery != null) this.recovery = recovery;\n Object.freeze(this);\n }\n\n // pair (bytes of r, bytes of s)\n static fromCompact(hex: Hex) {\n const l = 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 /**\n * @todo remove\n * @deprecated\n */\n assertValidity(): void {}\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 + numToSizedHex(radj, Fp.BYTES));\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 hexToBytes(this.toDERHex());\n }\n toDERHex() {\n return DER.hexFromSig(this);\n }\n\n // padded bytes of r, then padded bytes of s\n toCompactRawBytes() {\n return hexToBytes(this.toCompactHex());\n }\n toCompactHex() {\n const l = nByteLength;\n return numToSizedHex(this.r, l) + numToSizedHex(this.s, l);\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 = getMinHashLength(CURVE.n);\n return 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 | undefined {\n if (typeof item === 'bigint') return false;\n if (item instanceof Point) return true;\n const arr = ensureBytes('key', item);\n const len = arr.length;\n const fpl = Fp.BYTES;\n const compLen = fpl + 1; // e.g. 33 for 32\n const uncompLen = 2 * fpl + 1; // e.g. 65 for 32\n if (CURVE.allowedPrivateKeyLengths || nByteLength === compLen) {\n return undefined;\n } else {\n return len === compLen || len === uncompLen;\n }\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) === true) throw new Error('first arg must be private key');\n if (isProbPub(publicB) === false) 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 // Our custom check \"just in case\", for protection against DoS\n if (bytes.length > 8192) throw new Error('input is too large');\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 = bytesToNumberBE(bytes); // check for == u8 done here\n const delta = bytes.length * 8 - 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 = bitMask(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 aInRange('num < 2^' + nBitLength, num, _0n, ORDER_MASK);\n // works with order, can have different size than numToField!\n return numberToBytesBE(num, 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,\n // this will be invalid at least for P521. 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 validateSigVerOpts(opts);\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 && ent !== false) {\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 = 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 = 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 const { lowS, prehash, format } = opts;\n\n // Verify opts, deduce signature format\n validateSigVerOpts(opts);\n if ('strict' in opts) throw new Error('options.strict was renamed to lowS');\n if (format !== undefined && format !== 'compact' && format !== 'der')\n throw new Error('format must be compact or der');\n const isHex = typeof sg === 'string' || isBytes(sg);\n const isObj =\n !isHex &&\n !format &&\n typeof sg === 'object' &&\n sg !== null &&\n typeof sg.r === 'bigint' &&\n typeof sg.s === 'bigint';\n if (!isHex && !isObj)\n throw new Error('invalid signature, expected Uint8Array, hex string or Signature instance');\n\n let _sig: Signature | undefined = undefined;\n let P: ProjPointType<bigint>;\n try {\n if (isObj) _sig = new Signature(sg.r, sg.s);\n if (isHex) {\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 if (format !== 'compact') _sig = Signature.fromDER(sg);\n } catch (derError) {\n if (!(derError instanceof DER.Err)) throw derError;\n }\n if (!_sig && format !== 'der') _sig = Signature.fromCompact(sg);\n }\n P = Point.fromHex(publicKey);\n } catch (error) {\n return false;\n }\n if (!_sig) return false;\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>(\n Fp: IField<T>,\n Z: T\n): (u: T, v: T) => { isValid: boolean; value: 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: IField<T>,\n opts: {\n A: T;\n B: T;\n Z: T;\n }\n): (u: T) => { x: T; y: T } {\n 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 const tv4_inv = FpInvertBatch(Fp, [tv4], true)[0];\n x = Fp.mul(x, tv4_inv); // 25. x = x / tv4\n return { x, y };\n };\n}\n","/**\n * Utilities for short weierstrass curves, combined with noble-hashes.\n * @module\n */\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 type { CHash } from './abstract/utils.ts';\nimport { type CurveFn, type CurveType, weierstrass } from './abstract/weierstrass.ts';\n\n/** connects noble-curves to noble-hashes */\nexport function getHash(hash: CHash): {\n hash: CHash;\n hmac: (key: Uint8Array, ...msgs: Uint8Array[]) => Uint8Array;\n randomBytes: typeof randomBytes;\n} {\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 */\nexport type CurveDef = Readonly<Omit<CurveType, 'hash' | 'hmac' | 'randomBytes'>>;\nexport type CurveFnWithCreate = CurveFn & { create: (hash: CHash) => CurveFn };\n\nexport function createCurve(curveDef: CurveDef, defHash: CHash): CurveFnWithCreate {\n const create = (hash: CHash): CurveFn => weierstrass({ ...curveDef, ...getHash(hash) });\n return { ...create(defHash), create };\n}\n","/**\n * hash-to-curve from RFC 9380.\n * Hashes arbitrary-length byte strings to a list of one or more elements of a finite field F.\n * https://www.rfc-editor.org/rfc/rfc9380\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport type { AffinePoint, Group, GroupConstructor } from './curve.ts';\nimport { FpInvertBatch, type IField, mod } from './modular.ts';\nimport type { CHash } from './utils.ts';\nimport { abytes, bytesToNumberBE, concatBytes, utf8ToBytes, validateObject } from './utils.ts';\n\nexport type UnicodeOrBytes = string | Uint8Array;\n\n/**\n * * `DST` is a domain separation tag, defined in section 2.2.5\n * * `p` characteristic of F, where F is a finite field of characteristic p and order q = p^m\n * * `m` is extension degree (1 for prime fields)\n * * `k` is the target security target in bits (e.g. 128), from section 5.1\n * * `expand` is `xmd` (SHA2, SHA3, BLAKE) or `xof` (SHAKE, BLAKE-XOF)\n * * `hash` conforming to `utils.CHash` interface, with `outputLen` / `blockLen` props\n */\nexport type Opts = {\n DST: UnicodeOrBytes;\n p: bigint;\n m: number;\n k: number;\n expand: 'xmd' | 'xof';\n hash: CHash;\n};\n\n// Octet Stream to Integer. \"spec\" implementation of os2ip is 2.5x slower vs bytesToNumberBE.\nconst os2ip = bytesToNumberBE;\n\n// Integer to Octet Stream (numberToBytesBE)\nfunction i2osp(value: number, length: number): Uint8Array {\n anum(value);\n anum(length);\n if (value < 0 || value >= 1 << (8 * length)) throw new Error('invalid I2OSP input: ' + value);\n const res = Array.from({ length }).fill(0) as number[];\n for (let i = length - 1; i >= 0; i--) {\n res[i] = value & 0xff;\n value >>>= 8;\n }\n return new Uint8Array(res);\n}\n\nfunction strxor(a: Uint8Array, b: Uint8Array): Uint8Array {\n const arr = new Uint8Array(a.length);\n for (let i = 0; i < a.length; i++) {\n arr[i] = a[i] ^ b[i];\n }\n return arr;\n}\n\nfunction anum(item: unknown): void {\n if (!Number.isSafeInteger(item)) throw new Error('number expected');\n}\n\n/**\n * Produces a uniformly random byte string using a cryptographic hash function H that outputs b bits.\n * [RFC 9380 5.3.1](https://www.rfc-editor.org/rfc/rfc9380#section-5.3.1).\n */\nexport function expand_message_xmd(\n msg: Uint8Array,\n DST: Uint8Array,\n lenInBytes: number,\n H: CHash\n): Uint8Array {\n abytes(msg);\n abytes(DST);\n anum(lenInBytes);\n // https://www.rfc-editor.org/rfc/rfc9380#section-5.3.3\n if (DST.length > 255) DST = H(concatBytes(utf8ToBytes('H2C-OVERSIZE-DST-'), DST));\n const { outputLen: b_in_bytes, blockLen: r_in_bytes } = H;\n const ell = Math.ceil(lenInBytes / b_in_bytes);\n if (lenInBytes > 65535 || ell > 255) throw new Error('expand_message_xmd: invalid lenInBytes');\n const DST_prime = concatBytes(DST, i2osp(DST.length, 1));\n const Z_pad = i2osp(0, r_in_bytes);\n const l_i_b_str = i2osp(lenInBytes, 2); // len_in_bytes_str\n const b = new Array<Uint8Array>(ell);\n const b_0 = H(concatBytes(Z_pad, msg, l_i_b_str, i2osp(0, 1), DST_prime));\n b[0] = H(concatBytes(b_0, i2osp(1, 1), DST_prime));\n for (let i = 1; i <= ell; i++) {\n const args = [strxor(b_0, b[i - 1]), i2osp(i + 1, 1), DST_prime];\n b[i] = H(concatBytes(...args));\n }\n const pseudo_random_bytes = concatBytes(...b);\n return pseudo_random_bytes.slice(0, lenInBytes);\n}\n\n/**\n * Produces a uniformly random byte string using an extendable-output function (XOF) H.\n * 1. The collision resistance of H MUST be at least k bits.\n * 2. H MUST be an XOF that has been proved indifferentiable from\n * a random oracle under a reasonable cryptographic assumption.\n * [RFC 9380 5.3.2](https://www.rfc-editor.org/rfc/rfc9380#section-5.3.2).\n */\nexport function expand_message_xof(\n msg: Uint8Array,\n DST: Uint8Array,\n lenInBytes: number,\n k: number,\n H: CHash\n): Uint8Array {\n abytes(msg);\n abytes(DST);\n anum(lenInBytes);\n // https://www.rfc-editor.org/rfc/rfc9380#section-5.3.3\n // DST = H('H2C-OVERSIZE-DST-' || a_very_long_DST, Math.ceil((lenInBytes * k) / 8));\n if (DST.length > 255) {\n const dkLen = Math.ceil((2 * k) / 8);\n DST = H.create({ dkLen }).update(utf8ToBytes('H2C-OVERSIZE-DST-')).update(DST).digest();\n }\n if (lenInBytes > 65535 || DST.length > 255)\n throw new Error('expand_message_xof: invalid lenInBytes');\n return (\n H.create({ dkLen: lenInBytes })\n .update(msg)\n .update(i2osp(lenInBytes, 2))\n // 2. DST_prime = DST || I2OSP(len(DST), 1)\n .update(DST)\n .update(i2osp(DST.length, 1))\n .digest()\n );\n}\n\n/**\n * Hashes arbitrary-length byte strings to a list of one or more elements of a finite field F.\n * [RFC 9380 5.2](https://www.rfc-editor.org/rfc/rfc9380#section-5.2).\n * @param msg a byte string containing the message to hash\n * @param count the number of elements of F to output\n * @param options `{DST: string, p: bigint, m: number, k: number, expand: 'xmd' | 'xof', hash: H}`, see above\n * @returns [u_0, ..., u_(count - 1)], a list of field elements.\n */\nexport function hash_to_field(msg: Uint8Array, count: number, options: Opts): bigint[][] {\n validateObject(options, {\n DST: 'stringOrUint8Array',\n p: 'bigint',\n m: 'isSafeInteger',\n k: 'isSafeInteger',\n hash: 'hash',\n });\n const { p, k, m, hash, expand, DST: _DST } = options;\n abytes(msg);\n anum(count);\n const DST = typeof _DST === 'string' ? utf8ToBytes(_DST) : _DST;\n const log2p = p.toString(2).length;\n const L = Math.ceil((log2p + k) / 8); // section 5.1 of ietf draft link above\n const len_in_bytes = count * m * L;\n let prb; // pseudo_random_bytes\n if (expand === 'xmd') {\n prb = expand_message_xmd(msg, DST, len_in_bytes, hash);\n } else if (expand === 'xof') {\n prb = expand_message_xof(msg, DST, len_in_bytes, k, hash);\n } else if (expand === '_internal_pass') {\n // for internal tests only\n prb = msg;\n } else {\n throw new Error('expand must be \"xmd\" or \"xof\"');\n }\n const u = new Array(count);\n for (let i = 0; i < count; i++) {\n const e = new Array(m);\n for (let j = 0; j < m; j++) {\n const elm_offset = L * (j + i * m);\n const tv = prb.subarray(elm_offset, elm_offset + L);\n e[j] = mod(os2ip(tv), p);\n }\n u[i] = e;\n }\n return u;\n}\n\nexport type XY<T> = (x: T, y: T) => { x: T; y: T };\nexport type XYRatio<T> = [T[], T[], T[], T[]]; // xn/xd, yn/yd\nexport function isogenyMap<T, F extends IField<T>>(field: F, map: XYRatio<T>): XY<T> {\n // Make same order as in spec\n const coeff = map.map((i) => Array.from(i).reverse());\n return (x: T, y: T) => {\n const [xn, xd, yn, yd] = coeff.map((val) =>\n val.reduce((acc, i) => field.add(field.mul(acc, x), i))\n );\n // 6.6.3\n // Exceptional cases of iso_map are inputs that cause the denominator of\n // either rational function to evaluate to zero; such cases MUST return\n // the identity point on E.\n const [xd_inv, yd_inv] = FpInvertBatch(field, [xd, yd], true);\n x = field.mul(xn, xd_inv); // xNum / xDen\n y = field.mul(y, field.mul(yn, yd_inv)); // y * (yNum / yDev)\n return { x, y };\n };\n}\n\n/** Point interface, which curves must implement to work correctly with the module. */\nexport interface H2CPoint<T> extends Group<H2CPoint<T>> {\n add(rhs: H2CPoint<T>): H2CPoint<T>;\n toAffine(iz?: bigint): AffinePoint<T>;\n clearCofactor(): H2CPoint<T>;\n assertValidity(): void;\n}\n\nexport interface H2CPointConstructor<T> extends GroupConstructor<H2CPoint<T>> {\n fromAffine(ap: AffinePoint<T>): H2CPoint<T>;\n}\n\nexport type MapToCurve<T> = (scalar: bigint[]) => AffinePoint<T>;\n\n// Separated from initialization opts, so users won't accidentally change per-curve parameters\n// (changing DST is ok!)\nexport type htfBasicOpts = { DST: UnicodeOrBytes };\nexport type HTFMethod<T> = (msg: Uint8Array, options?: htfBasicOpts) => H2CPoint<T>;\nexport type MapMethod<T> = (scalars: bigint[]) => H2CPoint<T>;\nexport type Hasher<T> = {\n hashToCurve: HTFMethod<T>;\n encodeToCurve: HTFMethod<T>;\n mapToCurve: MapMethod<T>;\n defaults: Opts & { encodeDST?: UnicodeOrBytes };\n};\n\n/** Creates hash-to-curve methods from EC Point and mapToCurve function. */\nexport function createHasher<T>(\n Point: H2CPointConstructor<T>,\n mapToCurve: MapToCurve<T>,\n defaults: Opts & { encodeDST?: UnicodeOrBytes }\n): Hasher<T> {\n if (typeof mapToCurve !== 'function') throw new Error('mapToCurve() must be defined');\n function map(num: bigint[]) {\n return Point.fromAffine(mapToCurve(num));\n }\n function clear(initial: H2CPoint<T>) {\n const P = initial.clearCofactor();\n if (P.equals(Point.ZERO)) return Point.ZERO; // zero will throw in assert\n P.assertValidity();\n return P;\n }\n\n return {\n defaults,\n\n // Encodes byte string to elliptic curve.\n // hash_to_curve from https://www.rfc-editor.org/rfc/rfc9380#section-3\n hashToCurve(msg: Uint8Array, options?: htfBasicOpts): H2CPoint<T> {\n const u = hash_to_field(msg, 2, { ...defaults, DST: defaults.DST, ...options } as Opts);\n const u0 = map(u[0]);\n const u1 = map(u[1]);\n return clear(u0.add(u1));\n },\n\n // Encodes byte string to elliptic curve.\n // encode_to_curve from https://www.rfc-editor.org/rfc/rfc9380#section-3\n encodeToCurve(msg: Uint8Array, options?: htfBasicOpts): H2CPoint<T> {\n const u = hash_to_field(msg, 1, { ...defaults, DST: defaults.encodeDST, ...options } as Opts);\n return clear(map(u[0]));\n },\n\n // Same as encodeToCurve, but without hash\n mapToCurve(scalars: bigint[]): H2CPoint<T> {\n if (!Array.isArray(scalars)) throw new Error('expected array of bigints');\n for (const i of scalars)\n if (typeof i !== 'bigint') throw new Error('expected array of bigints');\n return clear(map(scalars));\n },\n };\n}\n","/**\n * NIST secp256k1. See [pdf](https://www.secg.org/sec2-v2.pdf).\n *\n * Seems to be rigid (not backdoored)\n * [as per discussion](https://bitcointalk.org/index.php?topic=289795.msg3183975#msg3183975).\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 * [See explanation](https://gist.github.com/paulmillr/eb670806793e84df628a7c434a873066).\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { sha256 } from '@noble/hashes/sha2';\nimport { randomBytes } from '@noble/hashes/utils';\nimport { createCurve, type CurveFnWithCreate } from './_shortw_utils.ts';\nimport { createHasher, type Hasher, type HTFMethod, isogenyMap } from './abstract/hash-to-curve.ts';\nimport { Field, mod, pow2 } from './abstract/modular.ts';\nimport type { Hex, PrivKey } from './abstract/utils.ts';\nimport {\n aInRange,\n bytesToNumberBE,\n concatBytes,\n ensureBytes,\n inRange,\n numberToBytesBE,\n} from './abstract/utils.ts';\nimport { mapToCurveSimpleSWU, type ProjPointType as PointType } from './abstract/weierstrass.ts';\n\nconst secp256k1P = BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f');\nconst secp256k1N = BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141');\nconst _0n = BigInt(0);\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 (!Fpk1.eql(Fpk1.sqr(root), y)) throw new Error('Cannot find square root');\n return root;\n}\n\nconst Fpk1 = Field(secp256k1P, undefined, undefined, { sqrt: sqrtMod });\n\n/**\n * secp256k1 curve, ECDSA and ECDH methods.\n *\n * Field: `2n**256n - 2n**32n - 2n**9n - 2n**8n - 2n**7n - 2n**6n - 2n**4n - 1n`\n *\n * @example\n * ```js\n * import { secp256k1 } from '@noble/curves/secp256k1';\n * const priv = secp256k1.utils.randomPrivateKey();\n * const pub = secp256k1.getPublicKey(priv);\n * const msg = new Uint8Array(32).fill(1); // message hash (not message) in ecdsa\n * const sig = secp256k1.sign(msg, priv); // `{prehash: true}` option is available\n * const isValid = secp256k1.verify(sig, msg, pub) === true;\n * ```\n */\nexport const secp256k1: CurveFnWithCreate = createCurve(\n {\n a: _0n,\n b: BigInt(7),\n Fp: Fpk1,\n n: secp256k1N,\n Gx: BigInt('55066263022277343669578718895168534326250603453777594175500187360389116729240'),\n Gy: BigInt('32670510020758816978083085130507043184471273380659243275938904335757337482424'),\n h: BigInt(1),\n lowS: true, // Allow only low-S signatures by default in sign() and verify()\n endo: {\n // Endomorphism, see above\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\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 = /* @__PURE__ */ (() => 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 aInRange('x', x, _1n, secp256k1P); // 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}\nconst num = bytesToNumberBE;\n/**\n * Create tagged hash, convert it to bigint, reduce modulo-n.\n */\nfunction challenge(...args: Uint8Array[]): bigint {\n return modN(num(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 ^ num(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(num(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(num(pub)); // P = lift_x(int(pk)); fail if that fails\n const r = num(sig.subarray(0, 32)); // Let r = int(sig[0:32]); fail if r ≥ p.\n if (!inRange(r, _1n, secp256k1P)) return false;\n const s = num(sig.subarray(32, 64)); // Let s = int(sig[32:64]); fail if s ≥ n.\n if (!inRange(s, _1n, secp256k1N)) 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 type SecpSchnorr = {\n getPublicKey: typeof schnorrGetPublicKey;\n sign: typeof schnorrSign;\n verify: typeof schnorrVerify;\n utils: {\n randomPrivateKey: () => Uint8Array;\n lift_x: typeof lift_x;\n pointToBytes: (point: PointType<bigint>) => Uint8Array;\n numberToBytesBE: typeof numberToBytesBE;\n bytesToNumberBE: typeof bytesToNumberBE;\n taggedHash: typeof taggedHash;\n mod: typeof mod;\n };\n};\n/**\n * Schnorr signatures over secp256k1.\n * https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki\n * @example\n * ```js\n * import { schnorr } from '@noble/curves/secp256k1';\n * const priv = schnorr.utils.randomPrivateKey();\n * const pub = schnorr.getPublicKey(priv);\n * const msg = new TextEncoder().encode('hello');\n * const sig = schnorr.sign(msg, priv);\n * const isValid = schnorr.verify(sig, msg, pub);\n * ```\n */\nexport const schnorr: SecpSchnorr = /* @__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 Fpk1,\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(Fpk1, {\n A: BigInt('0x3f8731abdd661adca08a5558f0f5d272e953d363cb6f0e5d405447c01a444533'),\n B: BigInt('1771'),\n Z: Fpk1.create(BigInt('-11')),\n }))();\n/** Hashing / encoding to secp256k1 points / field. RFC 9380 methods. */\nexport const secp256k1_hasher: Hasher<bigint> = /* @__PURE__ */ (() =>\n createHasher(\n secp256k1.ProjectivePoint,\n (scalars: bigint[]) => {\n const { x, y } = mapSWU(Fpk1.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: Fpk1.ORDER,\n m: 1,\n k: 128,\n expand: 'xmd',\n hash: sha256,\n } as const\n ))();\n\nexport const hashToCurve: HTFMethod<bigint> = /* @__PURE__ */ (() =>\n secp256k1_hasher.hashToCurve)();\n\nexport const encodeToCurve: HTFMethod<bigint> = /* @__PURE__ */ (() =>\n secp256k1_hasher.encodeToCurve)();\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|gas required exceeds allowance/\n\n constructor({\n cause,\n message,\n }: { cause?: BaseError | undefined; message?: string | undefined } = {}) {\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 name: 'ExecutionRevertedError',\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 constructor({\n cause,\n maxFeePerGas,\n }: {\n cause?: BaseError | undefined\n maxFeePerGas?: bigint | undefined\n } = {}) {\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 name: 'FeeCapTooHighError',\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 constructor({\n cause,\n maxFeePerGas,\n }: {\n cause?: BaseError | undefined\n maxFeePerGas?: bigint | undefined\n } = {}) {\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 name: 'FeeCapTooLowError',\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 constructor({\n cause,\n nonce,\n }: { cause?: BaseError | undefined; nonce?: number | undefined } = {}) {\n super(\n `Nonce provided for the transaction ${\n nonce ? `(${nonce}) ` : ''\n }is higher than the next one expected.`,\n { cause, name: 'NonceTooHighError' },\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 constructor({\n cause,\n nonce,\n }: { cause?: BaseError | undefined; nonce?: number | undefined } = {}) {\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, name: 'NonceTooLowError' },\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 constructor({\n cause,\n nonce,\n }: { cause?: BaseError | undefined; nonce?: number | undefined } = {}) {\n super(\n `Nonce provided for the transaction ${\n nonce ? `(${nonce}) ` : ''\n }exceeds the maximum allowed nonce.`,\n { cause, name: 'NonceMaxValueError' },\n )\n }\n}\n\nexport type InsufficientFundsErrorType = InsufficientFundsError & {\n name: 'InsufficientFundsError'\n}\nexport class InsufficientFundsError extends BaseError {\n static nodeMessage =\n /insufficient funds|exceeds transaction sender account balance/\n constructor({ cause }: { cause?: BaseError | undefined } = {}) {\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 name: 'InsufficientFundsError',\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 constructor({\n cause,\n gas,\n }: { cause?: BaseError | undefined; gas?: bigint | undefined } = {}) {\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 name: 'IntrinsicGasTooHighError',\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 constructor({\n cause,\n gas,\n }: { cause?: BaseError | undefined; gas?: bigint | undefined } = {}) {\n super(\n `The amount of gas ${\n gas ? `(${gas}) ` : ''\n }provided for the transaction is too low.`,\n {\n cause,\n name: 'IntrinsicGasTooLowError',\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 constructor({ cause }: { cause?: BaseError | undefined }) {\n super('The transaction type is not supported for this chain.', {\n cause,\n name: 'TransactionTypeNotSupportedError',\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 constructor({\n cause,\n maxPriorityFeePerGas,\n maxFeePerGas,\n }: {\n cause?: BaseError | undefined\n maxPriorityFeePerGas?: bigint | undefined\n maxFeePerGas?: bigint | undefined\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 name: 'TipAboveFeeCapError',\n },\n )\n }\n}\n\nexport type UnknownNodeErrorType = UnknownNodeError & {\n name: 'UnknownNodeError'\n}\nexport class UnknownNodeError extends BaseError {\n constructor({ cause }: { cause?: BaseError | undefined }) {\n super(`An error occurred while executing: ${cause?.shortMessage}`, {\n cause,\n name: 'UnknownNodeError',\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'\nimport type { ExactPartial } from '../../types/utils.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 = ExactPartial<\n SendTransactionParameters<any>\n>\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 =\n err instanceof BaseError\n ? err.walk(\n (e) =>\n (e as { code: number } | null | undefined)?.code ===\n ExecutionRevertedError.code,\n )\n : err\n if (executionRevertedError instanceof BaseError)\n return new ExecutionRevertedError({\n cause: err,\n message: executionRevertedError.details,\n }) as any\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'] | undefined },\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 type { ErrorType } from '../../errors/utils.js'\nimport type { Prettify } from '../../types/utils.js'\n\nexport type DefineFormatterErrorType = ErrorType\n\nexport function defineFormatter<type extends string, parameters, returnType>(\n type: type,\n format: (args: parameters, action?: string | undefined) => returnType,\n) {\n return <\n parametersOverride,\n returnTypeOverride,\n exclude extends (keyof parameters | keyof parametersOverride)[] = [],\n >({\n exclude,\n format: overrides,\n }: {\n exclude?: exclude | undefined\n format: (\n args: parametersOverride,\n action?: string | undefined,\n ) => returnTypeOverride\n }) => {\n return {\n exclude,\n format: (args: parametersOverride, action?: string | undefined) => {\n const formatted = format(args as any, action)\n if (exclude) {\n for (const key of exclude) {\n delete (formatted as any)[key]\n }\n }\n return {\n ...formatted,\n ...overrides(args, action),\n } as Prettify<returnTypeOverride> & {\n [_key in exclude[number]]: never\n }\n },\n type,\n }\n }\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { Account } from '../../types/account.js'\nimport type { AuthorizationList } from '../../types/authorization.js'\nimport type {\n Chain,\n ExtractChainFormatterParameters,\n} from '../../types/chain.js'\nimport type { ByteArray } from '../../types/misc.js'\nimport type {\n RpcAuthorizationList,\n RpcTransactionRequest,\n} from '../../types/rpc.js'\nimport type { TransactionRequest } from '../../types/transaction.js'\nimport type { ExactPartial } from '../../types/utils.js'\nimport { bytesToHex, numberToHex } from '../encoding/toHex.js'\nimport { type DefineFormatterErrorType, defineFormatter } from './formatter.js'\n\nexport type FormattedTransactionRequest<\n chain extends Chain | undefined = Chain | undefined,\n> = ExtractChainFormatterParameters<\n chain,\n 'transactionRequest',\n TransactionRequest\n>\n\nexport const rpcTransactionType = {\n legacy: '0x0',\n eip2930: '0x1',\n eip1559: '0x2',\n eip4844: '0x3',\n eip7702: '0x4',\n} as const\n\nexport type FormatTransactionRequestErrorType = ErrorType\n\nexport function formatTransactionRequest(\n request: ExactPartial<TransactionRequest> & { account?: Account | undefined },\n _?: string | undefined,\n) {\n const rpcRequest = {} as RpcTransactionRequest\n\n if (typeof request.authorizationList !== 'undefined')\n rpcRequest.authorizationList = formatAuthorizationList(\n request.authorizationList,\n )\n if (typeof request.accessList !== 'undefined')\n rpcRequest.accessList = request.accessList\n if (typeof request.blobVersionedHashes !== 'undefined')\n rpcRequest.blobVersionedHashes = request.blobVersionedHashes\n if (typeof request.blobs !== 'undefined') {\n if (typeof request.blobs[0] !== 'string')\n rpcRequest.blobs = (request.blobs as ByteArray[]).map((x) =>\n bytesToHex(x),\n )\n else rpcRequest.blobs = request.blobs\n }\n if (typeof request.data !== 'undefined') rpcRequest.data = request.data\n if (request.account) rpcRequest.from = request.account.address\n if (typeof request.from !== 'undefined') rpcRequest.from = request.from\n if (typeof request.gas !== 'undefined')\n rpcRequest.gas = numberToHex(request.gas)\n if (typeof request.gasPrice !== 'undefined')\n rpcRequest.gasPrice = numberToHex(request.gasPrice)\n if (typeof request.maxFeePerBlobGas !== 'undefined')\n rpcRequest.maxFeePerBlobGas = numberToHex(request.maxFeePerBlobGas)\n if (typeof request.maxFeePerGas !== 'undefined')\n rpcRequest.maxFeePerGas = numberToHex(request.maxFeePerGas)\n if (typeof request.maxPriorityFeePerGas !== 'undefined')\n rpcRequest.maxPriorityFeePerGas = numberToHex(request.maxPriorityFeePerGas)\n if (typeof request.nonce !== 'undefined')\n rpcRequest.nonce = numberToHex(request.nonce)\n if (typeof request.to !== 'undefined') rpcRequest.to = request.to\n if (typeof request.type !== 'undefined')\n rpcRequest.type = rpcTransactionType[request.type]\n if (typeof request.value !== 'undefined')\n rpcRequest.value = numberToHex(request.value)\n\n return rpcRequest\n}\n\nexport type DefineTransactionRequestErrorType =\n | DefineFormatterErrorType\n | ErrorType\n\nexport const defineTransactionRequest = /*#__PURE__*/ defineFormatter(\n 'transactionRequest',\n formatTransactionRequest,\n)\n\n//////////////////////////////////////////////////////////////////////////////\n\nfunction formatAuthorizationList(\n authorizationList: AuthorizationList<number, boolean>,\n): RpcAuthorizationList {\n return authorizationList.map(\n (authorization) =>\n ({\n address: authorization.address,\n r: authorization.r\n ? numberToHex(BigInt(authorization.r))\n : authorization.r,\n s: authorization.s\n ? numberToHex(BigInt(authorization.s))\n : authorization.s,\n chainId: numberToHex(authorization.chainId),\n nonce: numberToHex(authorization.nonce),\n ...(typeof authorization.yParity !== 'undefined'\n ? { yParity: numberToHex(authorization.yParity) }\n : {}),\n ...(typeof authorization.v !== 'undefined' &&\n typeof authorization.yParity === 'undefined'\n ? { v: numberToHex(authorization.v) }\n : {}),\n }) as any,\n ) as RpcAuthorizationList\n}\n","import {\n InvalidAddressError,\n type InvalidAddressErrorType,\n} from '../errors/address.js'\nimport {\n InvalidBytesLengthError,\n type InvalidBytesLengthErrorType,\n} from '../errors/data.js'\nimport {\n AccountStateConflictError,\n type AccountStateConflictErrorType,\n StateAssignmentConflictError,\n type StateAssignmentConflictErrorType,\n} from '../errors/stateOverride.js'\nimport type {\n RpcAccountStateOverride,\n RpcStateMapping,\n RpcStateOverride,\n} from '../types/rpc.js'\nimport type { StateMapping, StateOverride } from '../types/stateOverride.js'\nimport { isAddress } from './address/isAddress.js'\nimport { type NumberToHexErrorType, numberToHex } from './encoding/toHex.js'\n\ntype SerializeStateMappingParameters = StateMapping | undefined\n\ntype SerializeStateMappingErrorType = InvalidBytesLengthErrorType\n\n/** @internal */\nexport function serializeStateMapping(\n stateMapping: SerializeStateMappingParameters,\n): RpcStateMapping | undefined {\n if (!stateMapping || stateMapping.length === 0) return undefined\n return stateMapping.reduce((acc, { slot, value }) => {\n if (slot.length !== 66)\n throw new InvalidBytesLengthError({\n size: slot.length,\n targetSize: 66,\n type: 'hex',\n })\n if (value.length !== 66)\n throw new InvalidBytesLengthError({\n size: value.length,\n targetSize: 66,\n type: 'hex',\n })\n acc[slot] = value\n return acc\n }, {} as RpcStateMapping)\n}\n\ntype SerializeAccountStateOverrideParameters = Omit<\n StateOverride[number],\n 'address'\n>\n\ntype SerializeAccountStateOverrideErrorType =\n | NumberToHexErrorType\n | StateAssignmentConflictErrorType\n | SerializeStateMappingErrorType\n\n/** @internal */\nexport function serializeAccountStateOverride(\n parameters: SerializeAccountStateOverrideParameters,\n): RpcAccountStateOverride {\n const { balance, nonce, state, stateDiff, code } = parameters\n const rpcAccountStateOverride: RpcAccountStateOverride = {}\n if (code !== undefined) rpcAccountStateOverride.code = code\n if (balance !== undefined)\n rpcAccountStateOverride.balance = numberToHex(balance)\n if (nonce !== undefined) rpcAccountStateOverride.nonce = numberToHex(nonce)\n if (state !== undefined)\n rpcAccountStateOverride.state = serializeStateMapping(state)\n if (stateDiff !== undefined) {\n if (rpcAccountStateOverride.state) throw new StateAssignmentConflictError()\n rpcAccountStateOverride.stateDiff = serializeStateMapping(stateDiff)\n }\n return rpcAccountStateOverride\n}\n\ntype SerializeStateOverrideParameters = StateOverride | undefined\n\nexport type SerializeStateOverrideErrorType =\n | InvalidAddressErrorType\n | AccountStateConflictErrorType\n | SerializeAccountStateOverrideErrorType\n\n/** @internal */\nexport function serializeStateOverride(\n parameters?: SerializeStateOverrideParameters,\n): RpcStateOverride | undefined {\n if (!parameters) return undefined\n const rpcStateOverride: RpcStateOverride = {}\n for (const { address, ...accountState } of parameters) {\n if (!isAddress(address, { strict: false }))\n throw new InvalidAddressError({ address })\n if (rpcStateOverride[address])\n throw new AccountStateConflictError({ address: address })\n rpcStateOverride[address] = serializeAccountStateOverride(accountState)\n }\n return rpcStateOverride\n}\n","export const maxInt8 = 2n ** (8n - 1n) - 1n\nexport const maxInt16 = 2n ** (16n - 1n) - 1n\nexport const maxInt24 = 2n ** (24n - 1n) - 1n\nexport const maxInt32 = 2n ** (32n - 1n) - 1n\nexport const maxInt40 = 2n ** (40n - 1n) - 1n\nexport const maxInt48 = 2n ** (48n - 1n) - 1n\nexport const maxInt56 = 2n ** (56n - 1n) - 1n\nexport const maxInt64 = 2n ** (64n - 1n) - 1n\nexport const maxInt72 = 2n ** (72n - 1n) - 1n\nexport const maxInt80 = 2n ** (80n - 1n) - 1n\nexport const maxInt88 = 2n ** (88n - 1n) - 1n\nexport const maxInt96 = 2n ** (96n - 1n) - 1n\nexport const maxInt104 = 2n ** (104n - 1n) - 1n\nexport const maxInt112 = 2n ** (112n - 1n) - 1n\nexport const maxInt120 = 2n ** (120n - 1n) - 1n\nexport const maxInt128 = 2n ** (128n - 1n) - 1n\nexport const maxInt136 = 2n ** (136n - 1n) - 1n\nexport const maxInt144 = 2n ** (144n - 1n) - 1n\nexport const maxInt152 = 2n ** (152n - 1n) - 1n\nexport const maxInt160 = 2n ** (160n - 1n) - 1n\nexport const maxInt168 = 2n ** (168n - 1n) - 1n\nexport const maxInt176 = 2n ** (176n - 1n) - 1n\nexport const maxInt184 = 2n ** (184n - 1n) - 1n\nexport const maxInt192 = 2n ** (192n - 1n) - 1n\nexport const maxInt200 = 2n ** (200n - 1n) - 1n\nexport const maxInt208 = 2n ** (208n - 1n) - 1n\nexport const maxInt216 = 2n ** (216n - 1n) - 1n\nexport const maxInt224 = 2n ** (224n - 1n) - 1n\nexport const maxInt232 = 2n ** (232n - 1n) - 1n\nexport const maxInt240 = 2n ** (240n - 1n) - 1n\nexport const maxInt248 = 2n ** (248n - 1n) - 1n\nexport const maxInt256 = 2n ** (256n - 1n) - 1n\n\nexport const minInt8 = -(2n ** (8n - 1n))\nexport const minInt16 = -(2n ** (16n - 1n))\nexport const minInt24 = -(2n ** (24n - 1n))\nexport const minInt32 = -(2n ** (32n - 1n))\nexport const minInt40 = -(2n ** (40n - 1n))\nexport const minInt48 = -(2n ** (48n - 1n))\nexport const minInt56 = -(2n ** (56n - 1n))\nexport const minInt64 = -(2n ** (64n - 1n))\nexport const minInt72 = -(2n ** (72n - 1n))\nexport const minInt80 = -(2n ** (80n - 1n))\nexport const minInt88 = -(2n ** (88n - 1n))\nexport const minInt96 = -(2n ** (96n - 1n))\nexport const minInt104 = -(2n ** (104n - 1n))\nexport const minInt112 = -(2n ** (112n - 1n))\nexport const minInt120 = -(2n ** (120n - 1n))\nexport const minInt128 = -(2n ** (128n - 1n))\nexport const minInt136 = -(2n ** (136n - 1n))\nexport const minInt144 = -(2n ** (144n - 1n))\nexport const minInt152 = -(2n ** (152n - 1n))\nexport const minInt160 = -(2n ** (160n - 1n))\nexport const minInt168 = -(2n ** (168n - 1n))\nexport const minInt176 = -(2n ** (176n - 1n))\nexport const minInt184 = -(2n ** (184n - 1n))\nexport const minInt192 = -(2n ** (192n - 1n))\nexport const minInt200 = -(2n ** (200n - 1n))\nexport const minInt208 = -(2n ** (208n - 1n))\nexport const minInt216 = -(2n ** (216n - 1n))\nexport const minInt224 = -(2n ** (224n - 1n))\nexport const minInt232 = -(2n ** (232n - 1n))\nexport const minInt240 = -(2n ** (240n - 1n))\nexport const minInt248 = -(2n ** (248n - 1n))\nexport const minInt256 = -(2n ** (256n - 1n))\n\nexport const maxUint8 = 2n ** 8n - 1n\nexport const maxUint16 = 2n ** 16n - 1n\nexport const maxUint24 = 2n ** 24n - 1n\nexport const maxUint32 = 2n ** 32n - 1n\nexport const maxUint40 = 2n ** 40n - 1n\nexport const maxUint48 = 2n ** 48n - 1n\nexport const maxUint56 = 2n ** 56n - 1n\nexport const maxUint64 = 2n ** 64n - 1n\nexport const maxUint72 = 2n ** 72n - 1n\nexport const maxUint80 = 2n ** 80n - 1n\nexport const maxUint88 = 2n ** 88n - 1n\nexport const maxUint96 = 2n ** 96n - 1n\nexport const maxUint104 = 2n ** 104n - 1n\nexport const maxUint112 = 2n ** 112n - 1n\nexport const maxUint120 = 2n ** 120n - 1n\nexport const maxUint128 = 2n ** 128n - 1n\nexport const maxUint136 = 2n ** 136n - 1n\nexport const maxUint144 = 2n ** 144n - 1n\nexport const maxUint152 = 2n ** 152n - 1n\nexport const maxUint160 = 2n ** 160n - 1n\nexport const maxUint168 = 2n ** 168n - 1n\nexport const maxUint176 = 2n ** 176n - 1n\nexport const maxUint184 = 2n ** 184n - 1n\nexport const maxUint192 = 2n ** 192n - 1n\nexport const maxUint200 = 2n ** 200n - 1n\nexport const maxUint208 = 2n ** 208n - 1n\nexport const maxUint216 = 2n ** 216n - 1n\nexport const maxUint224 = 2n ** 224n - 1n\nexport const maxUint232 = 2n ** 232n - 1n\nexport const maxUint240 = 2n ** 240n - 1n\nexport const maxUint248 = 2n ** 248n - 1n\nexport const maxUint256 = 2n ** 256n - 1n\n","import {\n type ParseAccountErrorType,\n parseAccount,\n} from '../../accounts/utils/parseAccount.js'\nimport type { SendTransactionParameters } from '../../actions/wallet/sendTransaction.js'\nimport { maxUint256 } from '../../constants/number.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 type { FeeConflictErrorType } from '../../errors/transaction.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { ExactPartial } from '../../types/utils.js'\nimport { isAddress } from '../address/isAddress.js'\n\nexport type AssertRequestParameters = ExactPartial<\n SendTransactionParameters<Chain>\n>\n\nexport type AssertRequestErrorType =\n | InvalidAddressErrorType\n | FeeConflictErrorType\n | FeeCapTooHighErrorType\n | ParseAccountErrorType\n | TipAboveFeeCapErrorType\n | ErrorType\n\nexport function assertRequest(args: AssertRequestParameters) {\n const { account: account_, maxFeePerGas, maxPriorityFeePerGas, to } = 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\n if (maxFeePerGas && maxFeePerGas > maxUint256)\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 { 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, { strict: false }))\n throw new InvalidAddressError({ address: a })\n if (!isAddress(b, { strict: false }))\n throw new InvalidAddressError({ address: b })\n return a.toLowerCase() === b.toLowerCase()\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 constructor({\n blockNumber,\n chain,\n contract,\n }: {\n blockNumber?: bigint | undefined\n chain: Chain\n contract: { name: string; blockCreated?: number | undefined }\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 name: 'ChainDoesNotSupportContract',\n },\n )\n }\n}\n\nexport type ChainMismatchErrorType = ChainMismatchError & {\n name: 'ChainMismatchError'\n}\nexport class ChainMismatchError extends BaseError {\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 name: 'ChainMismatchError',\n },\n )\n }\n}\n\nexport type ChainNotFoundErrorType = ChainNotFoundError & {\n name: 'ChainNotFoundError'\n}\nexport class ChainNotFoundError extends BaseError {\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 name: 'ChainNotFoundError',\n },\n )\n }\n}\n\nexport type ClientChainNotConfiguredErrorType =\n ClientChainNotConfiguredError & {\n name: 'ClientChainNotConfiguredError'\n }\nexport class ClientChainNotConfiguredError extends BaseError {\n constructor() {\n super('No chain was provided to the Client.', {\n name: 'ClientChainNotConfiguredError',\n })\n }\n}\n\nexport type InvalidChainIdErrorType = InvalidChainIdError & {\n name: 'InvalidChainIdError'\n}\nexport class InvalidChainIdError extends BaseError {\n constructor({ chainId }: { chainId?: number | undefined }) {\n super(\n typeof chainId === 'number'\n ? `Chain ID \"${chainId}\" is invalid.`\n : 'Chain ID is invalid.',\n { name: 'InvalidChainIdError' },\n )\n }\n}\n","import type { Abi } from 'abitype'\n\nimport {\n AbiConstructorNotFoundError,\n type AbiConstructorNotFoundErrorType,\n AbiConstructorParamsNotFoundError,\n} from '../../errors/abi.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { ContractConstructorArgs } from '../../types/contract.js'\nimport type { Hex } from '../../types/misc.js'\nimport type { UnionEvaluate } from '../../types/utils.js'\nimport { type ConcatHexErrorType, concatHex } from '../data/concat.js'\nimport {\n type EncodeAbiParametersErrorType,\n encodeAbiParameters,\n} from './encodeAbiParameters.js'\n\nconst docsPath = '/docs/contract/encodeDeployData'\n\nexport type EncodeDeployDataParameters<\n abi extends Abi | readonly unknown[] = Abi,\n ///\n hasConstructor = abi extends Abi\n ? Abi extends abi\n ? true\n : [Extract<abi[number], { type: 'constructor' }>] extends [never]\n ? false\n : true\n : true,\n allArgs = ContractConstructorArgs<abi>,\n> = {\n abi: abi\n bytecode: Hex\n} & UnionEvaluate<\n hasConstructor extends false\n ? { args?: undefined }\n : readonly [] extends allArgs\n ? { args?: allArgs | undefined }\n : { args: allArgs }\n>\n\nexport type EncodeDeployDataReturnType = Hex\n\nexport type EncodeDeployDataErrorType =\n | AbiConstructorNotFoundErrorType\n | ConcatHexErrorType\n | EncodeAbiParametersErrorType\n | ErrorType\n\nexport function encodeDeployData<const abi extends Abi | readonly unknown[]>(\n parameters: EncodeDeployDataParameters<abi>,\n): EncodeDeployDataReturnType {\n const { abi, args, bytecode } = parameters as EncodeDeployDataParameters\n if (!args || args.length === 0) return bytecode\n\n const description = abi.find((x) => 'type' in x && x.type === 'constructor')\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(description.inputs, args)\n return concatHex([bytecode, data!])\n}\n","/** @internal */\nexport type PromiseWithResolvers<type> = {\n promise: Promise<type>\n resolve: (value: type | PromiseLike<type>) => void\n reject: (reason?: unknown) => void\n}\n\n/** @internal */\nexport function withResolvers<type>(): PromiseWithResolvers<type> {\n let resolve: PromiseWithResolvers<type>['resolve'] = () => undefined\n let reject: PromiseWithResolvers<type>['reject'] = () => undefined\n\n const promise = new Promise<type>((resolve_, reject_) => {\n resolve = resolve_\n reject = reject_\n })\n\n return { promise, resolve, reject }\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport { type PromiseWithResolvers, withResolvers } from './withResolvers.js'\n\ntype Resolved<returnType extends readonly unknown[] = any> = [\n result: returnType[number],\n results: returnType,\n]\n\ntype SchedulerItem = {\n args: unknown\n resolve: PromiseWithResolvers<unknown>['resolve']\n reject: PromiseWithResolvers<unknown>['reject']\n}\n\ntype BatchResultsCompareFn<result = unknown> = (a: result, b: result) => number\n\ntype CreateBatchSchedulerArguments<\n parameters = unknown,\n returnType extends readonly unknown[] = readonly unknown[],\n> = {\n fn: (args: parameters[]) => Promise<returnType>\n id: number | string\n shouldSplitBatch?: ((args: parameters[]) => boolean) | undefined\n wait?: number | undefined\n sort?: BatchResultsCompareFn<returnType[number]> | undefined\n}\n\ntype CreateBatchSchedulerReturnType<\n parameters = unknown,\n returnType extends readonly unknown[] = readonly unknown[],\n> = {\n flush: () => void\n schedule: parameters extends undefined\n ? (args?: parameters | undefined) => Promise<Resolved<returnType>>\n : (args: parameters) => Promise<Resolved<returnType>>\n}\n\nexport type CreateBatchSchedulerErrorType = ErrorType\n\nconst schedulerCache = /*#__PURE__*/ new Map<number | string, SchedulerItem[]>()\n\n/** @internal */\nexport function createBatchScheduler<\n parameters,\n returnType extends readonly unknown[],\n>({\n fn,\n id,\n shouldSplitBatch,\n wait = 0,\n sort,\n}: CreateBatchSchedulerArguments<\n parameters,\n returnType\n>): CreateBatchSchedulerReturnType<parameters, returnType> {\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 parameters[])\n .then((data) => {\n if (sort && Array.isArray(data)) data.sort(sort)\n for (let i = 0; i < scheduler.length; i++) {\n const { resolve } = scheduler[i]\n resolve?.([data[i], data])\n }\n })\n .catch((err) => {\n for (let i = 0; i < scheduler.length; i++) {\n const { reject } = scheduler[i]\n reject?.(err)\n }\n })\n }\n\n const flush = () => schedulerCache.delete(id)\n\n const getBatchedArgs = () =>\n getScheduler().map(({ args }) => args) as parameters[]\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: parameters) {\n const { promise, resolve, reject } = withResolvers()\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, resolve, reject })\n return promise\n }\n\n setScheduler({ args, resolve, reject })\n setTimeout(exec, wait)\n return promise\n },\n } as unknown as CreateBatchSchedulerReturnType<parameters, returnType>\n}\n","import type { Client } from '../clients/createClient.js'\nimport type { PublicActions } from '../clients/decorators/public.js'\nimport type { WalletActions } from '../clients/decorators/wallet.js'\nimport type { Transport } from '../clients/transports/createTransport.js'\nimport type { Account } from '../types/account.js'\nimport type { Chain } from '../types/chain.js'\nimport type { RpcSchema } from '../types/eip1193.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<\n transport extends Transport,\n chain extends Chain | undefined,\n account extends Account | undefined,\n rpcSchema extends RpcSchema | undefined,\n extended extends { [key: string]: unknown },\n client extends Client<transport, chain, account, rpcSchema, extended>,\n parameters,\n returnType,\n>(\n client: client,\n actionFn: (_: any, parameters: parameters) => returnType,\n // Some minifiers drop `Function.prototype.name`, or replace it with short letters,\n // meaning that `actionFn.name` will not always work. For that case, the consumer\n // needs to pass the name explicitly.\n name: keyof PublicActions | keyof WalletActions | (string & {}),\n): (parameters: parameters) => returnType {\n const action_implicit = client[actionFn.name]\n if (typeof action_implicit === 'function')\n return action_implicit as (params: parameters) => returnType\n\n const action_explicit = client[name]\n if (typeof action_explicit === 'function')\n return action_explicit as (params: parameters) => returnType\n\n return (params) => actionFn(client, params)\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 { RpcRequestError } from '../../errors/request.js'\nimport { InternalRpcError, InvalidInputRpcError } 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 | undefined\n docsPath?: string | undefined\n functionName: string\n sender?: Address | undefined\n },\n): GetContractErrorReturnType {\n const error = (\n err instanceof RawContractError\n ? err\n : err instanceof BaseError\n ? err.walk((err) => 'data' in (err as Error)) || err.walk()\n : {}\n ) as BaseError\n const { code, data, details, message, shortMessage } =\n error 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 || details || message || shortMessage)) ||\n (code === InvalidInputRpcError.code &&\n details === 'execution reverted' &&\n data)\n ) {\n return new ContractFunctionRevertedError({\n abi,\n data: typeof data === 'object' ? data.data : data,\n functionName,\n message:\n error instanceof RpcRequestError\n ? details\n : (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 { Address } from 'abitype'\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 { BaseError } from '../../errors/base.js'\nimport type { BlockTag } from '../../types/block.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { StateOverride } from '../../types/stateOverride.js'\nimport type { TransactionRequest } from '../../types/transaction.js'\nimport type { UnionOmit } from '../../types/utils.js'\nimport {\n type RecoverAuthorizationAddressErrorType,\n recoverAuthorizationAddress,\n} from '../../utils/authorization/recoverAuthorizationAddress.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 { serializeStateOverride } from '../../utils/stateOverride.js'\nimport {\n type AssertRequestErrorType,\n type AssertRequestParameters,\n assertRequest,\n} from '../../utils/transaction/assertRequest.js'\nimport {\n type PrepareTransactionRequestParameters,\n type PrepareTransactionRequestParameterType,\n prepareTransactionRequest,\n} from '../wallet/prepareTransactionRequest.js'\n\nexport type EstimateGasParameters<\n chain extends Chain | undefined = Chain | undefined,\n> = UnionOmit<FormattedEstimateGas<chain>, 'from'> & {\n account?: Account | Address | undefined\n prepare?:\n | boolean\n | readonly PrepareTransactionRequestParameterType[]\n | undefined\n stateOverride?: StateOverride | undefined\n} & (\n | {\n /** The balance of the account at a block number. */\n blockNumber?: bigint | undefined\n blockTag?: undefined\n }\n | {\n blockNumber?: undefined\n /**\n * The balance of the account at a block tag.\n * @default 'latest'\n */\n blockTag?: BlockTag | undefined\n }\n )\ntype FormattedEstimateGas<chain extends Chain | undefined = Chain | undefined> =\n FormattedTransactionRequest<chain>\n\nexport type EstimateGasReturnType = bigint\n\nexport type EstimateGasErrorType = GetEstimateGasErrorReturnType<\n | ParseAccountErrorType\n | NumberToHexErrorType\n | RequestErrorType\n | RecoverAuthorizationAddressErrorType\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\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 gas units). {@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 chain extends Chain | undefined,\n account extends Account | undefined = undefined,\n>(\n client: Client<Transport, chain, account>,\n args: EstimateGasParameters<chain>,\n): Promise<EstimateGasReturnType> {\n const { account: account_ = client.account, prepare = true } = args\n const account = account_ ? parseAccount(account_) : undefined\n\n const parameters = (() => {\n if (Array.isArray(prepare)) return prepare\n // Some RPC Providers do not compute versioned hashes from blobs. We will need\n // to compute them.\n if (account?.type !== 'local') return ['blobVersionedHashes']\n return undefined\n })()\n\n try {\n const to = await (async () => {\n // If `to` exists on the parameters, use that.\n if (args.to) return args.to\n\n // If no `to` exists, and we are sending a EIP-7702 transaction, use the\n // address of the first authorization in the list.\n if (args.authorizationList && args.authorizationList.length > 0)\n return await recoverAuthorizationAddress({\n authorization: args.authorizationList[0],\n }).catch(() => {\n throw new BaseError(\n '`to` is required. Could not infer from `authorizationList`',\n )\n })\n\n // Otherwise, we are sending a deployment transaction.\n return undefined\n })()\n\n const {\n accessList,\n authorizationList,\n blobs,\n blobVersionedHashes,\n blockNumber,\n blockTag,\n data,\n gas,\n gasPrice,\n maxFeePerBlobGas,\n maxFeePerGas,\n maxPriorityFeePerGas,\n nonce,\n value,\n stateOverride,\n ...rest\n } = prepare\n ? ((await prepareTransactionRequest(client, {\n ...args,\n parameters,\n to,\n } as PrepareTransactionRequestParameters)) as EstimateGasParameters)\n : args\n\n // If we get `gas` back from the prepared transaction request, which is\n // different from the `gas` we provided, it was likely filled by other means\n // during request preparation (e.g. `eth_fillTransaction` or `chain.transactionRequest.prepare`).\n // (e.g. `eth_fillTransaction` or `chain.transactionRequest.prepare`).\n if (gas && args.gas !== gas) return gas\n\n const blockNumberHex =\n typeof blockNumber === 'bigint' ? numberToHex(blockNumber) : undefined\n const block = blockNumberHex || blockTag\n\n const rpcStateOverride = serializeStateOverride(stateOverride)\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 {\n // Pick out extra data that might exist on the chain's transaction request type.\n ...extract(rest, { format: chainFormat }),\n account,\n accessList,\n authorizationList,\n blobs,\n blobVersionedHashes,\n data,\n gasPrice,\n maxFeePerBlobGas,\n maxFeePerGas,\n maxPriorityFeePerGas,\n nonce,\n to,\n value,\n } as TransactionRequest,\n 'estimateGas',\n )\n\n return BigInt(\n await client.request({\n method: 'eth_estimateGas',\n params: rpcStateOverride\n ? [\n request,\n block ?? client.experimental_blockTag ?? 'latest',\n rpcStateOverride,\n ]\n : block\n ? [request, block]\n : [request],\n }),\n )\n } catch (err) {\n throw getEstimateGasError(err as BaseError, {\n ...args,\n account,\n chain: client.chain,\n })\n }\n}\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","import type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray, Hex, Signature } from '../../types/misc.js'\nimport { type IsHexErrorType, isHex } from '../data/isHex.js'\nimport { size } from '../data/size.js'\nimport {\n type HexToNumberErrorType,\n hexToBigInt,\n hexToNumber,\n} from '../encoding/fromHex.js'\nimport { toHex } from '../encoding/toHex.js'\n\nexport type RecoverPublicKeyParameters = {\n hash: Hex | ByteArray\n signature: Hex | ByteArray | Signature\n}\n\nexport type RecoverPublicKeyReturnType = Hex\n\nexport type RecoverPublicKeyErrorType =\n | HexToNumberErrorType\n | IsHexErrorType\n | ErrorType\n\nexport async function recoverPublicKey({\n hash,\n signature,\n}: RecoverPublicKeyParameters): Promise<RecoverPublicKeyReturnType> {\n const hashHex = isHex(hash) ? hash : toHex(hash)\n\n const { secp256k1 } = await import('@noble/curves/secp256k1')\n const signature_ = (() => {\n // typeof signature: `Signature`\n if (typeof signature === 'object' && 'r' in signature && 's' in signature) {\n const { r, s, v, yParity } = signature\n const yParityOrV = Number(yParity ?? v)!\n const recoveryBit = toRecoveryBit(yParityOrV)\n return new secp256k1.Signature(\n hexToBigInt(r),\n hexToBigInt(s),\n ).addRecoveryBit(recoveryBit)\n }\n\n // typeof signature: `Hex | ByteArray`\n const signatureHex = isHex(signature) ? signature : toHex(signature)\n if (size(signatureHex) !== 65) throw new Error('invalid signature length')\n const yParityOrV = hexToNumber(`0x${signatureHex.slice(130)}`)\n const recoveryBit = toRecoveryBit(yParityOrV)\n return secp256k1.Signature.fromCompact(\n signatureHex.substring(2, 130),\n ).addRecoveryBit(recoveryBit)\n })()\n\n const publicKey = signature_\n .recoverPublicKey(hashHex.substring(2))\n .toHex(false)\n return `0x${publicKey}`\n}\n\nfunction toRecoveryBit(yParityOrV: number) {\n if (yParityOrV === 0 || yParityOrV === 1) return yParityOrV\n if (yParityOrV === 27) return 0\n if (yParityOrV === 28) return 1\n throw new Error('Invalid yParityOrV value')\n}\n","import type { Address } from 'abitype'\n\nimport { publicKeyToAddress } from '../../accounts/utils/publicKeyToAddress.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray, Hex, Signature } from '../../types/misc.js'\nimport { recoverPublicKey } from './recoverPublicKey.js'\n\nexport type RecoverAddressParameters = {\n hash: Hex | ByteArray\n signature: Hex | ByteArray | Signature\n}\n\nexport type RecoverAddressReturnType = Address\n\nexport type RecoverAddressErrorType = ErrorType\n\nexport async function recoverAddress({\n hash,\n signature,\n}: RecoverAddressParameters): Promise<RecoverAddressReturnType> {\n return publicKeyToAddress(await recoverPublicKey({ hash, signature }))\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { AuthorizationRequest } from '../../types/authorization.js'\nimport type { ByteArray, Hex } from '../../types/misc.js'\nimport { type ConcatHexErrorType, concatHex } from '../data/concat.js'\nimport { type HexToBytesErrorType, hexToBytes } from '../encoding/toBytes.js'\nimport { type NumberToHexErrorType, numberToHex } from '../encoding/toHex.js'\nimport { type ToRlpErrorType, toRlp } from '../encoding/toRlp.js'\nimport { type Keccak256ErrorType, keccak256 } from '../hash/keccak256.js'\n\ntype To = 'hex' | 'bytes'\n\nexport type HashAuthorizationParameters<to extends To> =\n AuthorizationRequest & {\n /** Output format. @default \"hex\" */\n to?: to | To | undefined\n }\n\nexport type HashAuthorizationReturnType<to extends To> =\n | (to extends 'bytes' ? ByteArray : never)\n | (to extends 'hex' ? Hex : never)\n\nexport type HashAuthorizationErrorType =\n | Keccak256ErrorType\n | ConcatHexErrorType\n | ToRlpErrorType\n | NumberToHexErrorType\n | HexToBytesErrorType\n | ErrorType\n\n/**\n * Computes an Authorization hash in [EIP-7702 format](https://eips.ethereum.org/EIPS/eip-7702): `keccak256('0x05' || rlp([chain_id, address, nonce]))`.\n */\nexport function hashAuthorization<to extends To = 'hex'>(\n parameters: HashAuthorizationParameters<to>,\n): HashAuthorizationReturnType<to> {\n const { chainId, nonce, to } = parameters\n const address = parameters.contractAddress ?? parameters.address\n const hash = keccak256(\n concatHex([\n '0x05',\n toRlp([\n chainId ? numberToHex(chainId) : '0x',\n address,\n nonce ? numberToHex(nonce) : '0x',\n ]),\n ]),\n )\n if (to === 'bytes') return hexToBytes(hash) as HashAuthorizationReturnType<to>\n return hash as HashAuthorizationReturnType<to>\n}\n","import { BaseError } from '../../errors/base.js'\nimport type { ErrorType } from '../../errors/utils.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 | readonly 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 as any)\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 type { Address } from 'abitype'\n\nimport type { ErrorType } from '../../errors/utils.js'\nimport type {\n Authorization,\n AuthorizationRequest,\n SignedAuthorization,\n} from '../../types/authorization.js'\nimport type { ByteArray, Hex, Signature } from '../../types/misc.js'\nimport type { OneOf } from '../../types/utils.js'\nimport {\n type RecoverAddressErrorType,\n recoverAddress,\n} from '../signature/recoverAddress.js'\nimport {\n type HashAuthorizationErrorType,\n hashAuthorization,\n} from './hashAuthorization.js'\n\nexport type RecoverAuthorizationAddressParameters<\n authorization extends OneOf<\n Authorization | AuthorizationRequest | SignedAuthorization\n > = OneOf<Authorization | AuthorizationRequest | SignedAuthorization>,\n //\n _signature = Hex | ByteArray | OneOf<Signature | SignedAuthorization>,\n> = {\n /**\n * The Authorization object.\n *\n * - If an unsigned `authorization` is provided, the `signature` property is required.\n * - If a signed `authorization` is provided, the `signature` property does not need to be provided.\n */\n authorization:\n | authorization\n | OneOf<Authorization | AuthorizationRequest | SignedAuthorization>\n} & (authorization extends SignedAuthorization\n ? {\n /** Signature of the Authorization. Not required if the `authorization` is signed. */\n signature?: _signature | undefined\n }\n : {\n /** Signature of the Authorization. Not required if the `authorization` is signed. */\n signature: _signature\n })\n\nexport type RecoverAuthorizationAddressReturnType = Address\n\nexport type RecoverAuthorizationAddressErrorType =\n | HashAuthorizationErrorType\n | RecoverAddressErrorType\n | ErrorType\n\nexport async function recoverAuthorizationAddress<\n const authorization extends OneOf<\n Authorization | AuthorizationRequest | SignedAuthorization\n >,\n>(\n parameters: RecoverAuthorizationAddressParameters<authorization>,\n): Promise<RecoverAuthorizationAddressReturnType> {\n const { authorization, signature } = parameters\n\n return recoverAddress({\n hash: hashAuthorization(authorization as AuthorizationRequest),\n signature: (signature ?? authorization) as Signature,\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 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>, 'account'> & {\n account?: Account | undefined\n chain?: Chain | undefined\n docsPath?: string | undefined\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 name: 'EstimateGasExecutionError',\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 | undefined\n chain?: Chain | undefined\n docsPath?: string | undefined\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 { Address } from 'abitype'\nimport 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 as 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 type { AccountNotFoundErrorType } from '../../errors/account.js'\nimport type { BaseError } from '../../errors/base.js'\nimport {\n Eip1559FeesNotSupportedError,\n MaxFeePerGasTooLowError,\n} from '../../errors/fee.js'\nimport type { DeriveAccount, GetAccountParameter } from '../../types/account.js'\nimport type { Block } from '../../types/block.js'\nimport type {\n Chain,\n DeriveChain,\n GetChainParameter,\n} from '../../types/chain.js'\nimport type { GetTransactionRequestKzgParameter } from '../../types/kzg.js'\nimport type {\n TransactionRequest,\n TransactionRequestEIP1559,\n TransactionRequestEIP2930,\n TransactionRequestEIP4844,\n TransactionRequestEIP7702,\n TransactionRequestLegacy,\n TransactionSerializable,\n} from '../../types/transaction.js'\nimport type {\n ExactPartial,\n IsNever,\n Prettify,\n UnionOmit,\n UnionRequiredBy,\n} from '../../types/utils.js'\nimport { blobsToCommitments } from '../../utils/blob/blobsToCommitments.js'\nimport { blobsToProofs } from '../../utils/blob/blobsToProofs.js'\nimport { commitmentsToVersionedHashes } from '../../utils/blob/commitmentsToVersionedHashes.js'\nimport { toBlobSidecars } from '../../utils/blob/toBlobSidecars.js'\nimport type { FormattedTransactionRequest } from '../../utils/formatters/transactionRequest.js'\nimport { getAction } from '../../utils/getAction.js'\nimport { LruMap } from '../../utils/lru.js'\nimport type { NonceManager } from '../../utils/nonceManager.js'\nimport {\n type AssertRequestErrorType,\n type AssertRequestParameters,\n assertRequest,\n} from '../../utils/transaction/assertRequest.js'\nimport {\n type GetTransactionType,\n getTransactionType,\n} from '../../utils/transaction/getTransactionType.js'\nimport {\n type FillTransactionErrorType,\n type FillTransactionParameters,\n fillTransaction,\n} from '../public/fillTransaction.js'\nimport { getChainId as getChainId_ } from '../public/getChainId.js'\n\nexport const defaultParameters = [\n 'blobVersionedHashes',\n 'chainId',\n 'fees',\n 'gas',\n 'nonce',\n 'type',\n] as const\n\n/** @internal */\nexport const eip1559NetworkCache = /*#__PURE__*/ new Map<string, boolean>()\n\n/** @internal */\nexport const supportsFillTransaction = /*#__PURE__*/ new LruMap<boolean>(128)\n\nexport type PrepareTransactionRequestParameterType =\n | 'blobVersionedHashes'\n | 'chainId'\n | 'fees'\n | 'gas'\n | 'nonce'\n | 'sidecars'\n | 'type'\ntype ParameterTypeToParameters<\n parameterType extends PrepareTransactionRequestParameterType,\n> = parameterType extends 'fees'\n ? 'maxFeePerGas' | 'maxPriorityFeePerGas' | 'gasPrice'\n : parameterType\n\nexport type PrepareTransactionRequestRequest<\n chain extends Chain | undefined = Chain | undefined,\n chainOverride extends Chain | undefined = Chain | undefined,\n ///\n _derivedChain extends Chain | undefined = DeriveChain<chain, chainOverride>,\n> = UnionOmit<FormattedTransactionRequest<_derivedChain>, 'from'> &\n GetTransactionRequestKzgParameter & {\n /**\n * Nonce manager to use for the transaction request.\n */\n nonceManager?: NonceManager | undefined\n /**\n * Parameters to prepare for the transaction request.\n *\n * @default ['blobVersionedHashes', 'chainId', 'fees', 'gas', 'nonce', 'type']\n */\n parameters?: readonly PrepareTransactionRequestParameterType[] | undefined\n }\n\nexport type PrepareTransactionRequestParameters<\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n chainOverride extends Chain | undefined = Chain | undefined,\n accountOverride extends Account | Address | undefined =\n | Account\n | Address\n | undefined,\n request extends PrepareTransactionRequestRequest<\n chain,\n chainOverride\n > = PrepareTransactionRequestRequest<chain, chainOverride>,\n> = request &\n GetAccountParameter<account, accountOverride, false, true> &\n GetChainParameter<chain, chainOverride> &\n GetTransactionRequestKzgParameter<request> & { chainId?: number | undefined }\n\nexport type PrepareTransactionRequestReturnType<\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n chainOverride extends Chain | undefined = Chain | undefined,\n accountOverride extends Account | Address | undefined =\n | Account\n | Address\n | undefined,\n request extends PrepareTransactionRequestRequest<\n chain,\n chainOverride\n > = PrepareTransactionRequestRequest<chain, chainOverride>,\n ///\n _derivedAccount extends Account | Address | undefined = DeriveAccount<\n account,\n accountOverride\n >,\n _derivedChain extends Chain | undefined = DeriveChain<chain, chainOverride>,\n _transactionType = request['type'] extends string | undefined\n ? request['type']\n : GetTransactionType<request> extends 'legacy'\n ? unknown\n : GetTransactionType<request>,\n _transactionRequest extends TransactionRequest =\n | (_transactionType extends 'legacy' ? TransactionRequestLegacy : never)\n | (_transactionType extends 'eip1559' ? TransactionRequestEIP1559 : never)\n | (_transactionType extends 'eip2930' ? TransactionRequestEIP2930 : never)\n | (_transactionType extends 'eip4844' ? TransactionRequestEIP4844 : never)\n | (_transactionType extends 'eip7702' ? TransactionRequestEIP7702 : never),\n> = Prettify<\n UnionRequiredBy<\n Extract<\n UnionOmit<FormattedTransactionRequest<_derivedChain>, 'from'> &\n (_derivedChain extends Chain\n ? { chain: _derivedChain }\n : { chain?: undefined }) &\n (_derivedAccount extends Account\n ? { account: _derivedAccount; from: Address }\n : { account?: undefined; from?: undefined }),\n IsNever<_transactionRequest> extends true\n ? unknown\n : ExactPartial<_transactionRequest>\n > & { chainId?: number | undefined },\n ParameterTypeToParameters<\n request['parameters'] extends readonly PrepareTransactionRequestParameterType[]\n ? request['parameters'][number]\n : (typeof defaultParameters)[number]\n >\n > &\n (unknown extends request['kzg'] ? {} : Pick<request, 'kzg'>)\n>\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\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 chain extends Chain | undefined,\n account extends Account | undefined,\n const request extends PrepareTransactionRequestRequest<chain, chainOverride>,\n accountOverride extends Account | Address | undefined = undefined,\n chainOverride extends Chain | undefined = undefined,\n>(\n client: Client<Transport, chain, account>,\n args: PrepareTransactionRequestParameters<\n chain,\n account,\n chainOverride,\n accountOverride,\n request\n >,\n): Promise<\n PrepareTransactionRequestReturnType<\n chain,\n account,\n chainOverride,\n accountOverride,\n request\n >\n> {\n let request = args as PrepareTransactionRequestParameters\n\n request.account ??= client.account\n request.parameters ??= defaultParameters\n\n const {\n account: account_,\n chain = client.chain,\n nonceManager,\n parameters,\n } = request\n\n const prepareTransactionRequest = (() => {\n if (typeof chain?.prepareTransactionRequest === 'function')\n return {\n fn: chain.prepareTransactionRequest,\n runAt: ['beforeFillTransaction'],\n }\n if (Array.isArray(chain?.prepareTransactionRequest))\n return {\n fn: chain.prepareTransactionRequest[0],\n runAt: chain.prepareTransactionRequest[1].runAt,\n }\n return undefined\n })()\n\n let chainId: number | undefined\n async function getChainId(): Promise<number> {\n if (chainId) return chainId\n if (typeof request.chainId !== 'undefined') return request.chainId\n if (chain) return chain.id\n const chainId_ = await getAction(client, getChainId_, 'getChainId')({})\n chainId = chainId_\n return chainId\n }\n\n const account = account_ ? parseAccount(account_) : account_\n\n let nonce = request.nonce\n if (\n parameters.includes('nonce') &&\n typeof nonce === 'undefined' &&\n account &&\n nonceManager\n ) {\n const chainId = await getChainId()\n nonce = await nonceManager.consume({\n address: account.address,\n chainId,\n client,\n })\n }\n\n if (\n prepareTransactionRequest?.fn &&\n prepareTransactionRequest.runAt?.includes('beforeFillTransaction')\n ) {\n request = await prepareTransactionRequest.fn(\n { ...request, chain },\n {\n phase: 'beforeFillTransaction',\n },\n )\n nonce ??= request.nonce\n }\n\n const attemptFill = (() => {\n // Do not attempt if blobs are provided.\n if (\n (parameters.includes('blobVersionedHashes') ||\n parameters.includes('sidecars')) &&\n request.kzg &&\n request.blobs\n )\n return false\n\n // Do not attempt if `eth_fillTransaction` is not supported.\n if (supportsFillTransaction.get(client.uid) === false) return false\n\n // Should attempt `eth_fillTransaction` if \"fees\" or \"gas\" are required to be populated,\n // otherwise, can just use the other individual calls.\n const shouldAttempt = ['fees', 'gas'].some((parameter) =>\n parameters.includes(parameter as PrepareTransactionRequestParameterType),\n )\n if (!shouldAttempt) return false\n\n // Check if `eth_fillTransaction` needs to be called.\n if (parameters.includes('chainId') && typeof request.chainId !== 'number')\n return true\n if (parameters.includes('nonce') && typeof nonce !== 'number') return true\n if (\n parameters.includes('fees') &&\n typeof request.gasPrice !== 'bigint' &&\n (typeof request.maxFeePerGas !== 'bigint' ||\n typeof (request as any).maxPriorityFeePerGas !== 'bigint')\n )\n return true\n if (parameters.includes('gas') && typeof request.gas !== 'bigint')\n return true\n return false\n })()\n\n const fillResult = attemptFill\n ? await getAction(\n client,\n fillTransaction,\n 'fillTransaction',\n )({ ...request, nonce } as FillTransactionParameters)\n .then((result) => {\n const {\n chainId,\n from,\n gas,\n gasPrice,\n nonce,\n maxFeePerBlobGas,\n maxFeePerGas,\n maxPriorityFeePerGas,\n type,\n ...rest\n } = result.transaction\n supportsFillTransaction.set(client.uid, true)\n return {\n ...request,\n ...(from ? { from } : {}),\n ...(type ? { type } : {}),\n ...(typeof chainId !== 'undefined' ? { chainId } : {}),\n ...(typeof gas !== 'undefined' ? { gas } : {}),\n ...(typeof gasPrice !== 'undefined' ? { gasPrice } : {}),\n ...(typeof nonce !== 'undefined' ? { nonce } : {}),\n ...(typeof maxFeePerBlobGas !== 'undefined'\n ? { maxFeePerBlobGas }\n : {}),\n ...(typeof maxFeePerGas !== 'undefined' ? { maxFeePerGas } : {}),\n ...(typeof maxPriorityFeePerGas !== 'undefined'\n ? { maxPriorityFeePerGas }\n : {}),\n ...('nonceKey' in rest && typeof rest.nonceKey !== 'undefined'\n ? { nonceKey: rest.nonceKey }\n : {}),\n }\n })\n .catch((e) => {\n const error = e as FillTransactionErrorType\n\n if (error.name !== 'TransactionExecutionError') return request\n\n const unsupported = error.walk?.((e) => {\n const error = e as BaseError\n return (\n error.name === 'MethodNotFoundRpcError' ||\n error.name === 'MethodNotSupportedRpcError'\n )\n })\n if (unsupported) supportsFillTransaction.set(client.uid, false)\n\n return request\n })\n : request\n\n nonce ??= fillResult.nonce\n\n request = {\n ...(fillResult as any),\n ...(account ? { from: account?.address } : {}),\n ...(nonce ? { nonce } : {}),\n }\n const { blobs, gas, kzg, type } = request\n\n if (\n prepareTransactionRequest?.fn &&\n prepareTransactionRequest.runAt?.includes('beforeFillParameters')\n ) {\n request = await prepareTransactionRequest.fn(\n { ...request, chain },\n {\n phase: 'beforeFillParameters',\n },\n )\n }\n\n let block: Block | undefined\n async function getBlock(): Promise<Block> {\n if (block) return block\n block = await getAction(\n client,\n getBlock_,\n 'getBlock',\n )({ blockTag: 'latest' })\n return block\n }\n\n if (\n parameters.includes('nonce') &&\n typeof nonce === 'undefined' &&\n account &&\n !nonceManager\n )\n request.nonce = await getAction(\n client,\n getTransactionCount,\n 'getTransactionCount',\n )({\n address: account.address,\n blockTag: 'pending',\n })\n\n if (\n (parameters.includes('blobVersionedHashes') ||\n parameters.includes('sidecars')) &&\n blobs &&\n kzg\n ) {\n const commitments = blobsToCommitments({ blobs, kzg })\n\n if (parameters.includes('blobVersionedHashes')) {\n const versionedHashes = commitmentsToVersionedHashes({\n commitments,\n to: 'hex',\n })\n request.blobVersionedHashes = versionedHashes\n }\n if (parameters.includes('sidecars')) {\n const proofs = blobsToProofs({ blobs, commitments, kzg })\n const sidecars = toBlobSidecars({\n blobs,\n commitments,\n proofs,\n to: 'hex',\n })\n request.sidecars = sidecars\n }\n }\n\n if (parameters.includes('chainId')) request.chainId = await getChainId()\n\n if (\n (parameters.includes('fees') || parameters.includes('type')) &&\n typeof type === 'undefined'\n ) {\n try {\n request.type = getTransactionType(\n request as TransactionSerializable,\n ) as any\n } catch {\n let isEip1559Network = eip1559NetworkCache.get(client.uid)\n if (typeof isEip1559Network === 'undefined') {\n const block = await getBlock()\n isEip1559Network = typeof block?.baseFeePerGas === 'bigint'\n eip1559NetworkCache.set(client.uid, isEip1559Network)\n }\n request.type = isEip1559Network ? 'eip1559' : 'legacy'\n }\n }\n\n if (parameters.includes('fees')) {\n // TODO(4844): derive blob base fees once https://github.com/ethereum/execution-apis/pull/486 is merged.\n\n if (request.type !== 'legacy' && request.type !== 'eip2930') {\n // EIP-1559 fees\n if (\n typeof request.maxFeePerGas === 'undefined' ||\n typeof request.maxPriorityFeePerGas === 'undefined'\n ) {\n const block = await getBlock()\n const { maxFeePerGas, maxPriorityFeePerGas } =\n await internal_estimateFeesPerGas(client, {\n block: block as Block,\n chain,\n request: request as PrepareTransactionRequestParameters,\n })\n\n if (\n typeof request.maxPriorityFeePerGas === 'undefined' &&\n request.maxFeePerGas &&\n request.maxFeePerGas < maxPriorityFeePerGas\n )\n throw new MaxFeePerGasTooLowError({\n maxPriorityFeePerGas,\n })\n\n request.maxPriorityFeePerGas = maxPriorityFeePerGas\n request.maxFeePerGas = maxFeePerGas\n }\n } else {\n // Legacy fees\n if (\n typeof request.maxFeePerGas !== 'undefined' ||\n typeof request.maxPriorityFeePerGas !== 'undefined'\n )\n throw new Eip1559FeesNotSupportedError()\n\n if (typeof request.gasPrice === 'undefined') {\n const block = await getBlock()\n const { gasPrice: gasPrice_ } = await internal_estimateFeesPerGas(\n client,\n {\n block: block as Block,\n chain,\n request: request as PrepareTransactionRequestParameters,\n type: 'legacy',\n },\n )\n request.gasPrice = gasPrice_\n }\n }\n }\n\n if (parameters.includes('gas') && typeof gas === 'undefined')\n request.gas = await getAction(\n client,\n estimateGas,\n 'estimateGas',\n )({\n ...request,\n account,\n prepare: account?.type === 'local' ? [] : ['blobVersionedHashes'],\n } as EstimateGasParameters)\n\n if (\n prepareTransactionRequest?.fn &&\n prepareTransactionRequest.runAt?.includes('afterFillParameters')\n )\n request = await prepareTransactionRequest.fn(\n { ...request, chain },\n {\n phase: 'afterFillParameters',\n },\n )\n\n assertRequest(request as AssertRequestParameters)\n\n delete request.parameters\n\n return request as any\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 constructor() {\n super('`baseFeeMultiplier` must be greater than 1.', {\n name: 'BaseFeeScalarError',\n })\n }\n}\n\nexport type Eip1559FeesNotSupportedErrorType = Eip1559FeesNotSupportedError & {\n name: 'Eip1559FeesNotSupportedError'\n}\nexport class Eip1559FeesNotSupportedError extends BaseError {\n constructor() {\n super('Chain does not support EIP-1559 fees.', {\n name: 'Eip1559FeesNotSupportedError',\n })\n }\n}\n\nexport type MaxFeePerGasTooLowErrorType = MaxFeePerGasTooLowError & {\n name: 'MaxFeePerGasTooLowError'\n}\nexport class MaxFeePerGasTooLowError extends BaseError {\n constructor({ maxPriorityFeePerGas }: { maxPriorityFeePerGas: bigint }) {\n super(\n `\\`maxFeePerGas\\` cannot be less than the \\`maxPriorityFeePerGas\\` (${formatGwei(\n maxPriorityFeePerGas,\n )} gwei).`,\n { name: 'MaxFeePerGasTooLowError' },\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 {\n Chain,\n ChainFeesFnParameters,\n GetChainParameter,\n} 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> = GetChainParameter<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#fees-defaultpriorityfee) if set.\n *\n * - Docs: https://viem.sh/docs/actions/public/estimateMaxPriorityFeePerGas\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?:\n | EstimateMaxPriorityFeePerGasParameters<chain, chainOverride>\n | undefined,\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 | undefined\n request?:\n | PrepareTransactionRequestParameters<\n chain,\n Account | undefined,\n chainOverride\n >\n | undefined\n },\n): Promise<EstimateMaxPriorityFeePerGasReturnType> {\n const { block: block_, chain = client.chain, request } = args || {}\n\n try {\n const maxPriorityFeePerGas =\n chain?.fees?.maxPriorityFeePerGas ?? chain?.fees?.defaultPriorityFee\n\n if (typeof maxPriorityFeePerGas === 'function') {\n const block =\n block_ || (await getAction(client, getBlock, 'getBlock')({}))\n const maxPriorityFeePerGas_ = await maxPriorityFeePerGas({\n block,\n client,\n request,\n } as ChainFeesFnParameters)\n if (maxPriorityFeePerGas_ === null) throw new Error()\n return maxPriorityFeePerGas_\n }\n\n if (typeof maxPriorityFeePerGas !== 'undefined') return maxPriorityFeePerGas\n\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 constructor({\n blockHash,\n blockNumber,\n }: {\n blockHash?: Hash | undefined\n blockNumber?: bigint | undefined\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.`, { name: 'BlockNotFoundError' })\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 { Prettify } 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 FormattedBlock,\n formatBlock,\n} from '../../utils/formatters/block.js'\n\nexport type GetBlockParameters<\n includeTransactions extends boolean = false,\n blockTag extends BlockTag = 'latest',\n> = {\n /** Whether or not to include transaction data in the response. */\n includeTransactions?: includeTransactions | undefined\n} & (\n | {\n /** Hash of the block. */\n blockHash?: Hash | undefined\n blockNumber?: undefined\n blockTag?: undefined\n }\n | {\n blockHash?: undefined\n /** The block number. */\n blockNumber?: bigint | undefined\n blockTag?: undefined\n }\n | {\n blockHash?: undefined\n blockNumber?: undefined\n /**\n * The block tag.\n * @default 'latest'\n */\n blockTag?: blockTag | BlockTag | undefined\n }\n)\n\nexport type GetBlockReturnType<\n chain extends Chain | undefined = undefined,\n includeTransactions extends boolean = false,\n blockTag extends BlockTag = 'latest',\n> = Prettify<FormattedBlock<chain, includeTransactions, blockTag>>\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\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 chain extends Chain | undefined,\n account extends Account | undefined,\n includeTransactions extends boolean = false,\n blockTag extends BlockTag = 'latest',\n>(\n client: Client<Transport, chain, account>,\n {\n blockHash,\n blockNumber,\n blockTag = client.experimental_blockTag ?? 'latest',\n includeTransactions: includeTransactions_,\n }: GetBlockParameters<includeTransactions, blockTag> = {},\n): Promise<GetBlockReturnType<chain, includeTransactions, blockTag>> {\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 {\n method: 'eth_getBlockByHash',\n params: [blockHash, includeTransactions],\n },\n { dedupe: true },\n )\n } else {\n block = await client.request(\n {\n method: 'eth_getBlockByNumber',\n params: [blockNumberHex || blockTag, includeTransactions],\n },\n { dedupe: Boolean(blockNumberHex) },\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, 'getBlock')\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { Block, BlockTag } from '../../types/block.js'\nimport type {\n Chain,\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 { ExactPartial, 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 chain extends Chain | undefined = undefined,\n includeTransactions extends boolean = boolean,\n blockTag extends BlockTag = BlockTag,\n _FormatterReturnType = ExtractChainFormatterReturnType<\n chain,\n 'block',\n Block<bigint, includeTransactions>\n >,\n _ExcludedPendingDependencies extends string = BlockPendingDependencies &\n ExtractChainFormatterExclude<chain, 'block'>,\n _Formatted = Omit<_FormatterReturnType, BlockPendingDependencies> & {\n [_key in _ExcludedPendingDependencies]: never\n } & Pick<\n Block<bigint, includeTransactions, blockTag>,\n BlockPendingDependencies\n >,\n _Transactions = includeTransactions extends true\n ? Prettify<FormattedTransaction<chain, blockTag>>[]\n : Hash[],\n> = Omit<_Formatted, 'transactions'> & {\n transactions: _Transactions\n}\n\nexport type FormatBlockErrorType = ErrorType\n\nexport function formatBlock(\n block: ExactPartial<RpcBlock>,\n _?: string | undefined,\n) {\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 blobGasUsed: block.blobGasUsed ? BigInt(block.blobGasUsed) : undefined,\n difficulty: block.difficulty ? BigInt(block.difficulty) : undefined,\n excessBlobGas: block.excessBlobGas\n ? BigInt(block.excessBlobGas)\n : 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 { SignedAuthorizationList } from '../../types/authorization.js'\nimport type { BlockTag } from '../../types/block.js'\nimport type {\n Chain,\n ExtractChainFormatterExclude,\n ExtractChainFormatterReturnType,\n} from '../../types/chain.js'\nimport type { Hex } from '../../types/misc.js'\nimport type { RpcAuthorizationList, RpcTransaction } from '../../types/rpc.js'\nimport type { Transaction, TransactionType } from '../../types/transaction.js'\nimport type { ExactPartial, UnionLooseOmit } 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 chain extends Chain | undefined = undefined,\n blockTag extends BlockTag = BlockTag,\n _FormatterReturnType = ExtractChainFormatterReturnType<\n chain,\n 'transaction',\n Transaction\n >,\n _ExcludedPendingDependencies extends string = TransactionPendingDependencies &\n ExtractChainFormatterExclude<chain, 'transaction'>,\n> = UnionLooseOmit<_FormatterReturnType, TransactionPendingDependencies> & {\n [_K in _ExcludedPendingDependencies]: never\n} & Pick<\n Transaction<bigint, number, blockTag extends 'pending' ? true : false>,\n TransactionPendingDependencies\n >\n\nexport const transactionType = {\n '0x0': 'legacy',\n '0x1': 'eip2930',\n '0x2': 'eip1559',\n '0x3': 'eip4844',\n '0x4': 'eip7702',\n} as const satisfies Record<Hex, TransactionType>\n\nexport type FormatTransactionErrorType = ErrorType\n\nexport function formatTransaction(\n transaction: ExactPartial<RpcTransaction>,\n _?: string | undefined,\n) {\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 maxFeePerBlobGas: transaction.maxFeePerBlobGas\n ? BigInt(transaction.maxFeePerBlobGas)\n : 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\n ? (transactionType as any)[transaction.type]\n : 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 if (transaction.authorizationList)\n transaction_.authorizationList = formatAuthorizationList(\n transaction.authorizationList,\n )\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_.maxFeePerBlobGas\n delete transaction_.maxFeePerGas\n delete transaction_.maxPriorityFeePerGas\n delete transaction_.yParity\n }\n if (transaction_.type === 'eip2930') {\n delete transaction_.maxFeePerBlobGas\n delete transaction_.maxFeePerGas\n delete transaction_.maxPriorityFeePerGas\n }\n if (transaction_.type === 'eip1559') delete transaction_.maxFeePerBlobGas\n\n return transaction_\n}\n\nexport type DefineTransactionErrorType = DefineFormatterErrorType | ErrorType\n\nexport const defineTransaction = /*#__PURE__*/ defineFormatter(\n 'transaction',\n formatTransaction,\n)\n\n//////////////////////////////////////////////////////////////////////////////\n\nfunction formatAuthorizationList(\n authorizationList: RpcAuthorizationList,\n): SignedAuthorizationList {\n return authorizationList.map((authorization) => ({\n address: (authorization as any).address,\n chainId: Number(authorization.chainId),\n nonce: Number(authorization.nonce),\n r: authorization.r,\n s: authorization.s,\n yParity: Number(authorization.yParity),\n })) as SignedAuthorizationList\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\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 chain extends Chain | undefined,\n account extends Account | undefined,\n>(client: Client<Transport, chain, account>): 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 { Account } from '../../types/account.js'\nimport type { Block } from '../../types/block.js'\nimport type {\n Chain,\n ChainEstimateFeesPerGasFnParameters,\n ChainFeesFnParameters,\n GetChainParameter,\n} 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 | undefined\n} & GetChainParameter<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#fees-estimatefeespergas) if set.\n *\n * - Docs: https://viem.sh/docs/actions/public/estimateFeesPerGas\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> | undefined,\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 | undefined\n request?: PrepareTransactionRequestParameters<Chain, Account> | undefined\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 const fees = (await 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 (fees !== null) return fees\n }\n\n if (type === 'eip1559') {\n if (typeof block.baseFeePerGas !== 'bigint')\n throw new Eip1559FeesNotSupportedError()\n\n const maxPriorityFeePerGas =\n typeof request?.maxPriorityFeePerGas === 'bigint'\n ? request.maxPriorityFeePerGas\n : await internal_estimateMaxPriorityFeePerGas(\n client as Client<Transport, Chain>,\n {\n block: block as 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 | undefined\n blockTag?: undefined\n }\n | {\n blockNumber?: undefined\n /** The block tag. Defaults to 'latest'. */\n blockTag?: BlockTag | undefined\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#transaction) an Account has sent.\n *\n * - Docs: https://viem.sh/docs/actions/public/getTransactionCount\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 chain extends Chain | undefined,\n account extends Account | undefined,\n>(\n client: Client<Transport, chain, account>,\n { address, blockTag = 'latest', blockNumber }: GetTransactionCountParameters,\n): Promise<GetTransactionCountReturnType> {\n const count = await client.request(\n {\n method: 'eth_getTransactionCount',\n params: [\n address,\n typeof blockNumber === 'bigint' ? numberToHex(blockNumber) : blockTag,\n ],\n },\n {\n dedupe: Boolean(blockNumber),\n },\n )\n return hexToNumber(count)\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { Kzg } from '../../types/kzg.js'\nimport type { ByteArray, Hex } from '../../types/misc.js'\nimport { type HexToBytesErrorType, hexToBytes } from '../encoding/toBytes.js'\nimport { type BytesToHexErrorType, bytesToHex } from '../encoding/toHex.js'\n\ntype To = 'hex' | 'bytes'\n\nexport type BlobsToCommitmentsParameters<\n blobs extends readonly ByteArray[] | readonly Hex[] =\n | readonly ByteArray[]\n | readonly Hex[],\n to extends To | undefined = undefined,\n> = {\n /** Blobs to transform into commitments. */\n blobs: blobs | readonly ByteArray[] | readonly Hex[]\n /** KZG implementation. */\n kzg: Pick<Kzg, 'blobToKzgCommitment'>\n /** Return type. */\n to?: to | To | undefined\n}\n\nexport type BlobsToCommitmentsReturnType<to extends To> =\n | (to extends 'bytes' ? readonly ByteArray[] : never)\n | (to extends 'hex' ? readonly Hex[] : never)\n\nexport type BlobsToCommitmentsErrorType =\n | HexToBytesErrorType\n | BytesToHexErrorType\n | ErrorType\n\n/**\n * Compute commitments from a list of blobs.\n *\n * @example\n * ```ts\n * import { blobsToCommitments, toBlobs } from 'viem'\n * import { kzg } from './kzg'\n *\n * const blobs = toBlobs({ data: '0x1234' })\n * const commitments = blobsToCommitments({ blobs, kzg })\n * ```\n */\nexport function blobsToCommitments<\n const blobs extends readonly ByteArray[] | readonly Hex[],\n to extends To =\n | (blobs extends readonly Hex[] ? 'hex' : never)\n | (blobs extends readonly ByteArray[] ? 'bytes' : never),\n>(\n parameters: BlobsToCommitmentsParameters<blobs, to>,\n): BlobsToCommitmentsReturnType<to> {\n const { kzg } = parameters\n\n const to =\n parameters.to ?? (typeof parameters.blobs[0] === 'string' ? 'hex' : 'bytes')\n const blobs = (\n typeof parameters.blobs[0] === 'string'\n ? parameters.blobs.map((x) => hexToBytes(x as any))\n : parameters.blobs\n ) as ByteArray[]\n\n const commitments: ByteArray[] = []\n for (const blob of blobs)\n commitments.push(Uint8Array.from(kzg.blobToKzgCommitment(blob)))\n\n return (to === 'bytes'\n ? commitments\n : commitments.map((x) =>\n bytesToHex(x),\n )) as {} as BlobsToCommitmentsReturnType<to>\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { Kzg } from '../../types/kzg.js'\nimport type { ByteArray, Hex } from '../../types/misc.js'\nimport { type HexToBytesErrorType, hexToBytes } from '../encoding/toBytes.js'\nimport { type BytesToHexErrorType, bytesToHex } from '../encoding/toHex.js'\n\ntype To = 'hex' | 'bytes'\n\nexport type blobsToProofsParameters<\n blobs extends readonly ByteArray[] | readonly Hex[],\n commitments extends readonly ByteArray[] | readonly Hex[],\n to extends To =\n | (blobs extends readonly Hex[] ? 'hex' : never)\n | (blobs extends readonly ByteArray[] ? 'bytes' : never),\n ///\n _blobsType =\n | (blobs extends readonly Hex[] ? readonly Hex[] : never)\n | (blobs extends readonly ByteArray[] ? readonly ByteArray[] : never),\n> = {\n /** Blobs to transform into proofs. */\n blobs: blobs\n /** Commitments for the blobs. */\n commitments: commitments &\n (commitments extends _blobsType\n ? {}\n : `commitments must be the same type as blobs`)\n /** KZG implementation. */\n kzg: Pick<Kzg, 'computeBlobKzgProof'>\n /** Return type. */\n to?: to | To | undefined\n}\n\nexport type blobsToProofsReturnType<to extends To> =\n | (to extends 'bytes' ? ByteArray[] : never)\n | (to extends 'hex' ? Hex[] : never)\n\nexport type blobsToProofsErrorType =\n | BytesToHexErrorType\n | HexToBytesErrorType\n | ErrorType\n\n/**\n * Compute the proofs for a list of blobs and their commitments.\n *\n * @example\n * ```ts\n * import {\n * blobsToCommitments,\n * toBlobs\n * } from 'viem'\n * import { kzg } from './kzg'\n *\n * const blobs = toBlobs({ data: '0x1234' })\n * const commitments = blobsToCommitments({ blobs, kzg })\n * const proofs = blobsToProofs({ blobs, commitments, kzg })\n * ```\n */\nexport function blobsToProofs<\n const blobs extends readonly ByteArray[] | readonly Hex[],\n const commitments extends readonly ByteArray[] | readonly Hex[],\n to extends To =\n | (blobs extends readonly Hex[] ? 'hex' : never)\n | (blobs extends readonly ByteArray[] ? 'bytes' : never),\n>(\n parameters: blobsToProofsParameters<blobs, commitments, to>,\n): blobsToProofsReturnType<to> {\n const { kzg } = parameters\n\n const to =\n parameters.to ?? (typeof parameters.blobs[0] === 'string' ? 'hex' : 'bytes')\n\n const blobs = (\n typeof parameters.blobs[0] === 'string'\n ? parameters.blobs.map((x) => hexToBytes(x as any))\n : parameters.blobs\n ) as ByteArray[]\n const commitments = (\n typeof parameters.commitments[0] === 'string'\n ? parameters.commitments.map((x) => hexToBytes(x as any))\n : parameters.commitments\n ) as ByteArray[]\n\n const proofs: ByteArray[] = []\n for (let i = 0; i < blobs.length; i++) {\n const blob = blobs[i]\n const commitment = commitments[i]\n proofs.push(Uint8Array.from(kzg.computeBlobKzgProof(blob, commitment)))\n }\n\n return (to === 'bytes'\n ? proofs\n : proofs.map((x) => bytesToHex(x))) as {} as blobsToProofsReturnType<to>\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray, Hex } from '../../types/misc.js'\nimport { type BytesToHexErrorType, bytesToHex } from '../encoding/toHex.js'\nimport { type Sha256ErrorType, sha256 } from '../hash/sha256.js'\n\ntype To = 'hex' | 'bytes'\n\nexport type CommitmentToVersionedHashParameters<\n commitment extends Uint8Array | Hex = Uint8Array | Hex,\n to extends To | undefined = undefined,\n> = {\n /** Commitment from blob. */\n commitment: commitment | Uint8Array | Hex\n /** Return type. */\n to?: to | To | undefined\n /** Version to tag onto the hash. */\n version?: number | undefined\n}\n\nexport type CommitmentToVersionedHashReturnType<to extends To> =\n | (to extends 'bytes' ? ByteArray : never)\n | (to extends 'hex' ? Hex : never)\n\nexport type CommitmentToVersionedHashErrorType =\n | Sha256ErrorType\n | BytesToHexErrorType\n | ErrorType\n\n/**\n * Transform a commitment to it's versioned hash.\n *\n * @example\n * ```ts\n * import {\n * blobsToCommitments,\n * commitmentToVersionedHash,\n * toBlobs\n * } from 'viem'\n * import { kzg } from './kzg'\n *\n * const blobs = toBlobs({ data: '0x1234' })\n * const [commitment] = blobsToCommitments({ blobs, kzg })\n * const versionedHash = commitmentToVersionedHash({ commitment })\n * ```\n */\nexport function commitmentToVersionedHash<\n const commitment extends Hex | ByteArray,\n to extends To =\n | (commitment extends Hex ? 'hex' : never)\n | (commitment extends ByteArray ? 'bytes' : never),\n>(\n parameters: CommitmentToVersionedHashParameters<commitment, to>,\n): CommitmentToVersionedHashReturnType<to> {\n const { commitment, version = 1 } = parameters\n const to = parameters.to ?? (typeof commitment === 'string' ? 'hex' : 'bytes')\n\n const versionedHash = sha256(commitment, 'bytes')\n versionedHash.set([version], 0)\n return (\n to === 'bytes' ? versionedHash : bytesToHex(versionedHash)\n ) as CommitmentToVersionedHashReturnType<to>\n}\n","/**\n * SHA2-256 a.k.a. sha256. In JS, it is the fastest hash, even faster than Blake3.\n *\n * To break sha256 using birthday attack, attackers need to try 2^128 hashes.\n * BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.\n *\n * Check out [FIPS 180-4](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf).\n * @module\n * @deprecated\n */\nimport {\n SHA224 as SHA224n,\n sha224 as sha224n,\n SHA256 as SHA256n,\n sha256 as sha256n,\n} from './sha2.ts';\n/** @deprecated Use import from `noble/hashes/sha2` module */\nexport const SHA256: typeof SHA256n = SHA256n;\n/** @deprecated Use import from `noble/hashes/sha2` module */\nexport const sha256: typeof sha256n = sha256n;\n/** @deprecated Use import from `noble/hashes/sha2` module */\nexport const SHA224: typeof SHA224n = SHA224n;\n/** @deprecated Use import from `noble/hashes/sha2` module */\nexport const sha224: typeof sha224n = sha224n;\n","import { sha256 as noble_sha256 } from '@noble/hashes/sha256'\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 Sha256Hash<to extends To> =\n | (to extends 'bytes' ? ByteArray : never)\n | (to extends 'hex' ? Hex : never)\n\nexport type Sha256ErrorType =\n | IsHexErrorType\n | ToBytesErrorType\n | ToHexErrorType\n | ErrorType\n\nexport function sha256<to extends To = 'hex'>(\n value: Hex | ByteArray,\n to_?: to | undefined,\n): Sha256Hash<to> {\n const to = to_ || 'hex'\n const bytes = noble_sha256(\n isHex(value, { strict: false }) ? toBytes(value) : value,\n )\n if (to === 'bytes') return bytes as Sha256Hash<to>\n return toHex(bytes) as Sha256Hash<to>\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray, Hex } from '../../types/misc.js'\nimport {\n type CommitmentToVersionedHashErrorType,\n commitmentToVersionedHash,\n} from './commitmentToVersionedHash.js'\n\ntype To = 'hex' | 'bytes'\n\nexport type CommitmentsToVersionedHashesParameters<\n commitments extends readonly Uint8Array[] | readonly Hex[] =\n | readonly Uint8Array[]\n | readonly Hex[],\n to extends To | undefined = undefined,\n> = {\n /** Commitments from blobs. */\n commitments: commitments | readonly Uint8Array[] | readonly Hex[]\n /** Return type. */\n to?: to | To | undefined\n /** Version to tag onto the hashes. */\n version?: number | undefined\n}\n\nexport type CommitmentsToVersionedHashesReturnType<to extends To> =\n | (to extends 'bytes' ? readonly ByteArray[] : never)\n | (to extends 'hex' ? readonly Hex[] : never)\n\nexport type CommitmentsToVersionedHashesErrorType =\n | CommitmentToVersionedHashErrorType\n | ErrorType\n\n/**\n * Transform a list of commitments to their versioned hashes.\n *\n * @example\n * ```ts\n * import {\n * blobsToCommitments,\n * commitmentsToVersionedHashes,\n * toBlobs\n * } from 'viem'\n * import { kzg } from './kzg'\n *\n * const blobs = toBlobs({ data: '0x1234' })\n * const commitments = blobsToCommitments({ blobs, kzg })\n * const versionedHashes = commitmentsToVersionedHashes({ commitments })\n * ```\n */\nexport function commitmentsToVersionedHashes<\n const commitments extends readonly Uint8Array[] | readonly Hex[],\n to extends To =\n | (commitments extends readonly Hex[] ? 'hex' : never)\n | (commitments extends readonly ByteArray[] ? 'bytes' : never),\n>(\n parameters: CommitmentsToVersionedHashesParameters<commitments, to>,\n): CommitmentsToVersionedHashesReturnType<to> {\n const { commitments, version } = parameters\n\n const to =\n parameters.to ?? (typeof commitments[0] === 'string' ? 'hex' : 'bytes')\n\n const hashes: Uint8Array[] | Hex[] = []\n for (const commitment of commitments) {\n hashes.push(\n commitmentToVersionedHash({\n commitment,\n to,\n version,\n }) as any,\n )\n }\n return hashes as any\n}\n","// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-4844.md#parameters\n\n/** Blob limit per transaction. */\nconst blobsPerTransaction = 6\n\n/** The number of bytes in a BLS scalar field element. */\nexport const bytesPerFieldElement = 32\n\n/** The number of field elements in a blob. */\nexport const fieldElementsPerBlob = 4096\n\n/** The number of bytes in a blob. */\nexport const bytesPerBlob = bytesPerFieldElement * fieldElementsPerBlob\n\n/** Blob bytes limit per transaction. */\nexport const maxBytesPerTransaction =\n bytesPerBlob * blobsPerTransaction -\n // terminator byte (0x80).\n 1 -\n // zero byte (0x00) appended to each field element.\n 1 * fieldElementsPerBlob * blobsPerTransaction\n","// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-4844.md#parameters\n\nexport const versionedHashVersionKzg = 1\n","import { versionedHashVersionKzg } from '../constants/kzg.js'\nimport type { Hash } from '../types/misc.js'\n\nimport { BaseError } from './base.js'\n\nexport type BlobSizeTooLargeErrorType = BlobSizeTooLargeError & {\n name: 'BlobSizeTooLargeError'\n}\nexport class BlobSizeTooLargeError extends BaseError {\n constructor({ maxSize, size }: { maxSize: number; size: number }) {\n super('Blob size is too large.', {\n metaMessages: [`Max: ${maxSize} bytes`, `Given: ${size} bytes`],\n name: 'BlobSizeTooLargeError',\n })\n }\n}\n\nexport type EmptyBlobErrorType = EmptyBlobError & {\n name: 'EmptyBlobError'\n}\nexport class EmptyBlobError extends BaseError {\n constructor() {\n super('Blob data must not be empty.', { name: 'EmptyBlobError' })\n }\n}\n\nexport type InvalidVersionedHashSizeErrorType =\n InvalidVersionedHashSizeError & {\n name: 'InvalidVersionedHashSizeError'\n }\nexport class InvalidVersionedHashSizeError extends BaseError {\n constructor({\n hash,\n size,\n }: {\n hash: Hash\n size: number\n }) {\n super(`Versioned hash \"${hash}\" size is invalid.`, {\n metaMessages: ['Expected: 32', `Received: ${size}`],\n name: 'InvalidVersionedHashSizeError',\n })\n }\n}\n\nexport type InvalidVersionedHashVersionErrorType =\n InvalidVersionedHashVersionError & {\n name: 'InvalidVersionedHashVersionError'\n }\nexport class InvalidVersionedHashVersionError extends BaseError {\n constructor({\n hash,\n version,\n }: {\n hash: Hash\n version: number\n }) {\n super(`Versioned hash \"${hash}\" version is invalid.`, {\n metaMessages: [\n `Expected: ${versionedHashVersionKzg}`,\n `Received: ${version}`,\n ],\n name: 'InvalidVersionedHashVersionError',\n })\n }\n}\n","import {\n bytesPerBlob,\n bytesPerFieldElement,\n fieldElementsPerBlob,\n maxBytesPerTransaction,\n} from '../../constants/blob.js'\nimport {\n BlobSizeTooLargeError,\n type BlobSizeTooLargeErrorType,\n EmptyBlobError,\n type EmptyBlobErrorType,\n} from '../../errors/blob.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray, Hex } from '../../types/misc.js'\nimport { type CreateCursorErrorType, createCursor } from '../cursor.js'\nimport { type SizeErrorType, size } from '../data/size.js'\nimport { type HexToBytesErrorType, hexToBytes } from '../encoding/toBytes.js'\nimport { type BytesToHexErrorType, bytesToHex } from '../encoding/toHex.js'\n\ntype To = 'hex' | 'bytes'\n\nexport type ToBlobsParameters<\n data extends Hex | ByteArray = Hex | ByteArray,\n to extends To | undefined = undefined,\n> = {\n /** Data to transform to a blob. */\n data: data | Hex | ByteArray\n /** Return type. */\n to?: to | To | undefined\n}\n\nexport type ToBlobsReturnType<to extends To> =\n | (to extends 'bytes' ? readonly ByteArray[] : never)\n | (to extends 'hex' ? readonly Hex[] : never)\n\nexport type ToBlobsErrorType =\n | BlobSizeTooLargeErrorType\n | BytesToHexErrorType\n | CreateCursorErrorType\n | EmptyBlobErrorType\n | HexToBytesErrorType\n | SizeErrorType\n | ErrorType\n\n/**\n * Transforms arbitrary data to blobs.\n *\n * @example\n * ```ts\n * import { toBlobs, stringToHex } from 'viem'\n *\n * const blobs = toBlobs({ data: stringToHex('hello world') })\n * ```\n */\nexport function toBlobs<\n const data extends Hex | ByteArray,\n to extends To =\n | (data extends Hex ? 'hex' : never)\n | (data extends ByteArray ? 'bytes' : never),\n>(parameters: ToBlobsParameters<data, to>): ToBlobsReturnType<to> {\n const to =\n parameters.to ?? (typeof parameters.data === 'string' ? 'hex' : 'bytes')\n const data = (\n typeof parameters.data === 'string'\n ? hexToBytes(parameters.data)\n : parameters.data\n ) as ByteArray\n\n const size_ = size(data)\n if (!size_) throw new EmptyBlobError()\n if (size_ > maxBytesPerTransaction)\n throw new BlobSizeTooLargeError({\n maxSize: maxBytesPerTransaction,\n size: size_,\n })\n\n const blobs = []\n\n let active = true\n let position = 0\n while (active) {\n const blob = createCursor(new Uint8Array(bytesPerBlob))\n\n let size = 0\n while (size < fieldElementsPerBlob) {\n const bytes = data.slice(position, position + (bytesPerFieldElement - 1))\n\n // Push a zero byte so the field element doesn't overflow the BLS modulus.\n blob.pushByte(0x00)\n\n // Push the current segment of data bytes.\n blob.pushBytes(bytes)\n\n // If we detect that the current segment of data bytes is less than 31 bytes,\n // we can stop processing and push a terminator byte to indicate the end of the blob.\n if (bytes.length < 31) {\n blob.pushByte(0x80)\n active = false\n break\n }\n\n size++\n position += 31\n }\n\n blobs.push(blob)\n }\n\n return (\n to === 'bytes'\n ? blobs.map((x) => x.bytes)\n : blobs.map((x) => bytesToHex(x.bytes))\n ) as any\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { BlobSidecars } from '../../types/eip4844.js'\nimport type { Kzg } from '../../types/kzg.js'\nimport type { ByteArray, Hex } from '../../types/misc.js'\nimport type { OneOf } from '../../types/utils.js'\nimport {\n type BlobsToCommitmentsErrorType,\n blobsToCommitments,\n} from './blobsToCommitments.js'\nimport { blobsToProofs, type blobsToProofsErrorType } from './blobsToProofs.js'\nimport { type ToBlobsErrorType, toBlobs } from './toBlobs.js'\n\ntype To = 'hex' | 'bytes'\n\nexport type ToBlobSidecarsParameters<\n data extends Hex | ByteArray | undefined = undefined,\n blobs extends readonly Hex[] | readonly ByteArray[] | undefined = undefined,\n to extends To =\n | (blobs extends readonly Hex[] ? 'hex' : never)\n | (blobs extends readonly ByteArray[] ? 'bytes' : never),\n ///\n _blobsType =\n | (blobs extends readonly Hex[] ? readonly Hex[] : never)\n | (blobs extends readonly ByteArray[] ? readonly ByteArray[] : never),\n> = {\n /** Return type. */\n to?: to | To | undefined\n} & OneOf<\n | {\n /** Data to transform into blobs. */\n data: data | Hex | ByteArray\n /** KZG implementation. */\n kzg: Kzg\n }\n | {\n /** Blobs. */\n blobs: blobs | readonly Hex[] | readonly ByteArray[]\n /** Commitment for each blob. */\n commitments: _blobsType | readonly Hex[] | readonly ByteArray[]\n /** Proof for each blob. */\n proofs: _blobsType | readonly Hex[] | readonly ByteArray[]\n }\n>\n\nexport type ToBlobSidecarsReturnType<to extends To> =\n | (to extends 'bytes' ? BlobSidecars<ByteArray> : never)\n | (to extends 'hex' ? BlobSidecars<Hex> : never)\n\nexport type ToBlobSidecarsErrorType =\n | BlobsToCommitmentsErrorType\n | ToBlobsErrorType\n | blobsToProofsErrorType\n | ErrorType\n\n/**\n * Transforms arbitrary data (or blobs, commitments, & proofs) into a sidecar array.\n *\n * @example\n * ```ts\n * import { toBlobSidecars, stringToHex } from 'viem'\n *\n * const sidecars = toBlobSidecars({ data: stringToHex('hello world') })\n * ```\n *\n * @example\n * ```ts\n * import {\n * blobsToCommitments,\n * toBlobs,\n * blobsToProofs,\n * toBlobSidecars,\n * stringToHex\n * } from 'viem'\n *\n * const blobs = toBlobs({ data: stringToHex('hello world') })\n * const commitments = blobsToCommitments({ blobs, kzg })\n * const proofs = blobsToProofs({ blobs, commitments, kzg })\n *\n * const sidecars = toBlobSidecars({ blobs, commitments, proofs })\n * ```\n */\nexport function toBlobSidecars<\n const data extends Hex | ByteArray | undefined = undefined,\n const blobs extends\n | readonly Hex[]\n | readonly ByteArray[]\n | undefined = undefined,\n to extends To =\n | (data extends Hex ? 'hex' : never)\n | (data extends ByteArray ? 'bytes' : never)\n | (blobs extends readonly Hex[] ? 'hex' : never)\n | (blobs extends readonly ByteArray[] ? 'bytes' : never),\n>(\n parameters: ToBlobSidecarsParameters<data, blobs, to>,\n): ToBlobSidecarsReturnType<to> {\n const { data, kzg, to } = parameters\n const blobs = parameters.blobs ?? toBlobs({ data: data!, to })\n const commitments =\n parameters.commitments ?? blobsToCommitments({ blobs, kzg: kzg!, to })\n const proofs =\n parameters.proofs ?? blobsToProofs({ blobs, commitments, kzg: kzg!, to })\n\n const sidecars: BlobSidecars = []\n for (let i = 0; i < blobs.length; i++)\n sidecars.push({\n blob: blobs[i],\n commitment: commitments[i],\n proof: proofs[i],\n })\n\n return sidecars as ToBlobSidecarsReturnType<to>\n}\n","import {\n InvalidSerializableTransactionError,\n type InvalidSerializableTransactionErrorType,\n} from '../../errors/transaction.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type {\n FeeValuesEIP1559,\n FeeValuesEIP4844,\n FeeValuesLegacy,\n} from '../../index.js'\nimport type {\n TransactionRequestGeneric,\n TransactionSerializableEIP2930,\n TransactionSerializableEIP4844,\n TransactionSerializableEIP7702,\n TransactionSerializableGeneric,\n} from '../../types/transaction.js'\nimport type { Assign, ExactPartial, IsNever, OneOf } from '../../types/utils.js'\n\nexport type GetTransactionType<\n transaction extends OneOf<\n TransactionSerializableGeneric | TransactionRequestGeneric\n > = TransactionSerializableGeneric,\n result =\n | (transaction extends LegacyProperties ? 'legacy' : never)\n | (transaction extends EIP1559Properties ? 'eip1559' : never)\n | (transaction extends EIP2930Properties ? 'eip2930' : never)\n | (transaction extends EIP4844Properties ? 'eip4844' : never)\n | (transaction extends EIP7702Properties ? 'eip7702' : never)\n | (transaction['type'] extends TransactionSerializableGeneric['type']\n ? Extract<transaction['type'], string>\n : never),\n> = IsNever<keyof transaction> extends true\n ? string\n : IsNever<result> extends false\n ? result\n : string\n\nexport type GetTransactionTypeErrorType =\n | InvalidSerializableTransactionErrorType\n | ErrorType\n\nexport function getTransactionType<\n const transaction extends OneOf<\n TransactionSerializableGeneric | TransactionRequestGeneric\n >,\n>(transaction: transaction): GetTransactionType<transaction> {\n if (transaction.type)\n return transaction.type as GetTransactionType<transaction>\n\n if (typeof transaction.authorizationList !== 'undefined')\n return 'eip7702' as any\n\n if (\n typeof transaction.blobs !== 'undefined' ||\n typeof transaction.blobVersionedHashes !== 'undefined' ||\n typeof transaction.maxFeePerBlobGas !== 'undefined' ||\n typeof transaction.sidecars !== 'undefined'\n )\n return 'eip4844' as any\n\n if (\n typeof transaction.maxFeePerGas !== 'undefined' ||\n typeof transaction.maxPriorityFeePerGas !== 'undefined'\n ) {\n return 'eip1559' as any\n }\n\n if (typeof transaction.gasPrice !== 'undefined') {\n if (typeof transaction.accessList !== 'undefined') return 'eip2930' as any\n return 'legacy' as any\n }\n\n throw new InvalidSerializableTransactionError({ transaction })\n}\n\n////////////////////////////////////////////////////////////////////////////////////////////\n// Types\n\ntype BaseProperties = {\n accessList?: undefined\n authorizationList?: undefined\n blobs?: undefined\n blobVersionedHashes?: undefined\n gasPrice?: undefined\n maxFeePerBlobGas?: undefined\n maxFeePerGas?: undefined\n maxPriorityFeePerGas?: undefined\n sidecars?: undefined\n}\n\ntype LegacyProperties = Assign<BaseProperties, FeeValuesLegacy>\ntype EIP1559Properties = Assign<\n BaseProperties,\n OneOf<\n | {\n maxFeePerGas: FeeValuesEIP1559['maxFeePerGas']\n }\n | {\n maxPriorityFeePerGas: FeeValuesEIP1559['maxPriorityFeePerGas']\n },\n FeeValuesEIP1559\n > & {\n accessList?: TransactionSerializableEIP2930['accessList'] | undefined\n }\n>\ntype EIP2930Properties = Assign<\n ExactPartial<LegacyProperties>,\n {\n accessList: TransactionSerializableEIP2930['accessList']\n }\n>\ntype EIP4844Properties = Assign<\n ExactPartial<EIP1559Properties>,\n ExactPartial<FeeValuesEIP4844> &\n OneOf<\n | {\n blobs: TransactionSerializableEIP4844['blobs']\n }\n | {\n blobVersionedHashes: TransactionSerializableEIP4844['blobVersionedHashes']\n }\n | {\n sidecars: TransactionSerializableEIP4844['sidecars']\n },\n TransactionSerializableEIP4844\n >\n>\ntype EIP7702Properties = Assign<\n ExactPartial<EIP1559Properties>,\n {\n authorizationList: TransactionSerializableEIP7702['authorizationList']\n }\n>\n","import type { Address } from 'abitype'\nimport { parseAccount } 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 { BaseFeeScalarError } from '../../errors/fee.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Account, GetAccountParameter } from '../../types/account.js'\nimport type {\n Chain,\n ChainFeesFnParameters,\n DeriveChain,\n GetChainParameter,\n} from '../../types/chain.js'\nimport type { Hex } from '../../types/misc.js'\nimport type { TransactionRequest } from '../../types/transaction.js'\nimport type { UnionOmit } from '../../types/utils.js'\nimport {\n type GetTransactionErrorReturnType,\n getTransactionError,\n} from '../../utils/errors/getTransactionError.js'\nimport { extract } from '../../utils/formatters/extract.js'\nimport {\n type FormattedTransaction,\n formatTransaction,\n} from '../../utils/formatters/transaction.js'\nimport {\n type FormattedTransactionRequest,\n formatTransactionRequest,\n} from '../../utils/formatters/transactionRequest.js'\nimport { getAction } from '../../utils/getAction.js'\nimport type { NonceManager } from '../../utils/nonceManager.js'\nimport { assertRequest } from '../../utils/transaction/assertRequest.js'\nimport { getBlock } from './getBlock.js'\nimport { getChainId as getChainId_ } from './getChainId.js'\n\nexport type FillTransactionParameters<\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n chainOverride extends Chain | undefined = Chain | undefined,\n accountOverride extends Account | Address | undefined =\n | Account\n | Address\n | undefined,\n ///\n _derivedChain extends Chain | undefined = DeriveChain<chain, chainOverride>,\n> = UnionOmit<FormattedTransactionRequest<_derivedChain>, 'from'> &\n GetAccountParameter<account, accountOverride, false, true> &\n GetChainParameter<chain, chainOverride> & {\n /**\n * Nonce manager to use for the transaction request.\n */\n nonceManager?: NonceManager | undefined\n }\n\nexport type FillTransactionReturnType<\n chain extends Chain | undefined = Chain | undefined,\n chainOverride extends Chain | undefined = Chain | undefined,\n ///\n _derivedChain extends Chain | undefined = DeriveChain<chain, chainOverride>,\n> = {\n raw: Hex\n transaction: FormattedTransaction<_derivedChain>\n}\n\nexport type FillTransactionErrorType =\n | GetTransactionErrorReturnType<ErrorType>\n | ErrorType\n\n/**\n * Fills a transaction request with the necessary fields to be signed over.\n *\n * - Docs: https://viem.sh/docs/actions/public/fillTransaction\n *\n * @param client - Client to use\n * @param parameters - {@link FillTransactionParameters}\n * @returns The filled transaction. {@link FillTransactionReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { fillTransaction } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const result = await fillTransaction(client, {\n * account: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',\n * to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',\n * value: parseEther('1'),\n * })\n */\nexport async function fillTransaction<\n chain extends Chain | undefined,\n account extends Account | undefined,\n chainOverride extends Chain | undefined = undefined,\n accountOverride extends Account | Address | undefined = undefined,\n>(\n client: Client<Transport, chain, account>,\n parameters: FillTransactionParameters<\n chain,\n account,\n chainOverride,\n accountOverride\n >,\n): Promise<FillTransactionReturnType<chain, chainOverride>> {\n const {\n account = client.account,\n accessList,\n authorizationList,\n chain = client.chain,\n blobVersionedHashes,\n blobs,\n data,\n gas,\n gasPrice,\n maxFeePerBlobGas,\n maxFeePerGas,\n maxPriorityFeePerGas,\n nonce: nonce_,\n nonceManager,\n to,\n type,\n value,\n ...rest\n } = parameters\n\n const nonce = await (async () => {\n if (!account) return nonce_\n if (!nonceManager) return nonce_\n if (typeof nonce_ !== 'undefined') return nonce_\n const account_ = parseAccount(account)\n const chainId = chain\n ? chain.id\n : await getAction(client, getChainId_, 'getChainId')({})\n return await nonceManager.consume({\n address: account_.address,\n chainId,\n client,\n })\n })()\n\n assertRequest(parameters)\n\n const chainFormat = chain?.formatters?.transactionRequest?.format\n const format = chainFormat || formatTransactionRequest\n\n const request = format(\n {\n // Pick out extra data that might exist on the chain's transaction request type.\n ...extract(rest, { format: chainFormat }),\n account: account ? parseAccount(account) : undefined,\n accessList,\n authorizationList,\n blobs,\n blobVersionedHashes,\n data,\n gas,\n gasPrice,\n maxFeePerBlobGas,\n maxFeePerGas,\n maxPriorityFeePerGas,\n nonce,\n to,\n type,\n value,\n } as TransactionRequest,\n 'fillTransaction',\n )\n\n try {\n const response = await client.request({\n method: 'eth_fillTransaction',\n params: [request],\n })\n const format = chain?.formatters?.transaction?.format || formatTransaction\n\n const transaction = format(response.tx)\n\n // Remove unnecessary fields.\n delete transaction.blockHash\n delete transaction.blockNumber\n delete transaction.r\n delete transaction.s\n delete transaction.transactionIndex\n delete transaction.v\n delete transaction.yParity\n\n // Rewrite fields.\n transaction.data = transaction.input\n\n // Preference supplied fees (some nodes do not take these preferences).\n if (transaction.gas) transaction.gas = parameters.gas ?? transaction.gas\n if (transaction.gasPrice)\n transaction.gasPrice = parameters.gasPrice ?? transaction.gasPrice\n if (transaction.maxFeePerBlobGas)\n transaction.maxFeePerBlobGas =\n parameters.maxFeePerBlobGas ?? transaction.maxFeePerBlobGas\n if (transaction.maxFeePerGas)\n transaction.maxFeePerGas =\n parameters.maxFeePerGas ?? transaction.maxFeePerGas\n if (transaction.maxPriorityFeePerGas)\n transaction.maxPriorityFeePerGas =\n parameters.maxPriorityFeePerGas ?? transaction.maxPriorityFeePerGas\n if (transaction.nonce)\n transaction.nonce = parameters.nonce ?? transaction.nonce\n\n // Build fee multiplier function.\n const feeMultiplier = await (async () => {\n if (typeof chain?.fees?.baseFeeMultiplier === 'function') {\n const block = await getAction(client, getBlock, 'getBlock')({})\n return chain.fees.baseFeeMultiplier({\n block,\n client,\n request: parameters,\n } as ChainFeesFnParameters)\n }\n return chain?.fees?.baseFeeMultiplier ?? 1.2\n })()\n if (feeMultiplier < 1) throw new BaseFeeScalarError()\n\n const decimals = feeMultiplier.toString().split('.')[1]?.length ?? 0\n const denominator = 10 ** decimals\n const multiplyFee = (base: bigint) =>\n (base * BigInt(Math.ceil(feeMultiplier * denominator))) /\n BigInt(denominator)\n\n // Apply fee multiplier.\n if (transaction.maxFeePerGas && !parameters.maxFeePerGas)\n transaction.maxFeePerGas = multiplyFee(transaction.maxFeePerGas)\n if (transaction.gasPrice && !parameters.gasPrice)\n transaction.gasPrice = multiplyFee(transaction.gasPrice)\n\n return {\n raw: response.raw,\n transaction: {\n from: request.from,\n ...transaction,\n },\n }\n } catch (err) {\n throw getTransactionError(\n err as BaseError,\n {\n ...parameters,\n chain: client.chain,\n } as never,\n )\n }\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 | null\n chain?: Chain | undefined\n docsPath?: string | undefined\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\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 chain extends Chain | undefined,\n account extends Account | undefined,\n>(client: Client<Transport, chain, account>): Promise<GetChainIdReturnType> {\n const chainIdHex = await client.request(\n {\n method: 'eth_chainId',\n },\n { dedupe: true },\n )\n return hexToNumber(chainIdHex)\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { Log } from '../../types/log.js'\nimport type { RpcLog } from '../../types/rpc.js'\nimport type { ExactPartial } from '../../types/utils.js'\n\nexport type FormatLogErrorType = ErrorType\n\nexport function formatLog(\n log: ExactPartial<RpcLog>,\n {\n args,\n eventName,\n }: { args?: unknown | undefined; eventName?: string | undefined } = {},\n) {\n return {\n ...log,\n blockHash: log.blockHash ? log.blockHash : null,\n blockNumber: log.blockNumber ? BigInt(log.blockNumber) : null,\n blockTimestamp: log.blockTimestamp\n ? BigInt(log.blockTimestamp)\n : log.blockTimestamp === null\n ? null\n : undefined,\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","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\n/** @internal */\nexport const listenersCache = /*#__PURE__*/ new Map<\n string,\n { id: number; fns: Callbacks }[]\n>()\n/** @internal */\nexport const cleanupCache = /*#__PURE__*/ new Map<\n string,\n () => void | Promise<void>\n>()\n\ntype EmitFunction<callbacks extends Callbacks> = (\n emit: callbacks,\n) => MaybePromise<void | (() => void) | (() => Promise<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<callbacks extends Callbacks>(\n observerId: string,\n callbacks: callbacks,\n fn: EmitFunction<callbacks>,\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 listeners = getListeners()\n if (!listeners.some((cb: any) => cb.id === callbackId)) return\n const cleanup = cleanupCache.get(observerId)\n if (listeners.length === 1 && cleanup) {\n const p = cleanup()\n if (p instanceof Promise) p.catch(() => {})\n }\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: callbacks = {} as callbacks\n for (const key in callbacks) {\n emit[key] = ((\n ...args: Parameters<NonNullable<callbacks[keyof callbacks]>>\n ) => {\n const listeners = getListeners()\n if (listeners.length === 0) return\n for (const listener of listeners) listener.fns[key]?.(...args)\n }) as callbacks[Extract<keyof callbacks, 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<data> = {\n // Whether or not to emit when the polling starts.\n emitOnBegin?: boolean | undefined\n // The initial wait time (in ms) before polling.\n initialWaitTime?: ((data: data | void) => Promise<number>) | undefined\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<data>(\n fn: ({ unpoll }: { unpoll: () => void }) => Promise<data | void>,\n { emitOnBegin, initialWaitTime, interval }: PollOptions<data>,\n) {\n let active = true\n\n const unwatch = () => (active = false)\n\n const watch = async () => {\n let data: data | undefined | void\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 { ErrorType } from '../../errors/utils.js'\n\n/** @internal */\nexport const promiseCache = /*#__PURE__*/ new Map()\n/** @internal */\nexport const responseCache = /*#__PURE__*/ new Map()\n\nexport type GetCacheErrorType = ErrorType\n\nexport function getCache<data>(cacheKey: string) {\n const buildCache = <data>(cacheKey: string, cache: Map<string, data>) => ({\n clear: () => cache.delete(cacheKey),\n get: () => cache.get(cacheKey),\n set: (data: data) => cache.set(cacheKey, data),\n })\n\n const promise = buildCache<Promise<data>>(cacheKey, promiseCache)\n const response = buildCache<{ created: Date; data: data }>(\n cacheKey,\n responseCache,\n )\n\n return {\n clear: () => {\n promise.clear()\n response.clear()\n },\n promise,\n response,\n }\n}\n\ntype 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 | undefined\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<data>(\n fn: () => Promise<data>,\n { cacheKey, cacheTime = Number.POSITIVE_INFINITY }: WithCacheParameters,\n) {\n const cache = getCache<data>(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 = Date.now() - 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 {\n type GetCacheErrorType,\n getCache,\n withCache,\n} from '../../utils/promise/withCache.js'\n\nexport type GetBlockNumberParameters = {\n /** Time (in ms) that cached block number will remain in memory. */\n cacheTime?: number | undefined\n}\n\nexport type GetBlockNumberReturnType = bigint\n\nexport type GetBlockNumberErrorType = RequestErrorType | ErrorType\n\nconst cacheKey = (id: string) => `blockNumber.${id}`\n\n/** @internal */\nexport type GetBlockNumberCacheErrorType = GetCacheErrorType | ErrorType\n\n/** @internal */\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\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<chain extends Chain | undefined>(\n client: Client<Transport, chain>,\n { cacheTime = client.cacheTime }: GetBlockNumberParameters = {},\n): Promise<GetBlockNumberReturnType> {\n const blockNumberHex = await withCache(\n () =>\n client.request({\n method: 'eth_blockNumber',\n }),\n { cacheKey: cacheKey(client.uid), cacheTime },\n )\n return BigInt(blockNumberHex)\n}\n","import type { Abi, 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 {\n AccountNotFoundError,\n type AccountNotFoundErrorType,\n} 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 {\n Chain,\n DeriveChain,\n GetChainParameter,\n} from '../../types/chain.js'\nimport type {\n ContractFunctionArgs,\n ContractFunctionName,\n ContractFunctionParameters,\n} from '../../types/contract.js'\nimport type { Hex } from '../../types/misc.js'\nimport type { Prettify, UnionEvaluate, 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 type { FormattedTransactionRequest } from '../../utils/formatters/transactionRequest.js'\nimport { getAction } from '../../utils/getAction.js'\nimport type { GetMutabilityAwareValue } from '../public/simulateContract.js'\nimport {\n type SendTransactionErrorType,\n type SendTransactionReturnType,\n sendTransaction,\n} from './sendTransaction.js'\nimport type { sendTransactionSync } from './sendTransactionSync.js'\n\nexport type WriteContractParameters<\n abi extends Abi | readonly unknown[] = Abi,\n functionName extends ContractFunctionName<\n abi,\n 'nonpayable' | 'payable'\n > = ContractFunctionName<abi, 'nonpayable' | 'payable'>,\n args extends ContractFunctionArgs<\n abi,\n 'nonpayable' | 'payable',\n functionName\n > = ContractFunctionArgs<abi, 'nonpayable' | 'payable', functionName>,\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n chainOverride extends Chain | undefined = Chain | undefined,\n ///\n allFunctionNames = ContractFunctionName<abi, 'nonpayable' | 'payable'>,\n derivedChain extends Chain | undefined = DeriveChain<chain, chainOverride>,\n> = ContractFunctionParameters<\n abi,\n 'nonpayable' | 'payable',\n functionName,\n args,\n false,\n allFunctionNames\n> &\n GetChainParameter<chain, chainOverride> &\n Prettify<\n GetAccountParameter<account, Account | Address, true, true> &\n GetMutabilityAwareValue<\n abi,\n 'nonpayable' | 'payable',\n functionName,\n FormattedTransactionRequest<derivedChain>['value'],\n args\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 | undefined\n }\n > &\n UnionEvaluate<\n UnionOmit<\n FormattedTransactionRequest<derivedChain>,\n 'data' | 'from' | 'to' | 'value'\n >\n >\n\nexport type WriteContractReturnType = SendTransactionReturnType\n\nexport type WriteContractErrorType =\n | EncodeFunctionDataErrorType\n | AccountNotFoundErrorType\n | ParseAccountErrorType\n | GetContractErrorReturnType<SendTransactionErrorType>\n | ErrorType\n\n/**\n * Executes a write function on a contract.\n *\n * - Docs: https://viem.sh/docs/contract/writeContract\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) is needed to be broadcast in order to change the state.\n *\n * Internally, uses a [Wallet Client](https://viem.sh/docs/clients/wallet) to call the [`sendTransaction` action](https://viem.sh/docs/actions/wallet/sendTransaction) with [ABI-encoded `data`](https://viem.sh/docs/contract/encodeFunctionData).\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#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#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 chain extends Chain | undefined,\n account extends Account | undefined,\n const abi extends Abi | readonly unknown[],\n functionName extends ContractFunctionName<abi, 'nonpayable' | 'payable'>,\n args extends ContractFunctionArgs<\n abi,\n 'nonpayable' | 'payable',\n functionName\n >,\n chainOverride extends Chain | undefined,\n>(\n client: Client<Transport, chain, account>,\n parameters: WriteContractParameters<\n abi,\n functionName,\n args,\n chain,\n account,\n chainOverride\n >,\n): Promise<WriteContractReturnType> {\n return writeContract.internal(\n client,\n sendTransaction,\n 'sendTransaction',\n parameters,\n ) as never\n}\n\nexport namespace writeContract {\n export async function internal<\n chain extends Chain | undefined,\n account extends Account | undefined,\n const abi extends Abi | readonly unknown[],\n functionName extends ContractFunctionName<abi, 'nonpayable' | 'payable'>,\n args extends ContractFunctionArgs<\n abi,\n 'nonpayable' | 'payable',\n functionName\n >,\n chainOverride extends Chain | undefined,\n >(\n client: Client<Transport, chain, account>,\n actionFn: typeof sendTransaction | typeof sendTransactionSync,\n name: 'sendTransaction' | 'sendTransactionSync',\n parameters: WriteContractParameters<\n abi,\n functionName,\n args,\n chain,\n account,\n chainOverride\n >,\n ) {\n const {\n abi,\n account: account_ = client.account,\n address,\n args,\n functionName,\n ...request\n } = parameters as WriteContractParameters\n\n if (typeof account_ === 'undefined')\n throw new AccountNotFoundError({\n docsPath: '/docs/contract/writeContract',\n })\n const account = account_ ? parseAccount(account_) : null\n\n const data = encodeFunctionData({\n abi,\n args,\n functionName,\n } as EncodeFunctionDataParameters)\n\n try {\n return await getAction(\n client,\n actionFn as never,\n name,\n )({\n data,\n to: address,\n account,\n ...request,\n })\n } catch (error) {\n throw getContractError(error as BaseError, {\n abi,\n address,\n args,\n docsPath: '/docs/contract/writeContract',\n functionName,\n sender: account?.address,\n })\n }\n }\n}\n","import { BaseError } from './base.js'\n\nexport type AccountNotFoundErrorType = AccountNotFoundError & {\n name: 'AccountNotFoundError'\n}\nexport class AccountNotFoundError extends BaseError {\n constructor({ docsPath }: { docsPath?: string | undefined } = {}) {\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 Client.',\n ].join('\\n'),\n {\n docsPath,\n docsSlug: 'account',\n name: 'AccountNotFoundError',\n },\n )\n }\n}\n\nexport type AccountTypeNotSupportedErrorType = AccountTypeNotSupportedError & {\n name: 'AccountTypeNotSupportedError'\n}\nexport class AccountTypeNotSupportedError extends BaseError {\n constructor({\n docsPath,\n metaMessages,\n type,\n }: {\n docsPath?: string | undefined\n metaMessages?: string[] | undefined\n type: string\n }) {\n super(`Account type \"${type}\" is not supported.`, {\n docsPath,\n metaMessages,\n name: 'AccountTypeNotSupportedError',\n })\n }\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 { SignTransactionErrorType } from '../../accounts/utils/signTransaction.js'\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport {\n AccountNotFoundError,\n type AccountNotFoundErrorType,\n AccountTypeNotSupportedError,\n type AccountTypeNotSupportedErrorType,\n} from '../../errors/account.js'\nimport { BaseError } from '../../errors/base.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { GetAccountParameter } from '../../types/account.js'\nimport type {\n Chain,\n DeriveChain,\n GetChainParameter,\n} from '../../types/chain.js'\nimport type { GetTransactionRequestKzgParameter } from '../../types/kzg.js'\nimport type { Hash, Hex } from '../../types/misc.js'\nimport type { TransactionRequest } from '../../types/transaction.js'\nimport type { UnionOmit } from '../../types/utils.js'\nimport {\n type RecoverAuthorizationAddressErrorType,\n recoverAuthorizationAddress,\n} from '../../utils/authorization/recoverAuthorizationAddress.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport {\n type AssertCurrentChainErrorType,\n assertCurrentChain,\n} from '../../utils/chain/assertCurrentChain.js'\nimport { concat } from '../../utils/data/concat.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 { LruMap } from '../../utils/lru.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 defaultParameters,\n type PrepareTransactionRequestErrorType,\n prepareTransactionRequest,\n} from './prepareTransactionRequest.js'\nimport {\n type SendRawTransactionErrorType,\n sendRawTransaction,\n} from './sendRawTransaction.js'\n\nconst supportsWalletNamespace = new LruMap<boolean>(128)\n\nexport type SendTransactionRequest<\n chain extends Chain | undefined = Chain | undefined,\n chainOverride extends Chain | undefined = Chain | undefined,\n ///\n _derivedChain extends Chain | undefined = DeriveChain<chain, chainOverride>,\n> = UnionOmit<FormattedTransactionRequest<_derivedChain>, 'from'> &\n GetTransactionRequestKzgParameter\n\nexport type SendTransactionParameters<\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n chainOverride extends Chain | undefined = Chain | undefined,\n request extends SendTransactionRequest<\n chain,\n chainOverride\n > = SendTransactionRequest<chain, chainOverride>,\n> = request &\n GetAccountParameter<account, Account | Address, true, true> &\n GetChainParameter<chain, chainOverride> &\n GetTransactionRequestKzgParameter<request> & {\n /** Whether to assert that the client chain is on the correct chain. @default true */\n assertChainId?: boolean | undefined\n /** Data to append to the end of the calldata. Takes precedence over `client.dataSuffix`. */\n dataSuffix?: Hex | undefined\n }\n\nexport type SendTransactionReturnType = Hash\n\nexport type SendTransactionErrorType =\n | ParseAccountErrorType\n | GetTransactionErrorReturnType<\n | AccountNotFoundErrorType\n | AccountTypeNotSupportedErrorType\n | AssertCurrentChainErrorType\n | AssertRequestErrorType\n | GetChainIdErrorType\n | PrepareTransactionRequestErrorType\n | SendRawTransactionErrorType\n | RecoverAuthorizationAddressErrorType\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\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#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 chain extends Chain | undefined,\n account extends Account | undefined,\n const request extends SendTransactionRequest<chain, chainOverride>,\n chainOverride extends Chain | undefined = undefined,\n>(\n client: Client<Transport, chain, account>,\n parameters: SendTransactionParameters<chain, account, chainOverride, request>,\n): Promise<SendTransactionReturnType> {\n const {\n account: account_ = client.account,\n assertChainId = true,\n chain = client.chain,\n accessList,\n authorizationList,\n blobs,\n data,\n dataSuffix = typeof client.dataSuffix === 'string'\n ? client.dataSuffix\n : client.dataSuffix?.value,\n gas,\n gasPrice,\n maxFeePerBlobGas,\n maxFeePerGas,\n maxPriorityFeePerGas,\n nonce,\n type,\n value,\n ...rest\n } = parameters\n\n if (typeof account_ === 'undefined')\n throw new AccountNotFoundError({\n docsPath: '/docs/actions/wallet/sendTransaction',\n })\n const account = account_ ? parseAccount(account_) : null\n\n try {\n assertRequest(parameters as AssertRequestParameters)\n\n const to = await (async () => {\n // If `to` exists on the parameters, use that.\n if (parameters.to) return parameters.to\n\n // If `to` is null, we are sending a deployment transaction.\n if (parameters.to === null) return undefined\n\n // If no `to` exists, and we are sending a EIP-7702 transaction, use the\n // address of the first authorization in the list.\n if (authorizationList && authorizationList.length > 0)\n return await recoverAuthorizationAddress({\n authorization: authorizationList[0],\n }).catch(() => {\n throw new BaseError(\n '`to` is required. Could not infer from `authorizationList`.',\n )\n })\n\n // Otherwise, we are sending a deployment transaction.\n return undefined\n })()\n\n if (account?.type === 'json-rpc' || account === null) {\n let chainId: number | undefined\n if (chain !== null) {\n chainId = await getAction(client, getChainId, 'getChainId')({})\n if (assertChainId)\n assertCurrentChain({\n currentChainId: chainId,\n chain,\n })\n }\n\n const chainFormat = client.chain?.formatters?.transactionRequest?.format\n const format = chainFormat || formatTransactionRequest\n\n const request = format(\n {\n // Pick out extra data that might exist on the chain's transaction request type.\n ...extract(rest, { format: chainFormat }),\n accessList,\n account,\n authorizationList,\n blobs,\n chainId,\n data: data ? concat([data, dataSuffix ?? '0x']) : data,\n gas,\n gasPrice,\n maxFeePerBlobGas,\n maxFeePerGas,\n maxPriorityFeePerGas,\n nonce,\n to,\n type,\n value,\n } as TransactionRequest,\n 'sendTransaction',\n )\n\n const isWalletNamespaceSupported = supportsWalletNamespace.get(client.uid)\n const method = isWalletNamespaceSupported\n ? 'wallet_sendTransaction'\n : 'eth_sendTransaction'\n\n try {\n return await client.request(\n {\n method,\n params: [request],\n },\n { retryCount: 0 },\n )\n } catch (e) {\n if (isWalletNamespaceSupported === false) throw e\n\n const error = e as BaseError\n // If the transport does not support the method or input, attempt to use the\n // `wallet_sendTransaction` method.\n if (\n error.name === 'InvalidInputRpcError' ||\n error.name === 'InvalidParamsRpcError' ||\n error.name === 'MethodNotFoundRpcError' ||\n error.name === 'MethodNotSupportedRpcError'\n ) {\n return await client\n .request(\n {\n method: 'wallet_sendTransaction',\n params: [request],\n },\n { retryCount: 0 },\n )\n .then((hash) => {\n supportsWalletNamespace.set(client.uid, true)\n return hash\n })\n .catch((e) => {\n const walletNamespaceError = e as BaseError\n if (\n walletNamespaceError.name === 'MethodNotFoundRpcError' ||\n walletNamespaceError.name === 'MethodNotSupportedRpcError'\n ) {\n supportsWalletNamespace.set(client.uid, false)\n throw error\n }\n\n throw walletNamespaceError\n })\n }\n\n throw error\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 authorizationList,\n blobs,\n chain,\n data: data ? concat([data, dataSuffix ?? '0x']) : data,\n gas,\n gasPrice,\n maxFeePerBlobGas,\n maxFeePerGas,\n maxPriorityFeePerGas,\n nonce,\n nonceManager: account.nonceManager,\n parameters: [...defaultParameters, 'sidecars'],\n type,\n value,\n ...rest,\n to,\n } as any)\n\n const serializer = chain?.serializers?.transaction\n const serializedTransaction = (await account.signTransaction(request, {\n serializer,\n })) as Hash\n return await getAction(\n client,\n sendRawTransaction,\n 'sendRawTransaction',\n )({\n serializedTransaction,\n })\n }\n\n if (account?.type === 'smart')\n throw new AccountTypeNotSupportedError({\n metaMessages: [\n 'Consider using the `sendUserOperation` Action instead.',\n ],\n docsPath: '/docs/actions/bundler/sendUserOperation',\n type: 'smart',\n })\n\n throw new AccountTypeNotSupportedError({\n docsPath: '/docs/actions/wallet/sendTransaction',\n type: (account as any)?.type,\n })\n } catch (err) {\n if (err instanceof AccountTypeNotSupportedError) throw err\n throw getTransactionError(err as BaseError, {\n ...parameters,\n account,\n chain: parameters.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 | undefined\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 { 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 { TransactionSerializedGeneric } from '../../types/transaction.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\n\nexport type SendRawTransactionParameters = {\n /** The signed serialized transaction. */\n serializedTransaction: TransactionSerializedGeneric\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\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<chain extends Chain | undefined>(\n client: Client<Transport, chain>,\n { serializedTransaction }: SendRawTransactionParameters,\n): Promise<SendRawTransactionReturnType> {\n return client.request(\n {\n method: 'eth_sendRawTransaction',\n params: [serializedTransaction],\n },\n { retryCount: 0 },\n )\n}\n","import type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport { BaseError } from '../../errors/base.js'\nimport { BundleFailedError } from '../../errors/calls.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport { getAction } from '../../utils/getAction.js'\nimport { type ObserveErrorType, observe } from '../../utils/observe.js'\nimport { type PollErrorType, poll } from '../../utils/poll.js'\nimport { withResolvers } from '../../utils/promise/withResolvers.js'\nimport {\n type WithRetryParameters,\n withRetry,\n} from '../../utils/promise/withRetry.js'\nimport { stringify } from '../../utils/stringify.js'\nimport {\n type GetCallsStatusErrorType,\n type GetCallsStatusReturnType,\n getCallsStatus,\n} from './getCallsStatus.js'\n\nexport type WaitForCallsStatusParameters = {\n /**\n * The id of the call batch to wait for.\n */\n id: string\n /**\n * Polling frequency (in ms). Defaults to the client's pollingInterval config.\n *\n * @default client.pollingInterval\n */\n pollingInterval?: number | undefined\n /**\n * Number of times to retry if the call bundle failed.\n * @default 4 (exponential backoff)\n */\n retryCount?: WithRetryParameters['retryCount'] | undefined\n /**\n * Time to wait (in ms) between retries.\n * @default `({ count }) => ~~(1 << count) * 200` (exponential backoff)\n */\n retryDelay?: WithRetryParameters['delay'] | undefined\n /**\n * The status range to wait for.\n *\n * @default (status) => status >= 200\n */\n status?: ((parameters: GetCallsStatusReturnType) => boolean) | undefined\n /**\n * Whether to throw an error if the call bundle fails.\n *\n * @default false\n */\n throwOnFailure?: boolean | undefined\n /**\n * Optional timeout (in milliseconds) to wait before stopping polling.\n *\n * @default 60_000\n */\n timeout?: number | undefined\n}\n\nexport type WaitForCallsStatusReturnType = GetCallsStatusReturnType\n\nexport type WaitForCallsStatusErrorType =\n | ObserveErrorType\n | PollErrorType\n | GetCallsStatusErrorType\n | WaitForCallsStatusTimeoutError\n | ErrorType\n\n/**\n * Waits for the status & receipts of a call bundle that was sent via `sendCalls`.\n *\n * - Docs: https://viem.sh/docs/actions/wallet/waitForCallsStatus\n * - JSON-RPC Methods: [`wallet_getCallsStatus`](https://eips.ethereum.org/EIPS/eip-5792)\n *\n * @param client - Client to use\n * @param parameters - {@link WaitForCallsStatusParameters}\n * @returns Status & receipts of the call bundle. {@link WaitForCallsStatusReturnType}\n *\n * @example\n * import { createWalletClient, custom } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { waitForCallsStatus } from 'viem/actions'\n *\n * const client = createWalletClient({\n * chain: mainnet,\n * transport: custom(window.ethereum),\n * })\n *\n * const { receipts, status } = await waitForCallsStatus(client, { id: '0xdeadbeef' })\n */\nexport async function waitForCallsStatus<chain extends Chain | undefined>(\n client: Client<Transport, chain>,\n parameters: WaitForCallsStatusParameters,\n): Promise<WaitForCallsStatusReturnType> {\n const {\n id,\n pollingInterval = client.pollingInterval,\n status = ({ statusCode }) => statusCode === 200 || statusCode >= 300,\n retryCount = 4,\n retryDelay = ({ count }) => ~~(1 << count) * 200, // exponential backoff\n timeout = 60_000,\n throwOnFailure = false,\n } = parameters\n const observerId = stringify(['waitForCallsStatus', client.uid, id])\n\n const { promise, resolve, reject } =\n withResolvers<WaitForCallsStatusReturnType>()\n\n let timer: Timer | undefined\n\n const unobserve = observe(observerId, { resolve, reject }, (emit) => {\n const unpoll = poll(\n async () => {\n const done = (fn: () => void) => {\n clearTimeout(timer)\n unpoll()\n fn()\n unobserve()\n }\n\n try {\n const result = await withRetry(\n async () => {\n const result = await getAction(\n client,\n getCallsStatus,\n 'getCallsStatus',\n )({ id })\n if (throwOnFailure && result.status === 'failure')\n throw new BundleFailedError(result)\n return result\n },\n {\n retryCount,\n delay: retryDelay,\n },\n )\n if (!status(result)) return\n done(() => emit.resolve(result))\n } catch (error) {\n done(() => emit.reject(error))\n }\n },\n {\n interval: pollingInterval,\n emitOnBegin: true,\n },\n )\n\n return unpoll\n })\n\n timer = timeout\n ? setTimeout(() => {\n unobserve()\n clearTimeout(timer)\n reject(new WaitForCallsStatusTimeoutError({ id }))\n }, timeout)\n : undefined\n\n return await promise\n}\n\nexport type WaitForCallsStatusTimeoutErrorType =\n WaitForCallsStatusTimeoutError & {\n name: 'WaitForCallsStatusTimeoutError'\n }\nexport class WaitForCallsStatusTimeoutError extends BaseError {\n constructor({ id }: { id: string }) {\n super(\n `Timed out while waiting for call bundle with id \"${id}\" to be confirmed.`,\n { name: 'WaitForCallsStatusTimeoutError' },\n )\n }\n}\n","import type { GetCallsStatusReturnType } from '../actions/wallet/getCallsStatus.js'\nimport { BaseError } from './base.js'\n\nexport type BundleFailedErrorType = BundleFailedError & {\n name: 'BundleFailedError'\n}\nexport class BundleFailedError extends BaseError {\n result: GetCallsStatusReturnType\n\n constructor(result: GetCallsStatusReturnType) {\n super(`Call bundle failed with status: ${result.statusCode}`, {\n name: 'BundleFailedError',\n })\n\n this.result = result\n }\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport { wait } from '../wait.js'\n\nexport type WithRetryParameters = {\n // The delay (in ms) between retries.\n delay?:\n | ((config: { count: number; error: Error }) => number)\n | number\n | undefined\n // The max number of times to retry.\n retryCount?: number | undefined\n // Whether or not to retry when an error is thrown.\n shouldRetry?:\n | (({\n count,\n error,\n }: {\n count: number\n error: Error\n }) => Promise<boolean> | boolean)\n | undefined\n}\n\nexport type WithRetryErrorType = ErrorType\n\nexport function withRetry<data>(\n fn: () => Promise<data>,\n {\n delay: delay_ = 100,\n retryCount = 2,\n shouldRetry = () => true,\n }: WithRetryParameters = {},\n) {\n return new Promise<data>((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 { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Account } from '../../types/account.js'\nimport type { ExtractCapabilities } from '../../types/capabilities.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { WalletGetCallsStatusReturnType } from '../../types/eip1193.js'\nimport type { Hex } from '../../types/misc.js'\nimport type { RpcTransactionReceipt } from '../../types/rpc.js'\nimport type { Prettify } from '../../types/utils.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport { sliceHex } from '../../utils/data/slice.js'\nimport { trim } from '../../utils/data/trim.js'\nimport { hexToBigInt, hexToNumber } from '../../utils/encoding/fromHex.js'\nimport { receiptStatuses } from '../../utils/formatters/transactionReceipt.js'\nimport {\n fallbackMagicIdentifier,\n fallbackTransactionErrorMagicIdentifier,\n} from './sendCalls.js'\n\nexport type GetCallsStatusParameters = { id: string }\n\nexport type GetCallsStatusReturnType = Prettify<\n Omit<\n WalletGetCallsStatusReturnType<\n ExtractCapabilities<'getCallsStatus', 'ReturnType'>,\n number,\n bigint,\n 'success' | 'reverted'\n >,\n 'status'\n > & {\n statusCode: number\n status: 'pending' | 'success' | 'failure' | undefined\n }\n>\n\nexport type GetCallsStatusErrorType = RequestErrorType | ErrorType\n\n/**\n * Returns the status of a call batch that was sent via `sendCalls`.\n *\n * - Docs: https://viem.sh/docs/actions/wallet/getCallsStatus\n * - JSON-RPC Methods: [`wallet_getCallsStatus`](https://eips.ethereum.org/EIPS/eip-5792)\n *\n * @param client - Client to use\n * @returns Status of the calls. {@link GetCallsStatusReturnType}\n *\n * @example\n * import { createWalletClient, custom } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getCallsStatus } from 'viem/actions'\n *\n * const client = createWalletClient({\n * chain: mainnet,\n * transport: custom(window.ethereum),\n * })\n * const { receipts, status } = await getCallsStatus(client, { id: '0xdeadbeef' })\n */\nexport async function getCallsStatus<\n chain extends Chain | undefined,\n account extends Account | undefined = undefined,\n>(\n client: Client<Transport, chain, account>,\n parameters: GetCallsStatusParameters,\n): Promise<GetCallsStatusReturnType> {\n async function getStatus(id: Hex) {\n const isTransactions = id.endsWith(fallbackMagicIdentifier.slice(2))\n if (isTransactions) {\n const chainId = trim(sliceHex(id, -64, -32))\n const hashes = sliceHex(id, 0, -64)\n .slice(2)\n .match(/.{1,64}/g)\n\n const receipts = await Promise.all(\n hashes!.map((hash) =>\n fallbackTransactionErrorMagicIdentifier.slice(2) !== hash\n ? client.request(\n {\n method: 'eth_getTransactionReceipt',\n params: [`0x${hash}`],\n },\n { dedupe: true },\n )\n : undefined,\n ),\n )\n\n const status = (() => {\n if (receipts.some((r) => r === null)) return 100 // pending\n if (receipts.every((r) => r?.status === '0x1')) return 200 // success\n if (receipts.every((r) => r?.status === '0x0')) return 500 // complete failure\n return 600 // partial failure\n })()\n\n return {\n atomic: false,\n chainId: hexToNumber(chainId),\n receipts: receipts.filter(Boolean) as RpcTransactionReceipt[],\n status,\n version: '2.0.0',\n }\n }\n return client.request({\n method: 'wallet_getCallsStatus',\n params: [id],\n })\n }\n\n const {\n atomic = false,\n chainId,\n receipts,\n version = '2.0.0',\n ...response\n } = await getStatus(parameters.id as Hex)\n const [status, statusCode] = (() => {\n const statusCode = response.status\n if (statusCode >= 100 && statusCode < 200)\n return ['pending', statusCode] as const\n if (statusCode >= 200 && statusCode < 300)\n return ['success', statusCode] as const\n if (statusCode >= 300 && statusCode < 700)\n return ['failure', statusCode] as const\n // @ts-expect-error: for backwards compatibility\n if (statusCode === 'CONFIRMED') return ['success', 200] as const\n // @ts-expect-error: for backwards compatibility\n if (statusCode === 'PENDING') return ['pending', 100] as const\n return [undefined, statusCode]\n })()\n return {\n ...response,\n atomic,\n // @ts-expect-error: for backwards compatibility\n chainId: chainId ? hexToNumber(chainId) : undefined,\n receipts:\n receipts?.map((receipt) => ({\n ...receipt,\n blockNumber: hexToBigInt(receipt.blockNumber),\n gasUsed: hexToBigInt(receipt.gasUsed),\n status: receiptStatuses[receipt.status as '0x0' | '0x1'],\n })) ?? [],\n statusCode,\n status,\n version,\n }\n}\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 type { ExactPartial } from '../../types/utils.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 chain extends Chain | undefined = undefined,\n> = ExtractChainFormatterReturnType<\n chain,\n 'transactionReceipt',\n TransactionReceipt\n>\n\nexport const receiptStatuses = {\n '0x0': 'reverted',\n '0x1': 'success',\n} as const\n\nexport type FormatTransactionReceiptErrorType = ErrorType\n\nexport function formatTransactionReceipt(\n transactionReceipt: ExactPartial<RpcTransactionReceipt>,\n _?: string | undefined,\n) {\n const receipt = {\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 ? receiptStatuses[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 if (transactionReceipt.blobGasPrice)\n receipt.blobGasPrice = BigInt(transactionReceipt.blobGasPrice)\n if (transactionReceipt.blobGasUsed)\n receipt.blobGasUsed = BigInt(transactionReceipt.blobGasUsed)\n\n return receipt\n}\n\nexport type DefineTransactionReceiptErrorType =\n | DefineFormatterErrorType\n | ErrorType\n\nexport const defineTransactionReceipt = /*#__PURE__*/ defineFormatter(\n 'transactionReceipt',\n formatTransactionReceipt,\n)\n","import type { Address, Narrow } from 'abitype'\nimport { parseAccount } from '../../accounts/utils/parseAccount.js'\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport { BaseError } from '../../errors/base.js'\nimport {\n AtomicityNotSupportedError,\n UnsupportedNonOptionalCapabilityError,\n} from '../../errors/rpc.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Account, GetAccountParameter } from '../../types/account.js'\nimport type { Call, Calls } from '../../types/calls.js'\nimport type { ExtractCapabilities } from '../../types/capabilities.js'\nimport type { Chain, DeriveChain } from '../../types/chain.js'\nimport type { WalletSendCallsParameters } from '../../types/eip1193.js'\nimport type { Hex } from '../../types/misc.js'\nimport type { Prettify } from '../../types/utils.js'\nimport { encodeFunctionData } from '../../utils/abi/encodeFunctionData.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport { concat } from '../../utils/data/concat.js'\nimport { hexToBigInt } from '../../utils/encoding/fromHex.js'\nimport { numberToHex } from '../../utils/encoding/toHex.js'\nimport { getTransactionError } from '../../utils/errors/getTransactionError.js'\nimport { sendTransaction } from './sendTransaction.js'\n\nexport const fallbackMagicIdentifier =\n '0x5792579257925792579257925792579257925792579257925792579257925792'\nexport const fallbackTransactionErrorMagicIdentifier = numberToHex(0, {\n size: 32,\n})\n\nexport type SendCallsParameters<\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n chainOverride extends Chain | undefined = Chain | undefined,\n calls extends readonly unknown[] = readonly unknown[],\n //\n _chain extends Chain | undefined = DeriveChain<chain, chainOverride>,\n> = {\n chain?: chainOverride | Chain | undefined\n calls: Calls<Narrow<calls>>\n capabilities?: ExtractCapabilities<'sendCalls', 'Request'> | undefined\n experimental_fallback?: boolean | undefined\n experimental_fallbackDelay?: number | undefined\n forceAtomic?: boolean | undefined\n id?: string | undefined\n version?: WalletSendCallsParameters[number]['version'] | undefined\n} & GetAccountParameter<account, Account | Address, false, true>\n\nexport type SendCallsReturnType = Prettify<{\n capabilities?: ExtractCapabilities<'sendCalls', 'ReturnType'> | undefined\n id: string\n}>\n\nexport type SendCallsErrorType = RequestErrorType | ErrorType\n\n/**\n * Requests the connected wallet to send a batch of calls.\n *\n * - Docs: https://viem.sh/docs/actions/wallet/sendCalls\n * - JSON-RPC Methods: [`wallet_sendCalls`](https://eips.ethereum.org/EIPS/eip-5792)\n *\n * @param client - Client to use\n * @returns Transaction identifier. {@link SendCallsReturnType}\n *\n * @example\n * import { createWalletClient, custom } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { sendCalls } from 'viem/actions'\n *\n * const client = createWalletClient({\n * chain: mainnet,\n * transport: custom(window.ethereum),\n * })\n * const id = await sendCalls(client, {\n * account: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',\n * calls: [\n * {\n * data: '0xdeadbeef',\n * to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',\n * },\n * {\n * to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',\n * value: 69420n,\n * },\n * ],\n * })\n */\nexport async function sendCalls<\n const calls extends readonly unknown[],\n chain extends Chain | undefined,\n account extends Account | undefined = undefined,\n chainOverride extends Chain | undefined = undefined,\n>(\n client: Client<Transport, chain, account>,\n parameters: SendCallsParameters<chain, account, chainOverride, calls>,\n): Promise<SendCallsReturnType> {\n const {\n account: account_ = client.account,\n chain = client.chain,\n experimental_fallback,\n experimental_fallbackDelay = 32,\n forceAtomic = false,\n id,\n version = '2.0.0',\n } = parameters\n\n const account = account_ ? parseAccount(account_) : null\n\n let capabilities = parameters.capabilities\n\n if (client.dataSuffix && !parameters.capabilities?.dataSuffix) {\n if (typeof client.dataSuffix === 'string')\n capabilities = {\n ...parameters.capabilities,\n dataSuffix: { value: client.dataSuffix, optional: true },\n }\n else\n capabilities = {\n ...parameters.capabilities,\n dataSuffix: {\n value: client.dataSuffix.value,\n ...(client.dataSuffix.required ? {} : { optional: true }),\n },\n }\n }\n\n const calls = parameters.calls.map((call_: unknown) => {\n const call = call_ as Call\n\n const data = call.abi\n ? encodeFunctionData({\n abi: call.abi,\n functionName: call.functionName,\n args: call.args,\n })\n : call.data\n\n return {\n data: call.dataSuffix && data ? concat([data, call.dataSuffix]) : data,\n to: call.to,\n value: call.value ? numberToHex(call.value) : undefined,\n }\n })\n\n try {\n const response = await client.request(\n {\n method: 'wallet_sendCalls',\n params: [\n {\n atomicRequired: forceAtomic,\n calls,\n capabilities,\n chainId: numberToHex(chain!.id),\n from: account?.address,\n id,\n version,\n },\n ],\n },\n { retryCount: 0 },\n )\n if (typeof response === 'string') return { id: response }\n return response as never\n } catch (err) {\n const error = err as BaseError\n\n // If the transport does not support EIP-5792, fall back to\n // `eth_sendTransaction`.\n if (\n experimental_fallback &&\n (error.name === 'MethodNotFoundRpcError' ||\n error.name === 'MethodNotSupportedRpcError' ||\n error.name === 'UnknownRpcError' ||\n error.details\n .toLowerCase()\n .includes('does not exist / is not available') ||\n error.details.toLowerCase().includes('missing or invalid. request()') ||\n error.details\n .toLowerCase()\n .includes('did not match any variant of untagged enum') ||\n error.details\n .toLowerCase()\n .includes('account upgraded to unsupported contract') ||\n error.details.toLowerCase().includes('eip-7702 not supported') ||\n error.details.toLowerCase().includes('unsupported wc_ method') ||\n // magic.link\n error.details\n .toLowerCase()\n .includes('feature toggled misconfigured') ||\n // Trust Wallet\n error.details\n .toLowerCase()\n .includes(\n 'jsonrpcengine: response has no error or result for request',\n ))\n ) {\n if (capabilities) {\n const hasNonOptionalCapability = Object.values(capabilities).some(\n (capability) => !capability.optional,\n )\n if (hasNonOptionalCapability) {\n const message =\n 'non-optional `capabilities` are not supported on fallback to `eth_sendTransaction`.'\n throw new UnsupportedNonOptionalCapabilityError(\n new BaseError(message, {\n details: message,\n }),\n )\n }\n }\n if (forceAtomic && calls.length > 1) {\n const message =\n '`forceAtomic` is not supported on fallback to `eth_sendTransaction`.'\n throw new AtomicityNotSupportedError(\n new BaseError(message, {\n details: message,\n }),\n )\n }\n\n const promises: Promise<Hex>[] = []\n for (const call of calls) {\n const promise = sendTransaction(client, {\n account,\n chain,\n data: call.data,\n to: call.to,\n value: call.value ? hexToBigInt(call.value) : undefined,\n })\n promises.push(promise)\n\n // Note: some browser wallets require a small delay between transactions\n // to prevent duplicate JSON-RPC requests.\n if (experimental_fallbackDelay > 0)\n await new Promise((resolve) =>\n setTimeout(resolve, experimental_fallbackDelay),\n )\n }\n\n const results = await Promise.allSettled(promises)\n if (results.every((r) => r.status === 'rejected')) throw results[0].reason\n\n const hashes = results.map((result) => {\n if (result.status === 'fulfilled') return result.value\n return fallbackTransactionErrorMagicIdentifier\n })\n return {\n id: concat([\n ...hashes,\n numberToHex(chain!.id, { size: 32 }),\n fallbackMagicIdentifier,\n ]),\n }\n }\n\n throw getTransactionError(err as BaseError, {\n ...parameters,\n account,\n chain: parameters.chain!,\n })\n }\n}\n","import type { Address } from 'abitype'\n\nimport type { JsonRpcAccount } from '../accounts/types.js'\nimport {\n type ParseAccountErrorType,\n parseAccount,\n} from '../accounts/utils/parseAccount.js'\nimport type { ErrorType } from '../errors/utils.js'\nimport type { Account } from '../types/account.js'\nimport type { BlockTag } from '../types/block.js'\nimport type { Chain } from '../types/chain.js'\nimport type { DataSuffix } from '../types/dataSuffix.js'\nimport type {\n EIP1193RequestFn,\n EIP1474Methods,\n RpcSchema,\n} from '../types/eip1193.js'\nimport type { ExactPartial, Prettify } from '../types/utils.js'\nimport type {\n CcipRequestParameters,\n CcipRequestReturnType,\n} from '../utils/ccip.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 rpcSchema extends RpcSchema | undefined = 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 * Default block tag to use for RPC requests.\n *\n * If the chain supports a pre-confirmation mechanism\n * (set via `chain.experimental_preconfirmationTime`), defaults to `'pending'`.\n *\n * @default 'latest'\n */\n experimental_blockTag?: BlockTag | undefined\n /**\n * Time (in ms) that cached data will remain in memory.\n * @default chain.blockTime / 3\n */\n cacheTime?: number | undefined\n /**\n * [CCIP Read](https://eips.ethereum.org/EIPS/eip-3668) configuration.\n * If `false`, the client will not support offchain CCIP lookups.\n */\n ccipRead?:\n | {\n /**\n * A function that will be called to make the offchain CCIP lookup request.\n * @see https://eips.ethereum.org/EIPS/eip-3668#client-lookup-protocol\n */\n request?: (\n parameters: CcipRequestParameters,\n ) => Promise<CcipRequestReturnType>\n }\n | false\n | undefined\n /** Chain for the client. */\n chain?: Chain | undefined | chain\n /** Data suffix to append to transaction data. */\n dataSuffix?: DataSuffix | undefined\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 chain.blockTime / 3\n */\n pollingInterval?: number | undefined\n /**\n * Typed JSON-RPC schema for the client.\n */\n rpcSchema?: rpcSchema | 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<\n transport extends Transport = Transport,\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n> = Pick<\n PublicActions<transport, chain, account>,\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<chain, account>, '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 &\n ExactPartial<ExtendableProtectedActions<transport, chain, account>>,\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'] | undefined\n /** Time (in ms) that cached data will remain in memory. */\n cacheTime: number\n /** [CCIP Read](https://eips.ethereum.org/EIPS/eip-3668) configuration. */\n ccipRead?: ClientConfig['ccipRead'] | undefined\n /** Chain for the client. */\n chain: chain\n /** Data suffix to append to transaction data. */\n dataSuffix?: DataSuffix | undefined\n /** Default block tag to use for RPC requests. */\n experimental_blockTag?: BlockTag | undefined\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 /** Enable deployless multicall. */\n deployless?: boolean | 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\nexport function createClient<\n transport extends Transport,\n chain extends Chain | undefined = undefined,\n accountOrAddress extends Account | Address | undefined = undefined,\n rpcSchema extends RpcSchema | undefined = undefined,\n>(\n parameters: ClientConfig<transport, chain, accountOrAddress, rpcSchema>,\n): Prettify<\n Client<\n transport,\n chain,\n accountOrAddress extends Address\n ? Prettify<JsonRpcAccount<accountOrAddress>>\n : accountOrAddress,\n rpcSchema\n >\n>\n\nexport function createClient(parameters: ClientConfig): Client {\n const {\n batch,\n chain,\n ccipRead,\n dataSuffix,\n key = 'base',\n name = 'Base Client',\n type = 'base',\n } = parameters\n\n const experimental_blockTag =\n parameters.experimental_blockTag ??\n (typeof chain?.experimental_preconfirmationTime === 'number'\n ? 'pending'\n : undefined)\n const blockTime = chain?.blockTime ?? 12_000\n\n const defaultPollingInterval = Math.min(\n Math.max(Math.floor(blockTime / 2), 500),\n 4_000,\n )\n const pollingInterval = parameters.pollingInterval ?? defaultPollingInterval\n const cacheTime = parameters.cacheTime ?? pollingInterval\n\n const account = parameters.account\n ? parseAccount(parameters.account)\n : undefined\n const { config, request, value } = parameters.transport({\n account,\n chain,\n pollingInterval,\n })\n const transport = { ...config, ...value }\n\n const client = {\n account,\n batch,\n cacheTime,\n ccipRead,\n chain,\n dataSuffix,\n key,\n name,\n pollingInterval,\n request,\n transport,\n type,\n uid: uid(),\n ...(experimental_blockTag ? { experimental_blockTag } : {}),\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 as any) })\n }\n }\n\n return Object.assign(client, { extend: extend(client) as any })\n}\n\n/**\n * Defines a typed JSON-RPC schema for the client.\n * Note: This is a runtime noop function.\n */\nexport function rpcSchema<rpcSchema extends RpcSchema>(): rpcSchema {\n return null as any\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 { ErrorType } from '../../errors/utils.js'\nimport type {\n AuthorizationList,\n SerializedAuthorizationList,\n} from '../../types/authorization.js'\nimport { toHex } from '../encoding/toHex.js'\nimport { toYParitySignatureArray } from '../transaction/serializeTransaction.js'\n\nexport type SerializeAuthorizationListReturnType = SerializedAuthorizationList\n\nexport type SerializeAuthorizationListErrorType = ErrorType\n\n/*\n * Serializes an EIP-7702 authorization list.\n */\nexport function serializeAuthorizationList(\n authorizationList?: AuthorizationList<number, true> | undefined,\n): SerializeAuthorizationListReturnType {\n if (!authorizationList || authorizationList.length === 0) return []\n\n const serializedAuthorizationList = []\n for (const authorization of authorizationList) {\n const { chainId, nonce, ...signature } = authorization\n const contractAddress = authorization.address\n serializedAuthorizationList.push([\n chainId ? toHex(chainId) : '0x',\n contractAddress,\n nonce ? toHex(nonce) : '0x',\n ...toYParitySignatureArray({}, signature),\n ])\n }\n\n return serializedAuthorizationList as {} as SerializeAuthorizationListReturnType\n}\n","import {\n InvalidLegacyVError,\n type InvalidLegacyVErrorType,\n} from '../../errors/transaction.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type {\n ByteArray,\n Hex,\n Signature,\n SignatureLegacy,\n} from '../../types/misc.js'\nimport type {\n TransactionSerializable,\n TransactionSerializableEIP1559,\n TransactionSerializableEIP2930,\n TransactionSerializableEIP4844,\n TransactionSerializableEIP7702,\n TransactionSerializableGeneric,\n TransactionSerializableLegacy,\n TransactionSerialized,\n TransactionSerializedEIP1559,\n TransactionSerializedEIP2930,\n TransactionSerializedEIP4844,\n TransactionSerializedEIP7702,\n TransactionSerializedLegacy,\n TransactionType,\n} from '../../types/transaction.js'\nimport type { MaybePromise, OneOf } from '../../types/utils.js'\nimport {\n type SerializeAuthorizationListErrorType,\n serializeAuthorizationList,\n} from '../authorization/serializeAuthorizationList.js'\nimport {\n type BlobsToCommitmentsErrorType,\n blobsToCommitments,\n} from '../blob/blobsToCommitments.js'\nimport {\n blobsToProofs,\n type blobsToProofsErrorType,\n} from '../blob/blobsToProofs.js'\nimport {\n type CommitmentsToVersionedHashesErrorType,\n commitmentsToVersionedHashes,\n} from '../blob/commitmentsToVersionedHashes.js'\nimport {\n type ToBlobSidecarsErrorType,\n toBlobSidecars,\n} from '../blob/toBlobSidecars.js'\nimport { type ConcatHexErrorType, concatHex } from '../data/concat.js'\nimport { trim } from '../data/trim.js'\nimport {\n bytesToHex,\n type NumberToHexErrorType,\n numberToHex,\n} from '../encoding/toHex.js'\nimport { type ToRlpErrorType, toRlp } from '../encoding/toRlp.js'\n\nimport {\n type AssertTransactionEIP1559ErrorType,\n type AssertTransactionEIP2930ErrorType,\n type AssertTransactionEIP4844ErrorType,\n type AssertTransactionEIP7702ErrorType,\n type AssertTransactionLegacyErrorType,\n assertTransactionEIP1559,\n assertTransactionEIP2930,\n assertTransactionEIP4844,\n assertTransactionEIP7702,\n assertTransactionLegacy,\n} from './assertTransaction.js'\nimport {\n type GetTransactionType,\n type GetTransactionTypeErrorType,\n getTransactionType,\n} from './getTransactionType.js'\nimport {\n type SerializeAccessListErrorType,\n serializeAccessList,\n} from './serializeAccessList.js'\n\nexport type SerializedTransactionReturnType<\n transaction extends TransactionSerializable = TransactionSerializable,\n ///\n _transactionType extends TransactionType = GetTransactionType<transaction>,\n> = TransactionSerialized<_transactionType>\n\nexport type SerializeTransactionFn<\n transaction extends TransactionSerializableGeneric = TransactionSerializable,\n ///\n _transactionType extends TransactionType = never,\n> = (\n transaction: OneOf<TransactionSerializable | transaction>,\n signature?: Signature | undefined,\n) => MaybePromise<\n SerializedTransactionReturnType<\n OneOf<TransactionSerializable | transaction>,\n _transactionType\n >\n>\n\nexport type SerializeTransactionErrorType =\n | GetTransactionTypeErrorType\n | SerializeTransactionEIP1559ErrorType\n | SerializeTransactionEIP2930ErrorType\n | SerializeTransactionEIP4844ErrorType\n | SerializeTransactionEIP7702ErrorType\n | SerializeTransactionLegacyErrorType\n | ErrorType\n\nexport function serializeTransaction<\n const transaction extends TransactionSerializable,\n ///\n _transactionType extends TransactionType = GetTransactionType<transaction>,\n>(\n transaction: transaction,\n signature?: Signature | undefined,\n): SerializedTransactionReturnType<transaction, _transactionType> {\n const type = getTransactionType(transaction) as GetTransactionType\n\n if (type === 'eip1559')\n return serializeTransactionEIP1559(\n transaction as TransactionSerializableEIP1559,\n signature,\n ) as SerializedTransactionReturnType<transaction>\n\n if (type === 'eip2930')\n return serializeTransactionEIP2930(\n transaction as TransactionSerializableEIP2930,\n signature,\n ) as SerializedTransactionReturnType<transaction>\n\n if (type === 'eip4844')\n return serializeTransactionEIP4844(\n transaction as TransactionSerializableEIP4844,\n signature,\n ) as SerializedTransactionReturnType<transaction>\n\n if (type === 'eip7702')\n return serializeTransactionEIP7702(\n transaction as TransactionSerializableEIP7702,\n signature,\n ) as SerializedTransactionReturnType<transaction>\n\n return serializeTransactionLegacy(\n transaction as TransactionSerializableLegacy,\n signature as SignatureLegacy,\n ) as SerializedTransactionReturnType<transaction>\n}\n\ntype SerializeTransactionEIP7702ErrorType =\n | AssertTransactionEIP7702ErrorType\n | SerializeAuthorizationListErrorType\n | ConcatHexErrorType\n | InvalidLegacyVErrorType\n | NumberToHexErrorType\n | ToRlpErrorType\n | SerializeAccessListErrorType\n | ErrorType\n\nfunction serializeTransactionEIP7702(\n transaction: TransactionSerializableEIP7702,\n signature?: Signature | undefined,\n): TransactionSerializedEIP7702 {\n const {\n authorizationList,\n chainId,\n gas,\n nonce,\n to,\n value,\n maxFeePerGas,\n maxPriorityFeePerGas,\n accessList,\n data,\n } = transaction\n\n assertTransactionEIP7702(transaction)\n\n const serializedAccessList = serializeAccessList(accessList)\n const serializedAuthorizationList =\n serializeAuthorizationList(authorizationList)\n\n return concatHex([\n '0x04',\n toRlp([\n numberToHex(chainId),\n nonce ? numberToHex(nonce) : '0x',\n maxPriorityFeePerGas ? numberToHex(maxPriorityFeePerGas) : '0x',\n maxFeePerGas ? numberToHex(maxFeePerGas) : '0x',\n gas ? numberToHex(gas) : '0x',\n to ?? '0x',\n value ? numberToHex(value) : '0x',\n data ?? '0x',\n serializedAccessList,\n serializedAuthorizationList,\n ...toYParitySignatureArray(transaction, signature),\n ]),\n ]) as TransactionSerializedEIP7702\n}\n\ntype SerializeTransactionEIP4844ErrorType =\n | AssertTransactionEIP4844ErrorType\n | BlobsToCommitmentsErrorType\n | CommitmentsToVersionedHashesErrorType\n | blobsToProofsErrorType\n | ToBlobSidecarsErrorType\n | ConcatHexErrorType\n | InvalidLegacyVErrorType\n | NumberToHexErrorType\n | ToRlpErrorType\n | SerializeAccessListErrorType\n | ErrorType\n\nfunction serializeTransactionEIP4844(\n transaction: TransactionSerializableEIP4844,\n signature?: Signature | undefined,\n): TransactionSerializedEIP4844 {\n const {\n chainId,\n gas,\n nonce,\n to,\n value,\n maxFeePerBlobGas,\n maxFeePerGas,\n maxPriorityFeePerGas,\n accessList,\n data,\n } = transaction\n\n assertTransactionEIP4844(transaction)\n\n let blobVersionedHashes = transaction.blobVersionedHashes\n let sidecars = transaction.sidecars\n // If `blobs` are passed, we will need to compute the KZG commitments & proofs.\n if (\n transaction.blobs &&\n (typeof blobVersionedHashes === 'undefined' ||\n typeof sidecars === 'undefined')\n ) {\n const blobs = (\n typeof transaction.blobs[0] === 'string'\n ? transaction.blobs\n : (transaction.blobs as ByteArray[]).map((x) => bytesToHex(x))\n ) as Hex[]\n const kzg = transaction.kzg!\n const commitments = blobsToCommitments({\n blobs,\n kzg,\n })\n\n if (typeof blobVersionedHashes === 'undefined')\n blobVersionedHashes = commitmentsToVersionedHashes({\n commitments,\n })\n if (typeof sidecars === 'undefined') {\n const proofs = blobsToProofs({ blobs, commitments, kzg })\n sidecars = toBlobSidecars({ blobs, commitments, proofs })\n }\n }\n\n const serializedAccessList = serializeAccessList(accessList)\n\n const serializedTransaction = [\n numberToHex(chainId),\n nonce ? numberToHex(nonce) : '0x',\n maxPriorityFeePerGas ? numberToHex(maxPriorityFeePerGas) : '0x',\n maxFeePerGas ? numberToHex(maxFeePerGas) : '0x',\n gas ? numberToHex(gas) : '0x',\n to ?? '0x',\n value ? numberToHex(value) : '0x',\n data ?? '0x',\n serializedAccessList,\n maxFeePerBlobGas ? numberToHex(maxFeePerBlobGas) : '0x',\n blobVersionedHashes ?? [],\n ...toYParitySignatureArray(transaction, signature),\n ] as const\n\n const blobs: Hex[] = []\n const commitments: Hex[] = []\n const proofs: Hex[] = []\n if (sidecars)\n for (let i = 0; i < sidecars.length; i++) {\n const { blob, commitment, proof } = sidecars[i]\n blobs.push(blob)\n commitments.push(commitment)\n proofs.push(proof)\n }\n\n return concatHex([\n '0x03',\n sidecars\n ? // If sidecars are enabled, envelope turns into a \"wrapper\":\n toRlp([serializedTransaction, blobs, commitments, proofs])\n : // If sidecars are disabled, standard envelope is used:\n toRlp(serializedTransaction),\n ]) as TransactionSerializedEIP4844\n}\n\ntype SerializeTransactionEIP1559ErrorType =\n | AssertTransactionEIP1559ErrorType\n | ConcatHexErrorType\n | InvalidLegacyVErrorType\n | NumberToHexErrorType\n | ToRlpErrorType\n | SerializeAccessListErrorType\n | ErrorType\n\nfunction serializeTransactionEIP1559(\n transaction: TransactionSerializableEIP1559,\n signature?: Signature | undefined,\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 numberToHex(chainId),\n nonce ? numberToHex(nonce) : '0x',\n maxPriorityFeePerGas ? numberToHex(maxPriorityFeePerGas) : '0x',\n maxFeePerGas ? numberToHex(maxFeePerGas) : '0x',\n gas ? numberToHex(gas) : '0x',\n to ?? '0x',\n value ? numberToHex(value) : '0x',\n data ?? '0x',\n serializedAccessList,\n ...toYParitySignatureArray(transaction, signature),\n ]\n\n return concatHex([\n '0x02',\n toRlp(serializedTransaction),\n ]) as TransactionSerializedEIP1559\n}\n\ntype SerializeTransactionEIP2930ErrorType =\n | AssertTransactionEIP2930ErrorType\n | ConcatHexErrorType\n | InvalidLegacyVErrorType\n | NumberToHexErrorType\n | ToRlpErrorType\n | SerializeAccessListErrorType\n | ErrorType\n\nfunction serializeTransactionEIP2930(\n transaction: TransactionSerializableEIP2930,\n signature?: Signature | undefined,\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 numberToHex(chainId),\n nonce ? numberToHex(nonce) : '0x',\n gasPrice ? numberToHex(gasPrice) : '0x',\n gas ? numberToHex(gas) : '0x',\n to ?? '0x',\n value ? numberToHex(value) : '0x',\n data ?? '0x',\n serializedAccessList,\n ...toYParitySignatureArray(transaction, signature),\n ]\n\n return concatHex([\n '0x01',\n toRlp(serializedTransaction),\n ]) as TransactionSerializedEIP2930\n}\n\ntype SerializeTransactionLegacyErrorType =\n | AssertTransactionLegacyErrorType\n | InvalidLegacyVErrorType\n | NumberToHexErrorType\n | ToRlpErrorType\n | ErrorType\n\nfunction serializeTransactionLegacy(\n transaction: TransactionSerializableLegacy,\n signature?: SignatureLegacy | undefined,\n): TransactionSerializedLegacy {\n const { chainId = 0, gas, data, nonce, to, value, gasPrice } = transaction\n\n assertTransactionLegacy(transaction)\n\n let serializedTransaction = [\n nonce ? numberToHex(nonce) : '0x',\n gasPrice ? numberToHex(gasPrice) : '0x',\n gas ? numberToHex(gas) : '0x',\n to ?? '0x',\n value ? numberToHex(value) : '0x',\n data ?? '0x',\n ]\n\n if (signature) {\n const v = (() => {\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 // EIP-155 (explicit chainId)\n if (chainId > 0)\n return BigInt(chainId * 2) + BigInt(35n + signature.v - 27n)\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 const r = trim(signature.r)\n const s = trim(signature.s)\n\n serializedTransaction = [\n ...serializedTransaction,\n numberToHex(v),\n r === '0x00' ? '0x' : r,\n s === '0x00' ? '0x' : s,\n ]\n } else if (chainId > 0) {\n serializedTransaction = [\n ...serializedTransaction,\n numberToHex(chainId),\n '0x',\n '0x',\n ]\n }\n\n return toRlp(serializedTransaction) as TransactionSerializedLegacy\n}\n\nexport function toYParitySignatureArray(\n transaction: TransactionSerializableGeneric,\n signature_?: Signature | undefined,\n) {\n const signature = signature_ ?? transaction\n const { v, yParity } = signature\n\n if (typeof signature.r === 'undefined') return []\n if (typeof signature.s === 'undefined') return []\n if (typeof v === 'undefined' && typeof yParity === 'undefined') return []\n\n const r = trim(signature.r)\n const s = trim(signature.s)\n\n const yParity_ = (() => {\n if (typeof yParity === 'number') return yParity ? numberToHex(1) : '0x'\n if (v === 0n) return '0x'\n if (v === 1n) return numberToHex(1)\n\n return v === 27n ? '0x' : numberToHex(1)\n })()\n\n return [yParity_, r === '0x00' ? '0x' : r, s === '0x00' ? '0x' : s]\n}\n","import { versionedHashVersionKzg } from '../../constants/kzg.js'\nimport { maxUint256 } from '../../constants/number.js'\nimport {\n InvalidAddressError,\n type InvalidAddressErrorType,\n} from '../../errors/address.js'\nimport { BaseError, type BaseErrorType } from '../../errors/base.js'\nimport {\n EmptyBlobError,\n type EmptyBlobErrorType,\n InvalidVersionedHashSizeError,\n type InvalidVersionedHashSizeErrorType,\n InvalidVersionedHashVersionError,\n type InvalidVersionedHashVersionErrorType,\n} from '../../errors/blob.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 TransactionSerializableEIP4844,\n TransactionSerializableEIP7702,\n TransactionSerializableLegacy,\n} from '../../types/transaction.js'\nimport { type IsAddressErrorType, isAddress } from '../address/isAddress.js'\nimport { size } from '../data/size.js'\nimport { slice } from '../data/slice.js'\nimport { hexToNumber } from '../encoding/fromHex.js'\n\nexport type AssertTransactionEIP7702ErrorType =\n | AssertTransactionEIP1559ErrorType\n | InvalidAddressErrorType\n | InvalidChainIdErrorType\n | ErrorType\n\nexport function assertTransactionEIP7702(\n transaction: TransactionSerializableEIP7702,\n) {\n const { authorizationList } = transaction\n if (authorizationList) {\n for (const authorization of authorizationList) {\n const { chainId } = authorization\n const address = authorization.address\n if (!isAddress(address)) throw new InvalidAddressError({ address })\n if (chainId < 0) throw new InvalidChainIdError({ chainId })\n }\n }\n assertTransactionEIP1559(transaction as {} as TransactionSerializableEIP1559)\n}\n\nexport type AssertTransactionEIP4844ErrorType =\n | AssertTransactionEIP1559ErrorType\n | EmptyBlobErrorType\n | InvalidVersionedHashSizeErrorType\n | InvalidVersionedHashVersionErrorType\n | ErrorType\n\nexport function assertTransactionEIP4844(\n transaction: TransactionSerializableEIP4844,\n) {\n const { blobVersionedHashes } = transaction\n if (blobVersionedHashes) {\n if (blobVersionedHashes.length === 0) throw new EmptyBlobError()\n for (const hash of blobVersionedHashes) {\n const size_ = size(hash)\n const version = hexToNumber(slice(hash, 0, 1))\n if (size_ !== 32)\n throw new InvalidVersionedHashSizeError({ hash, size: size_ })\n if (version !== versionedHashVersionKzg)\n throw new InvalidVersionedHashVersionError({\n hash,\n version,\n })\n }\n }\n assertTransactionEIP1559(transaction as {} as TransactionSerializableEIP1559)\n}\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, maxFeePerGas, to } = transaction\n if (chainId <= 0) throw new InvalidChainIdError({ chainId })\n if (to && !isAddress(to)) throw new InvalidAddressError({ address: to })\n if (maxFeePerGas && maxFeePerGas > maxUint256)\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 > maxUint256)\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 { chainId, maxPriorityFeePerGas, gasPrice, maxFeePerGas, to } =\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 > maxUint256)\n throw new FeeCapTooHighError({ maxFeePerGas: gasPrice })\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 | undefined,\n): RecursiveArray<Hex> {\n if (!accessList || accessList.length === 0) return []\n\n const serializedAccessList = []\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, { strict: false })) {\n throw new InvalidAddressError({ address })\n }\n\n serializedAccessList.push([address, storageKeys])\n }\n return serializedAccessList\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 AtomicityNotSupportedError,\n type AtomicityNotSupportedErrorType,\n AtomicReadyWalletRejectedUpgradeError,\n type AtomicReadyWalletRejectedUpgradeErrorType,\n BundleTooLargeError,\n type BundleTooLargeErrorType,\n ChainDisconnectedError,\n type ChainDisconnectedErrorType,\n DuplicateIdError,\n type DuplicateIdErrorType,\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 UnknownBundleIdError,\n type UnknownBundleIdErrorType,\n UnknownRpcError,\n type UnknownRpcErrorType,\n UnsupportedChainIdError,\n type UnsupportedChainIdErrorType,\n UnsupportedNonOptionalCapabilityError,\n type UnsupportedNonOptionalCapabilityErrorType,\n UnsupportedProviderMethodError,\n type UnsupportedProviderMethodErrorType,\n UserRejectedRequestError,\n type UserRejectedRequestErrorType,\n WalletConnectSessionSettlementError,\n type WalletConnectSessionSettlementErrorType,\n} from '../errors/rpc.js'\nimport type { ErrorType } from '../errors/utils.js'\nimport type {\n EIP1193RequestFn,\n EIP1193RequestOptions,\n} from '../types/eip1193.js'\nimport { stringToHex } from './encoding/toHex.js'\nimport type { CreateBatchSchedulerErrorType } from './promise/createBatchScheduler.js'\nimport { withDedupe } from './promise/withDedupe.js'\nimport { type WithRetryErrorType, withRetry } from './promise/withRetry.js'\nimport type { GetSocketRpcClientErrorType } from './rpc/socket.js'\nimport { stringify } from './stringify.js'\n\nexport type RequestErrorType =\n | AtomicityNotSupportedErrorType\n | AtomicReadyWalletRejectedUpgradeErrorType\n | BundleTooLargeErrorType\n | ChainDisconnectedErrorType\n | CreateBatchSchedulerErrorType\n | DuplicateIdErrorType\n | HttpRequestErrorType\n | InternalRpcErrorType\n | InvalidInputRpcErrorType\n | InvalidParamsRpcErrorType\n | InvalidRequestRpcErrorType\n | GetSocketRpcClientErrorType\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 | UnknownBundleIdErrorType\n | UnknownRpcErrorType\n | UnsupportedChainIdErrorType\n | UnsupportedNonOptionalCapabilityErrorType\n | UnsupportedProviderMethodErrorType\n | UserRejectedRequestErrorType\n | WalletConnectSessionSettlementErrorType\n | WebSocketRequestErrorType\n | WithRetryErrorType\n | ErrorType\n\nexport function buildRequest<request extends (args: any) => Promise<any>>(\n request: request,\n options: EIP1193RequestOptions = {},\n): EIP1193RequestFn {\n return async (args, overrideOptions = {}) => {\n const {\n dedupe = false,\n methods,\n retryDelay = 150,\n retryCount = 3,\n uid,\n } = {\n ...options,\n ...overrideOptions,\n }\n\n const { method } = args\n if (methods?.exclude?.includes(method))\n throw new MethodNotSupportedRpcError(new Error('method not supported'), {\n method,\n })\n if (methods?.include && !methods.include.includes(method))\n throw new MethodNotSupportedRpcError(new Error('method not supported'), {\n method,\n })\n\n const requestId = dedupe\n ? stringToHex(`${uid}.${stringify(args)}`)\n : undefined\n return withDedupe(\n () =>\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, { method: args.method })\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 method: args.method,\n })\n // -32005\n case LimitExceededRpcError.code:\n throw new LimitExceededRpcError(err)\n // -32006\n case JsonRpcVersionUnsupportedError.code:\n throw new JsonRpcVersionUnsupportedError(err)\n\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\n // 5700\n case UnsupportedNonOptionalCapabilityError.code:\n throw new UnsupportedNonOptionalCapabilityError(err)\n // 5710\n case UnsupportedChainIdError.code:\n throw new UnsupportedChainIdError(err)\n // 5720\n case DuplicateIdError.code:\n throw new DuplicateIdError(err)\n // 5730\n case UnknownBundleIdError.code:\n throw new UnknownBundleIdError(err)\n // 5740\n case BundleTooLargeError.code:\n throw new BundleTooLargeError(err)\n // 5750\n case AtomicReadyWalletRejectedUpgradeError.code:\n throw new AtomicReadyWalletRejectedUpgradeError(err)\n // 5760\n case AtomicityNotSupportedError.code:\n throw new AtomicityNotSupportedError(err)\n\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\n // WalletConnect: Session Settlement Failed\n // https://docs.walletconnect.com/2.0/specs/clients/sign/error-codes\n case WalletConnectSessionSettlementError.code:\n throw new WalletConnectSessionSettlementError(err)\n\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/))\n return Number.parseInt(retryAfter, 10) * 1000\n }\n\n // Otherwise, let's retry with an exponential backoff.\n return ~~(1 << count) * retryDelay\n },\n retryCount,\n shouldRetry: ({ error }) => shouldRetry(error),\n },\n ),\n { enabled: dedupe, id: requestId },\n )\n }\n}\n\n/** @internal */\nexport function shouldRetry(error: Error) {\n if ('code' in error && typeof error.code === 'number') {\n if (error.code === -1) return true // Unknown error\n if (error.code === LimitExceededRpcError.code) return true\n if (error.code === InternalRpcError.code) return true\n return false\n }\n if (error instanceof HttpRequestError && error.status) {\n // Forbidden\n if (error.status === 403) return true\n // Request Timeout\n if (error.status === 408) return true\n // Request Entity Too Large\n if (error.status === 413) return true\n // Too Many Requests\n if (error.status === 429) return true\n // Internal Server Error\n if (error.status === 500) return true\n // Bad Gateway\n if (error.status === 502) return true\n // Service Unavailable\n if (error.status === 503) return true\n // Gateway Timeout\n if (error.status === 504) return true\n return false\n }\n return true\n}\n","import { LruMap } from '../lru.js'\n\n/** @internal */\nexport const promiseCache = /*#__PURE__*/ new LruMap<Promise<any>>(8192)\n\ntype WithDedupeOptions = {\n enabled?: boolean | undefined\n id?: string | undefined\n}\n\n/** Deduplicates in-flight promises. */\nexport function withDedupe<data>(\n fn: () => Promise<data>,\n { enabled = true, id }: WithDedupeOptions,\n): Promise<data> {\n if (!enabled || !id) return fn()\n if (promiseCache.get(id)) return promiseCache.get(id)!\n const promise = fn().finally(() => promiseCache.delete(id))\n promiseCache.set(id, promise)\n return promise\n}\n","import type { Chain, ChainFormatters } from '../../types/chain.js'\nimport type { Assign, Prettify } from '../../types/utils.js'\n\nexport type DefineChainReturnType<chain extends Chain = Chain> = Prettify<\n chain &\n (chain['extendSchema'] extends Record<string, unknown>\n ? {\n extend: <const extended extends chain['extendSchema']>(\n extended: extended,\n ) => Assign<chain, extended>\n }\n : {})\n>\n\nexport function defineChain<\n formatters extends ChainFormatters,\n const chain extends Chain<formatters>,\n>(chain: chain): DefineChainReturnType<Assign<Chain<undefined>, chain>> {\n const chainInstance = {\n formatters: undefined,\n fees: undefined,\n serializers: undefined,\n ...chain,\n } as Assign<Chain<undefined>, chain>\n\n function extend(base: typeof chainInstance) {\n type ExtendFn = (base: typeof chainInstance) => unknown\n return (fnOrExtended: ExtendFn | Record<string, unknown>) => {\n const properties = (\n typeof fnOrExtended === 'function' ? fnOrExtended(base) : fnOrExtended\n ) as (typeof chainInstance)['extendSchema']\n const combined = { ...base, ...properties }\n return Object.assign(combined, { extend: extend(combined) })\n }\n }\n\n return Object.assign(chainInstance, {\n extend: extend(chainInstance),\n }) as never\n}\n\nexport function extendSchema<schema extends Record<string, unknown>>(): schema {\n return {} as schema\n}\n","// biome-ignore lint/performance/noBarrelFile: entrypoint module\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 {\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 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 type DecodeFunctionDataReturnType,\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 type EncodeEventTopicsReturnType,\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 { type EncodePackedErrorType, encodePacked } from './abi/encodePacked.js'\nexport {\n type FormatAbiItemErrorType,\n type FormatAbiParamErrorType,\n type FormatAbiParamsErrorType,\n formatAbiItem,\n formatAbiParams,\n} from './abi/formatAbiItem.js'\nexport {\n type FormatAbiItemWithArgsErrorType,\n formatAbiItemWithArgs,\n} from './abi/formatAbiItemWithArgs.js'\nexport {\n type GetAbiItemErrorType,\n type GetAbiItemParameters,\n getAbiItem,\n} from './abi/getAbiItem.js'\nexport {\n type ParseEventLogsErrorType,\n type ParseEventLogsParameters,\n type ParseEventLogsReturnType,\n parseEventLogs,\n} from './abi/parseEventLogs.js'\nexport {\n type ChecksumAddressErrorType,\n getAddress,\n} from './address/getAddress.js'\nexport {\n type GetContractAddressOptions,\n type GetCreate2AddressErrorType,\n type GetCreate2AddressOptions,\n type GetCreateAddressErrorType,\n type GetCreateAddressOptions,\n getContractAddress,\n getCreate2Address,\n getCreateAddress,\n} from './address/getContractAddress.js'\nexport { type IsAddressErrorType, isAddress } from './address/isAddress.js'\nexport {\n type IsAddressEqualErrorType,\n isAddressEqual,\n} from './address/isAddressEqual.js'\nexport {\n type HashAuthorizationErrorType,\n type HashAuthorizationParameters,\n type HashAuthorizationReturnType,\n hashAuthorization,\n} from './authorization/hashAuthorization.js'\nexport {\n type RecoverAuthorizationAddressErrorType,\n type RecoverAuthorizationAddressParameters,\n type RecoverAuthorizationAddressReturnType,\n recoverAuthorizationAddress,\n} from './authorization/recoverAuthorizationAddress.js'\nexport {\n type SerializeAuthorizationListErrorType,\n type SerializeAuthorizationListReturnType,\n serializeAuthorizationList,\n} from './authorization/serializeAuthorizationList.js'\nexport {\n type VerifyAuthorizationErrorType,\n type VerifyAuthorizationParameters,\n type VerifyAuthorizationReturnType,\n verifyAuthorization,\n} from './authorization/verifyAuthorization.js'\nexport {\n buildRequest,\n type RequestErrorType,\n} from './buildRequest.js'\nexport {\n ccipRequest,\n /** @deprecated Use `ccipRequest`. */\n ccipRequest as ccipFetch,\n type OffchainLookupErrorType,\n offchainLookup,\n offchainLookupAbiItem,\n offchainLookupSignature,\n} from './ccip.js'\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'\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 BytesToBigIntErrorType,\n type BytesToBigIntOpts,\n type BytesToBoolErrorType,\n type BytesToBoolOpts,\n type BytesToNumberErrorType,\n type BytesToNumberOpts,\n type BytesToStringErrorType,\n type BytesToStringOpts,\n bytesToBigInt,\n bytesToBigInt as bytesToBigint,\n bytesToBool,\n bytesToNumber,\n bytesToString,\n type FromBytesErrorType,\n type FromBytesParameters,\n type FromBytesReturnType,\n fromBytes,\n} from './encoding/fromBytes.js'\nexport {\n type AssertSizeErrorType,\n type FromHexErrorType,\n type FromHexParameters,\n type FromHexReturnType,\n fromHex,\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 hexToBigInt,\n hexToBool,\n hexToNumber,\n hexToString,\n} from './encoding/fromHex.js'\nexport {\n type FromRlpErrorType,\n fromRlp,\n} from './encoding/fromRlp.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 './encoding/toBytes.js'\nexport {\n type BoolToHexErrorType,\n type BoolToHexOpts,\n type BytesToHexErrorType,\n type BytesToHexOpts,\n boolToHex,\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 './encoding/toHex.js'\nexport {\n type BytesToRlpErrorType,\n type HexToRlpErrorType,\n type ToRlpErrorType,\n type ToRlpReturnType,\n toRlp,\n} from './encoding/toRlp.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 containsNodeError,\n type GetNodeErrorParameters,\n type GetNodeErrorReturnType,\n getNodeError,\n} from './errors/getNodeError.js'\nexport {\n type GetTransactionErrorParameters,\n type GetTransactionErrorReturnType,\n getTransactionError,\n} from './errors/getTransactionError.js'\nexport {\n type DefineBlockErrorType,\n defineBlock,\n type FormatBlockErrorType,\n type FormattedBlock,\n formatBlock,\n} from './formatters/block.js'\nexport { type ExtractErrorType, extract } from './formatters/extract.js'\nexport {\n type DefineFormatterErrorType,\n defineFormatter,\n} from './formatters/formatter.js'\nexport { type FormatLogErrorType, formatLog } from './formatters/log.js'\nexport {\n type DefineTransactionErrorType,\n defineTransaction,\n type FormatTransactionErrorType,\n type FormattedTransaction,\n formatTransaction,\n transactionType,\n} from './formatters/transaction.js'\nexport {\n type DefineTransactionReceiptErrorType,\n defineTransactionReceipt,\n type FormatTransactionReceiptErrorType,\n type FormattedTransactionReceipt,\n} from './formatters/transactionReceipt.js'\nexport {\n type DefineTransactionRequestErrorType,\n defineTransactionRequest,\n type FormatTransactionRequestErrorType,\n type FormattedTransactionRequest,\n formatTransactionRequest,\n} from './formatters/transactionRequest.js'\nexport { getAction } from './getAction.js'\nexport { type IsHashErrorType, isHash } from './hash/isHash.js'\nexport { type Keccak256ErrorType, keccak256 } from './hash/keccak256.js'\nexport { type Ripemd160ErrorType, ripemd160 } from './hash/ripemd160.js'\nexport { type Sha256ErrorType, sha256 } from './hash/sha256.js'\nexport {\n type ToEventHashErrorType,\n toEventHash,\n} from './hash/toEventHash.js'\nexport {\n type ToEventSelectorErrorType,\n /** @deprecated use `ToEventSelectorErrorType`. */\n type ToEventSelectorErrorType as GetEventSelectorErrorType,\n toEventSelector,\n /** @deprecated use `toEventSelector`. */\n toEventSelector as getEventSelector,\n} from './hash/toEventSelector.js'\nexport {\n type ToEventSignatureErrorType,\n /** @deprecated use `ToEventSignatureErrorType`. */\n type ToEventSignatureErrorType as GetEventSignatureErrorType,\n toEventSignature,\n /** @deprecated use `toEventSignature`. */\n toEventSignature as getEventSignature,\n} from './hash/toEventSignature.js'\nexport {\n type ToFunctionHashErrorType,\n toFunctionHash,\n} from './hash/toFunctionHash.js'\nexport {\n type ToFunctionSelectorErrorType,\n /** @deprecated use `ToFunctionSelectorErrorType`. */\n type ToFunctionSelectorErrorType as GetFunctionSelectorErrorType,\n toFunctionSelector,\n /** @deprecated use `toFunctionSelector`. */\n toFunctionSelector as getFunctionSelector,\n} from './hash/toFunctionSelector.js'\nexport {\n type ToFunctionSignatureErrorType,\n /** @deprecated use `ToFunctionSignatureErrorType`. */\n type ToFunctionSignatureErrorType as GetFunctionSignatureErrorType,\n toFunctionSignature,\n /** @deprecated use `toFunctionSignature`. */\n toFunctionSignature as getFunctionSignature,\n} from './hash/toFunctionSignature.js'\nexport {\n type CreateNonceManagerParameters,\n createNonceManager,\n type NonceManager,\n type NonceManagerSource,\n nonceManager,\n} from './nonceManager.js'\nexport { arrayRegex, bytesRegex, integerRegex } from './regex.js'\nexport {\n getSocket,\n rpc,\n type WebSocketAsyncErrorType,\n type WebSocketAsyncOptions,\n type WebSocketAsyncReturnType,\n type WebSocketErrorType,\n type WebSocketOptions,\n type WebSocketReturnType,\n} from './rpc/compat.js'\nexport {\n getHttpRpcClient,\n type HttpRequestErrorType,\n type HttpRequestParameters,\n type HttpRequestReturnType,\n type HttpRpcClient,\n type HttpRpcClientOptions,\n} from './rpc/http.js'\nexport {\n type GetSocketParameters,\n type GetSocketRpcClientErrorType,\n type GetSocketRpcClientParameters,\n getSocketRpcClient,\n type Socket,\n type SocketRpcClient,\n socketClientCache,\n} from './rpc/socket.js'\nexport { getWebSocketRpcClient } from './rpc/webSocket.js'\nexport {\n type HashMessageErrorType,\n type HashMessageReturnType,\n hashMessage,\n} from './signature/hashMessage.js'\nexport {\n type HashDomainErrorType,\n type HashStructErrorType,\n type HashTypedDataParameters,\n type HashTypedDataReturnType,\n hashStruct,\n hashTypedData,\n} from './signature/hashTypedData.js'\nexport {\n type IsErc6492SignatureErrorType,\n type IsErc6492SignatureParameters,\n type IsErc6492SignatureReturnType,\n isErc6492Signature,\n} from './signature/isErc6492Signature.js'\nexport {\n type IsErc8010SignatureErrorType,\n type IsErc8010SignatureParameters,\n type IsErc8010SignatureReturnType,\n isErc8010Signature,\n} from './signature/isErc8010Signature.js'\nexport {\n type ParseErc6492SignatureErrorType,\n type ParseErc6492SignatureParameters,\n type ParseErc6492SignatureReturnType,\n parseErc6492Signature,\n} from './signature/parseErc6492Signature.js'\nexport {\n type ParseErc8010SignatureErrorType,\n type ParseErc8010SignatureParameters,\n type ParseErc8010SignatureReturnType,\n parseErc8010Signature,\n} from './signature/parseErc8010Signature.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 SerializeErc6492SignatureErrorType,\n type SerializeErc6492SignatureParameters,\n type SerializeErc6492SignatureReturnType,\n serializeErc6492Signature,\n} from './signature/serializeErc6492Signature.js'\nexport {\n type SerializeErc8010SignatureErrorType,\n type SerializeErc8010SignatureParameters,\n type SerializeErc8010SignatureReturnType,\n serializeErc8010Signature,\n} from './signature/serializeErc8010Signature.js'\nexport {\n type VerifyHashErrorType,\n type VerifyHashParameters,\n type VerifyHashReturnType,\n verifyHash,\n} from './signature/verifyHash.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 { type StringifyErrorType, stringify } from './stringify.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 GetSerializedTransactionType,\n type GetSerializedTransactionTypeErrorType,\n getSerializedTransactionType,\n} from './transaction/getSerializedTransactionType.js'\nexport {\n type GetTransactionType,\n type GetTransactionTypeErrorType,\n getTransactionType,\n} from './transaction/getTransactionType.js'\nexport {\n type ParseTransactionErrorType,\n parseTransaction,\n} from './transaction/parseTransaction.js'\nexport {\n type SerializeAccessListErrorType,\n serializeAccessList,\n} from './transaction/serializeAccessList.js'\nexport {\n type SerializeTransactionErrorType,\n type SerializeTransactionFn,\n serializeTransaction,\n} from './transaction/serializeTransaction.js'\nexport {\n type DomainSeparatorErrorType,\n type SerializeTypedDataErrorType,\n serializeTypedData,\n type ValidateTypedDataErrorType,\n validateTypedData,\n} from './typedData.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 ParseEtherErrorType, parseEther } from './unit/parseEther.js'\nexport { type ParseGweiErrorType, parseGwei } from './unit/parseGwei.js'\nexport { type ParseUnitsErrorType, parseUnits } from './unit/parseUnits.js'\n","import {\n HttpRequestError,\n type HttpRequestErrorType as HttpRequestErrorType_,\n TimeoutError,\n type TimeoutErrorType,\n} from '../../errors/request.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { RpcRequest, RpcResponse } from '../../types/rpc.js'\nimport type { MaybePromise } from '../../types/utils.js'\nimport {\n type WithTimeoutErrorType,\n withTimeout,\n} from '../promise/withTimeout.js'\nimport { stringify } from '../stringify.js'\nimport { idCache } from './id.js'\n\nexport type HttpRpcClientOptions = {\n /** Override for the fetch function used to make requests. */\n fetchFn?:\n | ((input: string | URL | Request, init?: RequestInit) => Promise<Response>)\n | undefined\n /** Request configuration to pass to `fetch`. */\n fetchOptions?: Omit<RequestInit, 'body'> | undefined\n /** A callback to handle the request. */\n onRequest?:\n | ((\n request: Request,\n init: RequestInit,\n ) => MaybePromise<\n void | undefined | (RequestInit & { url?: string | undefined })\n >)\n | undefined\n /** A callback to handle the response. */\n onResponse?: ((response: Response) => Promise<void> | void) | undefined\n /** The timeout (in ms) for the request. */\n timeout?: number | undefined\n}\n\nexport type HttpRequestParameters<\n body extends RpcRequest | RpcRequest[] = RpcRequest,\n> = {\n /** The RPC request body. */\n body: body\n /** Override for the fetch function used to make requests. */\n fetchFn?: HttpRpcClientOptions['fetchFn'] | undefined\n /** Request configuration to pass to `fetch`. */\n fetchOptions?: HttpRpcClientOptions['fetchOptions'] | undefined\n /** A callback to handle the response. */\n onRequest?:\n | ((\n request: Request,\n init: RequestInit,\n ) => MaybePromise<\n void | undefined | (RequestInit & { url?: string | undefined })\n >)\n | undefined\n /** A callback to handle the response. */\n onResponse?: ((response: Response) => Promise<void> | void) | undefined\n /** The timeout (in ms) for the request. */\n timeout?: HttpRpcClientOptions['timeout'] | undefined\n}\n\nexport type HttpRequestReturnType<\n body extends RpcRequest | RpcRequest[] = RpcRequest,\n> = body extends RpcRequest[] ? RpcResponse[] : RpcResponse\n\nexport type HttpRequestErrorType =\n | HttpRequestErrorType_\n | TimeoutErrorType\n | WithTimeoutErrorType\n | ErrorType\n\nexport type HttpRpcClient = {\n request<body extends RpcRequest | RpcRequest[]>(\n params: HttpRequestParameters<body>,\n ): Promise<HttpRequestReturnType<body>>\n}\n\nexport function getHttpRpcClient(\n url_: string,\n options: HttpRpcClientOptions = {},\n): HttpRpcClient {\n const { url, headers: headers_url } = parseUrl(url_)\n\n return {\n async request(params) {\n const {\n body,\n fetchFn = options.fetchFn ?? fetch,\n onRequest = options.onRequest,\n onResponse = options.onResponse,\n timeout = options.timeout ?? 10_000,\n } = params\n\n const fetchOptions = {\n ...(options.fetchOptions ?? {}),\n ...(params.fetchOptions ?? {}),\n }\n\n const { headers, method, signal: signal_ } = fetchOptions\n\n try {\n const response = await withTimeout(\n async ({ signal }) => {\n const init: RequestInit = {\n ...fetchOptions,\n body: Array.isArray(body)\n ? stringify(\n body.map((body) => ({\n jsonrpc: '2.0',\n id: body.id ?? idCache.take(),\n ...body,\n })),\n )\n : stringify({\n jsonrpc: '2.0',\n id: body.id ?? idCache.take(),\n ...body,\n }),\n headers: {\n ...headers_url,\n 'Content-Type': 'application/json',\n ...headers,\n },\n method: method || 'POST',\n signal: signal_ || (timeout > 0 ? signal : null),\n }\n const request = new Request(url, init)\n const args = (await onRequest?.(request, init)) ?? { ...init, url }\n const response = await fetchFn(args.url ?? url, args)\n return response\n },\n {\n errorInstance: new TimeoutError({ body, url }),\n timeout,\n signal: true,\n },\n )\n\n if (onResponse) await onResponse(response)\n\n let data: any\n if (\n response.headers.get('Content-Type')?.startsWith('application/json')\n )\n data = await response.json()\n else {\n data = await response.text()\n try {\n data = JSON.parse(data || '{}')\n } catch (err) {\n if (response.ok) throw err\n data = { error: data }\n }\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 cause: err as Error,\n url,\n })\n }\n },\n }\n}\n\n/** @internal */\nexport function parseUrl(url_: string) {\n try {\n const url = new URL(url_)\n\n const result = (() => {\n // Handle Basic authentication credentials\n if (url.username) {\n const credentials = `${decodeURIComponent(url.username)}:${decodeURIComponent(url.password)}`\n url.username = ''\n url.password = ''\n\n return {\n url: url.toString(),\n headers: { Authorization: `Basic ${btoa(credentials)}` },\n }\n }\n\n return\n })()\n\n return { url: url.toString(), ...result }\n } catch {\n return { url: url_ }\n }\n}\n","import type { ErrorType } from '../../errors/utils.js'\n\nexport type WithTimeoutErrorType = ErrorType\n\nexport function withTimeout<data>(\n fn: ({\n signal,\n }: {\n signal: AbortController['signal'] | null\n }) => Promise<data>,\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 | undefined\n // The timeout (in ms).\n timeout: number\n // Whether or not the timeout should use an abort signal.\n signal?: boolean | undefined\n },\n): Promise<data> {\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) as NodeJS.Timeout // need to cast because bun globals.d.ts overrides @types/node\n }\n resolve(await fn({ signal: controller?.signal || null }))\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","function createIdStore() {\n return {\n current: 0,\n take() {\n return this.current++\n },\n reset() {\n this.current = 0\n },\n }\n}\n\nexport const idCache = /*#__PURE__*/ createIdStore()\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray, Hex, SignableMessage } from '../../types/misc.js'\nimport { type Keccak256ErrorType, keccak256 } from '../hash/keccak256.js'\nimport { toPrefixedMessage } from './toPrefixedMessage.js'\n\ntype To = 'hex' | 'bytes'\n\nexport type HashMessageReturnType<to extends To> =\n | (to extends 'bytes' ? ByteArray : never)\n | (to extends 'hex' ? Hex : never)\n\nexport type HashMessageErrorType = Keccak256ErrorType | ErrorType\n\nexport function hashMessage<to extends To = 'hex'>(\n message: SignableMessage,\n to_?: to | undefined,\n): HashMessageReturnType<to> {\n return keccak256(toPrefixedMessage(message), to_)\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 { Hex, SignableMessage } from '../../types/misc.js'\nimport { type ConcatErrorType, concat } from '../data/concat.js'\nimport { size } from '../data/size.js'\nimport {\n type BytesToHexErrorType,\n bytesToHex,\n type StringToHexErrorType,\n stringToHex,\n} from '../encoding/toHex.js'\n\nexport type ToPrefixedMessageErrorType =\n | ConcatErrorType\n | StringToHexErrorType\n | BytesToHexErrorType\n | ErrorType\n\nexport function toPrefixedMessage(message_: SignableMessage): Hex {\n const message = (() => {\n if (typeof message_ === 'string') return stringToHex(message_)\n if (typeof message_.raw === 'string') return message_.raw\n return bytesToHex(message_.raw)\n })()\n const prefix = stringToHex(`${presignMessagePrefix}${size(message)}`)\n return concat([prefix, message])\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 } from 'abitype'\n\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Hex } from '../../types/misc.js'\nimport type {\n EIP712DomainDefinition,\n MessageDefinition,\n TypedDataDefinition,\n} from '../../types/typedData.js'\nimport type { UnionOmit } from '../../types/utils.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 getTypesForEIP712Domain,\n type ValidateTypedDataErrorType,\n validateTypedData,\n} from '../typedData.js'\n\ntype MessageTypeProperty = {\n name: string\n type: string\n}\n\nexport type HashTypedDataParameters<\n typedData extends TypedData | Record<string, unknown> = TypedData,\n primaryType extends keyof typedData | 'EIP712Domain' = keyof typedData,\n> = TypedDataDefinition<typedData, primaryType>\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 typedData extends TypedData | Record<string, unknown>,\n primaryType extends keyof typedData | 'EIP712Domain',\n>(\n parameters: HashTypedDataParameters<typedData, primaryType>,\n): HashTypedDataReturnType {\n const {\n domain = {},\n message,\n primaryType,\n } = parameters as HashTypedDataParameters\n const types = {\n EIP712Domain: getTypesForEIP712Domain({ domain }),\n ...parameters.types,\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 })\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,\n types: types as Record<string, MessageTypeProperty[]>,\n }),\n )\n\n return keccak256(concat(parts))\n}\n\nexport type HashDomainErrorType = HashStructErrorType | ErrorType\n\nexport function hashDomain<\n const typedData extends TypedData | Record<string, unknown> = TypedData,\n>({\n domain,\n types,\n}: UnionOmit<EIP712DomainDefinition<typedData>, 'primaryType'>) {\n return hashStruct({\n data: domain as Record<string, unknown>,\n primaryType: 'EIP712Domain',\n types: types as Record<string, readonly MessageTypeProperty[]>,\n })\n}\n\nexport type HashStructErrorType =\n | EncodeDataErrorType\n | Keccak256ErrorType\n | ErrorType\n\nexport function hashStruct<\n const typedData extends TypedData | Record<string, unknown>,\n primaryType extends keyof typedData | 'EIP712Domain',\n>({\n data,\n primaryType,\n types,\n}: MessageDefinition<typedData, primaryType, 'data'>) {\n const encoded = encodeData({\n data: data as Record<string, unknown>,\n primaryType,\n types: types as Record<string, readonly MessageTypeProperty[]>,\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, readonly 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, readonly MessageTypeProperty[]>\n}) {\n const encodedHashType = toHex(encodeType({ primaryType, types }))\n return keccak256(encodedHashType)\n}\n\ntype EncodeTypeErrorType = FindTypeDependenciesErrorType\n\nexport function encodeType({\n primaryType,\n types,\n}: {\n primaryType: string\n types: Record<string, readonly 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, readonly 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, readonly 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') return [{ type: 'bytes32' }, keccak256(value)]\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 { TypedData, TypedDataDomain, TypedDataParameter } from 'abitype'\n\nimport { BytesSizeMismatchError } from '../errors/abi.js'\nimport { InvalidAddressError } from '../errors/address.js'\nimport {\n InvalidDomainError,\n InvalidPrimaryTypeError,\n InvalidStructTypeError,\n} from '../errors/typedData.js'\nimport type { ErrorType } from '../errors/utils.js'\nimport type { Hex } from '../types/misc.js'\nimport type { TypedDataDefinition } from '../types/typedData.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'\nimport { stringify } from './stringify.js'\n\nexport type SerializeTypedDataErrorType =\n | HashDomainErrorType\n | IsAddressErrorType\n | NumberToHexErrorType\n | SizeErrorType\n | ErrorType\n\nexport function serializeTypedData<\n const typedData extends TypedData | Record<string, unknown>,\n primaryType extends keyof typedData | 'EIP712Domain',\n>(parameters: TypedDataDefinition<typedData, primaryType>) {\n const {\n domain: domain_,\n message: message_,\n primaryType,\n types,\n } = parameters as unknown as TypedDataDefinition\n\n const normalizeData = (\n struct: readonly TypedDataParameter[],\n data_: Record<string, unknown>,\n ) => {\n const data = { ...data_ }\n for (const param of struct) {\n const { name, type } = param\n if (type === 'address') data[name] = (data[name] as string).toLowerCase()\n }\n return data\n }\n\n const domain = (() => {\n if (!types.EIP712Domain) return {}\n if (!domain_) return {}\n return normalizeData(types.EIP712Domain, domain_)\n })()\n\n const message = (() => {\n if (primaryType === 'EIP712Domain') return undefined\n return normalizeData(types[primaryType], message_)\n })()\n\n return stringify({ domain, message, primaryType, types })\n}\n\nexport type ValidateTypedDataErrorType =\n | HashDomainErrorType\n | IsAddressErrorType\n | NumberToHexErrorType\n | SizeErrorType\n | ErrorType\n\nexport function validateTypedData<\n const typedData extends TypedData | Record<string, unknown>,\n primaryType extends keyof typedData | 'EIP712Domain',\n>(parameters: TypedDataDefinition<typedData, primaryType>) {\n const { domain, message, primaryType, types } =\n parameters as unknown as TypedDataDefinition\n\n const validateData = (\n struct: readonly TypedDataParameter[],\n data: Record<string, unknown>,\n ) => {\n for (const param of struct) {\n const { name, type } = param\n const value = data[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: Number.parseInt(size_, 10) / 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) !== Number.parseInt(size_, 10))\n throw new BytesSizeMismatchError({\n expectedSize: Number.parseInt(size_, 10),\n givenSize: size(value as Hex),\n })\n }\n\n const struct = types[type]\n if (struct) {\n validateReference(type)\n validateData(struct, value as Record<string, unknown>)\n }\n }\n }\n\n // Validate domain types.\n if (types.EIP712Domain && domain) {\n if (typeof domain !== 'object') throw new InvalidDomainError({ domain })\n validateData(types.EIP712Domain, domain)\n }\n\n // Validate message types.\n if (primaryType !== 'EIP712Domain') {\n if (types[primaryType]) validateData(types[primaryType], message)\n else throw new InvalidPrimaryTypeError({ primaryType, types })\n }\n}\n\nexport type GetTypesForEIP712DomainErrorType = ErrorType\n\nexport function getTypesForEIP712Domain({\n domain,\n}: {\n domain?: TypedDataDomain | undefined\n}): 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 typeof domain?.chainId === 'bigint') && {\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: domain as never,\n types: {\n EIP712Domain: getTypesForEIP712Domain({ domain }),\n },\n })\n}\n\n/** @internal */\nfunction validateReference(type: string) {\n // Struct type must not be a Solidity type.\n if (\n type === 'address' ||\n type === 'bool' ||\n type === 'string' ||\n type.startsWith('bytes') ||\n type.startsWith('uint') ||\n type.startsWith('int')\n )\n throw new InvalidStructTypeError({ type })\n}\n","import type { TypedData } from 'abitype'\n\nimport { stringify } from '../utils/stringify.js'\nimport { BaseError } from './base.js'\n\nexport type InvalidDomainErrorType = InvalidDomainError & {\n name: 'InvalidDomainError'\n}\nexport class InvalidDomainError extends BaseError {\n constructor({ domain }: { domain: unknown }) {\n super(`Invalid domain \"${stringify(domain)}\".`, {\n metaMessages: ['Must be a valid EIP-712 domain.'],\n })\n }\n}\n\nexport type InvalidPrimaryTypeErrorType = InvalidPrimaryTypeError & {\n name: 'InvalidPrimaryTypeError'\n}\nexport class InvalidPrimaryTypeError extends BaseError {\n constructor({\n primaryType,\n types,\n }: { primaryType: string; types: TypedData | Record<string, unknown> }) {\n super(\n `Invalid primary type \\`${primaryType}\\` must be one of \\`${JSON.stringify(Object.keys(types))}\\`.`,\n {\n docsPath: '/api/glossary/Errors#typeddatainvalidprimarytypeerror',\n metaMessages: ['Check that the primary type is a key in `types`.'],\n },\n )\n }\n}\n\nexport type InvalidStructTypeErrorType = InvalidStructTypeError & {\n name: 'InvalidStructTypeError'\n}\nexport class InvalidStructTypeError extends BaseError {\n constructor({ type }: { type: string }) {\n super(`Struct type \"${type}\" is invalid.`, {\n metaMessages: ['Struct type must not be a Solidity type.'],\n name: 'InvalidStructTypeError',\n })\n }\n}\n","import { BaseError } from './base.js'\n\nexport type InvalidDecimalNumberErrorType = InvalidDecimalNumberError & {\n name: 'InvalidDecimalNumberError'\n}\nexport class InvalidDecimalNumberError extends BaseError {\n constructor({ value }: { value: string }) {\n super(`Number \\`${value}\\` is not a valid decimal number.`, {\n name: 'InvalidDecimalNumberError',\n })\n }\n}\n","import { InvalidDecimalNumberError } from '../../errors/unit.js'\nimport type { ErrorType } from '../../errors/utils.js'\n\nexport type ParseUnitsErrorType = ErrorType\n\n/**\n * Multiplies a string representation of a number by a given exponent of base 10 (10exponent).\n *\n * - Docs: https://viem.sh/docs/utilities/parseUnits\n *\n * @example\n * import { parseUnits } from 'viem'\n *\n * parseUnits('420', 9)\n * // 420000000000n\n */\nexport function parseUnits(value: string, decimals: number) {\n if (!/^(-?)([0-9]*)\\.?([0-9]*)$/.test(value))\n throw new InvalidDecimalNumberError({ value })\n\n let [integer, fraction = '0'] = value.split('.')\n\n const negative = integer.startsWith('-')\n if (negative) integer = integer.slice(1)\n\n // trim trailing zeros.\n fraction = fraction.replace(/(0+)$/, '')\n\n // round off if the fraction is larger than the number of decimals.\n if (decimals === 0) {\n if (Math.round(Number(`.${fraction}`)) === 1)\n integer = `${BigInt(integer) + 1n}`\n fraction = ''\n } else if (fraction.length > decimals) {\n const [left, unit, right] = [\n fraction.slice(0, decimals - 1),\n fraction.slice(decimals - 1, decimals),\n fraction.slice(decimals),\n ]\n\n const rounded = Math.round(Number(`${unit}.${right}`))\n if (rounded > 9)\n fraction = `${BigInt(left) + BigInt(1)}0`.padStart(left.length + 1, '0')\n else fraction = `${left}${rounded}`\n\n if (fraction.length > decimals) {\n fraction = fraction.slice(1)\n integer = `${BigInt(integer) + 1n}`\n }\n\n fraction = fraction.slice(0, decimals)\n } else {\n fraction = fraction.padEnd(decimals, '0')\n }\n\n return BigInt(`${negative ? '-' : ''}${integer}${fraction}`)\n}\n","import type { Address } from '../../accounts/index.js'\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport {\n TransactionNotFoundError,\n type TransactionNotFoundErrorType,\n} 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 { OneOf, Prettify } 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 FormattedTransaction,\n formatTransaction,\n} from '../../utils/formatters/transaction.js'\n\nexport type GetTransactionParameters<blockTag extends BlockTag = 'latest'> =\n OneOf<\n // eth_getTransactionByBlockHashAndIndex\n | {\n /** The block hash */\n blockHash: Hash\n /** The index of the transaction on the block. */\n index: number\n }\n // eth_getTransactionByBlockNumberAndIndex\n | {\n /** The block number */\n blockNumber: bigint\n /** The index of the transaction on the block. */\n index: number\n }\n // eth_getTransactionByBlockNumberAndIndex\n | {\n /** The block tag. */\n blockTag: blockTag | BlockTag\n /** The index of the transaction on the block. */\n index: number\n }\n // eth_getTransactionByHash\n | {\n /** The hash of the transaction. */\n hash: Hash\n }\n // eth_getTransactionBySenderAndNonce\n | {\n /** The sender of the transaction. */\n sender: Address\n /** The nonce of the transaction on the sender. */\n nonce: number\n }\n >\n\nexport type GetTransactionReturnType<\n chain extends Chain | undefined = undefined,\n blockTag extends BlockTag = 'latest',\n> = Prettify<FormattedTransaction<chain, blockTag>>\n\nexport type GetTransactionErrorType =\n | TransactionNotFoundErrorType\n | NumberToHexErrorType\n | RequestErrorType\n | ErrorType\n\n/**\n * Returns information about a [Transaction](https://viem.sh/docs/glossary/terms#transaction) given a hash or block identifier.\n *\n * - Docs: https://viem.sh/docs/actions/public/getTransaction\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 chain extends Chain | undefined,\n blockTag extends BlockTag = 'latest',\n>(\n client: Client<Transport, chain>,\n {\n blockHash,\n blockNumber,\n blockTag: blockTag_,\n hash,\n index,\n sender,\n nonce,\n }: GetTransactionParameters<blockTag>,\n): Promise<GetTransactionReturnType<chain, blockTag>> {\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 {\n method: 'eth_getTransactionByHash',\n params: [hash],\n },\n { dedupe: true },\n )\n } else if (blockHash) {\n transaction = await client.request(\n {\n method: 'eth_getTransactionByBlockHashAndIndex',\n params: [blockHash, numberToHex(index)],\n },\n { dedupe: true },\n )\n } else if ((blockNumberHex || blockTag) && typeof index === 'number') {\n transaction = await client.request(\n {\n method: 'eth_getTransactionByBlockNumberAndIndex',\n params: [blockNumberHex || blockTag, numberToHex(index)],\n },\n { dedupe: Boolean(blockNumberHex) },\n )\n } else if (sender && typeof nonce === 'number') {\n transaction = await client.request(\n {\n method: 'eth_getTransactionBySenderAndNonce',\n params: [sender, numberToHex(nonce)],\n },\n { dedupe: true },\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, 'getTransaction')\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 chain extends Chain | undefined = undefined,\n> = FormattedTransactionReceipt<chain>\n\nexport type GetTransactionReceiptErrorType =\n | RequestErrorType\n | TransactionReceiptNotFoundErrorType\n | ErrorType\n\n/**\n * Returns the [Transaction Receipt](https://viem.sh/docs/glossary/terms#transaction-receipt) given a [Transaction](https://viem.sh/docs/glossary/terms#transaction) hash.\n *\n * - Docs: https://viem.sh/docs/actions/public/getTransactionReceipt\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<chain extends Chain | undefined>(\n client: Client<Transport, chain>,\n { hash }: GetTransactionReceiptParameters,\n) {\n const receipt = await client.request(\n {\n method: 'eth_getTransactionReceipt',\n params: [hash],\n },\n { dedupe: true },\n )\n\n if (!receipt) throw new TransactionReceiptNotFoundError({ hash })\n\n const format =\n client.chain?.formatters?.transactionReceipt?.format ||\n formatTransactionReceipt\n return format(\n receipt,\n 'getTransactionReceipt',\n ) as GetTransactionReceiptReturnType<chain>\n}\n","import { secp256k1 } from '@noble/curves/secp256k1'\n\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray, Hex, Signature } from '../../types/misc.js'\nimport { type HexToBigIntErrorType, hexToBigInt } from '../encoding/fromHex.js'\nimport { hexToBytes } from '../encoding/toBytes.js'\nimport type { ToHexErrorType } from '../encoding/toHex.js'\n\ntype To = 'bytes' | 'hex'\n\nexport type SerializeSignatureParameters<to extends To = 'hex'> = Signature & {\n to?: to | To | undefined\n}\n\nexport type SerializeSignatureReturnType<to extends To = 'hex'> =\n | (to extends 'hex' ? Hex : never)\n | (to extends 'bytes' ? ByteArray : never)\n\nexport type SerializeSignatureErrorType =\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 * serializeSignature({\n * r: '0x6e100a352ec6ad1b70802290e18aeed190704973570f3b8ed42cb9808e2ea6bf',\n * s: '0x4a90a229a244495b41890987806fcbd2d5d23fc0dbe5f5256c2613c039d76db8',\n * yParity: 1\n * })\n * // \"0x6e100a352ec6ad1b70802290e18aeed190704973570f3b8ed42cb9808e2ea6bf4a90a229a244495b41890987806fcbd2d5d23fc0dbe5f5256c2613c039d76db81c\"\n */\nexport function serializeSignature<to extends To = 'hex'>({\n r,\n s,\n to = 'hex',\n v,\n yParity,\n}: SerializeSignatureParameters<to>): SerializeSignatureReturnType<to> {\n const yParity_ = (() => {\n if (yParity === 0 || yParity === 1) return yParity\n if (v && (v === 27n || v === 28n || v >= 35n)) return v % 2n === 0n ? 1 : 0\n throw new Error('Invalid `v` or `yParity` value')\n })()\n const signature = `0x${new secp256k1.Signature(\n hexToBigInt(r),\n hexToBigInt(s),\n ).toCompactHex()}${yParity_ === 0 ? '1b' : '1c'}` as const\n\n if (to === 'hex') return signature as SerializeSignatureReturnType<to>\n return hexToBytes(signature) as SerializeSignatureReturnType<to>\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 type WaitForTransactionReceiptTimeoutErrorType,\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 { withResolvers } from '../../utils/promise/withResolvers.js'\nimport {\n type WithRetryParameters,\n withRetry,\n} 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 chain extends Chain | undefined = Chain | undefined,\n> = {\n reason: ReplacementReason\n replacedTransaction: Transaction\n transaction: Transaction\n transactionReceipt: GetTransactionReceiptReturnType<chain>\n}\n\nexport type WaitForTransactionReceiptReturnType<\n chain extends Chain | undefined = Chain | undefined,\n> = GetTransactionReceiptReturnType<chain>\n\nexport type WaitForTransactionReceiptParameters<\n chain extends Chain | undefined = Chain | undefined,\n> = {\n /**\n * Whether to check for transaction replacements.\n * @default true\n */\n checkReplacement?: boolean | undefined\n /**\n * The number of confirmations (blocks that have passed) to wait before resolving.\n * @default 1\n */\n confirmations?: number | undefined\n /** The hash of the transaction. */\n hash: Hash\n /** Optional callback to emit if the transaction has been replaced. */\n onReplaced?: ((response: ReplacementReturnType<chain>) => void) | undefined\n /**\n * Polling frequency (in ms). Defaults to the client's pollingInterval config.\n * @default client.pollingInterval\n */\n pollingInterval?: number | undefined\n /**\n * Number of times to retry if the transaction or block is not found.\n * @default 6 (exponential backoff)\n */\n retryCount?: WithRetryParameters['retryCount'] | undefined\n /**\n * Time to wait (in ms) between retries.\n * @default `({ count }) => ~~(1 << count) * 200` (exponential backoff)\n */\n retryDelay?: WithRetryParameters['delay'] | undefined\n /**\n * Optional timeout (in milliseconds) to wait before stopping polling.\n * @default 180_000\n */\n timeout?: number | undefined\n}\n\nexport type WaitForTransactionReceiptErrorType =\n | ObserveErrorType\n | GetBlockErrorType\n | GetTransactionErrorType\n | GetTransactionReceiptErrorType\n | WatchBlockNumberErrorType\n | WaitForTransactionReceiptTimeoutErrorType\n | ErrorType\n\n/**\n * Waits for the [Transaction](https://viem.sh/docs/glossary/terms#transaction) to be included on a [Block](https://viem.sh/docs/glossary/terms#block) (one confirmation), and then returns the [Transaction Receipt](https://viem.sh/docs/glossary/terms#transaction-receipt).\n *\n * - Docs: https://viem.sh/docs/actions/public/waitForTransactionReceipt\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 chain extends Chain | undefined,\n>(\n client: Client<Transport, chain>,\n parameters: WaitForTransactionReceiptParameters<chain>,\n): Promise<WaitForTransactionReceiptReturnType<chain>> {\n const {\n checkReplacement = true,\n confirmations = 1,\n hash,\n onReplaced,\n retryCount = 6,\n retryDelay = ({ count }) => ~~(1 << count) * 200, // exponential backoff\n timeout = 180_000,\n } = parameters\n\n const observerId = stringify(['waitForTransactionReceipt', client.uid, hash])\n\n const pollingInterval = (() => {\n if (parameters.pollingInterval) return parameters.pollingInterval\n if (client.chain?.experimental_preconfirmationTime)\n return client.chain.experimental_preconfirmationTime\n return client.pollingInterval\n })()\n\n let transaction: GetTransactionReturnType<chain> | undefined\n let replacedTransaction: GetTransactionReturnType<chain> | undefined\n let receipt: GetTransactionReceiptReturnType<chain> | undefined\n let retrying = false\n\n let _unobserve: () => void\n let _unwatch: () => void\n\n const { promise, resolve, reject } =\n withResolvers<WaitForTransactionReceiptReturnType<chain>>()\n\n const timer = timeout\n ? setTimeout(() => {\n _unwatch?.()\n _unobserve?.()\n reject(new WaitForTransactionReceiptTimeoutError({ hash }))\n }, timeout)\n : undefined\n\n _unobserve = observe(\n observerId,\n { onReplaced, resolve, reject },\n async (emit) => {\n receipt = await getAction(\n client,\n getTransactionReceipt,\n 'getTransactionReceipt',\n )({ hash }).catch(() => undefined)\n\n if (receipt && confirmations <= 1) {\n clearTimeout(timer)\n emit.resolve(receipt)\n _unobserve?.()\n return\n }\n\n _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 const done = (fn: () => void) => {\n clearTimeout(timer)\n _unwatch?.()\n fn()\n _unobserve?.()\n }\n\n let blockNumber = blockNumber_\n\n if (retrying) return\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 (checkReplacement && !transaction) {\n retrying = true\n await withRetry(\n async () => {\n transaction = (await getAction(\n client,\n getTransaction,\n 'getTransaction',\n )({ hash })) as GetTransactionReturnType<chain>\n if (transaction.blockNumber)\n blockNumber = transaction.blockNumber\n },\n {\n delay: retryDelay,\n retryCount,\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 err instanceof TransactionNotFoundError ||\n err instanceof TransactionReceiptNotFoundError\n ) {\n if (!transaction) {\n retrying = false\n return\n }\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 delay: retryDelay,\n retryCount,\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 replacementTransaction.input === replacedTransaction.input\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! as any,\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 return promise\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 { HasTransportType } 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 WatchBlockNumberParameters<\n transport 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) | undefined\n} & (\n | (HasTransportType<transport, 'webSocket' | 'ipc'> extends true\n ? {\n emitMissed?: undefined\n emitOnBegin?: undefined\n /** Whether or not the WebSocket Transport should poll the JSON-RPC, rather than using `eth_subscribe`. */\n poll?: false | undefined\n pollingInterval?: undefined\n }\n : never)\n | {\n /** Whether or not to emit the missed block numbers to the callback. */\n emitMissed?: boolean | undefined\n /** Whether or not to emit the latest block number to the callback when the subscription opens. */\n emitOnBegin?: boolean | undefined\n poll?: true | undefined\n /** Polling frequency (in ms). Defaults to Client's pollingInterval config. */\n pollingInterval?: number | undefined\n }\n)\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\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 chain extends Chain | undefined,\n transport extends Transport,\n>(\n client: Client<transport, chain>,\n {\n emitOnBegin = false,\n emitMissed = false,\n onBlockNumber,\n onError,\n poll: poll_,\n pollingInterval = client.pollingInterval,\n }: WatchBlockNumberParameters<transport>,\n): WatchBlockNumberReturnType {\n const enablePolling = (() => {\n if (typeof poll_ !== 'undefined') return poll_\n if (\n client.transport.type === 'webSocket' ||\n client.transport.type === 'ipc'\n )\n return false\n if (\n client.transport.type === 'fallback' &&\n (client.transport.transports[0].config.type === 'webSocket' ||\n client.transport.transports[0].config.type === 'ipc')\n )\n return false\n return true\n })()\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 !== undefined) {\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 (\n prevBlockNumber === undefined ||\n blockNumber > prevBlockNumber\n ) {\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 const observerId = stringify([\n 'watchBlockNumber',\n client.uid,\n emitOnBegin,\n emitMissed,\n ])\n\n return observe(observerId, { onBlockNumber, onError }, (emit) => {\n let active = true\n let unsubscribe = () => (active = false)\n ;(async () => {\n try {\n const transport = (() => {\n if (client.transport.type === 'fallback') {\n const transport = client.transport.transports.find(\n (transport: ReturnType<Transport>) =>\n transport.config.type === 'webSocket' ||\n transport.config.type === 'ipc',\n )\n if (!transport) return client.transport\n return transport.value\n }\n return client.transport\n })()\n\n const { unsubscribe: unsubscribe_ } = await transport.subscribe({\n params: ['newHeads'],\n onData(data: any) {\n if (!active) return\n const blockNumber = hexToBigInt(data.result?.number)\n emit.onBlockNumber(blockNumber, prevBlockNumber)\n prevBlockNumber = blockNumber\n },\n onError(error: Error) {\n emit.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\n return enablePolling ? pollBlockNumber() : subscribeBlockNumber()\n}\n","import type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport { TransactionReceiptRevertedError } from '../../errors/transaction.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { TransactionSerializedGeneric } from '../../types/transaction.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport { formatTransactionReceipt } from '../../utils/formatters/transactionReceipt.js'\nimport {\n type FormattedTransactionReceipt,\n numberToHex,\n} from '../../utils/index.js'\n\nexport type SendRawTransactionSyncParameters = {\n /** The signed serialized transaction. */\n serializedTransaction: TransactionSerializedGeneric\n /** Whether to throw an error if the transaction was detected as reverted. @default true */\n throwOnReceiptRevert?: boolean | undefined\n /** The timeout for the transaction. */\n timeout?: number | undefined\n}\n\nexport type SendRawTransactionSyncReturnType<\n chain extends Chain | undefined = undefined,\n> = FormattedTransactionReceipt<chain>\n\nexport type SendRawTransactionSyncErrorType = RequestErrorType | ErrorType\n\n/**\n * Sends a **signed** transaction to the network synchronously,\n * and waits for the transaction to be included in a block.\n *\n * - Docs: https://viem.sh/docs/actions/wallet/sendRawTransactionSync\n * - JSON-RPC Method: [`eth_sendRawTransactionSync`](https://eips.ethereum.org/EIPS/eip-7966)\n *\n * @param client - Client to use\n * @param parameters - {@link SendRawTransactionParameters}\n * @returns The transaction receipt. {@link SendRawTransactionSyncReturnType}\n *\n * @example\n * import { createWalletClient, custom } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { sendRawTransactionSync } from 'viem/wallet'\n *\n * const client = createWalletClient({\n * chain: mainnet,\n * transport: custom(window.ethereum),\n * })\n *\n * const receipt = await sendRawTransactionSync(client, {\n * serializedTransaction: '0x02f850018203118080825208808080c080a04012522854168b27e5dc3d5839bab5e6b39e1a0ffd343901ce1622e3d64b48f1a04e00902ae0502c4728cbf12156290df99c3ed7de85b1dbfe20b5c36931733a33'\n * })\n */\nexport async function sendRawTransactionSync<chain extends Chain | undefined>(\n client: Client<Transport, chain>,\n {\n serializedTransaction,\n throwOnReceiptRevert,\n timeout,\n }: SendRawTransactionSyncParameters,\n): Promise<SendRawTransactionSyncReturnType<chain>> {\n const receipt = await client.request(\n {\n method: 'eth_sendRawTransactionSync',\n params: timeout\n ? [serializedTransaction, numberToHex(timeout)]\n : [serializedTransaction],\n },\n { retryCount: 0 },\n )\n const format =\n client.chain?.formatters?.transactionReceipt?.format ||\n formatTransactionReceipt\n\n const formatted = format(receipt) as SendRawTransactionSyncReturnType<chain>\n if (formatted.status === 'reverted' && throwOnReceiptRevert)\n throw new TransactionReceiptRevertedError({ receipt: formatted })\n return formatted\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\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 chain extends Chain | undefined,\n account extends Account | undefined,\n>(client: Client<Transport, chain, account>, { chain }: AddChainParameters) {\n const { id, name, nativeCurrency, rpcUrls, blockExplorers } = chain\n await client.request(\n {\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 { dedupe: true, retryCount: 0 },\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 { Chain, GetChainParameter } from '../../types/chain.js'\nimport type { ContractConstructorArgs } from '../../types/contract.js'\nimport type { Hex } from '../../types/misc.js'\nimport type { UnionEvaluate, UnionOmit } from '../../types/utils.js'\nimport { encodeDeployData } from '../../utils/abi/encodeDeployData.js'\nimport {\n type SendTransactionErrorType,\n type SendTransactionParameters,\n type SendTransactionReturnType,\n sendTransaction,\n} from './sendTransaction.js'\n\nexport type DeployContractParameters<\n abi extends Abi | readonly unknown[] = Abi,\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n chainOverride extends Chain | undefined = Chain | undefined,\n ///\n allArgs = ContractConstructorArgs<abi>,\n> = UnionOmit<\n SendTransactionParameters<chain, account, chainOverride>,\n 'accessList' | 'chain' | 'to' | 'data'\n> &\n GetChainParameter<chain, chainOverride> &\n UnionEvaluate<\n readonly [] extends allArgs\n ? { args?: allArgs | undefined }\n : { args: allArgs }\n > & {\n abi: abi\n bytecode: Hex\n }\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\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#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 abi extends Abi | readonly unknown[],\n chain extends Chain | undefined,\n account extends Account | undefined,\n chainOverride extends Chain | undefined,\n>(\n walletClient: Client<Transport, chain, account>,\n parameters: DeployContractParameters<abi, chain, account, chainOverride>,\n): Promise<DeployContractReturnType> {\n const { abi, args, bytecode, ...request } =\n parameters as DeployContractParameters\n const calldata = encodeDeployData({ abi, args, bytecode })\n return sendTransaction(walletClient, {\n ...request,\n ...(request.authorizationList ? { to: null } : {}),\n data: calldata,\n } as unknown as SendTransactionParameters<chain, account, chainOverride>)\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\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 chain extends Chain | undefined,\n account extends Account | undefined = undefined,\n>(client: Client<Transport, chain, account>): Promise<GetAddressesReturnType> {\n if (client.account?.type === 'local') return [client.account.address]\n const addresses = await client.request(\n { method: 'eth_accounts' },\n { dedupe: true },\n )\n return addresses.map((address) => checksumAddress(address))\n}\n","import type { Address } from 'abitype'\n\nimport { parseAccount } from '../../accounts/utils/parseAccount.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 { Account } from '../../types/account.js'\nimport type {\n Capabilities,\n ChainIdToCapabilities,\n ExtractCapabilities,\n} from '../../types/capabilities.js'\nimport type { Prettify } from '../../types/utils.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport { numberToHex } from '../../utils/encoding/toHex.js'\n\nexport type GetCapabilitiesParameters<\n chainId extends number | undefined = undefined,\n> = {\n account?: Account | Address | undefined\n chainId?: chainId | number | undefined\n}\n\nexport type GetCapabilitiesReturnType<\n chainId extends number | undefined = undefined,\n> = Prettify<\n chainId extends number\n ? ExtractCapabilities<'getCapabilities', 'ReturnType'>\n : ChainIdToCapabilities<\n Capabilities<ExtractCapabilities<'getCapabilities', 'ReturnType'>>,\n number\n >\n>\n\nexport type GetCapabilitiesErrorType = RequestErrorType | ErrorType\n\n/**\n * Extract capabilities that a connected wallet supports (e.g. paymasters, session keys, etc).\n *\n * - Docs: https://viem.sh/docs/actions/wallet/getCapabilities\n * - JSON-RPC Methods: [`wallet_getCapabilities`](https://eips.ethereum.org/EIPS/eip-5792)\n *\n * @param client - Client to use\n * @returns The wallet's capabilities. {@link GetCapabilitiesReturnType}\n *\n * @example\n * import { createWalletClient, custom } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getCapabilities } from 'viem/actions'\n *\n * const client = createWalletClient({\n * chain: mainnet,\n * transport: custom(window.ethereum),\n * })\n * const capabilities = await getCapabilities(client)\n */\nexport async function getCapabilities<\n chainId extends number | undefined = undefined,\n>(\n client: Client<Transport>,\n parameters: GetCapabilitiesParameters<chainId> = {},\n): Promise<GetCapabilitiesReturnType<chainId>> {\n const { account = client.account, chainId } = parameters\n\n const account_ = account ? parseAccount(account) : undefined\n\n const params = chainId\n ? ([account_?.address, [numberToHex(chainId)]] as const)\n : ([account_?.address] as const)\n const capabilities_raw = await client.request({\n method: 'wallet_getCapabilities',\n params,\n })\n\n const capabilities = {} as ChainIdToCapabilities<\n ExtractCapabilities<'getCapabilities', 'ReturnType'>,\n number\n >\n for (const [chainId, capabilities_] of Object.entries(capabilities_raw)) {\n capabilities[Number(chainId)] = {}\n for (let [key, value] of Object.entries(capabilities_)) {\n if (key === 'addSubAccount') key = 'unstable_addSubAccount'\n capabilities[Number(chainId)][key] = value\n }\n }\n return (\n typeof chainId === 'number' ? capabilities[chainId] : capabilities\n ) as never\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\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 chain extends Chain | undefined,\n account extends Account | undefined = undefined,\n>(client: Client<Transport, chain, account>) {\n const permissions = await client.request(\n { method: 'wallet_getPermissions' },\n { dedupe: true },\n )\n return permissions\n}\n","import type { Address } from 'abitype'\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 {\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 {\n Authorization,\n AuthorizationRequest,\n} from '../../types/authorization.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { PartialBy } from '../../types/utils.js'\nimport { isAddressEqual } from '../../utils/address/isAddressEqual.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport { getAction } from '../../utils/getAction.js'\nimport { getChainId } from '../public/getChainId.js'\nimport { getTransactionCount } from '../public/getTransactionCount.js'\n\nexport type PrepareAuthorizationParameters<\n account extends Account | undefined = Account | undefined,\n> = GetAccountParameter<account> &\n PartialBy<AuthorizationRequest, 'chainId' | 'nonce'> & {\n /**\n * Whether the EIP-7702 Transaction will be executed by the EOA (signing this Authorization) or another Account.\n *\n * By default, it will be assumed that the EIP-7702 Transaction will\n * be executed by another Account.\n */\n executor?: 'self' | Account | Address | undefined\n }\n\nexport type PrepareAuthorizationReturnType = Authorization\n\nexport type PrepareAuthorizationErrorType =\n | ParseAccountErrorType\n | RequestErrorType\n | AccountNotFoundErrorType\n | ErrorType\n\n/**\n * Prepares an [EIP-7702 Authorization](https://eips.ethereum.org/EIPS/eip-7702) object for signing.\n * This Action will fill the required fields of the Authorization object if they are not provided (e.g. `nonce` and `chainId`).\n *\n * With the prepared Authorization object, you can use [`signAuthorization`](https://viem.sh/docs/eip7702/signAuthorization) to sign over the Authorization object.\n *\n * @param client - Client to use\n * @param parameters - {@link PrepareAuthorizationParameters}\n * @returns The prepared Authorization object. {@link PrepareAuthorizationReturnType}\n *\n * @example\n * import { createClient, http } from 'viem'\n * import { privateKeyToAccount } from 'viem/accounts'\n * import { mainnet } from 'viem/chains'\n * import { prepareAuthorization } from 'viem/experimental'\n *\n * const client = createClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const authorization = await prepareAuthorization(client, {\n * account: privateKeyToAccount('0x..'),\n * contractAddress: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',\n * })\n *\n * @example\n * // Account Hoisting\n * import { createClient, http } from 'viem'\n * import { privateKeyToAccount } from 'viem/accounts'\n * import { mainnet } from 'viem/chains'\n * import { prepareAuthorization } from 'viem/experimental'\n *\n * const client = createClient({\n * account: privateKeyToAccount('0x…'),\n * chain: mainnet,\n * transport: http(),\n * })\n * const authorization = await prepareAuthorization(client, {\n * contractAddress: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',\n * })\n */\nexport async function prepareAuthorization<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(\n client: Client<Transport, chain, account>,\n parameters: PrepareAuthorizationParameters<account>,\n): Promise<PrepareAuthorizationReturnType> {\n const { account: account_ = client.account, chainId, nonce } = parameters\n\n if (!account_)\n throw new AccountNotFoundError({\n docsPath: '/docs/eip7702/prepareAuthorization',\n })\n const account = parseAccount(account_)\n\n const executor = (() => {\n if (!parameters.executor) return undefined\n if (parameters.executor === 'self') return parameters.executor\n return parseAccount(parameters.executor)\n })()\n\n const authorization = {\n address: parameters.contractAddress ?? parameters.address,\n chainId,\n nonce,\n } as Authorization\n\n if (typeof authorization.chainId === 'undefined')\n authorization.chainId =\n client.chain?.id ??\n (await getAction(client, getChainId, 'getChainId')({}))\n\n if (typeof authorization.nonce === 'undefined') {\n authorization.nonce = await getAction(\n client,\n getTransactionCount,\n 'getTransactionCount',\n )({\n address: account.address,\n blockTag: 'pending',\n })\n if (\n executor === 'self' ||\n (executor?.address && isAddressEqual(executor.address, account.address))\n )\n authorization.nonce += 1\n }\n\n return authorization\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\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 chain extends Chain | undefined,\n account extends Account | undefined = undefined,\n>(\n client: Client<Transport, chain, account>,\n): Promise<RequestAddressesReturnType> {\n const addresses = await client.request(\n { method: 'eth_requestAccounts' },\n { dedupe: true, retryCount: 0 },\n )\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\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 chain extends Chain | undefined,\n account extends Account | undefined = undefined,\n>(\n client: Client<Transport, chain, account>,\n permissions: RequestPermissionsParameters,\n) {\n return client.request(\n {\n method: 'wallet_requestPermissions',\n params: [permissions],\n },\n { retryCount: 0 },\n )\n}\n","import type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { Account } from '../../types/account.js'\nimport type { Chain } from '../../types/chain.js'\nimport { getAction } from '../../utils/getAction.js'\nimport type { GetCallsStatusReturnType } from './getCallsStatus.js'\nimport {\n type SendCallsErrorType,\n type SendCallsParameters,\n sendCalls,\n} from './sendCalls.js'\nimport {\n type WaitForCallsStatusParameters,\n waitForCallsStatus,\n} from './waitForCallsStatus.js'\n\nexport type SendCallsSyncParameters<\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n chainOverride extends Chain | undefined = Chain | undefined,\n calls extends readonly unknown[] = readonly unknown[],\n> = SendCallsParameters<chain, account, chainOverride, calls> &\n Pick<\n WaitForCallsStatusParameters,\n 'pollingInterval' | 'status' | 'throwOnFailure'\n > & {\n /** Timeout (ms) to wait for calls to be included in a block. @default chain.blockTime * 3 */\n timeout?: number | undefined\n }\n\nexport type SendCallsSyncReturnType = GetCallsStatusReturnType\n\nexport type SendCallsSyncErrorType = SendCallsErrorType\n\n/**\n * Requests the connected wallet to send a batch of calls, and waits for the calls to be included in a block.\n *\n * - Docs: https://viem.sh/docs/actions/wallet/sendCallsSync\n * - JSON-RPC Methods: [`wallet_sendCalls`](https://eips.ethereum.org/EIPS/eip-5792)\n *\n * @param client - Client to use\n * @returns Calls status. {@link SendCallsSyncReturnType}\n *\n * @example\n * import { createWalletClient, custom } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { sendCalls } from 'viem/actions'\n *\n * const client = createWalletClient({\n * chain: mainnet,\n * transport: custom(window.ethereum),\n * })\n * const status = await sendCallsSync(client, {\n * account: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',\n * calls: [\n * {\n * data: '0xdeadbeef',\n * to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',\n * },\n * {\n * to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',\n * value: 69420n,\n * },\n * ],\n * })\n */\nexport async function sendCallsSync<\n const calls extends readonly unknown[],\n chain extends Chain | undefined,\n account extends Account | undefined = undefined,\n chainOverride extends Chain | undefined = undefined,\n>(\n client: Client<Transport, chain, account>,\n parameters: SendCallsSyncParameters<chain, account, chainOverride, calls>,\n): Promise<SendCallsSyncReturnType> {\n const { chain = client.chain } = parameters\n const timeout =\n parameters.timeout ?? Math.max((chain?.blockTime ?? 0) * 3, 5_000)\n const result = await getAction(client, sendCalls, 'sendCalls')(parameters)\n const status = await getAction(\n client,\n waitForCallsStatus,\n 'waitForCallsStatus',\n )({\n ...parameters,\n id: result.id,\n timeout,\n })\n return status\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 { SignTransactionErrorType } from '../../accounts/utils/signTransaction.js'\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport {\n AccountNotFoundError,\n type AccountNotFoundErrorType,\n AccountTypeNotSupportedError,\n type AccountTypeNotSupportedErrorType,\n} from '../../errors/account.js'\nimport { BaseError } from '../../errors/base.js'\nimport {\n TransactionReceiptRevertedError,\n type TransactionReceiptRevertedErrorType,\n} from '../../errors/transaction.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { GetAccountParameter } from '../../types/account.js'\nimport type {\n Chain,\n DeriveChain,\n GetChainParameter,\n} from '../../types/chain.js'\nimport type { GetTransactionRequestKzgParameter } from '../../types/kzg.js'\nimport type { Hash, Hex } from '../../types/misc.js'\nimport type { TransactionRequest } from '../../types/transaction.js'\nimport type { UnionOmit } from '../../types/utils.js'\nimport {\n type RecoverAuthorizationAddressErrorType,\n recoverAuthorizationAddress,\n} from '../../utils/authorization/recoverAuthorizationAddress.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport {\n type AssertCurrentChainErrorType,\n assertCurrentChain,\n} from '../../utils/chain/assertCurrentChain.js'\nimport { concat } from '../../utils/data/concat.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 { LruMap } from '../../utils/lru.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 WaitForTransactionReceiptErrorType,\n waitForTransactionReceipt,\n} from '../public/waitForTransactionReceipt.js'\nimport {\n defaultParameters,\n type PrepareTransactionRequestErrorType,\n prepareTransactionRequest,\n} from './prepareTransactionRequest.js'\nimport {\n type SendRawTransactionSyncErrorType,\n type SendRawTransactionSyncReturnType,\n sendRawTransactionSync,\n} from './sendRawTransactionSync.js'\n\nconst supportsWalletNamespace = new LruMap<boolean>(128)\n\nexport type SendTransactionSyncRequest<\n chain extends Chain | undefined = Chain | undefined,\n chainOverride extends Chain | undefined = Chain | undefined,\n ///\n _derivedChain extends Chain | undefined = DeriveChain<chain, chainOverride>,\n> = UnionOmit<FormattedTransactionRequest<_derivedChain>, 'from'> &\n GetTransactionRequestKzgParameter\n\nexport type SendTransactionSyncParameters<\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n chainOverride extends Chain | undefined = Chain | undefined,\n request extends SendTransactionSyncRequest<\n chain,\n chainOverride\n > = SendTransactionSyncRequest<chain, chainOverride>,\n> = request &\n GetAccountParameter<account, Account | Address, true, true> &\n GetChainParameter<chain, chainOverride> &\n GetTransactionRequestKzgParameter<request> & {\n /** Whether to assert that the client chain is on the correct chain. @default true */\n assertChainId?: boolean | undefined\n /** Data to append to the end of the calldata. Takes precedence over `client.dataSuffix`. */\n dataSuffix?: Hex | undefined\n /** Polling interval (ms) to poll for the transaction receipt. @default client.pollingInterval */\n pollingInterval?: number | undefined\n /** Whether to throw an error if the transaction was detected as reverted. @default true */\n throwOnReceiptRevert?: boolean | undefined\n /** Timeout (ms) to wait for a response. @default Math.max(chain.blockTime * 3, 5_000) */\n timeout?: number | undefined\n }\n\nexport type SendTransactionSyncReturnType<\n chain extends Chain | undefined = Chain | undefined,\n> = SendRawTransactionSyncReturnType<chain>\n\nexport type SendTransactionSyncErrorType =\n | ParseAccountErrorType\n | GetTransactionErrorReturnType<\n | AccountNotFoundErrorType\n | AccountTypeNotSupportedErrorType\n | AssertCurrentChainErrorType\n | AssertRequestErrorType\n | GetChainIdErrorType\n | PrepareTransactionRequestErrorType\n | SendRawTransactionSyncErrorType\n | RecoverAuthorizationAddressErrorType\n | SignTransactionErrorType\n | TransactionReceiptRevertedErrorType\n | RequestErrorType\n >\n | WaitForTransactionReceiptErrorType\n | ErrorType\n\n/**\n * Creates, signs, and sends a new transaction to the network synchronously.\n * Returns the transaction receipt.\n *\n * @param client - Client to use\n * @param parameters - {@link SendTransactionSyncParameters}\n * @returns The transaction receipt. {@link SendTransactionSyncReturnType}\n *\n * @example\n * import { createWalletClient, custom } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { sendTransactionSync } from 'viem/wallet'\n *\n * const client = createWalletClient({\n * chain: mainnet,\n * transport: custom(window.ethereum),\n * })\n * const receipt = await sendTransactionSync(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 { sendTransactionSync } from 'viem/wallet'\n *\n * const client = createWalletClient({\n * account: privateKeyToAccount('0x…'),\n * chain: mainnet,\n * transport: http(),\n * })\n * const receipt = await sendTransactionSync(client, {\n * to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',\n * value: 1000000000000000000n,\n * })\n */\nexport async function sendTransactionSync<\n chain extends Chain | undefined,\n account extends Account | undefined,\n const request extends SendTransactionSyncRequest<chain, chainOverride>,\n chainOverride extends Chain | undefined = undefined,\n>(\n client: Client<Transport, chain, account>,\n parameters: SendTransactionSyncParameters<\n chain,\n account,\n chainOverride,\n request\n >,\n): Promise<SendTransactionSyncReturnType<chain>> {\n const {\n account: account_ = client.account,\n assertChainId = true,\n chain = client.chain,\n accessList,\n authorizationList,\n blobs,\n data,\n dataSuffix = typeof client.dataSuffix === 'string'\n ? client.dataSuffix\n : client.dataSuffix?.value,\n gas,\n gasPrice,\n maxFeePerBlobGas,\n maxFeePerGas,\n maxPriorityFeePerGas,\n nonce,\n pollingInterval,\n throwOnReceiptRevert,\n type,\n value,\n ...rest\n } = parameters\n const timeout =\n parameters.timeout ?? Math.max((chain?.blockTime ?? 0) * 3, 5_000)\n\n if (typeof account_ === 'undefined')\n throw new AccountNotFoundError({\n docsPath: '/docs/actions/wallet/sendTransactionSync',\n })\n const account = account_ ? parseAccount(account_) : null\n\n try {\n assertRequest(parameters as AssertRequestParameters)\n\n const to = await (async () => {\n // If `to` exists on the parameters, use that.\n if (parameters.to) return parameters.to\n\n // If `to` is null, we are sending a deployment transaction.\n if (parameters.to === null) return undefined\n\n // If no `to` exists, and we are sending a EIP-7702 transaction, use the\n // address of the first authorization in the list.\n if (authorizationList && authorizationList.length > 0)\n return await recoverAuthorizationAddress({\n authorization: authorizationList[0],\n }).catch(() => {\n throw new BaseError(\n '`to` is required. Could not infer from `authorizationList`.',\n )\n })\n\n // Otherwise, we are sending a deployment transaction.\n return undefined\n })()\n\n if (account?.type === 'json-rpc' || account === null) {\n let chainId: number | undefined\n if (chain !== null) {\n chainId = await getAction(client, getChainId, 'getChainId')({})\n if (assertChainId)\n assertCurrentChain({\n currentChainId: chainId,\n chain,\n })\n }\n\n const chainFormat = client.chain?.formatters?.transactionRequest?.format\n const format = chainFormat || formatTransactionRequest\n\n const request = format(\n {\n // Pick out extra data that might exist on the chain's transaction request type.\n ...extract(rest, { format: chainFormat }),\n accessList,\n account,\n authorizationList,\n blobs,\n chainId,\n data: data ? concat([data, dataSuffix ?? '0x']) : data,\n gas,\n gasPrice,\n maxFeePerBlobGas,\n maxFeePerGas,\n maxPriorityFeePerGas,\n nonce,\n to,\n type,\n value,\n } as TransactionRequest,\n 'sendTransaction',\n )\n\n const isWalletNamespaceSupported = supportsWalletNamespace.get(client.uid)\n const method = isWalletNamespaceSupported\n ? 'wallet_sendTransaction'\n : 'eth_sendTransaction'\n\n const hash = await (async () => {\n try {\n return await client.request(\n {\n method,\n params: [request],\n },\n { retryCount: 0 },\n )\n } catch (e) {\n if (isWalletNamespaceSupported === false) throw e\n\n const error = e as BaseError\n // If the transport does not support the method or input, attempt to use the\n // `wallet_sendTransaction` method.\n if (\n error.name === 'InvalidInputRpcError' ||\n error.name === 'InvalidParamsRpcError' ||\n error.name === 'MethodNotFoundRpcError' ||\n error.name === 'MethodNotSupportedRpcError'\n ) {\n return (await client\n .request(\n {\n method: 'wallet_sendTransaction',\n params: [request],\n },\n { retryCount: 0 },\n )\n .then((hash) => {\n supportsWalletNamespace.set(client.uid, true)\n return hash\n })\n .catch((e) => {\n const walletNamespaceError = e as BaseError\n if (\n walletNamespaceError.name === 'MethodNotFoundRpcError' ||\n walletNamespaceError.name === 'MethodNotSupportedRpcError'\n ) {\n supportsWalletNamespace.set(client.uid, false)\n throw error\n }\n\n throw walletNamespaceError\n })) as never\n }\n\n throw error\n }\n })()\n\n const receipt = await getAction(\n client,\n waitForTransactionReceipt,\n 'waitForTransactionReceipt',\n )({\n checkReplacement: false,\n hash,\n pollingInterval,\n timeout,\n })\n if (throwOnReceiptRevert && receipt.status === 'reverted')\n throw new TransactionReceiptRevertedError({ receipt })\n return receipt\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 authorizationList,\n blobs,\n chain,\n data: data ? concat([data, dataSuffix ?? '0x']) : data,\n gas,\n gasPrice,\n maxFeePerBlobGas,\n maxFeePerGas,\n maxPriorityFeePerGas,\n nonce,\n nonceManager: account.nonceManager,\n parameters: [...defaultParameters, 'sidecars'],\n type,\n value,\n ...rest,\n to,\n } as any)\n\n const serializer = chain?.serializers?.transaction\n const serializedTransaction = (await account.signTransaction(request, {\n serializer,\n })) as Hash\n return (await getAction(\n client,\n sendRawTransactionSync,\n 'sendRawTransactionSync',\n )({\n serializedTransaction,\n throwOnReceiptRevert,\n timeout: parameters.timeout,\n })) as never\n }\n\n if (account?.type === 'smart')\n throw new AccountTypeNotSupportedError({\n metaMessages: [\n 'Consider using the `sendUserOperation` Action instead.',\n ],\n docsPath: '/docs/actions/bundler/sendUserOperation',\n type: 'smart',\n })\n\n throw new AccountTypeNotSupportedError({\n docsPath: '/docs/actions/wallet/sendTransactionSync',\n type: (account as any)?.type,\n })\n } catch (err) {\n if (err instanceof AccountTypeNotSupportedError) throw err\n throw getTransactionError(err as BaseError, {\n ...parameters,\n account,\n chain: parameters.chain || undefined,\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 { Account } from '../../types/account.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\n\nexport type ShowCallsStatusParameters = { id: string }\n\nexport type ShowCallsStatusReturnType = void\n\nexport type ShowCallsStatusErrorType = RequestErrorType | ErrorType\n\n/**\n * Requests for the wallet to show information about a call batch\n * that was sent via `sendCalls`.\n *\n * - Docs: https://viem.sh/docs/actions/wallet/showCallsStatus\n * - JSON-RPC Methods: [`wallet_showCallsStatus`](https://eips.ethereum.org/EIPS/eip-5792)\n *\n * @param client - Client to use\n * @returns Status of the calls. {@link ShowCallsStatusReturnType}\n *\n * @example\n * import { createWalletClient, custom } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { showCallsStatus } from 'viem/actions'\n *\n * const client = createWalletClient({\n * chain: mainnet,\n * transport: custom(window.ethereum),\n * })\n * await showCallsStatus(client, { id: '0xdeadbeef' })\n */\nexport async function showCallsStatus<\n chain extends Chain | undefined,\n account extends Account | undefined = undefined,\n>(\n client: Client<Transport, chain, account>,\n parameters: ShowCallsStatusParameters,\n): Promise<ShowCallsStatusReturnType> {\n const { id } = parameters\n await client.request({\n method: 'wallet_showCallsStatus',\n params: [id],\n })\n return\n}\n","import type { Account } from '../../accounts/types.js'\nimport {\n type ParseAccountErrorType,\n parseAccount,\n} from '../../accounts/utils/parseAccount.js'\nimport type {\n SignAuthorizationErrorType as SignAuthorizationErrorType_account,\n SignAuthorizationReturnType as SignAuthorizationReturnType_account,\n} from '../../accounts/utils/signAuthorization.js'\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport {\n AccountNotFoundError,\n type AccountNotFoundErrorType,\n AccountTypeNotSupportedError,\n type AccountTypeNotSupportedErrorType,\n} from '../../errors/account.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport {\n type PrepareAuthorizationErrorType,\n type PrepareAuthorizationParameters,\n prepareAuthorization,\n} from './prepareAuthorization.js'\n\nexport type SignAuthorizationParameters<\n account extends Account | undefined = Account | undefined,\n> = PrepareAuthorizationParameters<account>\n\nexport type SignAuthorizationReturnType = SignAuthorizationReturnType_account\n\nexport type SignAuthorizationErrorType =\n | ParseAccountErrorType\n | AccountNotFoundErrorType\n | AccountTypeNotSupportedErrorType\n | PrepareAuthorizationErrorType\n | SignAuthorizationErrorType_account\n | ErrorType\n\n/**\n * Signs an [EIP-7702 Authorization](https://eips.ethereum.org/EIPS/eip-7702) object.\n *\n * With the calculated signature, you can:\n * - use [`verifyAuthorization`](https://viem.sh/docs/eip7702/verifyAuthorization) to verify the signed Authorization object,\n * - use [`recoverAuthorizationAddress`](https://viem.sh/docs/eip7702/recoverAuthorizationAddress) to recover the signing address from the signed Authorization object.\n *\n * @param client - Client to use\n * @param parameters - {@link SignAuthorizationParameters}\n * @returns The signed Authorization object. {@link SignAuthorizationReturnType}\n *\n * @example\n * import { createClient, http } from 'viem'\n * import { privateKeyToAccount } from 'viem/accounts'\n * import { mainnet } from 'viem/chains'\n * import { signAuthorization } from 'viem/experimental'\n *\n * const client = createClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const signature = await signAuthorization(client, {\n * account: privateKeyToAccount('0x..'),\n * contractAddress: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',\n * })\n *\n * @example\n * // Account Hoisting\n * import { createClient, http } from 'viem'\n * import { privateKeyToAccount } from 'viem/accounts'\n * import { mainnet } from 'viem/chains'\n * import { signAuthorization } from 'viem/experimental'\n *\n * const client = createClient({\n * account: privateKeyToAccount('0x…'),\n * chain: mainnet,\n * transport: http(),\n * })\n * const signature = await signAuthorization(client, {\n * contractAddress: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',\n * })\n */\nexport async function signAuthorization<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(\n client: Client<Transport, chain, account>,\n parameters: SignAuthorizationParameters<account>,\n): Promise<SignAuthorizationReturnType> {\n const { account: account_ = client.account } = parameters\n\n if (!account_)\n throw new AccountNotFoundError({\n docsPath: '/docs/eip7702/signAuthorization',\n })\n const account = parseAccount(account_)\n\n if (!account.signAuthorization)\n throw new AccountTypeNotSupportedError({\n docsPath: '/docs/eip7702/signAuthorization',\n metaMessages: [\n 'The `signAuthorization` Action does not support JSON-RPC Accounts.',\n ],\n type: account.type,\n })\n\n const authorization = await prepareAuthorization(client, parameters)\n return account.signAuthorization(authorization)\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 stringToHex,\n type ToHexErrorType,\n toHex,\n} from '../../utils/encoding/toHex.js'\n\nexport type SignMessageParameters<\n account extends Account | undefined = Account | undefined,\n> = GetAccountParameter<account> & {\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\n * - JSON-RPC Methods:\n * - JSON-RPC Accounts: [`personal_sign`](https://docs.metamask.io/guide/signing-data#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) to verify the signature,\n * - use [`recoverMessageAddress`](https://viem.sh/docs/utilities/recoverMessageAddress) 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 chain extends Chain | undefined,\n account extends Account | undefined,\n>(\n client: Client<Transport, chain, account>,\n {\n account: account_ = client.account,\n message,\n }: SignMessageParameters<account>,\n): Promise<SignMessageReturnType> {\n if (!account_)\n throw new AccountNotFoundError({\n docsPath: '/docs/actions/wallet/signMessage',\n })\n const account = parseAccount(account_)\n\n if (account.signMessage) 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 {\n method: 'personal_sign',\n params: [message_, account.address],\n },\n { retryCount: 0 },\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 {\n Chain,\n DeriveChain,\n GetChainParameter,\n} from '../../types/chain.js'\nimport type { GetTransactionRequestKzgParameter } from '../../types/kzg.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 { numberToHex } from '../../utils/encoding/toHex.js'\nimport {\n type FormattedTransactionRequest,\n formatTransactionRequest,\n} from '../../utils/formatters/transactionRequest.js'\nimport { getAction } from '../../utils/getAction.js'\nimport {\n type AssertRequestErrorType,\n assertRequest,\n} from '../../utils/transaction/assertRequest.js'\nimport type { GetTransactionType } from '../../utils/transaction/getTransactionType.js'\nimport { type GetChainIdErrorType, getChainId } from '../public/getChainId.js'\n\nexport type SignTransactionRequest<\n chain extends Chain | undefined = Chain | undefined,\n chainOverride extends Chain | undefined = Chain | undefined,\n ///\n _derivedChain extends Chain | undefined = DeriveChain<chain, chainOverride>,\n> = UnionOmit<FormattedTransactionRequest<_derivedChain>, 'from'>\n\nexport type SignTransactionParameters<\n chain extends Chain | undefined,\n account extends Account | undefined,\n chainOverride extends Chain | undefined = Chain | undefined,\n request extends SignTransactionRequest<\n chain,\n chainOverride\n > = SignTransactionRequest<chain, chainOverride>,\n> = request &\n GetAccountParameter<account> &\n GetChainParameter<chain, chainOverride> &\n GetTransactionRequestKzgParameter<request>\n\nexport type SignTransactionReturnType<\n request extends SignTransactionRequest = SignTransactionRequest,\n> = TransactionSerialized<GetTransactionType<request>>\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\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 transaction. {@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 chain extends Chain | undefined,\n account extends Account | undefined,\n chainOverride extends Chain | undefined = undefined,\n const request extends SignTransactionRequest<\n chain,\n chainOverride\n > = SignTransactionRequest<chain, chainOverride>,\n>(\n client: Client<Transport, chain, account>,\n parameters: SignTransactionParameters<chain, account, chainOverride, request>,\n): Promise<SignTransactionReturnType<request>> {\n const {\n account: account_ = client.account,\n chain = client.chain,\n ...transaction\n } = parameters\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 ...parameters,\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.signTransaction)\n return account.signTransaction(\n {\n ...transaction,\n chainId,\n } as TransactionSerializable,\n { serializer: client.chain?.serializers?.transaction },\n ) as Promise<SignTransactionReturnType<request>>\n\n return await client.request(\n {\n method: 'eth_signTransaction',\n params: [\n {\n ...format(\n {\n ...transaction,\n account,\n } as unknown as TransactionRequest,\n 'signTransaction',\n ),\n chainId: numberToHex(chainId),\n from: account.address,\n } as unknown as RpcTransactionRequest,\n ],\n },\n { retryCount: 0 },\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 } from '../../utils/data/isHex.js'\nimport type { StringifyErrorType } from '../../utils/stringify.js'\nimport {\n type GetTypesForEIP712DomainErrorType,\n getTypesForEIP712Domain,\n type SerializeTypedDataErrorType,\n serializeTypedData,\n type ValidateTypedDataErrorType,\n validateTypedData,\n} from '../../utils/typedData.js'\n\nexport type SignTypedDataParameters<\n typedData extends TypedData | Record<string, unknown> = TypedData,\n primaryType extends keyof typedData | 'EIP712Domain' = keyof typedData,\n account extends Account | undefined = undefined,\n ///\n primaryTypes = typedData extends TypedData ? keyof typedData : string,\n> = TypedDataDefinition<typedData, primaryType, primaryTypes> &\n GetAccountParameter<account>\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 | SerializeTypedDataErrorType\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\n * - JSON-RPC Methods:\n * - JSON-RPC Accounts: [`eth_signTypedData_v4`](https://docs.metamask.io/guide/signing-data#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 typedData extends TypedData | Record<string, unknown>,\n primaryType extends keyof typedData | 'EIP712Domain',\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(\n client: Client<Transport, chain, account>,\n parameters: SignTypedDataParameters<typedData, primaryType, account>,\n): Promise<SignTypedDataReturnType> {\n const {\n account: account_ = client.account,\n domain,\n message,\n primaryType,\n } = parameters as unknown as SignTypedDataParameters\n\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 ...parameters.types,\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({ domain, message, primaryType, types })\n\n if (account.signTypedData)\n return account.signTypedData({ domain, message, primaryType, types })\n\n const typedData = serializeTypedData({ domain, message, primaryType, types })\n return client.request(\n {\n method: 'eth_signTypedData_v4',\n params: [account.address, typedData],\n },\n { retryCount: 0 },\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\n * - JSON-RPC Methods: [`wallet_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 chain extends Chain | undefined,\n account extends Account | undefined = undefined,\n>(client: Client<Transport, chain, account>, { id }: SwitchChainParameters) {\n await client.request(\n {\n method: 'wallet_switchEthereumChain',\n params: [\n {\n chainId: numberToHex(id),\n },\n ],\n },\n { retryCount: 0 },\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\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 chain extends Chain | undefined,\n account extends Account | undefined = undefined,\n>(\n client: Client<Transport, chain, account>,\n params: WatchAssetParameters,\n): Promise<WatchAssetReturnType> {\n const added = await client.request(\n {\n method: 'wallet_watchAsset',\n params,\n },\n { retryCount: 0 },\n )\n return added\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 {\n ContractFunctionArgs,\n ContractFunctionName,\n} from '../../types/contract.js'\nimport {\n type SendTransactionSyncParameters,\n type SendTransactionSyncReturnType,\n sendTransactionSync,\n} from './sendTransactionSync.js'\nimport { type WriteContractParameters, writeContract } from './writeContract.js'\n\nexport type { WriteContractErrorType as WriteContractSyncErrorType } from './writeContract.js'\n\nexport type WriteContractSyncParameters<\n abi extends Abi | readonly unknown[] = Abi,\n functionName extends ContractFunctionName<\n abi,\n 'nonpayable' | 'payable'\n > = ContractFunctionName<abi, 'nonpayable' | 'payable'>,\n args extends ContractFunctionArgs<\n abi,\n 'nonpayable' | 'payable',\n functionName\n > = ContractFunctionArgs<abi, 'nonpayable' | 'payable', functionName>,\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n chainOverride extends Chain | undefined = Chain | undefined,\n> = WriteContractParameters<\n abi,\n functionName,\n args,\n chain,\n account,\n chainOverride\n> &\n Pick<\n SendTransactionSyncParameters<chain>,\n 'pollingInterval' | 'throwOnReceiptRevert' | 'timeout'\n >\n\nexport type WriteContractSyncReturnType<\n chain extends Chain | undefined = Chain | undefined,\n> = SendTransactionSyncReturnType<chain>\n\n/**\n * Executes a write function on a contract synchronously.\n * Returns the transaction receipt.\n *\n * - Docs: https://viem.sh/docs/contract/writeContractSync\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) is needed to be broadcast in order to change the state.\n *\n * Internally, uses a [Wallet Client](https://viem.sh/docs/clients/wallet) to call the [`sendTransaction` action](https://viem.sh/docs/actions/wallet/sendTransaction) with [ABI-encoded `data`](https://viem.sh/docs/contract/encodeFunctionData).\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#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#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 receipt = await writeContractSync(client, {\n * address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\n * abi: parseAbi(['function mint(uint32 tokenId) nonpayable']),\n * functionName: 'mint',\n * args: [69420],\n * })\n */\nexport async function writeContractSync<\n chain extends Chain | undefined,\n account extends Account | undefined,\n const abi extends Abi | readonly unknown[],\n functionName extends ContractFunctionName<abi, 'nonpayable' | 'payable'>,\n args extends ContractFunctionArgs<\n abi,\n 'nonpayable' | 'payable',\n functionName\n >,\n chainOverride extends Chain | undefined,\n>(\n client: Client<Transport, chain, account>,\n parameters: WriteContractSyncParameters<\n abi,\n functionName,\n args,\n chain,\n account,\n chainOverride\n >,\n): Promise<WriteContractSyncReturnType<chain>> {\n return writeContract.internal(\n client,\n sendTransactionSync,\n 'sendTransactionSync',\n parameters as never,\n ) as never\n}\n","import type { Abi, Address, TypedData } from 'abitype'\n\nimport type { Account } from '../../accounts/types.js'\nimport {\n type FillTransactionParameters,\n type FillTransactionReturnType,\n fillTransaction,\n} from '../../actions/public/fillTransaction.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 GetCallsStatusParameters,\n type GetCallsStatusReturnType,\n getCallsStatus,\n} from '../../actions/wallet/getCallsStatus.js'\nimport {\n type GetCapabilitiesParameters,\n type GetCapabilitiesReturnType,\n getCapabilities,\n} from '../../actions/wallet/getCapabilities.js'\nimport {\n type GetPermissionsReturnType,\n getPermissions,\n} from '../../actions/wallet/getPermissions.js'\nimport {\n type PrepareAuthorizationParameters,\n type PrepareAuthorizationReturnType,\n prepareAuthorization,\n} from '../../actions/wallet/prepareAuthorization.js'\nimport {\n type PrepareTransactionRequestParameters,\n type PrepareTransactionRequestRequest,\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 SendCallsParameters,\n type SendCallsReturnType,\n sendCalls,\n} from '../../actions/wallet/sendCalls.js'\nimport {\n type SendCallsSyncParameters,\n type SendCallsSyncReturnType,\n sendCallsSync,\n} from '../../actions/wallet/sendCallsSync.js'\nimport {\n type SendRawTransactionParameters,\n type SendRawTransactionReturnType,\n sendRawTransaction,\n} from '../../actions/wallet/sendRawTransaction.js'\nimport {\n type SendRawTransactionSyncParameters,\n type SendRawTransactionSyncReturnType,\n sendRawTransactionSync,\n} from '../../actions/wallet/sendRawTransactionSync.js'\nimport {\n type SendTransactionParameters,\n type SendTransactionRequest,\n type SendTransactionReturnType,\n sendTransaction,\n} from '../../actions/wallet/sendTransaction.js'\nimport {\n type SendTransactionSyncParameters,\n type SendTransactionSyncRequest,\n type SendTransactionSyncReturnType,\n sendTransactionSync,\n} from '../../actions/wallet/sendTransactionSync.js'\nimport {\n type ShowCallsStatusParameters,\n type ShowCallsStatusReturnType,\n showCallsStatus,\n} from '../../actions/wallet/showCallsStatus.js'\nimport {\n type SignAuthorizationParameters,\n type SignAuthorizationReturnType,\n signAuthorization,\n} from '../../actions/wallet/signAuthorization.js'\nimport {\n type SignMessageParameters,\n type SignMessageReturnType,\n signMessage,\n} from '../../actions/wallet/signMessage.js'\nimport {\n type SignTransactionParameters,\n type SignTransactionRequest,\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 WaitForCallsStatusParameters,\n type WaitForCallsStatusReturnType,\n waitForCallsStatus,\n} from '../../actions/wallet/waitForCallsStatus.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 {\n type WriteContractSyncParameters,\n type WriteContractSyncReturnType,\n writeContractSync,\n} from '../../actions/wallet/writeContractSync.js'\nimport type { Chain } from '../../types/chain.js'\nimport type {\n ContractFunctionArgs,\n ContractFunctionName,\n} from '../../types/contract.js'\nimport type { Client } from '../createClient.js'\nimport type { Transport } from '../transports/createTransport.js'\n\nexport type WalletActions<\n chain extends Chain | undefined = Chain | undefined,\n account 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\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\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#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 abi extends Abi | readonly unknown[],\n chainOverride extends Chain | undefined,\n >(\n args: DeployContractParameters<abi, chain, account, chainOverride>,\n ) => Promise<DeployContractReturnType>\n /**\n * Fills a transaction request with the necessary fields to be signed over.\n *\n * - Docs: https://viem.sh/docs/actions/public/fillTransaction\n *\n * @param client - Client to use\n * @param parameters - {@link FillTransactionParameters}\n * @returns The filled transaction. {@link FillTransactionReturnType}\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 result = await client.fillTransaction({\n * account: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',\n * to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',\n * value: parseEther('1'),\n * })\n */\n fillTransaction: <\n chainOverride extends Chain | undefined = undefined,\n accountOverride extends Account | Address | undefined = undefined,\n >(\n args: FillTransactionParameters<\n chain,\n account,\n chainOverride,\n accountOverride\n >,\n ) => Promise<FillTransactionReturnType<chain, chainOverride>>\n /**\n * Returns a list of account addresses owned by the wallet or client.\n *\n * - Docs: https://viem.sh/docs/actions/wallet/getAddresses\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 status of a call batch that was sent via `sendCalls`.\n *\n * - Docs: https://viem.sh/docs/actions/wallet/getCallsStatus\n * - JSON-RPC Methods: [`wallet_getCallsStatus`](https://eips.ethereum.org/EIPS/eip-5792)\n *\n * @param client - Client to use\n * @returns Status of the calls. {@link GetCallsStatusReturnType}\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 *\n * const { receipts, status } = await client.getCallsStatus({ id: '0xdeadbeef' })\n */\n getCallsStatus: (\n parameters: GetCallsStatusParameters,\n ) => Promise<GetCallsStatusReturnType>\n /**\n * Extract capabilities that a connected wallet supports (e.g. paymasters, session keys, etc).\n *\n * - Docs: https://viem.sh/docs/actions/wallet/getCapabilities\n * - JSON-RPC Methods: [`wallet_getCapabilities`](https://eips.ethereum.org/EIPS/eip-5792)\n *\n * @param client - Client to use\n * @returns The wallet's capabilities. {@link GetCapabilitiesReturnType}\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 *\n * const capabilities = await client.getCapabilities({\n * account: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',\n * })\n */\n getCapabilities: <chainId extends number | undefined>(\n parameters?: GetCapabilitiesParameters<chainId>,\n ) => Promise<GetCapabilitiesReturnType<chainId>>\n /**\n * Returns the chain ID associated with the current network.\n *\n * - Docs: https://viem.sh/docs/actions/public/getChainId\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\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 an [EIP-7702 Authorization](https://eips.ethereum.org/EIPS/eip-7702) object for signing.\n * This Action will fill the required fields of the Authorization object if they are not provided (e.g. `nonce` and `chainId`).\n *\n * With the prepared Authorization object, you can use [`signAuthorization`](https://viem.sh/docs/eip7702/signAuthorization) to sign over the Authorization object.\n *\n * @param client - Client to use\n * @param parameters - {@link PrepareAuthorizationParameters}\n * @returns The prepared Authorization object. {@link PrepareAuthorizationReturnType}\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 * chain: mainnet,\n * transport: http(),\n * })\n *\n * const authorization = await client.prepareAuthorization({\n * account: privateKeyToAccount('0x..'),\n * contractAddress: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',\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 *\n * const authorization = await client.prepareAuthorization({\n * contractAddress: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',\n * })\n */\n prepareAuthorization: (\n parameters: PrepareAuthorizationParameters<account>,\n ) => Promise<PrepareAuthorizationReturnType>\n /**\n * Prepares a transaction request for signing.\n *\n * - Docs: https://viem.sh/docs/actions/wallet/prepareTransactionRequest\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 const request extends PrepareTransactionRequestRequest<\n chain,\n chainOverride\n >,\n chainOverride extends Chain | undefined = undefined,\n accountOverride extends Account | Address | undefined = undefined,\n >(\n args: PrepareTransactionRequestParameters<\n chain,\n account,\n chainOverride,\n accountOverride,\n request\n >,\n ) => Promise<\n PrepareTransactionRequestReturnType<\n chain,\n account,\n chainOverride,\n accountOverride,\n request\n >\n >\n /**\n * Requests a list of accounts managed by a wallet.\n *\n * - Docs: https://viem.sh/docs/actions/wallet/requestAddresses\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\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 * Requests the connected wallet to send a batch of calls.\n *\n * - Docs: https://viem.sh/docs/actions/wallet/sendCalls\n * - JSON-RPC Methods: [`wallet_sendCalls`](https://eips.ethereum.org/EIPS/eip-5792)\n *\n * @param client - Client to use\n * @returns Transaction identifier. {@link SendCallsReturnType}\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 *\n * const id = await client.sendCalls({\n * account: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',\n * calls: [\n * {\n * data: '0xdeadbeef',\n * to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',\n * },\n * {\n * to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',\n * value: 69420n,\n * },\n * ],\n * })\n */\n sendCalls: <\n const calls extends readonly unknown[],\n chainOverride extends Chain | undefined = undefined,\n >(\n parameters: SendCallsParameters<chain, account, chainOverride, calls>,\n ) => Promise<SendCallsReturnType>\n /**\n * Requests the connected wallet to send a batch of calls, and waits for the calls to be included in a block.\n *\n * - Docs: https://viem.sh/docs/actions/wallet/sendCallsSync\n * - JSON-RPC Methods: [`wallet_sendCalls`](https://eips.ethereum.org/EIPS/eip-5792)\n *\n * @param client - Client to use\n * @returns Calls status. {@link SendCallsSyncReturnType}\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 *\n * const status = await client.sendCallsSync({\n * account: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',\n * calls: [\n * {\n * data: '0xdeadbeef',\n * to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',\n * },\n * {\n * to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',\n * value: 69420n,\n * },\n * ],\n * })\n */\n sendCallsSync: <\n const calls extends readonly unknown[],\n chainOverride extends Chain | undefined = undefined,\n >(\n parameters: SendCallsSyncParameters<chain, account, chainOverride, calls>,\n ) => Promise<SendCallsSyncReturnType>\n /**\n * Sends a **signed** transaction to the network\n *\n * - Docs: https://viem.sh/docs/actions/wallet/sendRawTransaction\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 * Sends a **signed** transaction to the network synchronously,\n * and waits for the transaction to be included in a block.\n *\n * - Docs: https://viem.sh/docs/actions/wallet/sendRawTransactionSync\n * - JSON-RPC Method: [`eth_sendRawTransactionSync`](https://eips.ethereum.org/EIPS/eip-7966)\n *\n * @param client - Client to use\n * @param parameters - {@link SendRawTransactionSyncParameters}\n * @returns The transaction receipt. {@link SendRawTransactionSyncReturnType}\n *\n * @example\n * import { createWalletClient, custom } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { sendRawTransactionSync } from 'viem/wallet'\n *\n * const client = createWalletClient({\n * chain: mainnet,\n * transport: custom(window.ethereum),\n * })\n *\n * const receipt = await client.sendRawTransactionSync({\n * serializedTransaction: '0x02f850018203118080825208808080c080a04012522854168b27e5dc3d5839bab5e6b39e1a0ffd343901ce1622e3d64b48f1a04e00902ae0502c4728cbf12156290df99c3ed7de85b1dbfe20b5c36931733a33'\n * })\n */\n sendRawTransactionSync: (\n args: SendRawTransactionSyncParameters,\n ) => Promise<SendRawTransactionSyncReturnType<chain>>\n /**\n * Creates, signs, and sends a new transaction to the network.\n *\n * - Docs: https://viem.sh/docs/actions/wallet/sendTransaction\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#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: <\n const request extends SendTransactionRequest<chain, chainOverride>,\n chainOverride extends Chain | undefined = undefined,\n >(\n args: SendTransactionParameters<chain, account, chainOverride, request>,\n ) => Promise<SendTransactionReturnType>\n /**\n * Creates, signs, and sends a new transaction to the network synchronously.\n * Returns the transaction receipt.\n *\n * - Docs: https://viem.sh/docs/actions/wallet/sendTransactionSync\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 receipt. {@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 receipt = await client.sendTransactionSync({\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 receipt = await client.sendTransactionSync({\n * to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',\n * value: 1000000000000000000n,\n * })\n */\n sendTransactionSync: <\n const request extends SendTransactionSyncRequest<chain, chainOverride>,\n chainOverride extends Chain | undefined = undefined,\n >(\n args: SendTransactionSyncParameters<chain, account, chainOverride, request>,\n ) => Promise<SendTransactionSyncReturnType<chain>>\n /**\n * Requests for the wallet to show information about a call batch\n * that was sent via `sendCalls`.\n *\n * - Docs: https://viem.sh/docs/actions/wallet/showCallsStatus\n * - JSON-RPC Methods: [`wallet_showCallsStatus`](https://eips.ethereum.org/EIPS/eip-5792)\n *\n * @param client - Client to use\n * @returns Displays status of the calls in wallet. {@link ShowCallsStatusReturnType}\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 *\n * await client.showCallsStatus({ id: '0xdeadbeef' })\n */\n showCallsStatus: (\n parameters: ShowCallsStatusParameters,\n ) => Promise<ShowCallsStatusReturnType>\n /**\n * Signs an [EIP-7702 Authorization](https://eips.ethereum.org/EIPS/eip-7702) object.\n *\n * With the calculated signature, you can:\n * - use [`verifyAuthorization`](https://viem.sh/docs/eip7702/verifyAuthorization) to verify the signed Authorization object,\n * - use [`recoverAuthorizationAddress`](https://viem.sh/docs/eip7702/recoverAuthorizationAddress) to recover the signing address from the signed Authorization object.\n *\n * @param client - Client to use\n * @param parameters - {@link SignAuthorizationParameters}\n * @returns The signed Authorization object. {@link SignAuthorizationReturnType}\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 * chain: mainnet,\n * transport: http(),\n * })\n *\n * const signature = await client.signAuthorization({\n * account: privateKeyToAccount('0x..'),\n * contractAddress: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',\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 *\n * const signature = await client.signAuthorization({\n * contractAddress: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',\n * })\n */\n signAuthorization: (\n parameters: SignAuthorizationParameters<account>,\n ) => Promise<SignAuthorizationReturnType>\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\n * - JSON-RPC Methods:\n * - JSON-RPC Accounts: [`personal_sign`](https://docs.metamask.io/guide/signing-data#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) to verify the signature,\n * - use [`recoverMessageAddress`](https://viem.sh/docs/utilities/recoverMessageAddress) 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<account>,\n ) => Promise<SignMessageReturnType>\n /**\n * Signs a transaction.\n *\n * - Docs: https://viem.sh/docs/actions/wallet/signTransaction\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: <\n chainOverride extends Chain | undefined,\n const request extends SignTransactionRequest<\n chain,\n chainOverride\n > = SignTransactionRequest<chain, chainOverride>,\n >(\n args: SignTransactionParameters<chain, account, chainOverride, request>,\n ) => Promise<SignTransactionReturnType<request>>\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\n * - JSON-RPC Methods:\n * - JSON-RPC Accounts: [`eth_signTypedData_v4`](https://docs.metamask.io/guide/signing-data#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 typedData extends TypedData | { [key: string]: unknown },\n primaryType extends string,\n >(\n args: SignTypedDataParameters<typedData, primaryType, account>,\n ) => Promise<SignTypedDataReturnType>\n /**\n * Switch the target chain in a wallet.\n *\n * - Docs: https://viem.sh/docs/actions/wallet/switchChain\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 * Waits for the status & receipts of a call bundle that was sent via `sendCalls`.\n *\n * - Docs: https://viem.sh/docs/actions/wallet/waitForCallsStatus\n * - JSON-RPC Methods: [`wallet_getCallsStatus`](https://eips.ethereum.org/EIPS/eip-5792)\n *\n * @param client - Client to use\n * @param parameters - {@link WaitForCallsStatusParameters}\n * @returns Status & receipts of the call bundle. {@link WaitForCallsStatusReturnType}\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 *\n * const { receipts, status } = await waitForCallsStatus(client, { id: '0xdeadbeef' })\n */\n waitForCallsStatus: (\n parameters: WaitForCallsStatusParameters,\n ) => Promise<WaitForCallsStatusReturnType>\n /**\n * Adds an EVM chain to the wallet.\n *\n * - Docs: https://viem.sh/docs/actions/wallet/watchAsset\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\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) is needed to be broadcast in order to change the state.\n *\n * Internally, uses a [Wallet Client](https://viem.sh/docs/clients/wallet) to call the [`sendTransaction` action](https://viem.sh/docs/actions/wallet/sendTransaction) with [ABI-encoded `data`](https://viem.sh/docs/contract/encodeFunctionData).\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#usage) before you execute it.__\n *\n * @param args - {@link WriteContractParameters}\n * @returns A [Transaction Hash](https://viem.sh/docs/glossary/terms#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 abi extends Abi | readonly unknown[],\n functionName extends ContractFunctionName<abi, 'payable' | 'nonpayable'>,\n args extends ContractFunctionArgs<\n abi,\n 'payable' | 'nonpayable',\n functionName\n >,\n chainOverride extends Chain | undefined = undefined,\n >(\n args: WriteContractParameters<\n abi,\n functionName,\n args,\n chain,\n account,\n chainOverride\n >,\n ) => Promise<WriteContractReturnType>\n /**\n * Executes a write function on a contract synchronously.\n * Returns the transaction receipt.\n *\n * - Docs: https://viem.sh/docs/contract/writeContract\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) is needed to be broadcast in order to change the state.\n *\n * Internally, uses a [Wallet Client](https://viem.sh/docs/clients/wallet) to call the [`sendTransaction` action](https://viem.sh/docs/actions/wallet/sendTransaction) with [ABI-encoded `data`](https://viem.sh/docs/contract/encodeFunctionData).\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#usage) before you execute it.__\n *\n * @param args - {@link WriteContractSyncParameters}\n * @returns A [Transaction Receipt](https://viem.sh/docs/glossary/terms#receipt). {@link WriteContractSyncReturnType}\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 receipt = await client.writeContractSync({\n * address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\n * abi: parseAbi(['function mint(uint32 tokenId) nonpayable']),\n * functionName: 'mint',\n * args: [69420],\n * })\n */\n writeContractSync: <\n const abi extends Abi | readonly unknown[],\n functionName extends ContractFunctionName<abi, 'payable' | 'nonpayable'>,\n args extends ContractFunctionArgs<\n abi,\n 'payable' | 'nonpayable',\n functionName\n >,\n chainOverride extends Chain | undefined = undefined,\n >(\n args: WriteContractSyncParameters<\n abi,\n functionName,\n args,\n chain,\n account,\n chainOverride\n >,\n ) => Promise<WriteContractSyncReturnType>\n}\n\nexport function walletActions<\n transport extends Transport,\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n>(client: Client<transport, chain, account>): WalletActions<chain, account> {\n return {\n addChain: (args) => addChain(client, args),\n deployContract: (args) => deployContract(client, args),\n fillTransaction: (args) => fillTransaction(client, args),\n getAddresses: () => getAddresses(client),\n getCallsStatus: (args) => getCallsStatus(client, args),\n getCapabilities: (args) => getCapabilities(client, args),\n getChainId: () => getChainId(client),\n getPermissions: () => getPermissions(client),\n prepareAuthorization: (args) => prepareAuthorization(client, args),\n prepareTransactionRequest: (args) =>\n prepareTransactionRequest(client as any, args as any) as any,\n requestAddresses: () => requestAddresses(client),\n requestPermissions: (args) => requestPermissions(client, args),\n sendCalls: (args) => sendCalls(client, args),\n sendCallsSync: (args) => sendCallsSync(client, args),\n sendRawTransaction: (args) => sendRawTransaction(client, args),\n sendRawTransactionSync: (args) => sendRawTransactionSync(client, args),\n sendTransaction: (args) => sendTransaction(client, args),\n sendTransactionSync: (args) => sendTransactionSync(client, args),\n showCallsStatus: (args) => showCallsStatus(client, args),\n signAuthorization: (args) => signAuthorization(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 waitForCallsStatus: (args) => waitForCallsStatus(client, args),\n watchAsset: (args) => watchAsset(client, args),\n writeContract: (args) => writeContract(client, args as any),\n writeContractSync: (args) => writeContractSync(client, args as any),\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 { RpcSchema, 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 rpcSchema extends RpcSchema | undefined = undefined,\n> = Prettify<\n Pick<\n ClientConfig<transport, chain, accountOrAddress, rpcSchema>,\n | 'account'\n | 'cacheTime'\n | 'ccipRead'\n | 'chain'\n | 'dataSuffix'\n | 'key'\n | 'name'\n | 'pollingInterval'\n | 'rpcSchema'\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 rpcSchema extends RpcSchema | undefined = undefined,\n> = Prettify<\n Client<\n transport,\n chain,\n account,\n rpcSchema extends RpcSchema\n ? [...WalletRpcSchema, ...rpcSchema]\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) configured for a [Chain](https://viem.sh/docs/clients/chains).\n *\n * - Docs: https://viem.sh/docs/clients/wallet\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).\n *\n * The Wallet Client supports signing over:\n * - [JSON-RPC Accounts](https://viem.sh/docs/clients/wallet#json-rpc-accounts) (e.g. Browser Extension Wallets, WalletConnect, etc).\n * - [Local Accounts](https://viem.sh/docs/clients/wallet#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 rpcSchema extends RpcSchema | undefined = undefined,\n>(\n parameters: WalletClientConfig<transport, chain, accountOrAddress, rpcSchema>,\n): WalletClient<transport, chain, ParseAccount<accountOrAddress>, rpcSchema>\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,\n type: 'walletClient',\n })\n return client.extend(walletActions)\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { Account } from '../../types/account.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { EIP1193RequestFn } from '../../types/eip1193.js'\nimport type { OneOf } from '../../types/utils.js'\nimport { buildRequest } from '../../utils/buildRequest.js'\nimport { uid as uid_ } from '../../utils/uid.js'\nimport type { ClientConfig } from '../createClient.js'\n\nexport type TransportConfig<\n type extends string = string,\n eip1193RequestFn extends EIP1193RequestFn = EIP1193RequestFn,\n> = {\n /** The name of the transport. */\n name: string\n /** The key of the transport. */\n key: string\n /** Methods to include or exclude from executing RPC requests. */\n methods?:\n | OneOf<\n | {\n include?: string[] | undefined\n }\n | {\n exclude?: string[] | undefined\n }\n >\n | undefined\n /** The JSON-RPC request function that matches the EIP-1193 request spec. */\n request: eip1193RequestFn\n /** The base delay (in ms) between retries. */\n retryDelay?: number | undefined\n /** The max number of times to retry. */\n retryCount?: number | undefined\n /** The timeout (in ms) for requests. */\n timeout?: number | undefined\n /** The type of the transport. */\n type: type\n}\n\nexport type Transport<\n type extends string = string,\n rpcAttributes = Record<string, any>,\n eip1193RequestFn extends EIP1193RequestFn = EIP1193RequestFn,\n> = <chain extends Chain | undefined = Chain>({\n chain,\n}: {\n account?: Account | undefined\n chain?: chain | undefined\n pollingInterval?: ClientConfig['pollingInterval'] | undefined\n retryCount?: TransportConfig['retryCount'] | undefined\n timeout?: TransportConfig['timeout'] | undefined\n}) => {\n config: TransportConfig<type>\n request: eip1193RequestFn\n value?: rpcAttributes | undefined\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 type extends string,\n rpcAttributes extends Record<string, any>,\n>(\n {\n key,\n methods,\n name,\n request,\n retryCount = 3,\n retryDelay = 150,\n timeout,\n type,\n }: TransportConfig<type>,\n value?: rpcAttributes | undefined,\n): ReturnType<Transport<type, rpcAttributes>> {\n const uid = uid_()\n return {\n config: {\n key,\n methods,\n name,\n request,\n retryCount,\n retryDelay,\n timeout,\n type,\n },\n request: buildRequest(request, { methods, retryCount, retryDelay, uid }),\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 type { EIP1193RequestFn, RpcSchema } from '../../types/eip1193.js'\nimport type { RpcRequest } from '../../types/rpc.js'\nimport { createBatchScheduler } from '../../utils/promise/createBatchScheduler.js'\nimport {\n getHttpRpcClient,\n type HttpRpcClientOptions,\n} from '../../utils/rpc/http.js'\n\nimport {\n type CreateTransportErrorType,\n createTransport,\n type Transport,\n type TransportConfig,\n} from './createTransport.js'\n\nexport type HttpTransportConfig<\n rpcSchema extends RpcSchema | undefined = undefined,\n raw extends boolean = false,\n> = {\n /**\n * Whether to enable Batch JSON-RPC.\n * @link https://www.jsonrpc.org/specification#batch\n */\n batch?:\n | boolean\n | {\n /** The maximum number of JSON-RPC requests to send in a batch. @default 1_000 */\n batchSize?: number | undefined\n /** The maximum number of milliseconds to wait before sending a batch. @default 0 */\n wait?: number | undefined\n }\n | undefined\n fetchFn?: HttpRpcClientOptions['fetchFn'] | undefined\n /**\n * Request configuration to pass to `fetch`.\n * @link https://developer.mozilla.org/en-US/docs/Web/API/fetch\n */\n fetchOptions?: HttpRpcClientOptions['fetchOptions'] | undefined\n /** A callback to handle the response from `fetch`. */\n onFetchRequest?: HttpRpcClientOptions['onRequest'] | undefined\n /** A callback to handle the response from `fetch`. */\n onFetchResponse?: HttpRpcClientOptions['onResponse'] | undefined\n /** The key of the HTTP transport. */\n key?: TransportConfig['key'] | undefined\n /** Methods to include or exclude from executing RPC requests. */\n methods?: TransportConfig['methods'] | undefined\n /** The name of the HTTP transport. */\n name?: TransportConfig['name'] | undefined\n /** Whether to return JSON RPC errors as responses instead of throwing. */\n raw?: raw | boolean | undefined\n /** The max number of times to retry. */\n retryCount?: TransportConfig['retryCount'] | undefined\n /** The base delay (in ms) between retries. */\n retryDelay?: TransportConfig['retryDelay'] | undefined\n /** Typed JSON-RPC schema for the transport. */\n rpcSchema?: rpcSchema | RpcSchema | undefined\n /** The timeout (in ms) for the HTTP request. Default: 10_000 */\n timeout?: TransportConfig['timeout'] | undefined\n}\n\nexport type HttpTransport<\n rpcSchema extends RpcSchema | undefined = undefined,\n raw extends boolean = false,\n> = Transport<\n 'http',\n {\n fetchOptions?: HttpTransportConfig['fetchOptions'] | undefined\n url?: string | undefined\n },\n EIP1193RequestFn<rpcSchema, raw>\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 rpcSchema extends RpcSchema | undefined = undefined,\n raw extends boolean = false,\n>(\n /** URL of the JSON-RPC API. Defaults to the chain's public RPC URL. */\n url?: string | undefined,\n config: HttpTransportConfig<rpcSchema, raw> = {},\n): HttpTransport<rpcSchema, raw> {\n const {\n batch,\n fetchFn,\n fetchOptions,\n key = 'http',\n methods,\n name = 'HTTP JSON-RPC',\n onFetchRequest,\n onFetchResponse,\n retryDelay,\n raw,\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\n const rpcClient = getHttpRpcClient(url_, {\n fetchFn,\n fetchOptions,\n onRequest: onFetchRequest,\n onResponse: onFetchResponse,\n timeout,\n })\n\n return createTransport(\n {\n key,\n methods,\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 rpcClient.request({\n body,\n }),\n sort: (a, b) => a.id - b.id,\n })\n\n const fn = async (body: RpcRequest) =>\n batch\n ? schedule(body)\n : [\n await rpcClient.request({\n body,\n }),\n ]\n\n const [{ error, result }] = await fn(body)\n\n if (raw) return { error, result }\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: 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 name: 'UrlRequiredError',\n },\n )\n }\n}\n","// biome-ignore lint/performance/noBarrelFile: entrypoint module\nexport {\n type Abi,\n type AbiEvent,\n type AbiFunction,\n type AbiParameter,\n type AbiParameterKind,\n type AbiParameterToPrimitiveType,\n type AbiStateMutability,\n type Address,\n CircularReferenceError,\n InvalidAbiItemError,\n InvalidAbiParameterError,\n InvalidAbiParametersError,\n InvalidAbiTypeParameterError,\n InvalidFunctionModifierError,\n InvalidModifierError,\n InvalidParameterError,\n InvalidParenthesisError,\n InvalidSignatureError,\n InvalidStructSignatureError,\n type Narrow,\n type ParseAbi,\n type ParseAbiItem,\n type ParseAbiParameter,\n type ParseAbiParameters,\n parseAbi,\n parseAbiItem,\n parseAbiParameter,\n parseAbiParameters,\n SolidityProtectedKeywordError,\n type TypedData,\n type TypedDataDomain,\n type TypedDataParameter,\n UnknownSignatureError,\n UnknownTypeError,\n} from 'abitype'\nexport type {\n BlockOverrides,\n Rpc as RpcBlockOverrides,\n} from 'ox/BlockOverrides'\nexport type { EntryPointVersion } from './account-abstraction/types/entryPointVersion.js'\nexport type {\n RpcEstimateUserOperationGasReturnType,\n RpcGetUserOperationByHashReturnType,\n RpcUserOperation,\n RpcUserOperationReceipt,\n RpcUserOperationRequest,\n} from './account-abstraction/types/rpc.js'\nexport type {\n EstimateUserOperationGasReturnType,\n GetUserOperationByHashReturnType,\n PackedUserOperation,\n UserOperation,\n UserOperationReceipt,\n UserOperationRequest,\n} from './account-abstraction/types/userOperation.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 {\n GetEnsAddressErrorType,\n GetEnsAddressParameters,\n GetEnsAddressReturnType,\n} from './actions/ens/getEnsAddress.js'\nexport type {\n GetEnsAvatarErrorType,\n GetEnsAvatarParameters,\n GetEnsAvatarReturnType,\n} from './actions/ens/getEnsAvatar.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 GetEnsTextErrorType,\n GetEnsTextParameters,\n GetEnsTextReturnType,\n} from './actions/ens/getEnsText.js'\nexport {\n type GetContractErrorType,\n type GetContractParameters,\n type GetContractReturnType,\n getContract,\n} from './actions/getContract.js'\nexport type {\n CallErrorType,\n CallParameters,\n CallReturnType,\n} from './actions/public/call.js'\nexport type {\n CreateAccessListErrorType,\n CreateAccessListParameters,\n CreateAccessListReturnType,\n} from './actions/public/createAccessList.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 EstimateContractGasErrorType,\n EstimateContractGasParameters,\n EstimateContractGasReturnType,\n} from './actions/public/estimateContractGas.js'\nexport type {\n EstimateFeesPerGasErrorType,\n EstimateFeesPerGasParameters,\n EstimateFeesPerGasReturnType,\n} from './actions/public/estimateFeesPerGas.js'\nexport type {\n EstimateGasErrorType,\n EstimateGasParameters,\n EstimateGasReturnType,\n} from './actions/public/estimateGas.js'\nexport type {\n EstimateMaxPriorityFeePerGasErrorType,\n EstimateMaxPriorityFeePerGasParameters,\n EstimateMaxPriorityFeePerGasReturnType,\n} from './actions/public/estimateMaxPriorityFeePerGas.js'\nexport type {\n FillTransactionErrorType,\n FillTransactionParameters,\n FillTransactionReturnType,\n} from './actions/public/fillTransaction.js'\nexport type {\n GetBalanceErrorType,\n GetBalanceParameters,\n GetBalanceReturnType,\n} from './actions/public/getBalance.js'\nexport type {\n GetBlobBaseFeeErrorType,\n GetBlobBaseFeeReturnType,\n} from './actions/public/getBlobBaseFee.js'\nexport type {\n GetBlockErrorType,\n GetBlockParameters,\n GetBlockReturnType,\n} from './actions/public/getBlock.js'\nexport type {\n GetBlockNumberErrorType,\n GetBlockNumberParameters,\n GetBlockNumberReturnType,\n} from './actions/public/getBlockNumber.js'\nexport type {\n GetBlockTransactionCountErrorType,\n GetBlockTransactionCountParameters,\n GetBlockTransactionCountReturnType,\n} from './actions/public/getBlockTransactionCount.js'\nexport type {\n GetChainIdErrorType,\n GetChainIdReturnType,\n} from './actions/public/getChainId.js'\nexport type {\n /** @deprecated Use `GetCodeErrorType` instead */\n GetCodeErrorType as GetBytecodeErrorType,\n GetCodeErrorType,\n /** @deprecated Use `GetCodeParameters` instead */\n GetCodeParameters as GetBytecodeParameters,\n GetCodeParameters,\n /** @deprecated Use `GetCodeReturnType` instead */\n GetCodeReturnType as GetBytecodeReturnType,\n GetCodeReturnType,\n} from './actions/public/getCode.js'\nexport type {\n GetContractEventsErrorType,\n GetContractEventsParameters,\n GetContractEventsReturnType,\n} from './actions/public/getContractEvents.js'\nexport type {\n GetEip712DomainErrorType,\n GetEip712DomainParameters,\n GetEip712DomainReturnType,\n} from './actions/public/getEip712Domain.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 GetProofErrorType,\n GetProofParameters,\n GetProofReturnType,\n} from './actions/public/getProof.js'\nexport type {\n GetStorageAtErrorType,\n GetStorageAtParameters,\n GetStorageAtReturnType,\n} from './actions/public/getStorageAt.js'\nexport type {\n GetTransactionErrorType,\n GetTransactionParameters,\n GetTransactionReturnType,\n} from './actions/public/getTransaction.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 GetTransactionReceiptErrorType,\n GetTransactionReceiptParameters,\n GetTransactionReceiptReturnType,\n} from './actions/public/getTransactionReceipt.js'\nexport type {\n MulticallErrorType,\n MulticallParameters,\n MulticallReturnType,\n} from './actions/public/multicall.js'\nexport type {\n ReadContractErrorType,\n ReadContractParameters,\n ReadContractReturnType,\n} from './actions/public/readContract.js'\nexport type {\n SimulateBlocksErrorType,\n SimulateBlocksParameters,\n SimulateBlocksReturnType,\n} from './actions/public/simulateBlocks.js'\nexport type {\n SimulateCallsErrorType,\n SimulateCallsParameters,\n SimulateCallsReturnType,\n} from './actions/public/simulateCalls.js'\nexport type {\n GetMutabilityAwareValue,\n SimulateContractErrorType,\n SimulateContractParameters,\n SimulateContractReturnType,\n} from './actions/public/simulateContract.js'\nexport type {\n UninstallFilterErrorType,\n UninstallFilterParameters,\n UninstallFilterReturnType,\n} from './actions/public/uninstallFilter.js'\nexport type {\n VerifyHashErrorType as VerifyHashActionErrorType,\n VerifyHashParameters as VerifyHashActionParameters,\n VerifyHashReturnType as VerifyHashActionReturnType,\n} from './actions/public/verifyHash.js'\nexport type {\n VerifyMessageErrorType as VerifyMessageActionErrorType,\n VerifyMessageParameters as VerifyMessageActionParameters,\n VerifyMessageReturnType as VerifyMessageActionReturnType,\n} from './actions/public/verifyMessage.js'\nexport type {\n VerifyTypedDataErrorType as VerifyTypedDataActionErrorType,\n VerifyTypedDataParameters as VerifyTypedDataActionParameters,\n VerifyTypedDataReturnType as VerifyTypedDataActionReturnType,\n} from './actions/public/verifyTypedData.js'\nexport type {\n ReplacementReason,\n ReplacementReturnType,\n WaitForTransactionReceiptErrorType,\n WaitForTransactionReceiptParameters,\n WaitForTransactionReceiptReturnType,\n} from './actions/public/waitForTransactionReceipt.js'\nexport type {\n OnBlockNumberFn,\n OnBlockNumberParameter,\n WatchBlockNumberErrorType,\n WatchBlockNumberParameters,\n WatchBlockNumberReturnType,\n} from './actions/public/watchBlockNumber.js'\nexport type {\n OnBlock,\n OnBlockParameter,\n WatchBlocksErrorType,\n WatchBlocksParameters,\n WatchBlocksReturnType,\n} from './actions/public/watchBlocks.js'\nexport type {\n WatchContractEventErrorType,\n WatchContractEventOnLogsFn,\n WatchContractEventOnLogsParameter,\n WatchContractEventParameters,\n WatchContractEventReturnType,\n} from './actions/public/watchContractEvent.js'\nexport type {\n WatchEventErrorType,\n WatchEventOnLogsFn,\n WatchEventOnLogsParameter,\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 DropTransactionErrorType,\n DropTransactionParameters,\n} from './actions/test/dropTransaction.js'\nexport type {\n DumpStateErrorType,\n DumpStateReturnType,\n} from './actions/test/dumpState.js'\nexport type {\n GetAutomineErrorType,\n GetAutomineReturnType,\n} from './actions/test/getAutomine.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 ImpersonateAccountErrorType,\n ImpersonateAccountParameters,\n} from './actions/test/impersonateAccount.js'\nexport type {\n IncreaseTimeErrorType,\n IncreaseTimeParameters,\n} from './actions/test/increaseTime.js'\nexport type {\n InspectTxpoolErrorType,\n InspectTxpoolReturnType,\n} from './actions/test/inspectTxpool.js'\nexport type {\n LoadStateErrorType,\n LoadStateParameters,\n LoadStateReturnType,\n} from './actions/test/loadState.js'\nexport type { MineErrorType, MineParameters } from './actions/test/mine.js'\nexport type { RemoveBlockTimestampIntervalErrorType } from './actions/test/removeBlockTimestampInterval.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 SendUnsignedTransactionErrorType,\n SendUnsignedTransactionParameters,\n SendUnsignedTransactionReturnType,\n} from './actions/test/sendUnsignedTransaction.js'\nexport type { SetAutomineErrorType } from './actions/test/setAutomine.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 { SetLoggingEnabledErrorType } from './actions/test/setLoggingEnabled.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 { SetRpcUrlErrorType } from './actions/test/setRpcUrl.js'\nexport type {\n SetStorageAtErrorType,\n SetStorageAtParameters,\n} from './actions/test/setStorageAt.js'\nexport type { SnapshotErrorType } from './actions/test/snapshot.js'\nexport type {\n StopImpersonatingAccountErrorType,\n StopImpersonatingAccountParameters,\n} from './actions/test/stopImpersonatingAccount.js'\nexport type {\n AddChainErrorType,\n AddChainParameters,\n} from './actions/wallet/addChain.js'\nexport type {\n DeployContractErrorType,\n DeployContractParameters,\n DeployContractReturnType,\n} from './actions/wallet/deployContract.js'\nexport type {\n GetAddressesErrorType,\n GetAddressesReturnType,\n} from './actions/wallet/getAddresses.js'\nexport type {\n GetCallsStatusErrorType,\n GetCallsStatusParameters,\n GetCallsStatusReturnType,\n} from './actions/wallet/getCallsStatus.js'\nexport type {\n GetCapabilitiesErrorType,\n GetCapabilitiesParameters,\n GetCapabilitiesReturnType,\n} from './actions/wallet/getCapabilities.js'\nexport type {\n GetPermissionsErrorType,\n GetPermissionsReturnType,\n} from './actions/wallet/getPermissions.js'\nexport type {\n PrepareAuthorizationErrorType,\n PrepareAuthorizationParameters,\n PrepareAuthorizationReturnType,\n} from './actions/wallet/prepareAuthorization.js'\nexport type {\n PrepareTransactionRequestErrorType,\n PrepareTransactionRequestParameters,\n PrepareTransactionRequestParameterType,\n PrepareTransactionRequestRequest,\n PrepareTransactionRequestReturnType,\n} from './actions/wallet/prepareTransactionRequest.js'\nexport type {\n RequestAddressesErrorType,\n RequestAddressesReturnType,\n} from './actions/wallet/requestAddresses.js'\nexport type {\n RequestPermissionsErrorType,\n RequestPermissionsParameters,\n RequestPermissionsReturnType,\n} from './actions/wallet/requestPermissions.js'\nexport type {\n SendCallsErrorType,\n SendCallsParameters,\n SendCallsReturnType,\n} from './actions/wallet/sendCalls.js'\nexport type {\n SendCallsSyncErrorType,\n SendCallsSyncParameters,\n SendCallsSyncReturnType,\n} from './actions/wallet/sendCallsSync.js'\nexport type {\n SendRawTransactionErrorType,\n SendRawTransactionParameters,\n SendRawTransactionReturnType,\n} from './actions/wallet/sendRawTransaction.js'\nexport type {\n SendRawTransactionSyncErrorType,\n SendRawTransactionSyncParameters,\n SendRawTransactionSyncReturnType,\n} from './actions/wallet/sendRawTransactionSync.js'\nexport type {\n SendTransactionErrorType,\n SendTransactionParameters,\n SendTransactionRequest,\n SendTransactionReturnType,\n} from './actions/wallet/sendTransaction.js'\nexport type {\n SendTransactionSyncErrorType,\n SendTransactionSyncParameters,\n SendTransactionSyncRequest,\n SendTransactionSyncReturnType,\n} from './actions/wallet/sendTransactionSync.js'\nexport type {\n ShowCallsStatusErrorType,\n ShowCallsStatusParameters,\n ShowCallsStatusReturnType,\n} from './actions/wallet/showCallsStatus.js'\nexport type {\n SignAuthorizationErrorType,\n SignAuthorizationParameters,\n SignAuthorizationReturnType,\n} from './actions/wallet/signAuthorization.js'\nexport type {\n SignMessageErrorType,\n SignMessageParameters,\n SignMessageReturnType,\n} from './actions/wallet/signMessage.js'\nexport type {\n SignTransactionErrorType,\n SignTransactionParameters,\n SignTransactionRequest,\n SignTransactionReturnType,\n} from './actions/wallet/signTransaction.js'\nexport type {\n SignTypedDataErrorType,\n SignTypedDataParameters,\n SignTypedDataReturnType,\n} from './actions/wallet/signTypedData.js'\nexport type {\n SwitchChainErrorType,\n SwitchChainParameters,\n} from './actions/wallet/switchChain.js'\nexport type {\n WaitForCallsStatusErrorType,\n WaitForCallsStatusParameters,\n WaitForCallsStatusReturnType,\n WaitForCallsStatusTimeoutErrorType,\n} from './actions/wallet/waitForCallsStatus.js'\nexport { WaitForCallsStatusTimeoutError } from './actions/wallet/waitForCallsStatus.js'\nexport type {\n WatchAssetErrorType,\n WatchAssetParameters,\n WatchAssetReturnType,\n} from './actions/wallet/watchAsset.js'\nexport type {\n WriteContractErrorType,\n WriteContractParameters,\n WriteContractReturnType,\n} from './actions/wallet/writeContract.js'\nexport type {\n WriteContractSyncErrorType,\n WriteContractSyncParameters,\n WriteContractSyncReturnType,\n} from './actions/wallet/writeContractSync.js'\nexport {\n type Client,\n type ClientConfig,\n type CreateClientErrorType,\n createClient,\n type MulticallBatchOptions,\n rpcSchema,\n} from './clients/createClient.js'\nexport {\n type CreatePublicClientErrorType,\n createPublicClient,\n type PublicClient,\n type PublicClientConfig,\n} from './clients/createPublicClient.js'\nexport {\n type CreateTestClientErrorType,\n createTestClient,\n type TestClient,\n type TestClientConfig,\n} from './clients/createTestClient.js'\nexport {\n type CreateWalletClientErrorType,\n createWalletClient,\n type WalletClient,\n type WalletClientConfig,\n} from './clients/createWalletClient.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 CreateTransportErrorType,\n createTransport,\n type Transport,\n type TransportConfig,\n} from './clients/transports/createTransport.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 shouldThrow,\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 WebSocketTransport,\n type WebSocketTransportConfig,\n type WebSocketTransportErrorType,\n webSocket,\n} from './clients/transports/webSocket.js'\nexport {\n erc20Abi,\n erc20Abi_bytes32,\n erc721Abi,\n erc1155Abi,\n erc4626Abi,\n erc6492SignatureValidatorAbi,\n /** @deprecated use `erc6492SignatureValidatorAbi` instead. */\n erc6492SignatureValidatorAbi as universalSignatureValidatorAbi,\n multicall3Abi,\n} from './constants/abis.js'\nexport { ethAddress, zeroAddress } from './constants/address.js'\nexport { zeroHash } from './constants/bytes.js'\nexport {\n deploylessCallViaBytecodeBytecode,\n deploylessCallViaFactoryBytecode,\n erc6492SignatureValidatorByteCode,\n /** @deprecated use `erc6492SignatureValidatorByteCode` instead. */\n erc6492SignatureValidatorByteCode as universalSignatureValidatorByteCode,\n} from './constants/contracts.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 { presignMessagePrefix } from './constants/strings.js'\nexport { etherUnits, gweiUnits, weiUnits } from './constants/unit.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 AbiEncodingBytesSizeMismatchError,\n type AbiEncodingBytesSizeMismatchErrorType,\n AbiEncodingLengthMismatchError,\n type AbiEncodingLengthMismatchErrorType,\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 {\n InvalidAddressError,\n type InvalidAddressErrorType,\n} from './errors/address.js'\nexport { BaseError, type BaseErrorType, setErrorConfig } from './errors/base.js'\nexport {\n BlockNotFoundError,\n type BlockNotFoundErrorType,\n} from './errors/block.js'\nexport {\n BundleFailedError,\n type BundleFailedErrorType,\n} from './errors/calls.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 CallExecutionError,\n type CallExecutionErrorType,\n ContractFunctionExecutionError,\n type ContractFunctionExecutionErrorType,\n ContractFunctionRevertedError,\n type ContractFunctionRevertedErrorType,\n ContractFunctionZeroDataError,\n type ContractFunctionZeroDataErrorType,\n CounterfactualDeploymentFailedError,\n type CounterfactualDeploymentFailedErrorType,\n RawContractError,\n type RawContractErrorType,\n} from './errors/contract.js'\nexport {\n SizeExceedsPaddingSizeError,\n type SizeExceedsPaddingSizeErrorType,\n SliceOffsetOutOfBoundsError,\n type SliceOffsetOutOfBoundsErrorType,\n} from './errors/data.js'\nexport {\n IntegerOutOfRangeError,\n type IntegerOutOfRangeErrorType,\n InvalidBytesBooleanError,\n type InvalidBytesBooleanErrorType,\n InvalidHexBooleanError,\n type InvalidHexBooleanErrorType,\n InvalidHexValueError,\n type InvalidHexValueErrorType,\n SizeOverflowError,\n type SizeOverflowErrorType,\n} from './errors/encoding.js'\nexport {\n type EnsAvatarInvalidMetadataError,\n type EnsAvatarInvalidMetadataErrorType,\n EnsAvatarInvalidNftUriError,\n type EnsAvatarInvalidNftUriErrorType,\n EnsAvatarUnsupportedNamespaceError,\n type EnsAvatarUnsupportedNamespaceErrorType,\n EnsAvatarUriResolutionError,\n type EnsAvatarUriResolutionErrorType,\n EnsInvalidChainIdError,\n type EnsInvalidChainIdErrorType,\n} from './errors/ens.js'\nexport {\n EstimateGasExecutionError,\n type EstimateGasExecutionErrorType,\n} from './errors/estimateGas.js'\nexport {\n BaseFeeScalarError,\n type BaseFeeScalarErrorType,\n Eip1559FeesNotSupportedError,\n type Eip1559FeesNotSupportedErrorType,\n MaxFeePerGasTooLowError,\n type MaxFeePerGasTooLowErrorType,\n} from './errors/fee.js'\nexport {\n FilterTypeNotSupportedError,\n type FilterTypeNotSupportedErrorType,\n} from './errors/log.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 HttpRequestError,\n type HttpRequestErrorType,\n RpcRequestError,\n type RpcRequestErrorType,\n SocketClosedError,\n type SocketClosedErrorType,\n TimeoutError,\n type TimeoutErrorType,\n WebSocketRequestError,\n type WebSocketRequestErrorType,\n} from './errors/request.js'\nexport {\n AtomicityNotSupportedError,\n type AtomicityNotSupportedErrorType,\n AtomicReadyWalletRejectedUpgradeError,\n type AtomicReadyWalletRejectedUpgradeErrorType,\n BundleTooLargeError,\n type BundleTooLargeErrorType,\n ChainDisconnectedError,\n type ChainDisconnectedErrorType,\n DuplicateIdError,\n type DuplicateIdErrorType,\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 RpcErrorCode,\n type RpcErrorType,\n SwitchChainError,\n TransactionRejectedRpcError,\n type TransactionRejectedRpcErrorType,\n UnauthorizedProviderError,\n type UnauthorizedProviderErrorType,\n UnknownBundleIdError,\n type UnknownBundleIdErrorType,\n UnknownRpcError,\n type UnknownRpcErrorType,\n UnsupportedChainIdError,\n type UnsupportedChainIdErrorType,\n UnsupportedNonOptionalCapabilityError,\n type UnsupportedNonOptionalCapabilityErrorType,\n UnsupportedProviderMethodError,\n type UnsupportedProviderMethodErrorType,\n UserRejectedRequestError,\n type UserRejectedRequestErrorType,\n} from './errors/rpc.js'\nexport {\n AccountStateConflictError,\n type AccountStateConflictErrorType,\n StateAssignmentConflictError,\n type StateAssignmentConflictErrorType,\n} from './errors/stateOverride.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 UrlRequiredError,\n type UrlRequiredErrorType,\n} from './errors/transport.js'\nexport {\n InvalidDomainError,\n type InvalidDomainErrorType,\n InvalidPrimaryTypeError,\n type InvalidPrimaryTypeErrorType,\n InvalidStructTypeError,\n type InvalidStructTypeErrorType,\n} from './errors/typedData.js'\nexport {\n InvalidDecimalNumberError,\n type InvalidDecimalNumberErrorType,\n} from './errors/unit.js'\nexport type {\n DeriveAccount,\n HDKey,\n ParseAccount,\n} from './types/account.js'\nexport type {\n Authorization,\n AuthorizationList,\n AuthorizationRequest,\n SerializedAuthorization,\n SerializedAuthorizationList,\n SignedAuthorization,\n SignedAuthorizationList,\n} from './types/authorization.js'\nexport type {\n Block,\n BlockIdentifier,\n BlockNumber,\n BlockTag,\n Uncle,\n} from './types/block.js'\nexport type { Call, Calls } from './types/calls.js'\nexport type {\n Capabilities,\n /** @deprecated Use `Capabilities` instead. */\n Capabilities as WalletCapabilities,\n CapabilitiesSchema,\n /** @deprecated Use `ChainIdToCapabilities` instead. */\n ChainIdToCapabilities as WalletCapabilitiesRecord,\n ChainIdToCapabilities,\n ExtractCapabilities,\n} from './types/capabilities.js'\nexport type {\n Chain,\n ChainConfig,\n ChainContract,\n ChainEstimateFeesPerGasFn,\n ChainEstimateFeesPerGasFnParameters,\n ChainFees,\n ChainFeesFnParameters,\n ChainFormatter,\n ChainFormatters,\n ChainMaxPriorityFeePerGasFn,\n ChainSerializers,\n DeriveChain,\n ExtractChainFormatterExclude,\n ExtractChainFormatterParameters,\n ExtractChainFormatterReturnType,\n GetChainParameter,\n} from './types/chain.js'\nexport type {\n AbiEventParametersToPrimitiveTypes,\n AbiEventParameterToPrimitiveType,\n AbiEventTopicToPrimitiveType,\n AbiItem,\n AbiItemArgs,\n AbiItemName,\n ContractConstructorArgs,\n ContractErrorArgs,\n ContractErrorName,\n ContractEventArgs,\n ContractEventArgsFromTopics,\n ContractEventName,\n ContractFunctionArgs,\n ContractFunctionName,\n ContractFunctionParameters,\n ContractFunctionReturnType,\n EventDefinition,\n ExtractAbiFunctionForArgs,\n ExtractAbiItem,\n ExtractAbiItemForArgs,\n ExtractAbiItemNames,\n GetEventArgs,\n GetValue,\n LogTopicType,\n MaybeAbiEventName,\n MaybeExtractEventArgsFromAbi,\n UnionWiden,\n Widen,\n} from './types/contract.js'\nexport type { DataSuffix } from './types/dataSuffix.js'\nexport type {\n AddEthereumChainParameter,\n BundlerRpcSchema,\n DebugBundlerRpcSchema,\n EIP1193EventMap,\n EIP1193Events,\n EIP1193Parameters,\n EIP1193Provider,\n EIP1193RequestFn,\n EIP1474Methods,\n NetworkSync,\n PaymasterRpcSchema,\n ProviderConnectInfo,\n ProviderMessage,\n ProviderRpcErrorType as EIP1193ProviderRpcErrorType,\n PublicRpcSchema,\n RpcSchema,\n RpcSchemaOverride,\n TestRpcSchema,\n WalletCallReceipt,\n WalletGetAssetsParameters,\n WalletGetAssetsReturnType,\n WalletGetCallsStatusReturnType,\n WalletGrantPermissionsParameters,\n WalletGrantPermissionsReturnType,\n WalletPermission,\n WalletPermissionCaveat,\n WalletRpcSchema,\n WalletSendCallsParameters,\n WalletSendCallsReturnType,\n WatchAssetParams,\n} from './types/eip1193.js'\nexport { ProviderRpcError as EIP1193ProviderRpcError } from './types/eip1193.js'\nexport type { BlobSidecar, BlobSidecars } from './types/eip4844.js'\nexport type { AssetGateway, AssetGatewayUrls } from './types/ens.js'\nexport type {\n FeeHistory,\n FeeValues,\n FeeValuesEIP1559,\n FeeValuesEIP4844,\n FeeValuesLegacy,\n FeeValuesType,\n} from './types/fee.js'\nexport type { Filter, FilterType } from './types/filter.js'\nexport type { GetTransactionRequestKzgParameter, Kzg } from './types/kzg.js'\nexport type { Log } from './types/log.js'\nexport type {\n ByteArray,\n CompactSignature,\n Hash,\n Hex,\n LogTopic,\n SignableMessage,\n Signature,\n} from './types/misc.js'\nexport type {\n MulticallContracts,\n MulticallResponse,\n MulticallResults,\n} from './types/multicall.js'\nexport type { Register, ResolvedRegister } from './types/register.js'\nexport type {\n Index,\n Quantity,\n RpcAccountStateOverride,\n RpcAuthorization,\n RpcAuthorizationList,\n RpcBlock,\n RpcBlockIdentifier,\n RpcBlockNumber,\n RpcFeeHistory,\n RpcFeeValues,\n RpcLog,\n RpcProof,\n RpcStateMapping,\n RpcStateOverride,\n RpcTransaction,\n RpcTransactionReceipt,\n RpcTransactionRequest,\n RpcUncle,\n Status,\n} from './types/rpc.js'\nexport type {\n StateMapping,\n StateOverride,\n} from './types/stateOverride.js'\nexport type {\n AccessList,\n Transaction,\n TransactionBase,\n TransactionEIP1559,\n TransactionEIP2930,\n TransactionEIP4844,\n TransactionEIP7702,\n TransactionLegacy,\n TransactionReceipt,\n TransactionRequest,\n TransactionRequestBase,\n TransactionRequestEIP1559,\n TransactionRequestEIP2930,\n TransactionRequestEIP4844,\n TransactionRequestEIP7702,\n TransactionRequestGeneric,\n TransactionRequestLegacy,\n TransactionSerializable,\n TransactionSerializableBase,\n TransactionSerializableEIP1559,\n TransactionSerializableEIP2930,\n TransactionSerializableEIP4844,\n TransactionSerializableEIP7702,\n TransactionSerializableGeneric,\n TransactionSerializableLegacy,\n TransactionSerialized,\n TransactionSerializedEIP1559,\n TransactionSerializedEIP2930,\n TransactionSerializedEIP4844,\n TransactionSerializedEIP7702,\n TransactionSerializedGeneric,\n TransactionSerializedLegacy,\n TransactionType,\n} from './types/transaction.js'\nexport type { GetPollOptions, GetTransportConfig } from './types/transport.js'\nexport type {\n EIP712DomainDefinition,\n MessageDefinition,\n TypedDataDefinition,\n} from './types/typedData.js'\nexport type {\n Assign,\n Branded,\n Evaluate,\n ExactPartial,\n ExactRequired,\n IsNarrowable,\n IsNever,\n IsUndefined,\n IsUnion,\n LooseOmit,\n MaybePartial,\n MaybePromise,\n MaybeRequired,\n Mutable,\n NoInfer,\n NoUndefined,\n Omit,\n OneOf,\n Or,\n PartialBy,\n Prettify,\n RequiredBy,\n Some,\n UnionEvaluate,\n UnionLooseOmit,\n UnionOmit,\n UnionPartialBy,\n UnionPick,\n UnionRequiredBy,\n UnionToTuple,\n ValueOf,\n} from './types/utils.js'\nexport type { Withdrawal } from './types/withdrawal.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 type DecodeFunctionDataReturnType,\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 type EncodeDeployDataReturnType,\n encodeDeployData,\n} from './utils/abi/encodeDeployData.js'\nexport {\n type EncodeErrorResultErrorType,\n type EncodeErrorResultParameters,\n type EncodeErrorResultReturnType,\n encodeErrorResult,\n} from './utils/abi/encodeErrorResult.js'\nexport {\n type EncodeEventTopicsErrorType,\n type EncodeEventTopicsParameters,\n type EncodeEventTopicsReturnType,\n encodeEventTopics,\n} from './utils/abi/encodeEventTopics.js'\nexport {\n type EncodeFunctionDataErrorType,\n type EncodeFunctionDataParameters,\n type EncodeFunctionDataReturnType,\n encodeFunctionData,\n} from './utils/abi/encodeFunctionData.js'\nexport {\n type EncodeFunctionResultErrorType,\n type EncodeFunctionResultParameters,\n type EncodeFunctionResultReturnType,\n encodeFunctionResult,\n} from './utils/abi/encodeFunctionResult.js'\nexport {\n type EncodePackedErrorType,\n encodePacked,\n} from './utils/abi/encodePacked.js'\nexport {\n type GetAbiItemErrorType,\n type GetAbiItemParameters,\n type GetAbiItemReturnType,\n getAbiItem,\n} from './utils/abi/getAbiItem.js'\nexport {\n type ParseEventLogsErrorType,\n type ParseEventLogsParameters,\n type ParseEventLogsReturnType,\n parseEventLogs,\n} from './utils/abi/parseEventLogs.js'\nexport {\n type PrepareEncodeFunctionDataErrorType,\n type PrepareEncodeFunctionDataParameters,\n type PrepareEncodeFunctionDataReturnType,\n prepareEncodeFunctionData,\n} from './utils/abi/prepareEncodeFunctionData.js'\nexport {\n type ChecksumAddressErrorType,\n checksumAddress,\n type GetAddressErrorType,\n getAddress,\n} from './utils/address/getAddress.js'\nexport {\n type GetContractAddressOptions,\n type GetCreate2AddressErrorType,\n type GetCreate2AddressOptions,\n type GetCreateAddressErrorType,\n type GetCreateAddressOptions,\n getContractAddress,\n getCreate2Address,\n getCreateAddress,\n} from './utils/address/getContractAddress.js'\nexport {\n type IsAddressErrorType,\n type IsAddressOptions,\n isAddress,\n} from './utils/address/isAddress.js'\nexport {\n type IsAddressEqualErrorType,\n type IsAddressEqualReturnType,\n isAddressEqual,\n} from './utils/address/isAddressEqual.js'\nexport {\n type BlobsToCommitmentsErrorType,\n type BlobsToCommitmentsParameters,\n type BlobsToCommitmentsReturnType,\n blobsToCommitments,\n} from './utils/blob/blobsToCommitments.js'\nexport {\n blobsToProofs,\n type blobsToProofsErrorType,\n type blobsToProofsParameters,\n type blobsToProofsReturnType,\n} from './utils/blob/blobsToProofs.js'\nexport {\n type CommitmentsToVersionedHashesErrorType,\n type CommitmentsToVersionedHashesParameters,\n type CommitmentsToVersionedHashesReturnType,\n commitmentsToVersionedHashes,\n} from './utils/blob/commitmentsToVersionedHashes.js'\nexport {\n type CommitmentToVersionedHashErrorType,\n type CommitmentToVersionedHashParameters,\n type CommitmentToVersionedHashReturnType,\n commitmentToVersionedHash,\n} from './utils/blob/commitmentToVersionedHash.js'\nexport {\n type FromBlobsErrorType,\n type FromBlobsParameters,\n type FromBlobsReturnType,\n fromBlobs,\n} from './utils/blob/fromBlobs.js'\nexport {\n type SidecarsToVersionedHashesErrorType,\n type SidecarsToVersionedHashesParameters,\n type SidecarsToVersionedHashesReturnType,\n sidecarsToVersionedHashes,\n} from './utils/blob/sidecarsToVersionedHashes.js'\nexport {\n type ToBlobSidecarsErrorType,\n type ToBlobSidecarsParameters,\n type ToBlobSidecarsReturnType,\n toBlobSidecars,\n} from './utils/blob/toBlobSidecars.js'\nexport {\n type ToBlobsErrorType,\n type ToBlobsParameters,\n type ToBlobsReturnType,\n toBlobs,\n} from './utils/blob/toBlobs.js'\nexport {\n type CcipRequestErrorType,\n type CcipRequestParameters,\n ccipRequest,\n /** @deprecated Use `ccipRequest`. */\n ccipRequest as ccipFetch,\n type OffchainLookupErrorType,\n offchainLookup,\n offchainLookupAbiItem,\n offchainLookupSignature,\n} from './utils/ccip.js'\nexport {\n type AssertCurrentChainErrorType,\n type AssertCurrentChainParameters,\n assertCurrentChain,\n} from './utils/chain/assertCurrentChain.js'\nexport {\n type DefineChainReturnType,\n defineChain,\n extendSchema,\n} 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 ConcatBytesErrorType,\n type ConcatErrorType,\n type ConcatHexErrorType,\n type ConcatReturnType,\n concat,\n concatBytes,\n concatHex,\n} from './utils/data/concat.js'\nexport { type IsBytesErrorType, isBytes } from './utils/data/isBytes.js'\nexport { type IsHexErrorType, isHex } from './utils/data/isHex.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 { 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 {\n type TrimErrorType,\n type TrimReturnType,\n trim,\n} from './utils/data/trim.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 bytesToBigInt,\n bytesToBool,\n bytesToNumber,\n bytesToString,\n type FromBytesErrorType,\n type FromBytesParameters,\n fromBytes,\n} from './utils/encoding/fromBytes.js'\nexport {\n type FromHexErrorType,\n fromHex,\n type HexToBigIntErrorType,\n type HexToBoolErrorType,\n type HexToNumberErrorType,\n type HexToStringErrorType,\n hexToBigInt,\n hexToBool,\n hexToNumber,\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 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 type BytesToHexErrorType,\n type BytesToHexOpts,\n boolToHex,\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 BytesToRlpErrorType,\n bytesToRlp,\n type HexToRlpErrorType,\n hexToRlp,\n type ToRlpErrorType,\n type ToRlpReturnType,\n toRlp,\n} from './utils/encoding/toRlp.js'\nexport { type LabelhashErrorType, labelhash } from './utils/ens/labelhash.js'\nexport { type NamehashErrorType, namehash } from './utils/ens/namehash.js'\nexport {\n type ToCoinTypeError,\n toCoinType,\n} from './utils/ens/toCoinType.js'\nexport {\n type GetContractErrorReturnType,\n getContractError,\n} from './utils/errors/getContractError.js'\nexport {\n type DefineBlockErrorType,\n defineBlock,\n type FormatBlockErrorType,\n type FormattedBlock,\n formatBlock,\n} from './utils/formatters/block.js'\nexport { type FormatLogErrorType, formatLog } from './utils/formatters/log.js'\nexport {\n type DefineTransactionErrorType,\n defineTransaction,\n type FormatTransactionErrorType,\n type FormattedTransaction,\n formatTransaction,\n transactionType,\n} from './utils/formatters/transaction.js'\nexport {\n type DefineTransactionReceiptErrorType,\n defineTransactionReceipt,\n type FormatTransactionReceiptErrorType,\n type FormattedTransactionReceipt,\n formatTransactionReceipt,\n} from './utils/formatters/transactionReceipt.js'\nexport {\n type DefineTransactionRequestErrorType,\n defineTransactionRequest,\n type FormatTransactionRequestErrorType,\n type FormattedTransactionRequest,\n formatTransactionRequest,\n rpcTransactionType,\n} from './utils/formatters/transactionRequest.js'\nexport { type IsHashErrorType, isHash } from './utils/hash/isHash.js'\nexport {\n type Keccak256ErrorType,\n type Keccak256Hash,\n keccak256,\n} from './utils/hash/keccak256.js'\nexport {\n type Ripemd160ErrorType,\n type Ripemd160Hash,\n ripemd160,\n} from './utils/hash/ripemd160.js'\nexport {\n type Sha256ErrorType,\n type Sha256Hash,\n sha256,\n} from './utils/hash/sha256.js'\nexport {\n type ToEventHashErrorType,\n toEventHash,\n} from './utils/hash/toEventHash.js'\nexport {\n type ToEventSelectorErrorType,\n /** @deprecated use `ToEventSelectorErrorType`. */\n type ToEventSelectorErrorType as GetEventSelectorErrorType,\n toEventSelector,\n /** @deprecated use `toEventSelector`. */\n toEventSelector as getEventSelector,\n} from './utils/hash/toEventSelector.js'\nexport {\n type ToEventSignatureErrorType,\n /** @deprecated use `ToEventSignatureErrorType`. */\n type ToEventSignatureErrorType as GetEventSignatureErrorType,\n toEventSignature,\n /** @deprecated use `toEventSignature`. */\n toEventSignature as getEventSignature,\n} from './utils/hash/toEventSignature.js'\nexport {\n type ToFunctionHashErrorType,\n toFunctionHash,\n} from './utils/hash/toFunctionHash.js'\nexport {\n type ToFunctionSelectorErrorType,\n /** @deprecated use `ToFunctionSelectorErrorType`. */\n type ToFunctionSelectorErrorType as GetFunctionSelectorErrorType,\n toFunctionSelector,\n /** @deprecated use `toFunctionSelector`. */\n toFunctionSelector as getFunctionSelector,\n} from './utils/hash/toFunctionSelector.js'\nexport {\n type ToFunctionSignatureErrorType,\n /** @deprecated use `ToFunctionSignatureErrorType`. */\n type ToFunctionSignatureErrorType as GetFunctionSignatureErrorType,\n toFunctionSignature,\n /** @deprecated use `toFunctionSignature`. */\n toFunctionSignature as getFunctionSignature,\n} from './utils/hash/toFunctionSignature.js'\nexport {\n type DefineKzgErrorType,\n type DefineKzgParameters,\n type DefineKzgReturnType,\n defineKzg,\n} from './utils/kzg/defineKzg.js'\nexport {\n type SetupKzgErrorType,\n type SetupKzgParameters,\n type SetupKzgReturnType,\n setupKzg,\n} from './utils/kzg/setupKzg.js'\nexport {\n type CreateNonceManagerParameters,\n createNonceManager,\n type NonceManager,\n type NonceManagerSource,\n nonceManager,\n} from './utils/nonceManager.js'\nexport { withCache } from './utils/promise/withCache.js'\nexport {\n type WithRetryErrorType,\n withRetry,\n} from './utils/promise/withRetry.js'\nexport {\n type WithTimeoutErrorType,\n withTimeout,\n} from './utils/promise/withTimeout.js'\nexport {\n type CompactSignatureToSignatureErrorType,\n compactSignatureToSignature,\n} from './utils/signature/compactSignatureToSignature.js'\nexport {\n type HashMessageErrorType,\n hashMessage,\n} from './utils/signature/hashMessage.js'\nexport {\n type HashDomainErrorType,\n type HashStructErrorType,\n type HashTypedDataErrorType,\n type HashTypedDataParameters,\n type HashTypedDataReturnType,\n hashDomain,\n hashStruct,\n hashTypedData,\n} from './utils/signature/hashTypedData.js'\nexport {\n type IsErc6492SignatureErrorType,\n type IsErc6492SignatureParameters,\n type IsErc6492SignatureReturnType,\n isErc6492Signature,\n} from './utils/signature/isErc6492Signature.js'\nexport {\n type IsErc8010SignatureErrorType,\n type IsErc8010SignatureParameters,\n type IsErc8010SignatureReturnType,\n isErc8010Signature,\n} from './utils/signature/isErc8010Signature.js'\nexport {\n /** @deprecated Use `ParseCompactSignatureErrorType`. */\n type ParseCompactSignatureErrorType as HexToCompactSignatureErrorType,\n type ParseCompactSignatureErrorType,\n /** @deprecated Use `parseCompactSignature`. */\n parseCompactSignature as hexToCompactSignature,\n parseCompactSignature,\n} from './utils/signature/parseCompactSignature.js'\nexport {\n type ParseErc6492SignatureErrorType,\n type ParseErc6492SignatureParameters,\n type ParseErc6492SignatureReturnType,\n parseErc6492Signature,\n} from './utils/signature/parseErc6492Signature.js'\nexport {\n type ParseErc8010SignatureErrorType,\n type ParseErc8010SignatureParameters,\n type ParseErc8010SignatureReturnType,\n parseErc8010Signature,\n} from './utils/signature/parseErc8010Signature.js'\nexport {\n /** @deprecated Use `ParseSignatureErrorType`. */\n type ParseSignatureErrorType as HexToSignatureErrorType,\n type ParseSignatureErrorType,\n /** @deprecated Use `parseSignature`. */\n parseSignature as hexToSignature,\n parseSignature,\n} from './utils/signature/parseSignature.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 RecoverTransactionAddressErrorType,\n type RecoverTransactionAddressParameters,\n type RecoverTransactionAddressReturnType,\n recoverTransactionAddress,\n} from './utils/signature/recoverTransactionAddress.js'\nexport {\n type RecoverTypedDataAddressErrorType,\n type RecoverTypedDataAddressParameters,\n type RecoverTypedDataAddressReturnType,\n recoverTypedDataAddress,\n} from './utils/signature/recoverTypedDataAddress.js'\nexport {\n /** @deprecated Use `SignatureToHexErrorType` instead. */\n type SerializeCompactSignatureErrorType as CompactSignatureToHexErrorType,\n type SerializeCompactSignatureErrorType,\n /** @deprecated Use `serializeCompactSignature` instead. */\n serializeCompactSignature as compactSignatureToHex,\n serializeCompactSignature,\n} from './utils/signature/serializeCompactSignature.js'\nexport {\n type SerializeErc6492SignatureErrorType,\n type SerializeErc6492SignatureParameters,\n type SerializeErc6492SignatureReturnType,\n serializeErc6492Signature,\n} from './utils/signature/serializeErc6492Signature.js'\nexport {\n type SerializeErc8010SignatureErrorType,\n type SerializeErc8010SignatureParameters,\n type SerializeErc8010SignatureReturnType,\n serializeErc8010Signature,\n} from './utils/signature/serializeErc8010Signature.js'\nexport {\n /** @deprecated Use `SignatureToHexErrorType` instead. */\n type SerializeSignatureErrorType as SignatureToHexErrorType,\n type SerializeSignatureErrorType,\n type SerializeSignatureParameters,\n type SerializeSignatureReturnType,\n /** @deprecated Use `serializeSignature` instead. */\n serializeSignature as signatureToHex,\n serializeSignature,\n} from './utils/signature/serializeSignature.js'\nexport {\n type SignatureToCompactSignatureErrorType,\n signatureToCompactSignature,\n} from './utils/signature/signatureToCompactSignature.js'\nexport {\n type ToPrefixedMessageErrorType,\n toPrefixedMessage,\n} from './utils/signature/toPrefixedMessage.js'\nexport {\n type VerifyHashErrorType,\n type VerifyHashParameters,\n type VerifyHashReturnType,\n verifyHash,\n} from './utils/signature/verifyHash.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 { type StringifyErrorType, stringify } from './utils/stringify.js'\nexport {\n type AssertRequestErrorType,\n assertRequest,\n} from './utils/transaction/assertRequest.js'\nexport {\n type AssertTransactionEIP1559ErrorType,\n type AssertTransactionEIP2930ErrorType,\n type AssertTransactionLegacyErrorType,\n assertTransactionEIP1559,\n assertTransactionEIP2930,\n assertTransactionLegacy,\n} from './utils/transaction/assertTransaction.js'\nexport {\n type GetSerializedTransactionType,\n type GetSerializedTransactionTypeErrorType,\n getSerializedTransactionType,\n} from './utils/transaction/getSerializedTransactionType.js'\nexport {\n type GetTransactionType,\n type GetTransactionTypeErrorType,\n getTransactionType,\n} from './utils/transaction/getTransactionType.js'\nexport {\n type ParseTransactionErrorType,\n type ParseTransactionReturnType,\n parseTransaction,\n} from './utils/transaction/parseTransaction.js'\nexport {\n type SerializeAccessListErrorType,\n serializeAccessList,\n} from './utils/transaction/serializeAccessList.js'\nexport {\n type SerializedTransactionReturnType,\n type SerializeTransactionErrorType,\n type SerializeTransactionFn,\n serializeTransaction,\n} from './utils/transaction/serializeTransaction.js'\nexport {\n type DomainSeparatorErrorType,\n domainSeparator,\n type GetTypesForEIP712DomainErrorType,\n getTypesForEIP712Domain,\n type SerializeTypedDataErrorType,\n serializeTypedData,\n type ValidateTypedDataErrorType,\n validateTypedData,\n} from './utils/typedData.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 ParseEtherErrorType,\n parseEther,\n} from './utils/unit/parseEther.js'\nexport { type ParseGweiErrorType, parseGwei } from './utils/unit/parseGwei.js'\nexport {\n type ParseUnitsErrorType,\n parseUnits,\n} from './utils/unit/parseUnits.js'\n","import { secp256k1 } from '@noble/curves/secp256k1'\nimport type { ErrorType } from '../errors/utils.js'\nimport type { Hex } from '../types/misc.js'\nimport { type ToHexErrorType, toHex } from '../utils/encoding/toHex.js'\nimport type { NonceManager } from '../utils/nonceManager.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 SignErrorType, sign } from './utils/sign.js'\nimport { signAuthorization } from './utils/signAuthorization.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 PrivateKeyToAccountOptions = {\n nonceManager?: NonceManager | undefined\n}\n\nexport type PrivateKeyToAccountErrorType =\n | ToAccountErrorType\n | ToHexErrorType\n | PublicKeyToAddressErrorType\n | SignErrorType\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(\n privateKey: Hex,\n options: PrivateKeyToAccountOptions = {},\n): PrivateKeyAccount {\n const { nonceManager } = options\n const publicKey = toHex(secp256k1.getPublicKey(privateKey.slice(2), false))\n const address = publicKeyToAddress(publicKey)\n\n const account = toAccount({\n address,\n nonceManager,\n async sign({ hash }) {\n return sign({ hash, privateKey, to: 'hex' })\n },\n async signAuthorization(authorization) {\n return signAuthorization({ ...authorization, privateKey })\n },\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 } as any)\n },\n })\n\n return {\n ...account,\n publicKey,\n source: 'privateKey',\n } as PrivateKeyAccount\n}\n","// TODO(v3): Rename to `toLocalAccount` + add `source` property to define source (privateKey, mnemonic, hdKey, etc).\n\nimport type { Address } from 'abitype'\n\nimport {\n InvalidAddressError,\n type InvalidAddressErrorType,\n} from '../errors/address.js'\nimport type { ErrorType } from '../errors/utils.js'\nimport {\n type IsAddressErrorType,\n isAddress,\n} from '../utils/address/isAddress.js'\nimport type {\n AccountSource,\n CustomSource,\n JsonRpcAccount,\n LocalAccount,\n} from './types.js'\n\ntype GetAccountReturnType<accountSource extends AccountSource> =\n | (accountSource extends Address ? JsonRpcAccount : never)\n | (accountSource 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<accountSource extends AccountSource>(\n source: accountSource,\n): GetAccountReturnType<accountSource> {\n if (typeof source === 'string') {\n if (!isAddress(source, { strict: false }))\n throw new InvalidAddressError({ address: source })\n return {\n address: source,\n type: 'json-rpc',\n } as GetAccountReturnType<accountSource>\n }\n\n if (!isAddress(source.address, { strict: false }))\n throw new InvalidAddressError({ address: source.address })\n return {\n address: source.address,\n nonceManager: source.nonceManager,\n sign: source.sign,\n signAuthorization: source.signAuthorization,\n signMessage: source.signMessage,\n signTransaction: source.signTransaction,\n signTypedData: source.signTypedData,\n source: 'custom',\n type: 'local',\n } as GetAccountReturnType<accountSource>\n}\n","// TODO(v3): Convert to sync.\n\nimport { secp256k1 } from '@noble/curves/secp256k1'\n\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { ByteArray, Hex, Signature } from '../../types/misc.js'\nimport { type IsHexErrorType, isHex } from '../../utils/data/isHex.js'\nimport {\n type HexToBytesErrorType,\n hexToBytes,\n} from '../../utils/encoding/toBytes.js'\nimport {\n type NumberToHexErrorType,\n numberToHex,\n} from '../../utils/encoding/toHex.js'\nimport { serializeSignature } from '../../utils/signature/serializeSignature.js'\n\ntype To = 'object' | 'bytes' | 'hex'\n\nexport type SignParameters<to extends To = 'object'> = {\n hash: Hex\n privateKey: Hex\n to?: to | To | undefined\n}\n\nexport type SignReturnType<to extends To = 'object'> =\n | (to extends 'object' ? Signature : never)\n | (to extends 'bytes' ? ByteArray : never)\n | (to extends 'hex' ? Hex : never)\n\nexport type SignErrorType =\n | HexToBytesErrorType\n | IsHexErrorType\n | NumberToHexErrorType\n | ErrorType\n\nlet extraEntropy: Hex | boolean = false\n\n/**\n * Sets extra entropy for signing functions.\n */\nexport function setSignEntropy(entropy: true | Hex) {\n if (!entropy) throw new Error('must be a `true` or a hex value.')\n extraEntropy = entropy\n}\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<to extends To = 'object'>({\n hash,\n privateKey,\n to = 'object',\n}: SignParameters<to>): Promise<SignReturnType<to>> {\n const { r, s, recovery } = secp256k1.sign(\n hash.slice(2),\n privateKey.slice(2),\n {\n lowS: true,\n extraEntropy: isHex(extraEntropy, { strict: false })\n ? hexToBytes(extraEntropy)\n : extraEntropy,\n },\n )\n const signature = {\n r: numberToHex(r, { size: 32 }),\n s: numberToHex(s, { size: 32 }),\n v: recovery ? 28n : 27n,\n yParity: recovery,\n }\n return (() => {\n if (to === 'bytes' || to === 'hex')\n return serializeSignature({ ...signature, to })\n return signature\n })() as SignReturnType<to>\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type {\n AuthorizationRequest,\n SignedAuthorization,\n} from '../../types/authorization.js'\nimport type { Hex, Signature } from '../../types/misc.js'\nimport type { Prettify } from '../../types/utils.js'\nimport {\n type HashAuthorizationErrorType,\n hashAuthorization,\n} from '../../utils/authorization/hashAuthorization.js'\nimport {\n type SignErrorType,\n type SignParameters,\n type SignReturnType,\n sign,\n} from './sign.js'\n\ntype To = 'object' | 'bytes' | 'hex'\n\nexport type SignAuthorizationParameters<to extends To = 'object'> =\n AuthorizationRequest & {\n /** The private key to sign with. */\n privateKey: Hex\n to?: SignParameters<to>['to'] | undefined\n }\n\nexport type SignAuthorizationReturnType<to extends To = 'object'> = Prettify<\n to extends 'object' ? SignedAuthorization : SignReturnType<to>\n>\n\nexport type SignAuthorizationErrorType =\n | SignErrorType\n | HashAuthorizationErrorType\n | ErrorType\n\n/**\n * Signs an Authorization hash in [EIP-7702 format](https://eips.ethereum.org/EIPS/eip-7702): `keccak256('0x05' || rlp([chain_id, address, nonce]))`.\n */\nexport async function signAuthorization<to extends To = 'object'>(\n parameters: SignAuthorizationParameters<to>,\n): Promise<SignAuthorizationReturnType<to>> {\n const { chainId, nonce, privateKey, to = 'object' } = parameters\n const address = parameters.contractAddress ?? parameters.address\n const signature = await sign({\n hash: hashAuthorization({ address, chainId, nonce }),\n privateKey,\n to,\n })\n if (to === 'object')\n return {\n address,\n chainId,\n nonce,\n ...(signature as Signature),\n } as any\n return signature as any\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'\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 | 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 return await sign({ hash: hashMessage(message), privateKey, to: 'hex' })\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 serializer extends\n SerializeTransactionFn<TransactionSerializable> = SerializeTransactionFn<TransactionSerializable>,\n transaction extends Parameters<serializer>[0] = Parameters<serializer>[0],\n> = {\n privateKey: Hex\n transaction: transaction\n serializer?: serializer | undefined\n}\n\nexport type SignTransactionReturnType<\n serializer extends\n SerializeTransactionFn<TransactionSerializable> = SerializeTransactionFn<TransactionSerializable>,\n transaction extends Parameters<serializer>[0] = Parameters<serializer>[0],\n> = TransactionSerialized<GetTransactionType<transaction>>\n\nexport type SignTransactionErrorType =\n | Keccak256ErrorType\n | SignErrorType\n | ErrorType\n\nexport async function signTransaction<\n serializer extends\n SerializeTransactionFn<TransactionSerializable> = SerializeTransactionFn<TransactionSerializable>,\n transaction extends Parameters<serializer>[0] = Parameters<serializer>[0],\n>(\n parameters: SignTransactionParameters<serializer, transaction>,\n): Promise<SignTransactionReturnType<serializer, transaction>> {\n const {\n privateKey,\n transaction,\n serializer = serializeTransaction,\n } = parameters\n\n const signableTransaction = (() => {\n // For EIP-4844 Transactions, we want to sign the transaction payload body (tx_payload_body) without the sidecars (ie. without the network wrapper).\n // See: https://github.com/ethereum/EIPs/blob/e00f4daa66bd56e2dbd5f1d36d09fd613811a48b/EIPS/eip-4844.md#networking\n if (transaction.type === 'eip4844')\n return {\n ...transaction,\n sidecars: false,\n }\n return transaction\n })()\n\n const signature = await sign({\n hash: keccak256(await serializer(signableTransaction)),\n privateKey,\n })\n return (await serializer(\n transaction,\n signature,\n )) as SignTransactionReturnType<serializer, transaction>\n}\n","import type { TypedData } from 'abitype'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { 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 { type SignErrorType, sign } from './sign.js'\n\nexport type SignTypedDataParameters<\n typedData extends TypedData | Record<string, unknown> = TypedData,\n primaryType extends keyof typedData | 'EIP712Domain' = keyof typedData,\n> = TypedDataDefinition<typedData, primaryType> & {\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 | ErrorType\n\n/**\n * @description Signs typed data and calculates an Ethereum-specific signature in [https://eips.ethereum.org/EIPS/eip-712](https://eips.ethereum.org/EIPS/eip-712):\n * `sign(keccak256(\"\\x19\\x01\" ‖ domainSeparator ‖ hashStruct(message)))`.\n *\n * @returns The signature.\n */\nexport async function signTypedData<\n const typedData extends TypedData | Record<string, unknown>,\n primaryType extends keyof typedData | 'EIP712Domain',\n>(\n parameters: SignTypedDataParameters<typedData, primaryType>,\n): Promise<SignTypedDataReturnType> {\n const { privateKey, ...typedData } =\n parameters as unknown as SignTypedDataParameters\n return await sign({\n hash: hashTypedData(typedData),\n privateKey,\n to: 'hex',\n })\n}\n","import type { Chain } from '../types/chain.js'\n\n/**\n * Predeploy contracts for OP Stack.\n * @see https://github.com/ethereum-optimism/optimism/blob/develop/specs/predeploys.md\n */\nexport const contracts = {\n gasPriceOracle: { address: '0x420000000000000000000000000000000000000F' },\n l1Block: { address: '0x4200000000000000000000000000000000000015' },\n l2CrossDomainMessenger: {\n address: '0x4200000000000000000000000000000000000007',\n },\n l2Erc721Bridge: { address: '0x4200000000000000000000000000000000000014' },\n l2StandardBridge: { address: '0x4200000000000000000000000000000000000010' },\n l2ToL1MessagePasser: {\n address: '0x4200000000000000000000000000000000000016',\n },\n} as const satisfies Chain['contracts']\n","import type { ChainFormatters } from '../types/chain.js'\nimport type { RpcTransaction } from '../types/rpc.js'\nimport { hexToBigInt } from '../utils/encoding/fromHex.js'\nimport { defineBlock } from '../utils/formatters/block.js'\nimport {\n defineTransaction,\n formatTransaction,\n} from '../utils/formatters/transaction.js'\nimport { defineTransactionReceipt } from '../utils/formatters/transactionReceipt.js'\nimport type { OpStackBlock, OpStackRpcBlock } from './types/block.js'\nimport type {\n OpStackRpcTransaction,\n OpStackRpcTransactionReceipt,\n OpStackTransaction,\n OpStackTransactionReceipt,\n} from './types/transaction.js'\n\nexport const formatters = {\n block: /*#__PURE__*/ defineBlock({\n format(args: OpStackRpcBlock): OpStackBlock {\n const transactions = args.transactions?.map((transaction) => {\n if (typeof transaction === 'string') return transaction\n const formatted = formatTransaction(\n transaction as RpcTransaction,\n ) as OpStackTransaction\n if (formatted.typeHex === '0x7e') {\n formatted.isSystemTx = transaction.isSystemTx\n formatted.mint = transaction.mint\n ? hexToBigInt(transaction.mint)\n : undefined\n formatted.sourceHash = transaction.sourceHash\n formatted.type = 'deposit'\n }\n return formatted\n })\n return {\n transactions,\n stateRoot: args.stateRoot,\n } as OpStackBlock\n },\n }),\n transaction: /*#__PURE__*/ defineTransaction({\n format(args: OpStackRpcTransaction): OpStackTransaction {\n const transaction = {} as OpStackTransaction\n if (args.type === '0x7e') {\n transaction.isSystemTx = args.isSystemTx\n transaction.mint = args.mint ? hexToBigInt(args.mint) : undefined\n transaction.sourceHash = args.sourceHash\n transaction.type = 'deposit'\n }\n return transaction\n },\n }),\n transactionReceipt: /*#__PURE__*/ defineTransactionReceipt({\n format(args: OpStackRpcTransactionReceipt): OpStackTransactionReceipt {\n return {\n l1GasPrice: args.l1GasPrice ? hexToBigInt(args.l1GasPrice) : null,\n l1GasUsed: args.l1GasUsed ? hexToBigInt(args.l1GasUsed) : null,\n l1Fee: args.l1Fee ? hexToBigInt(args.l1Fee) : null,\n l1FeeScalar: args.l1FeeScalar ? Number(args.l1FeeScalar) : null,\n } as OpStackTransactionReceipt\n },\n }),\n} as const satisfies ChainFormatters\n","import { InvalidAddressError } from '../errors/address.js'\nimport type { ErrorType } from '../errors/utils.js'\nimport type { ChainSerializers } from '../types/chain.js'\nimport type { Hex, Signature } from '../types/misc.js'\nimport type { TransactionSerializable } from '../types/transaction.js'\nimport type { RequiredBy } from '../types/utils.js'\nimport { isAddress } from '../utils/address/isAddress.js'\nimport { concatHex } from '../utils/data/concat.js'\nimport { toHex } from '../utils/encoding/toHex.js'\nimport { toRlp } from '../utils/encoding/toRlp.js'\nimport {\n type SerializeTransactionErrorType as SerializeTransactionErrorType_,\n serializeTransaction as serializeTransaction_,\n} from '../utils/transaction/serializeTransaction.js'\nimport type {\n OpStackTransactionSerializable,\n TransactionSerializableDeposit,\n TransactionSerializedDeposit,\n} from './types/transaction.js'\n\nexport type SerializeTransactionReturnType = ReturnType<\n typeof serializeTransaction\n>\n\nexport type SerializeTransactionErrorType =\n | SerializeTransactionErrorType_\n | ErrorType\n\nexport function serializeTransaction(\n transaction: OpStackTransactionSerializable,\n signature?: Signature,\n) {\n if (isDeposit(transaction)) return serializeTransactionDeposit(transaction)\n return serializeTransaction_(\n transaction as TransactionSerializable,\n signature,\n )\n}\n\nexport const serializers = {\n transaction: serializeTransaction,\n} as const satisfies ChainSerializers\n\n//////////////////////////////////////////////////////////////////////////////\n// Serializers\n\nexport type SerializeTransactionDepositReturnType = TransactionSerializedDeposit\n\nfunction serializeTransactionDeposit(\n transaction: TransactionSerializableDeposit,\n): SerializeTransactionDepositReturnType {\n assertTransactionDeposit(transaction)\n\n const { sourceHash, data, from, gas, isSystemTx, mint, to, value } =\n transaction\n\n const serializedTransaction: Hex[] = [\n sourceHash,\n from,\n to ?? '0x',\n mint ? toHex(mint) : '0x',\n value ? toHex(value) : '0x',\n gas ? toHex(gas) : '0x',\n isSystemTx ? '0x1' : '0x',\n data ?? '0x',\n ]\n\n return concatHex([\n '0x7e',\n toRlp(serializedTransaction),\n ]) as SerializeTransactionDepositReturnType\n}\n\nfunction isDeposit(\n transaction: OpStackTransactionSerializable,\n): transaction is RequiredBy<TransactionSerializableDeposit, 'type'> {\n if (transaction.type === 'deposit') return true\n if (typeof transaction.sourceHash !== 'undefined') return true\n return false\n}\n\nexport function assertTransactionDeposit(\n transaction: TransactionSerializableDeposit,\n) {\n const { from, to } = transaction\n if (from && !isAddress(from)) throw new InvalidAddressError({ address: from })\n if (to && !isAddress(to)) throw new InvalidAddressError({ address: to })\n}\n","import { contracts } from './contracts.js'\nimport { formatters } from './formatters.js'\nimport { serializers } from './serializers.js'\n\nexport const chainConfig = {\n blockTime: 2_000,\n contracts,\n formatters,\n serializers,\n} as const\n","import { defineChain } from '../../utils/chain/defineChain.js'\n\nexport const arbitrum = /*#__PURE__*/ defineChain({\n id: 42_161,\n name: 'Arbitrum One',\n nativeCurrency: { name: 'Ether', symbol: 'ETH', decimals: 18 },\n blockTime: 250,\n rpcUrls: {\n default: {\n http: ['https://arb1.arbitrum.io/rpc'],\n },\n },\n blockExplorers: {\n default: {\n name: 'Arbiscan',\n url: 'https://arbiscan.io',\n apiUrl: 'https://api.arbiscan.io/api',\n },\n },\n contracts: {\n multicall3: {\n address: '0xca11bde05977b3631167028862be2a173976ca11',\n blockCreated: 7654707,\n },\n },\n})\n","import { defineChain } from '../../utils/chain/defineChain.js'\n\nexport const arbitrumSepolia = /*#__PURE__*/ defineChain({\n id: 421_614,\n name: 'Arbitrum Sepolia',\n blockTime: 250,\n nativeCurrency: {\n name: 'Arbitrum Sepolia Ether',\n symbol: 'ETH',\n decimals: 18,\n },\n rpcUrls: {\n default: {\n http: ['https://sepolia-rollup.arbitrum.io/rpc'],\n },\n },\n blockExplorers: {\n default: {\n name: 'Arbiscan',\n url: 'https://sepolia.arbiscan.io',\n apiUrl: 'https://api-sepolia.arbiscan.io/api',\n },\n },\n contracts: {\n multicall3: {\n address: '0xca11bde05977b3631167028862be2a173976ca11',\n blockCreated: 81930,\n },\n },\n testnet: true,\n})\n","import { chainConfig } from '../../op-stack/chainConfig.js'\nimport { defineChain } from '../../utils/chain/defineChain.js'\n\nconst sourceId = 1 // mainnet\n\nexport const base = /*#__PURE__*/ defineChain({\n ...chainConfig,\n id: 8453,\n name: 'Base',\n nativeCurrency: { name: 'Ether', symbol: 'ETH', decimals: 18 },\n rpcUrls: {\n default: {\n http: ['https://mainnet.base.org'],\n },\n },\n blockExplorers: {\n default: {\n name: 'Basescan',\n url: 'https://basescan.org',\n apiUrl: 'https://api.basescan.org/api',\n },\n },\n contracts: {\n ...chainConfig.contracts,\n disputeGameFactory: {\n [sourceId]: {\n address: '0x43edB88C4B80fDD2AdFF2412A7BebF9dF42cB40e',\n },\n },\n l2OutputOracle: {\n [sourceId]: {\n address: '0x56315b90c40730925ec5485cf004d835058518A0',\n },\n },\n multicall3: {\n address: '0xca11bde05977b3631167028862be2a173976ca11',\n blockCreated: 5022,\n },\n portal: {\n [sourceId]: {\n address: '0x49048044D57e1C92A77f79988d21Fa8fAF74E97e',\n blockCreated: 17482143,\n },\n },\n l1StandardBridge: {\n [sourceId]: {\n address: '0x3154Cf16ccdb4C6d922629664174b904d80F2C35',\n blockCreated: 17482143,\n },\n },\n },\n sourceId,\n})\n\nexport const basePreconf = /*#__PURE__*/ defineChain({\n ...base,\n experimental_preconfirmationTime: 200,\n rpcUrls: {\n default: {\n http: ['https://mainnet-preconf.base.org'],\n },\n },\n})\n","import { chainConfig } from '../../op-stack/chainConfig.js'\nimport { defineChain } from '../../utils/chain/defineChain.js'\n\nconst sourceId = 11_155_111 // sepolia\n\nexport const baseSepolia = /*#__PURE__*/ defineChain({\n ...chainConfig,\n id: 84532,\n network: 'base-sepolia',\n name: 'Base Sepolia',\n nativeCurrency: { name: 'Sepolia Ether', symbol: 'ETH', decimals: 18 },\n rpcUrls: {\n default: {\n http: ['https://sepolia.base.org'],\n },\n },\n blockExplorers: {\n default: {\n name: 'Basescan',\n url: 'https://sepolia.basescan.org',\n apiUrl: 'https://api-sepolia.basescan.org/api',\n },\n },\n contracts: {\n ...chainConfig.contracts,\n disputeGameFactory: {\n [sourceId]: {\n address: '0xd6E6dBf4F7EA0ac412fD8b65ED297e64BB7a06E1',\n },\n },\n l2OutputOracle: {\n [sourceId]: {\n address: '0x84457ca9D0163FbC4bbfe4Dfbb20ba46e48DF254',\n },\n },\n portal: {\n [sourceId]: {\n address: '0x49f53e41452c74589e85ca1677426ba426459e85',\n blockCreated: 4446677,\n },\n },\n l1StandardBridge: {\n [sourceId]: {\n address: '0xfd0Bf71F60660E2f608ed56e1659C450eB113120',\n blockCreated: 4446677,\n },\n },\n multicall3: {\n address: '0xca11bde05977b3631167028862be2a173976ca11',\n blockCreated: 1059647,\n },\n },\n testnet: true,\n sourceId,\n})\n\nexport const baseSepoliaPreconf = /*#__PURE__*/ defineChain({\n ...baseSepolia,\n experimental_preconfirmationTime: 200,\n rpcUrls: {\n default: {\n http: ['https://sepolia-preconf.base.org'],\n },\n },\n})\n","import { keccak256, stringToBytes } from 'viem';\nimport type { Address } from 'viem';\n\n// ============================================================================\n// EIP-712 type hashes\n// ============================================================================\n\n/**\n * keccak256 of the PaymentIntent type string — used for manual digest\n * verification. viem's signTypedData computes this internally; you don't\n * need this value for signing, only for low-level verification.\n */\nexport const PAYMENT_INTENT_TYPEHASH: `0x${string}` = keccak256(\n stringToBytes('PaymentIntent(address bot,address to,address token,uint256 amount,uint256 deadline,bytes32 ref)'),\n);\n\n/** keccak256 of the ExecuteIntent type string for DeFi protocol interactions. */\nexport const EXECUTE_INTENT_TYPEHASH: `0x${string}` = keccak256(\n stringToBytes(\n 'ExecuteIntent(address bot,address protocol,bytes32 calldataHash,address token,uint256 amount,uint256 deadline,bytes32 ref)',\n ),\n);\n\n/** keccak256 of the SwapIntent type string for in-vault token rebalancing. */\nexport const SWAP_INTENT_TYPEHASH: `0x${string}` = keccak256(\n stringToBytes('SwapIntent(address bot,address toToken,uint256 minToAmount,uint256 deadline,bytes32 ref)'),\n);\n\n/** EIP-712 domain name and version for AxonVault. Matches the constructor. */\nexport const EIP712_DOMAIN_NAME = 'AxonVault' as const;\nexport const EIP712_DOMAIN_VERSION = '1' as const;\n\n// ============================================================================\n// Native ETH sentinel\n// ============================================================================\n\n/** Sentinel address representing native ETH in PaymentIntents and deposits. */\nexport const NATIVE_ETH: Address = '0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE';\n\n// ============================================================================\n// USDC addresses per chain\n// ============================================================================\n\nexport const USDC: Record<number, Address> = {\n // Base mainnet\n 8453: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913',\n // Base Sepolia\n 84532: '0x036CbD53842c5426634e7929541eC2318f3dCF7e',\n // Arbitrum One\n 42161: '0xaf88d065e77c8cC2239327C5EDb3A432268e5831',\n // Arbitrum Sepolia\n 421614: '0x75faf114eafb1BDbe2F0316DF893fd58CE46AA4d',\n};\n\n// ============================================================================\n// Chain enum & supported chain IDs\n// ============================================================================\n\nexport enum Chain {\n Base = 8453,\n BaseSepolia = 84532,\n Arbitrum = 42161,\n ArbitrumSepolia = 421614,\n}\n\nexport const SUPPORTED_CHAIN_IDS = [8453, 84532, 42161, 421614] as const;\nexport type SupportedChainId = (typeof SUPPORTED_CHAIN_IDS)[number];\n\n// ============================================================================\n// Chain metadata (names & block explorers)\n// ============================================================================\n\n/** Human-readable chain names. */\nexport const CHAIN_NAMES: Record<number, string> = {\n [Chain.Base]: 'Base',\n [Chain.BaseSepolia]: 'Base Sepolia',\n [Chain.Arbitrum]: 'Arbitrum One',\n [Chain.ArbitrumSepolia]: 'Arbitrum Sepolia',\n // Future v1 chains (metadata only — not in SUPPORTED_CHAIN_IDS yet)\n 10: 'Optimism',\n 11155420: 'OP Sepolia',\n 137: 'Polygon',\n 80002: 'Polygon Amoy',\n};\n\n/** Block explorer TX URL prefix per chain. */\nexport const EXPLORER_TX: Record<number, string> = {\n [Chain.Base]: 'https://basescan.org/tx/',\n [Chain.BaseSepolia]: 'https://sepolia.basescan.org/tx/',\n [Chain.Arbitrum]: 'https://arbiscan.io/tx/',\n [Chain.ArbitrumSepolia]: 'https://sepolia.arbiscan.io/tx/',\n 10: 'https://optimistic.etherscan.io/tx/',\n 11155420: 'https://sepolia-optimism.etherscan.io/tx/',\n 137: 'https://polygonscan.com/tx/',\n 80002: 'https://amoy.polygonscan.com/tx/',\n};\n\n/** Block explorer address URL prefix per chain. */\nexport const EXPLORER_ADDR: Record<number, string> = {\n [Chain.Base]: 'https://basescan.org/address/',\n [Chain.BaseSepolia]: 'https://sepolia.basescan.org/address/',\n [Chain.Arbitrum]: 'https://arbiscan.io/address/',\n [Chain.ArbitrumSepolia]: 'https://sepolia.arbiscan.io/address/',\n 10: 'https://optimistic.etherscan.io/address/',\n 11155420: 'https://sepolia-optimism.etherscan.io/address/',\n 137: 'https://polygonscan.com/address/',\n 80002: 'https://amoy.polygonscan.com/address/',\n};\n\n// ============================================================================\n// Time constants (seconds)\n// ============================================================================\n\n/** Default intent validity window when no deadline is specified. */\nexport const DEFAULT_DEADLINE_SECONDS = 300; // 5 minutes\n\n/** Window presets for SpendingLimit.windowSeconds. */\nexport const WINDOW = {\n ONE_HOUR: 3600n,\n ONE_DAY: 86400n,\n ONE_WEEK: 604800n,\n THIRTY_DAYS: 2592000n,\n} as const;\n\n// ============================================================================\n// Payment rejection error codes\n// ============================================================================\n\n/**\n * Structured error codes returned by the relayer when a payment is rejected.\n * Bots should import these to programmatically handle failures.\n */\nexport const PaymentErrorCode = {\n /** Payment destination is the vault itself */\n SELF_PAYMENT: 'SELF_PAYMENT',\n /** Payment destination is the zero address */\n ZERO_ADDRESS: 'ZERO_ADDRESS',\n /** Payment amount is zero */\n ZERO_AMOUNT: 'ZERO_AMOUNT',\n /** Vault does not hold enough of the requested token */\n INSUFFICIENT_BALANCE: 'INSUFFICIENT_BALANCE',\n /** EIP-712 signature verification failed */\n INVALID_SIGNATURE: 'INVALID_SIGNATURE',\n /** Payment intent deadline has passed */\n DEADLINE_EXPIRED: 'DEADLINE_EXPIRED',\n /** Bot is temporarily paused by the operator */\n BOT_PAUSED: 'BOT_PAUSED',\n /** Bot address is not registered/active in the vault */\n BOT_NOT_ACTIVE: 'BOT_NOT_ACTIVE',\n /** Destination address is on the global or vault blacklist */\n BLACKLISTED: 'BLACKLISTED',\n /** Rolling-window spending limit (USD amount) exceeded */\n SPENDING_LIMIT_EXCEEDED: 'SPENDING_LIMIT_EXCEEDED',\n /** Rolling-window transaction count limit exceeded */\n TX_COUNT_EXCEEDED: 'TX_COUNT_EXCEEDED',\n /** Single transaction exceeds the bot's on-chain maxPerTxAmount */\n MAX_PER_TX_EXCEEDED: 'MAX_PER_TX_EXCEEDED',\n /** Vault-level daily aggregate spending limit exceeded */\n VAULT_AGGREGATE_EXCEEDED: 'VAULT_AGGREGATE_EXCEEDED',\n /** eth_call simulation of the on-chain transaction reverted */\n SIMULATION_FAILED: 'SIMULATION_FAILED',\n /** Routed to human review (AI scan flagged or no consensus) */\n PENDING_REVIEW: 'PENDING_REVIEW',\n /** Relayer wallet has insufficient gas to submit the transaction */\n RELAYER_OUT_OF_GAS: 'RELAYER_OUT_OF_GAS',\n /** On-chain transaction submission failed */\n SUBMISSION_FAILED: 'SUBMISSION_FAILED',\n /** Destination not in the vault/bot whitelist */\n DESTINATION_NOT_WHITELISTED: 'DESTINATION_NOT_WHITELISTED',\n /** Vault address is not a valid AxonVault or was not deployed by a known factory */\n INVALID_VAULT: 'INVALID_VAULT',\n /** Rebalance output token is not in the whitelist (on-chain or relayer default) */\n REBALANCE_TOKEN_NOT_ALLOWED: 'REBALANCE_TOKEN_NOT_ALLOWED',\n /** Rebalance input amount exceeds the bot's maxRebalanceAmount cap */\n MAX_REBALANCE_AMOUNT_EXCEEDED: 'MAX_REBALANCE_AMOUNT_EXCEEDED',\n /** Unknown or internal error */\n INTERNAL_ERROR: 'INTERNAL_ERROR',\n} as const;\n\nexport type PaymentErrorCode = (typeof PaymentErrorCode)[keyof typeof PaymentErrorCode];\n\n// ============================================================================\n// Relayer API paths\n// ============================================================================\n\nexport const RELAYER_API = {\n PAYMENTS: '/v1/payments',\n payment: (requestId: string) => `/v1/payments/${requestId}`,\n EXECUTE: '/v1/execute',\n execute: (requestId: string) => `/v1/execute/${requestId}`,\n SWAP: '/v1/swap',\n swap: (requestId: string) => `/v1/swap/${requestId}`,\n\n // Vault read endpoints (relayer reads chain on behalf of bots)\n vaultBalance: (vault: string, token: string, chainId: number) =>\n `/v1/vault/${vault}/balance/${token}?chainId=${chainId}`,\n vaultBalances: (vault: string, chainId: number) => `/v1/vault/${vault}/balances`,\n vaultInfo: (vault: string, chainId: number) => `/v1/vault/${vault}/info?chainId=${chainId}`,\n botStatus: (vault: string, bot: string, chainId: number) => `/v1/vault/${vault}/bot/${bot}/status?chainId=${chainId}`,\n destinationCheck: (vault: string, bot: string, destination: string, chainId: number) =>\n `/v1/vault/${vault}/bot/${bot}/destination/${destination}?chainId=${chainId}`,\n protocolCheck: (vault: string, protocol: string, chainId: number) =>\n `/v1/vault/${vault}/protocol/${protocol}?chainId=${chainId}`,\n rebalanceTokens: (vault: string, chainId: number) => `/v1/vault/${vault}/rebalance-tokens?chainId=${chainId}`,\n rebalanceTokenCheck: (vault: string, token: string, chainId: number) =>\n `/v1/vault/${vault}/rebalance-token/${token}?chainId=${chainId}`,\n\n // TOS endpoints\n tosStatus: (wallet: string) => `/v1/tos/status?wallet=${wallet}`,\n TOS_ACCEPT: '/v1/tos/accept',\n} as const;\n","import { keccak256, stringToBytes } from 'viem';\nimport type { WalletClient, Hex, Address } from 'viem';\nimport type { PaymentIntent, ExecuteIntent, SwapIntent } from './types.js';\nimport { EIP712_DOMAIN_NAME, EIP712_DOMAIN_VERSION } from './constants.js';\n\n// EIP-712 types for PaymentIntent — field order matches the Solidity struct exactly.\nconst PAYMENT_INTENT_TYPES = {\n PaymentIntent: [\n { name: 'bot', type: 'address' },\n { name: 'to', type: 'address' },\n { name: 'token', type: 'address' },\n { name: 'amount', type: 'uint256' },\n { name: 'deadline', type: 'uint256' },\n { name: 'ref', type: 'bytes32' },\n ],\n} as const;\n\n// EIP-712 types for ExecuteIntent — DeFi protocol interactions.\nconst EXECUTE_INTENT_TYPES = {\n ExecuteIntent: [\n { name: 'bot', type: 'address' },\n { name: 'protocol', type: 'address' },\n { name: 'calldataHash', type: 'bytes32' },\n { name: 'token', type: 'address' },\n { name: 'amount', type: 'uint256' },\n { name: 'deadline', type: 'uint256' },\n { name: 'ref', type: 'bytes32' },\n ],\n} as const;\n\n// EIP-712 types for SwapIntent — in-vault token rebalancing.\nconst SWAP_INTENT_TYPES = {\n SwapIntent: [\n { name: 'bot', type: 'address' },\n { name: 'toToken', type: 'address' },\n { name: 'minToAmount', type: 'uint256' },\n { name: 'deadline', type: 'uint256' },\n { name: 'ref', type: 'bytes32' },\n ],\n} as const;\n\nfunction makeDomain(vaultAddress: Address, chainId: number) {\n return {\n name: EIP712_DOMAIN_NAME,\n version: EIP712_DOMAIN_VERSION,\n chainId,\n verifyingContract: vaultAddress,\n } as const;\n}\n\n/**\n * Sign a PaymentIntent using EIP-712 typed structured data.\n *\n * The resulting signature can be submitted to the Axon relayer API, which\n * passes it to AxonVault.executePayment() on-chain.\n */\nexport async function signPayment(\n walletClient: WalletClient,\n vaultAddress: Address,\n chainId: number,\n intent: PaymentIntent,\n): Promise<Hex> {\n if (!walletClient.account) {\n throw new Error('walletClient has no account attached');\n }\n\n return walletClient.signTypedData({\n account: walletClient.account,\n domain: makeDomain(vaultAddress, chainId),\n types: PAYMENT_INTENT_TYPES,\n primaryType: 'PaymentIntent',\n message: {\n bot: intent.bot,\n to: intent.to,\n token: intent.token,\n amount: intent.amount,\n deadline: intent.deadline,\n ref: intent.ref,\n },\n });\n}\n\n/**\n * Sign an ExecuteIntent using EIP-712 typed structured data.\n *\n * The resulting signature can be submitted to the Axon relayer API, which\n * passes it to AxonVault.executeProtocol() on-chain.\n */\nexport async function signExecuteIntent(\n walletClient: WalletClient,\n vaultAddress: Address,\n chainId: number,\n intent: ExecuteIntent,\n): Promise<Hex> {\n if (!walletClient.account) {\n throw new Error('walletClient has no account attached');\n }\n\n return walletClient.signTypedData({\n account: walletClient.account,\n domain: makeDomain(vaultAddress, chainId),\n types: EXECUTE_INTENT_TYPES,\n primaryType: 'ExecuteIntent',\n message: {\n bot: intent.bot,\n protocol: intent.protocol,\n calldataHash: intent.calldataHash,\n token: intent.token,\n amount: intent.amount,\n deadline: intent.deadline,\n ref: intent.ref,\n },\n });\n}\n\n/**\n * Sign a SwapIntent using EIP-712 typed structured data.\n *\n * The resulting signature can be submitted to the Axon relayer API, which\n * passes it to AxonVault.executeSwap() on-chain.\n */\nexport async function signSwapIntent(\n walletClient: WalletClient,\n vaultAddress: Address,\n chainId: number,\n intent: SwapIntent,\n): Promise<Hex> {\n if (!walletClient.account) {\n throw new Error('walletClient has no account attached');\n }\n\n return walletClient.signTypedData({\n account: walletClient.account,\n domain: makeDomain(vaultAddress, chainId),\n types: SWAP_INTENT_TYPES,\n primaryType: 'SwapIntent',\n message: {\n bot: intent.bot,\n toToken: intent.toToken,\n minToAmount: intent.minToAmount,\n deadline: intent.deadline,\n ref: intent.ref,\n },\n });\n}\n\n/**\n * Derive the on-chain `ref` bytes32 from a human-readable memo string.\n *\n * The full memo text is stored off-chain by the relayer (PostgreSQL), linked\n * to the transaction. The keccak256 hash goes into the signed PaymentIntent\n * and is emitted in the PaymentExecuted on-chain event.\n *\n * @param memo Human-readable description, e.g. \"API call #1234 — weather data\"\n * @returns keccak256 hash of the UTF-8 encoded memo, as a bytes32 hex.\n */\nexport function encodeRef(memo: string): Hex {\n return keccak256(stringToBytes(memo));\n}\n","import { createPublicClient, createWalletClient, http } from 'viem';\nimport { privateKeyToAccount } from 'viem/accounts';\nimport { base, baseSepolia, arbitrum, arbitrumSepolia } from 'viem/chains';\nimport type { PublicClient, WalletClient, Address, Hex, Chain } from 'viem';\nimport { AxonVaultAbi } from './abis/AxonVault.js';\nimport { AxonVaultFactoryAbi } from './abis/AxonVaultFactory.js';\nimport type { BotConfig, OperatorCeilings, VaultInfo, DestinationCheckResult } from './types.js';\n\n// ============================================================================\n// Chain helpers\n// ============================================================================\n\n/** Returns the viem Chain object for a supported Axon chain ID. */\nexport function getChain(chainId: number): Chain {\n switch (chainId) {\n case 8453:\n return base;\n case 84532:\n return baseSepolia;\n case 42161:\n return arbitrum;\n case 421614:\n return arbitrumSepolia;\n default:\n throw new Error(\n `Unsupported chainId: ${chainId}. Supported: 8453 (Base), 84532 (Base Sepolia), 42161 (Arbitrum), 421614 (Arbitrum Sepolia)`,\n );\n }\n}\n\n/** Create a viem PublicClient for the given chain and RPC URL. */\nexport function createAxonPublicClient(chainId: number, rpcUrl: string): PublicClient {\n return createPublicClient({\n chain: getChain(chainId),\n transport: http(rpcUrl),\n });\n}\n\n/** Create a viem WalletClient from a raw private key (signing-only, no RPC needed). */\nexport function createAxonWalletClient(privateKey: Hex, chainId: number): WalletClient {\n const account = privateKeyToAccount(privateKey);\n return createWalletClient({\n account,\n chain: getChain(chainId),\n transport: http(), // signing is local — transport is unused but required by viem\n });\n}\n\n// ============================================================================\n// Read-only vault helpers\n// ============================================================================\n\n/**\n * Returns the full BotConfig for a bot address from the vault.\n * If the bot has never been added, isActive will be false and all\n * numeric fields will be 0n.\n */\nexport async function getBotConfig(\n publicClient: PublicClient,\n vaultAddress: Address,\n botAddress: Address,\n): Promise<BotConfig> {\n const result = await publicClient.readContract({\n address: vaultAddress,\n abi: AxonVaultAbi,\n functionName: 'getBotConfig',\n args: [botAddress],\n });\n\n return {\n isActive: result.isActive,\n registeredAt: result.registeredAt,\n maxPerTxAmount: result.maxPerTxAmount,\n maxRebalanceAmount: result.maxRebalanceAmount,\n spendingLimits: result.spendingLimits.map((sl) => ({\n amount: sl.amount,\n maxCount: sl.maxCount,\n windowSeconds: sl.windowSeconds,\n })),\n aiTriggerThreshold: result.aiTriggerThreshold,\n requireAiVerification: result.requireAiVerification,\n };\n}\n\n/** Returns whether a bot address is currently active in the vault. */\nexport async function isBotActive(\n publicClient: PublicClient,\n vaultAddress: Address,\n botAddress: Address,\n): Promise<boolean> {\n return publicClient.readContract({\n address: vaultAddress,\n abi: AxonVaultAbi,\n functionName: 'isBotActive',\n args: [botAddress],\n });\n}\n\n/** Returns the operator ceilings set by the vault owner. */\nexport async function getOperatorCeilings(\n publicClient: PublicClient,\n vaultAddress: Address,\n): Promise<OperatorCeilings> {\n const result = await publicClient.readContract({\n address: vaultAddress,\n abi: AxonVaultAbi,\n functionName: 'operatorCeilings',\n });\n\n // viem returns multiple named outputs as a tuple; destructure by position\n const [maxPerTxAmount, maxBotDailyLimit, maxOperatorBots, vaultDailyAggregate, minAiTriggerFloor] = result as [\n bigint,\n bigint,\n bigint,\n bigint,\n bigint,\n ];\n\n return {\n maxPerTxAmount,\n maxBotDailyLimit,\n maxOperatorBots,\n vaultDailyAggregate,\n minAiTriggerFloor,\n };\n}\n\n/**\n * Returns the maximum USDC an operator-compromised wallet could drain per day.\n * Computed on-chain as: min(maxOperatorBots × maxBotDailyLimit, vaultDailyAggregate).\n * Returns 0n if operator has no bot-add permission.\n */\nexport async function operatorMaxDrainPerDay(publicClient: PublicClient, vaultAddress: Address): Promise<bigint> {\n return publicClient.readContract({\n address: vaultAddress,\n abi: AxonVaultAbi,\n functionName: 'operatorMaxDrainPerDay',\n });\n}\n\n/** Returns whether the vault is currently paused. */\nexport async function isVaultPaused(publicClient: PublicClient, vaultAddress: Address): Promise<boolean> {\n return publicClient.readContract({\n address: vaultAddress,\n abi: AxonVaultAbi,\n functionName: 'paused',\n });\n}\n\n/** Returns the EIP-712 domain separator for this vault (for off-chain verification). */\nexport async function getDomainSeparator(publicClient: PublicClient, vaultAddress: Address): Promise<Hex> {\n return publicClient.readContract({\n address: vaultAddress,\n abi: AxonVaultAbi,\n functionName: 'DOMAIN_SEPARATOR',\n });\n}\n\n/** Returns the vault contract version number. */\nexport async function getVaultVersion(publicClient: PublicClient, vaultAddress: Address): Promise<number> {\n const version = await publicClient.readContract({\n address: vaultAddress,\n abi: AxonVaultAbi,\n functionName: 'VERSION',\n });\n return Number(version);\n}\n\n/** Returns the vault owner address. */\nexport async function getVaultOwner(publicClient: PublicClient, vaultAddress: Address): Promise<Address> {\n return publicClient.readContract({\n address: vaultAddress,\n abi: AxonVaultAbi,\n functionName: 'owner',\n });\n}\n\n/** Returns the vault operator address (address(0) if no operator set). */\nexport async function getVaultOperator(publicClient: PublicClient, vaultAddress: Address): Promise<Address> {\n return publicClient.readContract({\n address: vaultAddress,\n abi: AxonVaultAbi,\n functionName: 'operator',\n });\n}\n\n/**\n * Check whether a destination address is allowed for a given bot.\n *\n * Logic mirrors the on-chain enforcement order:\n * 1. If destination is on the global blacklist → blocked\n * 2. If global whitelist is non-empty → destination must be on it\n * 3. If bot-specific whitelist is non-empty → destination must be on it\n * 4. Otherwise → allowed\n */\nexport async function isDestinationAllowed(\n publicClient: PublicClient,\n vaultAddress: Address,\n botAddress: Address,\n destination: Address,\n): Promise<DestinationCheckResult> {\n // Step 1: Check global blacklist\n const isBlacklisted = await publicClient.readContract({\n address: vaultAddress,\n abi: AxonVaultAbi,\n functionName: 'globalDestinationBlacklist',\n args: [destination],\n });\n if (isBlacklisted) {\n return { allowed: false, reason: 'Destination is on the global blacklist' };\n }\n\n // Step 2: Check global whitelist (if non-empty, destination must be on it)\n const globalCount = await publicClient.readContract({\n address: vaultAddress,\n abi: AxonVaultAbi,\n functionName: 'globalDestinationCount',\n });\n if (globalCount > 0n) {\n const isGlobalWhitelisted = await publicClient.readContract({\n address: vaultAddress,\n abi: AxonVaultAbi,\n functionName: 'globalDestinationWhitelist',\n args: [destination],\n });\n if (!isGlobalWhitelisted) {\n return { allowed: false, reason: 'Destination is not on the global whitelist' };\n }\n }\n\n // Step 3: Check bot-specific whitelist (if non-empty, destination must be on it)\n const botCount = await publicClient.readContract({\n address: vaultAddress,\n abi: AxonVaultAbi,\n functionName: 'botDestinationCount',\n args: [botAddress],\n });\n if (botCount > 0n) {\n const isBotWhitelisted = await publicClient.readContract({\n address: vaultAddress,\n abi: AxonVaultAbi,\n functionName: 'botDestinationWhitelist',\n args: [botAddress, destination],\n });\n if (!isBotWhitelisted) {\n return { allowed: false, reason: 'Destination is not on the bot whitelist' };\n }\n }\n\n return { allowed: true };\n}\n\n// ============================================================================\n// Rebalance token whitelist (on-chain reads)\n// ============================================================================\n\n/** Returns the number of tokens in the vault's on-chain rebalance whitelist. 0 = no on-chain whitelist. */\nexport async function getRebalanceTokenCount(publicClient: PublicClient, vaultAddress: Address): Promise<number> {\n const count = await publicClient.readContract({\n address: vaultAddress,\n abi: AxonVaultAbi,\n functionName: 'rebalanceTokenCount',\n });\n return Number(count);\n}\n\n/** Returns whether a token is in the vault's on-chain rebalance whitelist. */\nexport async function isRebalanceTokenWhitelisted(\n publicClient: PublicClient,\n vaultAddress: Address,\n token: Address,\n): Promise<boolean> {\n return publicClient.readContract({\n address: vaultAddress,\n abi: AxonVaultAbi,\n functionName: 'rebalanceTokenWhitelist',\n args: [token],\n });\n}\n\n// ============================================================================\n// Factory — deploy a new vault\n// ============================================================================\n\n/**\n * Deploy a new AxonVault via the factory.\n *\n * The vault is owned by the walletClient's account. Permissionless — any\n * address can deploy, no Axon approval required.\n *\n * @param walletClient Wallet that will own the deployed vault.\n * @param factoryAddress Address of the deployed AxonVaultFactory.\n * @returns Address of the newly deployed vault.\n */\nexport async function deployVault(\n walletClient: WalletClient,\n publicClient: PublicClient,\n factoryAddress: Address,\n): Promise<Address> {\n if (!walletClient.account) {\n throw new Error('walletClient has no account attached');\n }\n\n const hash = await walletClient.writeContract({\n address: factoryAddress,\n abi: AxonVaultFactoryAbi,\n functionName: 'deployVault',\n args: [],\n account: walletClient.account,\n chain: walletClient.chain ?? null,\n });\n\n const receipt = await publicClient.waitForTransactionReceipt({ hash });\n\n // Extract vault address from the VaultDeployed event\n for (const log of receipt.logs) {\n try {\n // The second indexed topic is the vault address (owner is first indexed)\n if (log.topics.length >= 3 && log.topics[2]) {\n const vaultAddress = `0x${log.topics[2].slice(26)}` as Address;\n return vaultAddress;\n }\n } catch {\n // Not a VaultDeployed log, continue\n }\n }\n\n throw new Error('VaultDeployed event not found in transaction receipt');\n}\n","import type { Address } from 'viem';\n\n// ============================================================================\n// Token enum — type-safe token symbols for SDK consumers\n// ============================================================================\n\nexport enum Token {\n USDC = 'USDC',\n USDT = 'USDT',\n DAI = 'DAI',\n WETH = 'WETH',\n WBTC = 'WBTC',\n cbBTC = 'cbBTC',\n cbETH = 'cbETH',\n wstETH = 'wstETH',\n rETH = 'rETH',\n LINK = 'LINK',\n UNI = 'UNI',\n AAVE = 'AAVE',\n COMP = 'COMP',\n CRV = 'CRV',\n SNX = 'SNX',\n ARB = 'ARB',\n AERO = 'AERO',\n GMX = 'GMX',\n}\n\n// ============================================================================\n// Known token registry — single source of truth for all packages\n// ============================================================================\n\nexport interface KnownToken {\n symbol: string;\n name: string;\n decimals: number;\n /** Address per chainId. Missing key = not available on that chain. */\n addresses: Partial<Record<number, Address>>;\n}\n\n/**\n * Master token registry keyed by symbol.\n * At a glance you see which chains each token lives on.\n *\n * Chain IDs: 8453 = Base, 84532 = Base Sepolia, 42161 = Arbitrum One, 421614 = Arbitrum Sepolia\n */\nexport const KNOWN_TOKENS = {\n // ── Core stables + wrapped ──────────────────────────────\n USDC: {\n symbol: 'USDC',\n name: 'USD Coin',\n decimals: 6,\n addresses: {\n 8453: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913',\n 84532: '0x036CbD53842c5426634e7929541eC2318f3dCF7e',\n 42161: '0xaf88d065e77c8cC2239327C5EDb3A432268e5831',\n 421614: '0x75faf114eafb1BDbe2F0316DF893fd58CE46AA4d',\n },\n },\n USDT: {\n symbol: 'USDT',\n name: 'Tether USD',\n decimals: 6,\n addresses: {\n 8453: '0xfde4C96c8593536E31F229EA8f37b2ADa2699bb2',\n 84532: '0x323e78f944A9a1FcF3a10efcC5319DBb0bB6e673',\n 42161: '0xFd086bC7CD5C481DCC9C85ebE478A1C0b69FCbb9',\n },\n },\n DAI: {\n symbol: 'DAI',\n name: 'Dai Stablecoin',\n decimals: 18,\n addresses: {\n 8453: '0x50c5725949A6F0c72E6C4a641F24049A917DB0Cb',\n 84532: '0x819ffecd4e64f193e959944bcd57eedc7755e17a',\n 42161: '0xDA10009cBd5D07dd0CeCc66161FC93D7c9000da1',\n },\n },\n WETH: {\n symbol: 'WETH',\n name: 'Wrapped Ether',\n decimals: 18,\n addresses: {\n 8453: '0x4200000000000000000000000000000000000006',\n 84532: '0x4200000000000000000000000000000000000006',\n 42161: '0x82aF49447D8a07e3bd95BD0d56f35241523fBab1',\n },\n },\n WBTC: {\n symbol: 'WBTC',\n name: 'Wrapped BTC',\n decimals: 8,\n addresses: {\n 8453: '0x0555E30da8f98308EdB960aa94C0Db47230d2B9c',\n 42161: '0x2f2a2543B76A4166549F7aaB2e75Bef0aefC5B0f',\n },\n },\n cbBTC: {\n symbol: 'cbBTC',\n name: 'Coinbase Wrapped BTC',\n decimals: 8,\n addresses: {\n 8453: '0xcbB7C0000aB88B473b1f5aFd9ef808440eed33Bf',\n 42161: '0xcbB7C0000aB88B473b1f5aFd9ef808440eed33Bf',\n },\n },\n\n // ── Liquid staking ──────────────────────────────────────\n cbETH: {\n symbol: 'cbETH',\n name: 'Coinbase Staked ETH',\n decimals: 18,\n addresses: {\n 8453: '0x2Ae3F1Ec7F1F5012CFEab0185bfc7aa3cf0DEc22',\n 42161: '0x1DEBd73E752bEaF79865Fd6446b0c970EaE7732f',\n },\n },\n wstETH: {\n symbol: 'wstETH',\n name: 'Lido Wrapped stETH',\n decimals: 18,\n addresses: {\n 8453: '0xc1CBa3fCea344f92D9239c08C0568f6F2F0ee452',\n 42161: '0x5979D7b546E38E414F7E9822514be443A4800529',\n },\n },\n rETH: {\n symbol: 'rETH',\n name: 'Rocket Pool ETH',\n decimals: 18,\n addresses: {\n 42161: '0xEC70Dcb4A1EFa46b8F2D97C310C9c4790ba5ffA8',\n },\n },\n\n // ── DeFi blue-chips ─────────────────────────────────────\n LINK: {\n symbol: 'LINK',\n name: 'Chainlink',\n decimals: 18,\n addresses: {\n 8453: '0x88Fb150BDc53A65fe94Dea0c9BA0a6dAf8C6e196',\n 84532: '0xE4aB69C077896252FAFBD49EFD26B5D171A32410',\n 42161: '0xf97f4df75117a78c1A5a0DBb814Af92458539FB4',\n },\n },\n UNI: {\n symbol: 'UNI',\n name: 'Uniswap',\n decimals: 18,\n addresses: {\n 8453: '0xc3De830EA07524a0761646a6a4e4be0e114a3C83',\n 42161: '0xFa7F8980b0f1E64A2062791cc3b0871572f1F7f0',\n },\n },\n AAVE: {\n symbol: 'AAVE',\n name: 'Aave',\n decimals: 18,\n addresses: {\n 8453: '0x63706e401c06ac8513145b7687A14804d17f814b',\n 42161: '0xba5DdD1f9d7F570dc94a51479a000E3BCE967196',\n },\n },\n COMP: {\n symbol: 'COMP',\n name: 'Compound',\n decimals: 18,\n addresses: {\n 8453: '0x9e1028F5F1D5eDE59748FFceE5532509976840E0',\n 42161: '0x354A6dA3fcde098F8389cad84b0182725c6C91dE',\n },\n },\n CRV: {\n symbol: 'CRV',\n name: 'Curve DAO',\n decimals: 18,\n addresses: {\n 8453: '0x8Ee73c484A26e0A5df2Ee2a4960B789967dd0415',\n 42161: '0x11cDb42B0EB46D95f990BeDD4695A6e3fA034978',\n },\n },\n SNX: {\n symbol: 'SNX',\n name: 'Synthetix',\n decimals: 18,\n addresses: {\n 8453: '0x22e6966B799c4D5B13BE962E1D117b56327FDa66',\n },\n },\n\n // ── Chain-native governance ─────────────────────────────\n ARB: {\n symbol: 'ARB',\n name: 'Arbitrum',\n decimals: 18,\n addresses: {\n 42161: '0x912CE59144191C1204E64559FE8253a0e49E6548',\n },\n },\n AERO: {\n symbol: 'AERO',\n name: 'Aerodrome',\n decimals: 18,\n addresses: {\n 8453: '0x940181a94A35A4569E4529A3CDfB74e38FD98631',\n },\n },\n GMX: {\n symbol: 'GMX',\n name: 'GMX',\n decimals: 18,\n addresses: {\n 42161: '0xfc5A1A6EB076a2C7aD06eD22C90d7E710E35ad0a',\n },\n },\n} as const satisfies Record<string, KnownToken>;\n\nexport type KnownTokenSymbol = keyof typeof KNOWN_TOKENS;\n\n// Pre-build reverse lookup map: lowercase address → symbol\nconst addressToSymbol = new Map<string, string>();\nfor (const token of Object.values(KNOWN_TOKENS)) {\n for (const addr of Object.values(token.addresses)) {\n addressToSymbol.set((addr as string).toLowerCase(), token.symbol);\n }\n}\n\n/** All known tokens available on a specific chain. */\nexport function getKnownTokensForChain(chainId: number): (KnownToken & { address: Address })[] {\n const result: (KnownToken & { address: Address })[] = [];\n for (const token of Object.values(KNOWN_TOKENS)) {\n const addr = (token.addresses as Record<number, Address | undefined>)[chainId];\n if (addr) {\n result.push({ ...token, address: addr });\n }\n }\n return result;\n}\n\n/** Reverse-lookup: address → symbol (case-insensitive). Returns null if unknown. */\nexport function getTokenSymbolByAddress(address: string): string | null {\n return addressToSymbol.get(address.toLowerCase()) ?? null;\n}\n\n/**\n * Resolve a Token enum symbol to its on-chain address for a given chain.\n * If an Address (0x...) is passed, it is returned as-is.\n *\n * @throws if the symbol has no address on the given chain.\n */\nexport function resolveToken(token: Address | Token | KnownTokenSymbol, chainId: number): Address {\n // Already an address — pass through (with zero-address guard)\n if (typeof token === 'string' && token.startsWith('0x')) {\n if (token === '0x0000000000000000000000000000000000000000') {\n throw new Error('Token address cannot be the zero address');\n }\n return token as Address;\n }\n\n const entry = KNOWN_TOKENS[token as keyof typeof KNOWN_TOKENS];\n if (!entry) {\n throw new Error(`Unknown token symbol: ${token}`);\n }\n\n const addr = (entry.addresses as Record<number, Address | undefined>)[chainId];\n if (!addr) {\n throw new Error(`Token ${token} is not available on chain ${chainId}`);\n }\n\n return addr;\n}\n","import { parseUnits } from 'viem';\nimport type { Address } from 'viem';\nimport { KNOWN_TOKENS, getTokenSymbolByAddress, type KnownTokenSymbol } from './tokens.js';\nimport type { Token } from './tokens.js';\n\n// ============================================================================\n// Human-friendly amount conversion\n// ============================================================================\n\n/**\n * Look up decimals for a token by symbol, Token enum, or address.\n *\n * @param token - A KnownTokenSymbol ('USDC'), Token enum (Token.USDC), or address ('0x...')\n * @param chainId - Optional chain ID (unused for decimal lookup, but reserved for future use)\n * @returns The number of decimals for the token\n * @throws If the token is an unknown address with no entry in KNOWN_TOKENS\n */\nexport function resolveTokenDecimals(token: Address | Token | KnownTokenSymbol, chainId?: number): number {\n // If it looks like an address, reverse-lookup the symbol first\n if (typeof token === 'string' && token.startsWith('0x')) {\n const symbol = getTokenSymbolByAddress(token);\n if (!symbol) {\n throw new Error(\n `Unknown token address ${token} — cannot determine decimals. Use a bigint amount instead, or pass a known token symbol.`,\n );\n }\n const entry = KNOWN_TOKENS[symbol as KnownTokenSymbol];\n return entry.decimals;\n }\n\n // Symbol or Token enum\n const entry = KNOWN_TOKENS[token as KnownTokenSymbol];\n if (!entry) {\n throw new Error(\n `Unknown token symbol \"${token}\" — cannot determine decimals. Use a bigint amount instead, or use a known symbol (${Object.keys(KNOWN_TOKENS).join(', ')}).`,\n );\n }\n return entry.decimals;\n}\n\n/**\n * Convert a human-friendly amount to raw base units (bigint).\n *\n * - **bigint** → passed through as-is (already in base units)\n * - **number** → converted to string, then parsed via `parseUnits(str, decimals)`\n * - **string** → parsed directly via `parseUnits(str, decimals)`\n *\n * @param amount - The amount as bigint (raw), number (human), or string (human)\n * @param token - Token identifier used to look up decimals (symbol, enum, or address)\n * @param chainId - Optional chain ID (passed to resolveTokenDecimals)\n * @returns The amount in token base units as bigint\n *\n * @example\n * ```ts\n * parseAmount(5_000_000n, 'USDC') // 5000000n (passthrough)\n * parseAmount(5.2, 'USDC') // 5200000n\n * parseAmount('5.2', 'USDC') // 5200000n\n * parseAmount(0.001, 'WETH') // 1000000000000000n\n * ```\n *\n * @throws If the amount has more decimal places than the token supports\n * @throws If the token is unknown and amount is not bigint\n */\nexport function parseAmount(\n amount: bigint | number | string,\n token: Address | Token | KnownTokenSymbol,\n chainId?: number,\n): bigint {\n // bigint = raw base units, pass through\n if (typeof amount === 'bigint') {\n return amount;\n }\n\n const decimals = resolveTokenDecimals(token, chainId);\n\n // Convert number to string first\n const str = typeof amount === 'number' ? amount.toString() : amount;\n\n // Validate precision: count decimal places in the string\n const dotIndex = str.indexOf('.');\n if (dotIndex !== -1) {\n const decimalPlaces = str.length - dotIndex - 1;\n if (decimalPlaces > decimals) {\n throw new Error(\n `Amount \"${str}\" has ${decimalPlaces} decimal places, but ${typeof token === 'string' && token.startsWith('0x') ? 'this token' : token} only supports ${decimals}. Truncate or round your amount.`,\n );\n }\n }\n\n return parseUnits(str, decimals);\n}\n","// ============================================================================\n// Shared utilities\n// ============================================================================\n\n/**\n * Tiny UUID v4 generator (no external dependency).\n *\n * Uses `crypto.getRandomValues` in browsers and Node ≥19, with a\n * `require('crypto').randomBytes` fallback for older Node versions.\n */\nexport function generateUuid(): string {\n const bytes = new Uint8Array(16);\n if (typeof crypto !== 'undefined' && crypto.getRandomValues) {\n crypto.getRandomValues(bytes);\n } else {\n // Node.js fallback\n const { randomBytes } = require('crypto') as typeof import('crypto');\n const buf = randomBytes(16);\n for (let i = 0; i < 16; i++) bytes[i] = buf[i] ?? 0;\n }\n bytes[6] = (bytes[6]! & 0x0f) | 0x40; // version 4\n bytes[8] = (bytes[8]! & 0x3f) | 0x80; // variant bits\n const hex = Array.from(bytes)\n .map((b) => b.toString(16).padStart(2, '0'))\n .join('');\n return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;\n}\n","import type { WalletClient, Address, Hex } from 'viem';\nimport type {\n AxonClientConfig,\n PayInput,\n PaymentIntent,\n PaymentResult,\n ExecuteInput,\n ExecuteIntent,\n SwapInput,\n SwapIntent,\n VaultInfo,\n DestinationCheckResult,\n RebalanceTokensResult,\n TosStatus,\n} from './types.js';\nimport { signPayment, signExecuteIntent, signSwapIntent, encodeRef } from './signer.js';\nimport { createAxonWalletClient } from './vault.js';\nimport { DEFAULT_DEADLINE_SECONDS, RELAYER_API } from './constants.js';\nimport { resolveToken } from './tokens.js';\nimport { parseAmount } from './amounts.js';\nimport { generateUuid } from './utils.js';\nimport { keccak256 } from 'viem';\n\n// ============================================================================\n// AxonClient\n// ============================================================================\n\n/**\n * Main entry point for bots interacting with Axon.\n *\n * Handles EIP-712 signing, relayer communication, and status polling.\n * Bots never submit transactions directly — they sign intents and the relayer\n * handles all on-chain execution.\n *\n * All chain reads (balances, bot status, vault info) go through the relayer\n * API — bots never need an RPC endpoint.\n *\n * @example\n * ```ts\n * import { AxonClient, USDC } from '@axonfi/sdk'\n *\n * const client = new AxonClient({\n * vaultAddress: '0x...',\n * chainId: 84532, // Base Sepolia\n * botPrivateKey: '0x...',\n * })\n *\n * const result = await client.pay({\n * to: '0x...recipient...',\n * token: 'USDC',\n * amount: 5, // 5 USDC — SDK handles decimals\n * memo: 'API call #1234 — weather data',\n * })\n *\n * console.log(result.status, result.txHash)\n * ```\n */\nexport class AxonClient {\n private readonly vaultAddress: Address;\n private readonly chainId: number;\n private readonly relayerUrl: string;\n private readonly walletClient: WalletClient;\n\n constructor(config: AxonClientConfig) {\n this.vaultAddress = config.vaultAddress;\n this.chainId = config.chainId;\n this.relayerUrl = 'https://relay.axonfi.xyz';\n\n if (!config.botPrivateKey) {\n throw new Error('botPrivateKey is required in AxonClientConfig');\n }\n this.walletClient = createAxonWalletClient(config.botPrivateKey, config.chainId);\n }\n\n // ============================================================================\n // Bot address\n // ============================================================================\n\n /** Returns the bot's address derived from the configured private key. */\n get botAddress(): Address {\n const account = this.walletClient.account;\n if (!account) throw new Error('No account on walletClient');\n return account.address;\n }\n\n // ============================================================================\n // pay()\n // ============================================================================\n\n /**\n * Create, sign, and submit a payment intent to the Axon relayer.\n *\n * Three possible outcomes (all included in PaymentResult.status):\n * - `\"approved\"`: fast path — txHash available immediately\n * - `\"pending_review\"`: AI scan or human review in progress — poll for status\n * - `\"rejected\"`: payment was rejected — reason field explains why\n */\n async pay(input: PayInput): Promise<PaymentResult> {\n const intent = this._buildPaymentIntent(input);\n const signature = await signPayment(this.walletClient, this.vaultAddress, this.chainId, intent);\n return this._submitPayment(intent, signature, input);\n }\n\n // ============================================================================\n // execute()\n // ============================================================================\n\n /**\n * Sign and submit a DeFi protocol execution to the Axon relayer.\n *\n * The vault approves `token` to `protocol`, calls it with `callData`,\n * then revokes the approval. Tokens stay in the vault or go to the protocol\n * as specified by the calldata.\n */\n async execute(input: ExecuteInput): Promise<PaymentResult> {\n const intent = this._buildExecuteIntent(input);\n const signature = await signExecuteIntent(this.walletClient, this.vaultAddress, this.chainId, intent);\n return this._submitExecute(intent, signature, input);\n }\n\n // ============================================================================\n // swap()\n // ============================================================================\n\n /**\n * Sign and submit an in-vault token swap to the Axon relayer.\n *\n * Swaps tokens within the vault (no external recipient). Useful for\n * rebalancing vault holdings.\n */\n async swap(input: SwapInput): Promise<PaymentResult> {\n const intent = this._buildSwapIntent(input);\n const signature = await signSwapIntent(this.walletClient, this.vaultAddress, this.chainId, intent);\n return this._submitSwap(intent, signature, input);\n }\n\n // ============================================================================\n // getBalance() — via relayer\n // ============================================================================\n\n /** Read the vault's ERC-20 balance for a given token (via relayer). */\n async getBalance(token: Address): Promise<bigint> {\n const path = RELAYER_API.vaultBalance(this.vaultAddress, token, this.chainId);\n const data = await this._get(path);\n return BigInt(data.balance);\n }\n\n // ============================================================================\n // getBalances() — via relayer\n // ============================================================================\n\n /**\n * Read the vault's ERC-20 balances for multiple tokens in a single call (via relayer).\n * Returns a record mapping token address → balance.\n */\n async getBalances(tokens: Address[]): Promise<Record<Address, bigint>> {\n const path = RELAYER_API.vaultBalances(this.vaultAddress, this.chainId);\n const url = `${this.relayerUrl}${path}?chainId=${this.chainId}&tokens=${tokens.join(',')}`;\n\n const response = await fetch(url, {\n method: 'GET',\n headers: { 'Content-Type': 'application/json' },\n });\n\n if (!response.ok) {\n const body = await response.text();\n throw new Error(`Relayer request failed [${response.status}]: ${body}`);\n }\n\n const data = (await response.json()) as { balances: Record<string, string> };\n const result: Record<Address, bigint> = {};\n for (const [addr, val] of Object.entries(data.balances)) {\n result[addr as Address] = BigInt(val);\n }\n return result;\n }\n\n // ============================================================================\n // isActive() — via relayer\n // ============================================================================\n\n /** Returns whether this bot is registered and active in the vault (via relayer). */\n async isActive(): Promise<boolean> {\n const path = RELAYER_API.botStatus(this.vaultAddress, this.botAddress, this.chainId);\n const data = await this._get(path);\n return data.isActive;\n }\n\n // ============================================================================\n // isPaused() — via relayer\n // ============================================================================\n\n /** Returns whether the vault is currently paused (via relayer). */\n async isPaused(): Promise<boolean> {\n const path = RELAYER_API.vaultInfo(this.vaultAddress, this.chainId);\n const data = await this._get(path);\n return data.paused;\n }\n\n // ============================================================================\n // getVaultInfo() — via relayer\n // ============================================================================\n\n /** Returns high-level vault info (owner, operator, paused, version) via relayer. */\n async getVaultInfo(): Promise<VaultInfo> {\n const path = RELAYER_API.vaultInfo(this.vaultAddress, this.chainId);\n return this._get(path) as Promise<VaultInfo>;\n }\n\n // ============================================================================\n // canPayTo() — via relayer\n // ============================================================================\n\n /**\n * Check whether this bot can pay to a given destination address (via relayer).\n * Checks blacklist → global whitelist → bot whitelist, matching on-chain logic.\n */\n async canPayTo(destination: Address): Promise<DestinationCheckResult> {\n const path = RELAYER_API.destinationCheck(this.vaultAddress, this.botAddress, destination, this.chainId);\n return this._get(path) as Promise<DestinationCheckResult>;\n }\n\n // ============================================================================\n // isProtocolApproved() — via relayer\n // ============================================================================\n\n /** Returns whether a protocol address is approved for executeProtocol() calls (via relayer). */\n async isProtocolApproved(protocol: Address): Promise<boolean> {\n const path = RELAYER_API.protocolCheck(this.vaultAddress, protocol, this.chainId);\n const data = await this._get(path);\n return data.approved;\n }\n\n // ============================================================================\n // getRebalanceTokens() — via relayer\n // ============================================================================\n\n /**\n * Returns the effective rebalance token whitelist for this vault.\n *\n * If the owner set tokens on-chain, those override entirely.\n * If no on-chain whitelist, returns relayer defaults (USDC, WETH, USDT).\n * Use this before calling swap() to check which output tokens are allowed.\n */\n async getRebalanceTokens(): Promise<RebalanceTokensResult> {\n const path = RELAYER_API.rebalanceTokens(this.vaultAddress, this.chainId);\n return this._get(path) as Promise<RebalanceTokensResult>;\n }\n\n // ============================================================================\n // isRebalanceTokenAllowed() — via relayer\n // ============================================================================\n\n /** Check if a specific token is allowed for rebalancing (executeSwap output) on this vault. */\n async isRebalanceTokenAllowed(token: Address): Promise<{ allowed: boolean; source: 'default' | 'on_chain' }> {\n const path = RELAYER_API.rebalanceTokenCheck(this.vaultAddress, token, this.chainId);\n return this._get(path) as Promise<{ allowed: boolean; source: 'default' | 'on_chain' }>;\n }\n\n // ============================================================================\n // TOS (Terms of Service)\n // ============================================================================\n\n /** Check if a wallet has accepted the current TOS version. */\n async getTosStatus(wallet: string): Promise<TosStatus> {\n return this._get(RELAYER_API.tosStatus(wallet)) as Promise<TosStatus>;\n }\n\n /**\n * Sign and submit TOS acceptance. Uses the owner's wallet (not the bot key).\n *\n * @param signer - Object with a `signMessage` method (e.g. a viem WalletClient\n * or ethers Signer). This should be the vault owner's wallet, not the bot key.\n * @param wallet - The owner's wallet address (must match the signer).\n */\n async acceptTos(\n signer: { signMessage: (args: { message: string }) => Promise<Hex> },\n wallet: string,\n ): Promise<TosStatus> {\n // 1. Get current TOS version from relayer\n const { tosVersion } = await this.getTosStatus(wallet);\n\n // 2. Construct and sign the acceptance message\n const timestamp = Math.floor(Date.now() / 1000);\n const message = `I accept the Axon Terms of Service (${tosVersion}).\\nWallet: ${wallet}\\nTimestamp: ${timestamp}`;\n const signature = await signer.signMessage({ message });\n\n // 3. Submit to relayer\n const url = `${this.relayerUrl}${RELAYER_API.TOS_ACCEPT}`;\n const response = await fetch(url, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ wallet, signature, tosVersion, timestamp }),\n });\n\n if (!response.ok) {\n const body = await response.text();\n throw new Error(`TOS acceptance failed [${response.status}]: ${body}`);\n }\n\n return response.json() as Promise<TosStatus>;\n }\n\n // ============================================================================\n // poll() / pollExecute() / pollSwap()\n // ============================================================================\n\n /**\n * Poll the relayer for the status of an async payment.\n *\n * Use this when pay() returns `status: \"pending_review\"`. Poll until\n * status is `\"approved\"` or `\"rejected\"`.\n *\n * Recommended polling interval: 5–10 seconds.\n */\n async poll(requestId: string): Promise<PaymentResult> {\n return this._get(RELAYER_API.payment(requestId)) as Promise<PaymentResult>;\n }\n\n /** Poll the relayer for the status of an async protocol execution. */\n async pollExecute(requestId: string): Promise<PaymentResult> {\n return this._get(RELAYER_API.execute(requestId)) as Promise<PaymentResult>;\n }\n\n /** Poll the relayer for the status of an async swap. */\n async pollSwap(requestId: string): Promise<PaymentResult> {\n return this._get(RELAYER_API.swap(requestId)) as Promise<PaymentResult>;\n }\n\n // ============================================================================\n // signPayment() — low-level access\n // ============================================================================\n\n /**\n * Sign a PaymentIntent directly without submitting to the relayer.\n *\n * Use this if you want to build the intent yourself and pass the signature\n * to another system (e.g. a custom relayer integration).\n */\n async signPayment(intent: PaymentIntent): Promise<Hex> {\n return signPayment(this.walletClient, this.vaultAddress, this.chainId, intent);\n }\n\n // ============================================================================\n // Internal helpers\n // ============================================================================\n\n private async _get(path: string): Promise<any> {\n const url = `${this.relayerUrl}${path}`;\n const response = await fetch(url, {\n method: 'GET',\n headers: { 'Content-Type': 'application/json' },\n });\n\n if (!response.ok) {\n const body = await response.text();\n throw new Error(`Relayer request failed [${response.status}]: ${body}`);\n }\n\n return response.json();\n }\n\n private _defaultDeadline(): bigint {\n return BigInt(Math.floor(Date.now() / 1000) + DEFAULT_DEADLINE_SECONDS);\n }\n\n private _resolveRef(memo?: string, ref?: Hex): Hex {\n if (ref) return ref;\n if (memo) return encodeRef(memo);\n return '0x0000000000000000000000000000000000000000000000000000000000000000';\n }\n\n private _buildPaymentIntent(input: PayInput): PaymentIntent {\n if (input.to === '0x0000000000000000000000000000000000000000') {\n throw new Error('Payment recipient cannot be the zero address');\n }\n return {\n bot: this.botAddress,\n to: input.to,\n token: resolveToken(input.token, this.chainId),\n amount: parseAmount(input.amount, input.token, this.chainId),\n deadline: input.deadline ?? this._defaultDeadline(),\n ref: this._resolveRef(input.memo, input.ref),\n };\n }\n\n private _buildExecuteIntent(input: ExecuteInput): ExecuteIntent {\n return {\n bot: this.botAddress,\n protocol: input.protocol,\n calldataHash: keccak256(input.callData),\n token: resolveToken(input.token, this.chainId),\n amount: parseAmount(input.amount, input.token, this.chainId),\n deadline: input.deadline ?? this._defaultDeadline(),\n ref: this._resolveRef(input.memo, input.ref),\n };\n }\n\n private _buildSwapIntent(input: SwapInput): SwapIntent {\n return {\n bot: this.botAddress,\n toToken: resolveToken(input.toToken, this.chainId),\n minToAmount: parseAmount(input.minToAmount, input.toToken, this.chainId),\n deadline: input.deadline ?? this._defaultDeadline(),\n ref: this._resolveRef(input.memo, input.ref),\n };\n }\n\n private async _submitPayment(intent: PaymentIntent, signature: Hex, input: PayInput): Promise<PaymentResult> {\n const idempotencyKey = input.idempotencyKey ?? generateUuid();\n\n const body = {\n // Routing\n chainId: this.chainId,\n vaultAddress: this.vaultAddress,\n\n // Flat intent fields (matches relayer DTO)\n bot: intent.bot,\n to: intent.to,\n token: intent.token,\n amount: intent.amount.toString(),\n deadline: intent.deadline.toString(),\n ref: intent.ref,\n signature,\n\n // Off-chain metadata\n idempotencyKey,\n ...(input.memo !== undefined && { memo: input.memo }),\n ...(input.resourceUrl !== undefined && { resourceUrl: input.resourceUrl }),\n ...(input.invoiceId !== undefined && { invoiceId: input.invoiceId }),\n ...(input.orderId !== undefined && { orderId: input.orderId }),\n ...(input.recipientLabel !== undefined && { recipientLabel: input.recipientLabel }),\n ...(input.metadata !== undefined && { metadata: input.metadata }),\n };\n\n return this._post(RELAYER_API.PAYMENTS, idempotencyKey, body);\n }\n\n private async _submitExecute(intent: ExecuteIntent, signature: Hex, input: ExecuteInput): Promise<PaymentResult> {\n const idempotencyKey = input.idempotencyKey ?? generateUuid();\n\n // Resolve optional pre-swap fields\n const fromToken = input.fromToken !== undefined ? resolveToken(input.fromToken, this.chainId) : undefined;\n const maxFromAmount =\n input.maxFromAmount !== undefined\n ? parseAmount(input.maxFromAmount, input.fromToken ?? input.token, this.chainId)\n : undefined;\n\n const body = {\n chainId: this.chainId,\n vaultAddress: this.vaultAddress,\n\n // Flat intent fields\n bot: intent.bot,\n protocol: intent.protocol,\n calldataHash: intent.calldataHash,\n token: intent.token,\n amount: intent.amount.toString(),\n deadline: intent.deadline.toString(),\n ref: intent.ref,\n signature,\n\n // Protocol calldata\n callData: input.callData,\n\n // Optional pre-swap\n ...(fromToken !== undefined && { fromToken }),\n ...(maxFromAmount !== undefined && { maxFromAmount: maxFromAmount.toString() }),\n\n // Off-chain metadata\n idempotencyKey,\n ...(input.memo !== undefined && { memo: input.memo }),\n ...(input.protocolName !== undefined && { protocolName: input.protocolName }),\n ...(input.metadata !== undefined && { metadata: input.metadata }),\n };\n\n return this._post(RELAYER_API.EXECUTE, idempotencyKey, body);\n }\n\n private async _submitSwap(intent: SwapIntent, signature: Hex, input: SwapInput): Promise<PaymentResult> {\n const idempotencyKey = input.idempotencyKey ?? generateUuid();\n\n // Resolve optional source token fields\n const fromToken = input.fromToken !== undefined ? resolveToken(input.fromToken, this.chainId) : undefined;\n const maxFromAmount =\n input.maxFromAmount !== undefined\n ? parseAmount(input.maxFromAmount, input.fromToken ?? input.toToken, this.chainId)\n : undefined;\n\n const body = {\n chainId: this.chainId,\n vaultAddress: this.vaultAddress,\n\n // Flat intent fields\n bot: intent.bot,\n toToken: intent.toToken,\n minToAmount: intent.minToAmount.toString(),\n deadline: intent.deadline.toString(),\n ref: intent.ref,\n signature,\n\n // Optional source token\n ...(fromToken !== undefined && { fromToken }),\n ...(maxFromAmount !== undefined && { maxFromAmount: maxFromAmount.toString() }),\n\n // Off-chain metadata\n idempotencyKey,\n ...(input.memo !== undefined && { memo: input.memo }),\n };\n\n return this._post(RELAYER_API.SWAP, idempotencyKey, body);\n }\n\n private async _post(path: string, idempotencyKey: string, body: Record<string, unknown>): Promise<PaymentResult> {\n const url = `${this.relayerUrl}${path}`;\n\n const response = await fetch(url, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'Idempotency-Key': idempotencyKey,\n },\n body: JSON.stringify(body),\n });\n\n if (!response.ok) {\n const responseBody = await response.text();\n throw new Error(`Relayer request failed [${response.status}]: ${responseBody}`);\n }\n\n return response.json() as Promise<PaymentResult>;\n }\n}\n","import { Service, type IAgentRuntime } from '@elizaos/core';\nimport { AxonClient, type Chain } from '@axonfi/sdk';\n\nexport class AxonService extends Service {\n static serviceType = 'AXON';\n capabilityDescription = 'Enables gasless payments, token swaps, and DeFi interactions through Axon non-custodial vaults.';\n\n client!: AxonClient;\n\n static async start(runtime: IAgentRuntime): Promise<AxonService> {\n const svc = new AxonService(runtime);\n\n const botPrivateKey = runtime.getSetting('AXON_BOT_PRIVATE_KEY') as string;\n if (!botPrivateKey) throw new Error('AXON_BOT_PRIVATE_KEY is required');\n\n const vaultAddress = runtime.getSetting('AXON_VAULT_ADDRESS') as string;\n if (!vaultAddress) throw new Error('AXON_VAULT_ADDRESS is required');\n\n const chainId = runtime.getSetting('AXON_CHAIN_ID');\n if (!chainId) throw new Error('AXON_CHAIN_ID is required');\n\n svc.client = new AxonClient({\n botPrivateKey: botPrivateKey as `0x${string}`,\n vaultAddress: vaultAddress as `0x${string}`,\n chainId: Number(chainId) as Chain,\n });\n\n // Verify bot is registered and active on the vault\n const active = await svc.client.isActive();\n if (!active) {\n runtime.logger.warn(\n `Axon bot ${svc.client.botAddress} is NOT active on vault ${vaultAddress}. Payments will fail.`\n );\n } else {\n runtime.logger.info(\n `Axon plugin ready — bot ${svc.client.botAddress} on vault ${vaultAddress} (chain ${chainId})`\n );\n }\n\n return svc;\n }\n\n async stop(): Promise<void> {\n // AxonClient is stateless — nothing to clean up\n }\n}\n","import type { Action, IAgentRuntime, Memory, State, HandlerOptions, HandlerCallback } from '@elizaos/core';\nimport { AxonService } from '../service.js';\n\nexport const sendPaymentAction: Action = {\n name: 'AXON_SEND_PAYMENT',\n description:\n 'Send a token payment from the agent\\'s Axon vault. Supports USDC (default), WETH, and other ERC-20 tokens. Specify recipient address, amount, and optionally token and memo.',\n similes: ['PAY', 'SEND', 'TRANSFER', 'SEND_PAYMENT', 'SEND_USDC', 'PAY_USDC'],\n\n validate: async (runtime: IAgentRuntime, _message: Memory) => {\n return runtime.getSetting('AXON_BOT_PRIVATE_KEY') !== null;\n },\n\n handler: async (\n runtime: IAgentRuntime,\n message: Memory,\n state: State | undefined,\n _options: HandlerOptions | undefined,\n callback: HandlerCallback | undefined,\n ) => {\n const svc = runtime.getService<AxonService>('AXON');\n if (!svc) {\n await callback?.({ text: 'Axon service is not available. Check plugin configuration.' });\n return { success: false, error: 'Axon service not found' };\n }\n\n // Use LLM to extract structured payment params from the message\n const context = `Extract payment details from this message. Return JSON only, no markdown:\n{\"to\": \"0x... recipient address\", \"amount\": \"numeric amount as string\", \"token\": \"token symbol or address (default USDC)\", \"memo\": \"optional memo or null\"}\n\nMessage: \"${message.content.text}\"`;\n\n let params: { to: string; amount: string; token?: string; memo?: string };\n try {\n const response = await runtime.useModel('TEXT_SMALL' as any, {\n prompt: context,\n stopSequences: [],\n });\n params = JSON.parse(response);\n } catch {\n await callback?.({\n text: 'I couldn\\'t parse the payment details. Please specify: recipient address, amount, and optionally token (default USDC).',\n });\n return { success: false, error: 'Failed to parse payment params' };\n }\n\n if (!params.to || !params.amount) {\n await callback?.({\n text: 'Missing recipient address or amount. Example: \"Send 50 USDC to 0xabc...\"',\n });\n return { success: false, error: 'Missing required fields' };\n }\n\n try {\n const result = await svc.client.pay({\n to: params.to as `0x${string}`,\n token: (params.token ?? 'USDC') as any,\n amount: params.amount,\n memo: params.memo ?? undefined,\n });\n\n if (result.status === 'approved') {\n await callback?.({\n text: `Payment sent! ${params.amount} ${params.token ?? 'USDC'} to ${params.to}\\nTx: ${result.txHash}`,\n });\n } else if (result.status === 'pending_review') {\n await callback?.({\n text: `Payment is pending human review (request ${result.requestId}). The vault owner will be notified.`,\n });\n } else {\n await callback?.({\n text: `Payment rejected: ${result.reason ?? 'unknown reason'}`,\n });\n }\n\n return { success: result.status === 'approved', data: { ...result } as Record<string, unknown> };\n } catch (err: any) {\n await callback?.({ text: `Payment failed: ${err.message}` });\n return { success: false, error: err.message };\n }\n },\n\n examples: [\n [\n { name: 'user', content: { text: 'Send 50 USDC to 0x1234567890abcdef1234567890abcdef12345678' } },\n { name: 'agent', content: { text: 'Sending payment...', action: 'AXON_SEND_PAYMENT' } },\n ],\n [\n { name: 'user', content: { text: 'Pay 0.5 WETH to 0xabcdefabcdefabcdefabcdefabcdefabcdefabcd with memo \"API invoice #42\"' } },\n { name: 'agent', content: { text: 'Processing WETH payment...', action: 'AXON_SEND_PAYMENT' } },\n ],\n ],\n};\n","import type { Action, IAgentRuntime, Memory, State, HandlerOptions, HandlerCallback } from '@elizaos/core';\nimport { AxonService } from '../service.js';\n\nexport const swapTokensAction: Action = {\n name: 'AXON_SWAP_TOKENS',\n description:\n 'Swap tokens within the agent\\'s Axon vault (in-vault rebalancing). Specify source token, destination token, and amount to swap.',\n similes: ['SWAP', 'CONVERT', 'EXCHANGE', 'REBALANCE', 'SWAP_TOKENS'],\n\n validate: async (runtime: IAgentRuntime, _message: Memory) => {\n return runtime.getSetting('AXON_BOT_PRIVATE_KEY') !== null;\n },\n\n handler: async (\n runtime: IAgentRuntime,\n message: Memory,\n _state: State | undefined,\n _options: HandlerOptions | undefined,\n callback: HandlerCallback | undefined,\n ) => {\n const svc = runtime.getService<AxonService>('AXON');\n if (!svc) {\n await callback?.({ text: 'Axon service is not available. Check plugin configuration.' });\n return { success: false, error: 'Axon service not found' };\n }\n\n const context = `Extract swap details from this message. Return JSON only, no markdown:\n{\"fromToken\": \"source token symbol or address\", \"toToken\": \"destination token symbol or address\", \"amount\": \"numeric amount as string\"}\n\nMessage: \"${message.content.text}\"`;\n\n let params: { fromToken: string; toToken: string; amount: string };\n try {\n const response = await runtime.useModel('TEXT_SMALL' as any, {\n prompt: context,\n stopSequences: [],\n });\n params = JSON.parse(response);\n } catch {\n await callback?.({\n text: 'I couldn\\'t parse the swap details. Please specify: source token, destination token, and amount. Example: \"Swap 100 USDC to WETH\"',\n });\n return { success: false, error: 'Failed to parse swap params' };\n }\n\n if (!params.fromToken || !params.toToken || !params.amount) {\n await callback?.({\n text: 'Missing swap details. Example: \"Swap 100 USDC to WETH\"',\n });\n return { success: false, error: 'Missing required fields' };\n }\n\n try {\n const result = await svc.client.swap({\n fromToken: params.fromToken as any,\n maxFromAmount: params.amount,\n toToken: params.toToken as any,\n minToAmount: '0',\n });\n\n if (result.status === 'approved') {\n await callback?.({\n text: `Swap complete! ${params.amount} ${params.fromToken} → ${params.toToken}\\nTx: ${result.txHash}`,\n });\n } else if (result.status === 'pending_review') {\n await callback?.({\n text: `Swap is pending review (request ${result.requestId}).`,\n });\n } else {\n await callback?.({\n text: `Swap rejected: ${result.reason ?? 'unknown reason'}`,\n });\n }\n\n return { success: result.status === 'approved', data: { ...result } as Record<string, unknown> };\n } catch (err: any) {\n await callback?.({ text: `Swap failed: ${err.message}` });\n return { success: false, error: err.message };\n }\n },\n\n examples: [\n [\n { name: 'user', content: { text: 'Swap 100 USDC to WETH in my vault' } },\n { name: 'agent', content: { text: 'Swapping tokens...', action: 'AXON_SWAP_TOKENS' } },\n ],\n [\n { name: 'user', content: { text: 'Convert 0.05 WETH to USDC' } },\n { name: 'agent', content: { text: 'Processing swap...', action: 'AXON_SWAP_TOKENS' } },\n ],\n ],\n};\n","import type { Action, IAgentRuntime, Memory, State, HandlerOptions, HandlerCallback } from '@elizaos/core';\nimport { AxonService } from '../service.js';\n\nexport const executeProtocolAction: Action = {\n name: 'AXON_EXECUTE_PROTOCOL',\n description:\n 'Execute a DeFi protocol interaction through the agent\\'s Axon vault. Requires protocol address, calldata, token, and amount. This is an advanced action for structured DeFi calls (approve → call → revoke).',\n similes: ['EXECUTE', 'CALL_PROTOCOL', 'DEFI', 'INTERACT', 'PROTOCOL'],\n\n validate: async (runtime: IAgentRuntime, _message: Memory) => {\n return runtime.getSetting('AXON_BOT_PRIVATE_KEY') !== null;\n },\n\n handler: async (\n runtime: IAgentRuntime,\n message: Memory,\n _state: State | undefined,\n _options: HandlerOptions | undefined,\n callback: HandlerCallback | undefined,\n ) => {\n const svc = runtime.getService<AxonService>('AXON');\n if (!svc) {\n await callback?.({ text: 'Axon service is not available. Check plugin configuration.' });\n return { success: false, error: 'Axon service not found' };\n }\n\n const context = `Extract DeFi protocol execution details from this message. Return JSON only, no markdown:\n{\"protocol\": \"0x... protocol contract address\", \"callData\": \"0x... encoded calldata\", \"token\": \"token symbol or address for approval\", \"amount\": \"numeric amount as string\", \"protocolName\": \"human-readable protocol name or null\", \"memo\": \"optional memo or null\"}\n\nIf the message doesn't contain explicit calldata or protocol address, return {\"error\": \"insufficient details\"}.\n\nMessage: \"${message.content.text}\"`;\n\n let params: {\n protocol?: string;\n callData?: string;\n token?: string;\n amount?: string;\n protocolName?: string;\n memo?: string;\n error?: string;\n };\n try {\n const response = await runtime.useModel('TEXT_SMALL' as any, {\n prompt: context,\n stopSequences: [],\n });\n params = JSON.parse(response);\n } catch {\n await callback?.({\n text: 'I couldn\\'t parse the protocol execution details. This action requires: protocol address, calldata, token, and amount.',\n });\n return { success: false, error: 'Failed to parse execute params' };\n }\n\n if (params.error || !params.protocol || !params.callData || !params.token || !params.amount) {\n await callback?.({\n text: 'Protocol execution requires structured input: protocol address, encoded calldata, token, and amount. This is typically used programmatically rather than via natural language.',\n });\n return { success: false, error: 'Missing required fields for protocol execution' };\n }\n\n try {\n const result = await svc.client.execute({\n protocol: params.protocol as `0x${string}`,\n callData: params.callData as `0x${string}`,\n token: params.token as any,\n amount: params.amount,\n protocolName: params.protocolName ?? undefined,\n memo: params.memo ?? undefined,\n });\n\n if (result.status === 'approved') {\n await callback?.({\n text: `Protocol execution complete!${params.protocolName ? ` (${params.protocolName})` : ''}\\nTx: ${result.txHash}`,\n });\n } else if (result.status === 'pending_review') {\n await callback?.({\n text: `Protocol execution is pending review (request ${result.requestId}).`,\n });\n } else {\n await callback?.({\n text: `Protocol execution rejected: ${result.reason ?? 'unknown reason'}`,\n });\n }\n\n return { success: result.status === 'approved', data: { ...result } as Record<string, unknown> };\n } catch (err: any) {\n await callback?.({ text: `Protocol execution failed: ${err.message}` });\n return { success: false, error: err.message };\n }\n },\n\n examples: [\n [\n { name: 'user', content: { text: 'Execute a deposit of 500 USDC into Aave at 0x1234...' } },\n { name: 'agent', content: { text: 'Processing protocol execution...', action: 'AXON_EXECUTE_PROTOCOL' } },\n ],\n ],\n};\n","import type { Action, IAgentRuntime, Memory, State, HandlerOptions, HandlerCallback } from '@elizaos/core';\nimport { AxonService } from '../service.js';\nimport { USDC, CHAIN_NAMES, type Chain } from '@axonfi/sdk';\n\nexport const checkBalanceAction: Action = {\n name: 'AXON_CHECK_BALANCE',\n description:\n 'Check the current token balances in the agent\\'s Axon vault. Returns USDC balance by default, or specify a token.',\n similes: ['BALANCE', 'CHECK_BALANCE', 'HOW_MUCH', 'FUNDS', 'VAULT_BALANCE'],\n\n validate: async (runtime: IAgentRuntime, _message: Memory) => {\n return runtime.getSetting('AXON_BOT_PRIVATE_KEY') !== null;\n },\n\n handler: async (\n runtime: IAgentRuntime,\n _message: Memory,\n _state: State | undefined,\n _options: HandlerOptions | undefined,\n callback: HandlerCallback | undefined,\n ) => {\n const svc = runtime.getService<AxonService>('AXON');\n if (!svc) {\n await callback?.({ text: 'Axon service is not available. Check plugin configuration.' });\n return { success: false, error: 'Axon service not found' };\n }\n\n try {\n const chainId = Number(runtime.getSetting('AXON_CHAIN_ID')) as Chain;\n const vaultAddress = runtime.getSetting('AXON_VAULT_ADDRESS') as string;\n const usdcAddress = USDC[chainId];\n const chainName = CHAIN_NAMES[chainId] ?? `Chain ${chainId}`;\n\n const balance = await svc.client.getBalance(usdcAddress);\n const formatted = (Number(balance) / 1e6).toFixed(2);\n\n const info = await svc.client.getVaultInfo();\n const status = info.paused ? 'PAUSED' : 'active';\n\n const text = `Axon vault ${vaultAddress.slice(0, 6)}...${vaultAddress.slice(-4)} on ${chainName}: ${formatted} USDC. Status: ${status}.`;\n\n await callback?.({ text });\n return {\n success: true,\n data: { balance: formatted, status, chainName, vaultAddress },\n };\n } catch (err: any) {\n await callback?.({ text: `Failed to check balance: ${err.message}` });\n return { success: false, error: err.message };\n }\n },\n\n examples: [\n [\n { name: 'user', content: { text: \"What's my vault balance?\" } },\n { name: 'agent', content: { text: 'Checking vault balance...', action: 'AXON_CHECK_BALANCE' } },\n ],\n [\n { name: 'user', content: { text: 'How much USDC do I have?' } },\n { name: 'agent', content: { text: 'Let me check...', action: 'AXON_CHECK_BALANCE' } },\n ],\n ],\n};\n","import type { Provider, IAgentRuntime, Memory, State } from '@elizaos/core';\nimport { AxonService } from '../service.js';\nimport { USDC, CHAIN_NAMES, type Chain } from '@axonfi/sdk';\n\nconst CACHE_TTL_MS = 30_000;\n\nlet cachedText: string | null = null;\nlet cachedAt = 0;\n\nexport const vaultContextProvider: Provider = {\n name: 'AXON_VAULT_CONTEXT',\n description: 'Provides current Axon vault balance and status for agent context.',\n dynamic: false,\n position: 10,\n\n get: async (\n runtime: IAgentRuntime,\n _message: Memory,\n _state: State,\n ) => {\n const now = Date.now();\n if (cachedText && now - cachedAt < CACHE_TTL_MS) {\n return { text: cachedText };\n }\n\n const svc = runtime.getService<AxonService>('AXON');\n if (!svc) {\n return { text: 'Axon vault: not configured.' };\n }\n\n try {\n const chainId = Number(runtime.getSetting('AXON_CHAIN_ID')) as Chain;\n const vaultAddress = runtime.getSetting('AXON_VAULT_ADDRESS') as string;\n const usdcAddress = USDC[chainId];\n const chainName = CHAIN_NAMES[chainId] ?? `Chain ${chainId}`;\n\n const [balance, info] = await Promise.all([\n svc.client.getBalance(usdcAddress),\n svc.client.getVaultInfo(),\n ]);\n\n const formatted = (Number(balance) / 1e6).toFixed(2);\n const status = info.paused ? 'PAUSED' : 'active';\n const short = `${vaultAddress.slice(0, 6)}...${vaultAddress.slice(-4)}`;\n\n cachedText = `Axon vault ${short} on ${chainName}: ${formatted} USDC. Status: ${status}.`;\n cachedAt = now;\n\n return {\n text: cachedText,\n values: {\n axonVaultAddress: vaultAddress,\n axonChain: chainName,\n axonBalance: formatted,\n axonStatus: status,\n },\n };\n } catch {\n return { text: 'Axon vault: unable to fetch balance.' };\n }\n },\n};\n","import type { Plugin } from '@elizaos/core';\nimport { AxonService } from './service.js';\nimport { sendPaymentAction } from './actions/sendPayment.js';\nimport { swapTokensAction } from './actions/swapTokens.js';\nimport { executeProtocolAction } from './actions/executeProtocol.js';\nimport { checkBalanceAction } from './actions/checkBalance.js';\nimport { vaultContextProvider } from './providers/vaultContext.js';\n\nexport const axonPlugin: Plugin = {\n name: 'plugin-axon',\n description:\n 'Treasury and payment infrastructure for AI agents via AxonFi. Gasless payments, token swaps, and DeFi interactions through non-custodial vaults.',\n services: [AxonService as any],\n actions: [sendPaymentAction, swapTokensAction, executeProtocolAction, checkBalanceAction],\n providers: [vaultContextProvider],\n};\n\nexport default axonPlugin;\nexport { AxonService } from './service.js';\nexport { sendPaymentAction } from './actions/sendPayment.js';\nexport { swapTokensAction } from './actions/swapTokens.js';\nexport { executeProtocolAction } from './actions/executeProtocol.js';\nexport { checkBalanceAction } from './actions/checkBalance.js';\nexport { vaultContextProvider } from './providers/vaultContext.js';\n"]}